123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979 |
- //
- // KMHomeViewController.swift
- // PDF Reader Pro
- //
- // Created by wanjun on 2022/10/13.
- //
- import Cocoa
- @objc enum KMHomeToolState : Int {
- case OpenPDF = 0
- case CreatePDF
- case Home
- case PDFTools
- case FavoriteDocuments
- case CloudDocuments
- }
- @objc enum KMAIHomeToolState : Int {
- case Home = 0
- case AITranslation
- case AIRewriting
- case AIErrorCorrection
- }
- @objcMembers class KMHomeViewController: NSViewController {
- @IBOutlet weak var leftBox: NSBox!
- @IBOutlet weak var rightBox: NSBox!
- @IBOutlet weak var homeSplitView: NSSplitView!
- @IBOutlet weak var homeRightScrollViewView: NSScrollView!
- @IBOutlet weak var rightTopBox: NSBox!
- @IBOutlet weak var rightBottomBox: NSBox!
- @IBOutlet weak var rightFullBox: NSBox!
- @IBOutlet weak var rightTopBoxHeightConstraint: NSLayoutConstraint!
-
- @IBOutlet var fastToolViewController: KMHomeFastToolViewController!
- @IBOutlet var historyFileViewController: KMHomeHistoryFileViewController!
- @IBOutlet var pdfToolsViewController: KMPDFToolsViewController!
- @IBOutlet var cloudDocumentsViewController: KMCloudDocumentsViewController!
-
- @IBOutlet weak var dragView: KMHomeDragView!
-
- // AI 临时UI
- @IBOutlet weak var aiHomeBox: KMBox!
- @IBOutlet weak var aiHomeImageView: NSImageView!
- @IBOutlet weak var aiHomeLabel: NSTextField!
- @IBOutlet weak var aiTranslationBox: KMBox!
- @IBOutlet weak var aiTranslationImageView: NSImageView!
- @IBOutlet weak var aiTranslationLabel: NSTextField!
- @IBOutlet weak var aiRewritingBox: KMBox!
- @IBOutlet weak var aiRewritingImageView: NSImageView!
- @IBOutlet weak var aiRewritingLabel: NSTextField!
- @IBOutlet weak var aiErrorCorrectionBox: KMBox!
- @IBOutlet weak var aiErrorCorrectionImageView: NSImageView!
- @IBOutlet weak var aiErrorCorrectionLabel: NSTextField!
- @IBOutlet var aiOpenPDFFilesViewController: KMAIOpenPDFFilesVC!
- @IBOutlet var aiTranslationViewController: KMAITranslationVC!
- @IBOutlet var aiRewritingViewController: KMAIRewritingVC!
-
- @IBOutlet weak var creatPDFView: KMCreatPDFView!
-
- //HomeContentView
- @IBOutlet weak var homeContentView: KMHomeContentView!
- //广告 互推
- @IBOutlet weak var advertisementTableView: KMAdvertisementTableView!
- @IBOutlet weak var advertisementTableViewHeightConstraint: NSLayoutConstraint!
- @IBOutlet weak var advertisementShowView: KMAdvertisementShowView!
-
- //合并
- var mergeWindowController: KMMergeWindowController?
-
- var aiHomeState: KMAIHomeToolState = .Home
-
- let ScrollerViewWidget: CGFloat = 15.0
-
- var homeWindowController : MainWindowController!
-
- var isShowQuickTour: Bool = false
- var myDocument: NSDocument?
- var currentWindowController: NSWindowController?
- var homeState: KMHomeToolState = .Home
-
- var urlToPDFWindowController: KMURLToPDFWindowController?
-
- var openPDFButtonVC: KMDesignButton?
- var createPDFButtonVC: KMDesignButton?
- var createPDFImage: KMDesignButton?
- var createPDFAddButtonVC: KMDesignButton?
- var homeButtonVC: KMTextImageButtonVC?
- var pdfToolsButtonVC: KMTextImageButtonVC?
- var cloudDocumentsButtonVC: KMTextImageButtonVC?
- var pdfSeriesButtonVC: KMTextImageButtonVC?
- var pdfOthersButtonVC: KMTextImageButtonVC?
- var popover: NSPopover?
- var deviceBrowserWC: KMDeviceBrowserWindowController?
- var progressController: SKProgressController?
- var timer: Timer?
- var timerCounter = 0.0
-
- //AI相关
-
- //试用相关
- var didTrialExpiredLoad: Bool = false
- var repeatTrialAlertLoad: Bool = false
-
- @IBOutlet weak var rightBottonHeight: NSLayoutConstraint!
-
- var currentController: NSWindowController?
- deinit {
- NotificationCenter.default.removeObserver(self)
- }
-
- override func viewWillAppear() {
- super.viewWillAppear()
- if !KMLightMemberManager.manager.isLogin() {
- KMLightMemberManager.manager.canShowAdvancedView = true
- }
- self.homeContentView.reloadData()
- #if VERSION_DMG
- let kDMGFirstInstallKey = "DMGFirstInstallKey"
- if KMDataManager.ud_object(forKey: kDMGFirstInstallKey) == nil {
- KMDataManager.ud_set("Show", forKey: kDMGFirstInstallKey)
- KMTools.openURL(urlString: "http://www.pdfreaderpro.com/thank-you-for-installation")
- }
- #else
- // [self loadAIInfo];
- #endif
- }
-
- override func viewWillDisappear() {
- super.viewWillDisappear()
-
- // self.homeContentView.reloadData()
- }
-
- override func viewDidLoad() {
- super.viewDidLoad()
- // Do view setup here.
-
- openPDFButtonVC = KMDesignButton.init(withType: .Text)
- createPDFButtonVC = KMDesignButton.init(withType: .Text)
- createPDFImage = KMDesignButton.init(withType: .Image)
- createPDFAddButtonVC = KMDesignButton.init(withType: .Image)
- homeButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
- pdfToolsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
- cloudDocumentsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
- pdfSeriesButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
- pdfOthersButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
- self.homeSplitView.setPosition(270.0, ofDividerAt: 0)
- self.leftBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
- self.rightBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
-
- NSEvent.addLocalMonitorForEvents(matching: .leftMouseDown) { (aEvent) -> NSEvent? in
- self.otherMouseDown(with: aEvent)
- return aEvent
- }
- self.initNetworkingData()
- // self.initLocalization()
- // self.initializeUI()
- self.initializeUI_DMG()
-
- self.setup()
- // refreshUI()
- self.updateUI()
- self.changeEffectiveAppearance()
-
- NotificationCenter.default.addObserver(self, selector: #selector(homeFileRectChange(_:)), name: Notification.Name("KMHomeFileRectChange"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(changeEffectiveAppearance), name: NSNotification.Name(rawValue: "kEffectiveAppearance"), object: nil)
- // setAppearance(isDarkMode: KMAdvertisementConfig.isDarkModel())
- // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name(NSApplication.didUpdateNotification.rawValue), object: nil)
- // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name(NSWindow.didBecomeMainNotification.rawValue), object: nil)
- // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name("AppleInterfaceThemeChangedNotification"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(openNewWindowAlertV), name: Notification.Name("KMCTTableChangeShowAlertView"), object: nil)
- #if VERSION_DMG
- NotificationCenter.default.addObserver(self, selector: #selector(deviceVerifyFinishNotification), name: Notification.Name.init(NSNotification.Name.deviceVerifyFinish.rawValue), object: nil)
- #endif
-
- NotificationCenter.default.addObserver(self, selector: #selector(importFromCamera), name: Notification.Name("kDeviceCameraMenuItemNotification"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(importFromScanner), name: Notification.Name("kDeviceScannerMenuItemNotification"), object: nil)
- self.loadFunctionGuide()
-
- }
-
- override func viewDidAppear() {
- super.viewDidAppear()
- refreshScrollView()
- }
-
- override func viewDidLayout() {
- super.viewDidLayout()
-
- refreshScrollView()
-
- // self.loadAITipIconGuide()
- }
-
- func initNetworkingData() {
- KMAdvertisementManager.manager.fetchDataWithResponseObject { [unowned self] data, responseObject, error in
- KMPrint("获取广告数据成功")
- if data != nil {
- advertisementTableView.inputData = data!.recommondContent
- advertisementTableView.didSelect = { view, item in
- let string = KMAdvertisementModelTransition.transitionLanguage(langeuage: item.linkURL)
- if string.count != 0 {
- NSWorkspace.shared.open(URL.init(string: string)!)
- }
- }
-
- advertisementShowView.inputData = data!.advertisement
- advertisementShowView.didSelect = { view, item in
- let string = KMAdvertisementModelTransition.transitionLanguage(langeuage: item.linkURL)
- if string.count != 0 {
- NSWorkspace.shared.open(URL.init(string: string)!)
- }
- }
-
- if KMAdvertisementManager.manager.infoDict.allKeys.count > 0 {
- if let adsInfo = KMAdvertisementManager.manager.infoDict["adsInfo"] {
- let infoDict: NSDictionary = KMAdvertisementManager.manager.infoDict["adsInfo"] as! NSDictionary
- let array: [[String: Any]] = infoDict["content"] as! [[String : Any]]
-
- let arrM = NSMutableArray.init()
- for dict in array {
- let adsInfo = KMAdsInfo.init()
- let mutableDictionary = NSMutableDictionary(dictionary: dict)
- adsInfo.infoDict = mutableDictionary
- arrM.add(adsInfo)
- }
- KMAdsInfoManager.shareInstance.adsInfoArrM = arrM
- }
- }
- }
- }
- }
-
- func setup() {
- //creatPDF
- self.creatPDFView.openPDFAction = { [unowned self] view, sender in
- self.openPDFAction(sender)
- }
-
- self.creatPDFView.creatPDFAction = { [unowned self] view, sender in
- self.creatPDFAction(sender)
- }
-
- //history
- self.homeContentView.historyDidSelect = { [unowned self] view, item in
- self.openHistoryFilePath(url: item.url!)
- }
-
- self.homeContentView.historyRemoveFileAction = { [unowned self] view, item in
- self.historyFile(deleteDocuments: [ item.url!])
- }
-
- self.homeContentView.historyShowPathAction = { [unowned self] view, item in
- if FileManager.default.fileExists(atPath: item.url!.path) {
- NSWorkspace.shared.activateFileViewerSelecting([item.url!])
- }
- }
-
- self.homeContentView.historyRemoveAllFileAction = { [unowned self] view in
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = String(format: "%@?", NSLocalizedString("Clear All Recents", comment: ""))
- alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
- alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
- alert.beginSheetModal(for: self.view.window!) { response in
- if response == .alertFirstButtonReturn {
- let urls: Array<URL> = NSDocumentController.shared.recentDocumentURLs
- self.historyFileDeleteAction(urls)
- }
- }
- }
-
- //quciktools
- self.homeContentView.qucikToolsDidSelect = { [unowned self] view, item in
- self.fastToolItemAction(item.type!)
- }
-
- self.homeContentView.qucikToolsAddAction = { [unowned self] view, item in
- KMBatchQuickActionManager.defaultManager.actionType = .add
- self.fastToolItemAction(item.type!)
- }
-
- self.homeContentView.qucikToolsRemoveAction = { [unowned self] view, item in
- KMBatchQuickActionManager.defaultManager.actionType = .remove
- self.fastToolItemAction(item.type!)
- }
-
- if IAPProductsManager.default().isAvailableAllFunction() {
- self.advertisementShowView.isHidden = true
- } else {
- self.advertisementShowView.isHidden = false
- }
-
- NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "KMIAPProductPurchasedNotification"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "kDeviceActivateNotification"), object: nil)
-
- }
-
- // MARK: Init
-
- func initializeUI() {
- rightTopBox.fillColor = .white
- rightBottomBox.fillColor = .white
- rightFullBox.fillColor = .white
-
- self.refreshRightBoxUI(.Home)
- fastToolViewController.delete = self
- historyFileViewController.delete = self
- pdfToolsViewController.delete = self
- dragView.delete = self
- }
-
- func initLocalization() {
- // self.favoriteDocumentsLabel.stringValue = NSLocalizedString("Favorite Documents", comment: "")
-
- homeButtonVC?.stringValue = NSLocalizedString("Home", comment: "")
- pdfToolsButtonVC?.stringValue = NSLocalizedString("PDF Tools", comment: "")
- cloudDocumentsButtonVC?.stringValue = NSLocalizedString("Cloud Documents", comment: "")
- openPDFButtonVC?.stringValue = NSLocalizedString("Open File", comment: "")
- // openPDFBox.toolTip = NSLocalizedString("Open PDF", comment: "")
- createPDFButtonVC?.stringValue = NSLocalizedString("Create PDF", comment: "")
- // createPDFBox.toolTip = NSLocalizedString("Create PDF", comment: "")
- pdfSeriesButtonVC?.stringValue = NSLocalizedString("PDF Pro Series", comment: "")
- pdfOthersButtonVC?.stringValue = NSLocalizedString("Others", comment: "")
- }
-
- // MARK: Action
- func initializeUI_DMG() -> Void {
- rightTopBox.fillColor = .white
- rightBottomBox.fillColor = .white
- rightFullBox.fillColor = .white
- self.aiHomeBox.fillColor = .clear
- self.aiHomeBox.cornerRadius = 8.0
- self.aiHomeImageView.image = NSImage(named: "icon_home")
- self.aiHomeLabel.stringValue = NSLocalizedString("Home", comment: "")
- self.aiHomeLabel.textColor = NSColor.km_init(hex: "#252629")
- self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
- self.aiHomeBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
- if aiHomeState != .Home {
- if mouseEntered {
- self.aiHomeBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
- } else {
- self.aiHomeBox.fillColor = .clear
- }
- }
- }
- self.aiHomeBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
- if aiHomeState != .Home {
- if downEntered {
- self.aiHomeState = .Home
-
- self.refreshAIUI()
- }
- }
- }
- self.aiTranslationBox.fillColor = .clear
- self.aiTranslationBox.cornerRadius = 8.0
- self.aiTranslationImageView.image = NSImage(named: "ic_function_other")
- self.aiTranslationLabel.stringValue = NSLocalizedString("AI Translation", comment: "")
- self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
- self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
- self.aiTranslationBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
- if aiHomeState != .AITranslation {
- if mouseEntered {
- self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
- } else {
- self.aiTranslationBox.fillColor = .clear
- }
- }
- }
- self.aiTranslationBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
- if aiHomeState != .AITranslation {
- if downEntered {
- self.aiHomeState = .AITranslation
-
- self.trackEvent_ai(eventName: "AI Translation")
-
- self.refreshAIUI()
- }
- }
- }
- self.aiRewritingBox.fillColor = .clear
- self.aiRewritingBox.cornerRadius = 8.0
- self.aiRewritingImageView.image = NSImage(named: "ic_ai_Rewriting")
- self.aiRewritingLabel.stringValue = NSLocalizedString("AI Rewriting", comment: "")
- self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
- self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
- self.aiRewritingBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
- if aiHomeState != .AIRewriting {
- if mouseEntered {
- self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
- } else {
- self.aiRewritingBox.fillColor = .clear
- }
- }
- }
- self.aiRewritingBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
- if aiHomeState != .AIRewriting {
- if downEntered {
- self.aiHomeState = .AIRewriting
-
- self.trackEvent_ai(eventName: "AI Rewriting")
-
- self.refreshAIUI()
- }
- }
- }
- self.aiErrorCorrectionBox.fillColor = .clear
- self.aiErrorCorrectionBox.cornerRadius = 8.0
- self.aiErrorCorrectionImageView.image = NSImage(named: "ic_ai_ErrorCorrection")
- self.aiErrorCorrectionLabel.stringValue = NSLocalizedString("AI Error Correction", comment: "")
- self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
- self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
- self.aiErrorCorrectionBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
- if aiHomeState != .AIErrorCorrection {
- if mouseEntered {
- self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
- } else {
- self.aiErrorCorrectionBox.fillColor = .clear
- }
- }
- }
- self.aiErrorCorrectionBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
- if aiHomeState != .AIErrorCorrection {
- if downEntered {
- self.aiHomeState = .AIErrorCorrection
-
- self.trackEvent_ai(eventName: "AI Correction")
-
- self.refreshAIUI()
- }
- }
- }
-
- self.refreshAIUI()
-
- historyFileViewController.delete = self
- dragView.delete = self
- }
-
- func updateUI() {
- self.leftBox.fillColor = KMAppearance.Layout.l0Color()
- // self.homeSplitView.backgroundColor(KMAppearance.Layout.l0Color())
- }
-
- @objc func changeEffectiveAppearance() {
- let isDarkModel = KMAdvertisementConfig.isDarkModel()
- if isDarkModel {
- self.view.appearance = NSAppearance(named: .darkAqua)
- } else {
- self.view.appearance = NSAppearance(named: .aqua)
- }
- self.updateUI()
- self.advertisementTableView.reloadData()
- }
-
- // MARK: Public Methods
-
- func savePDFDocument(_ pdf: CPDFDocument, password: String) -> Void {
- DispatchQueue.global(qos: .`default`).async {
- var isSuccessfully = false
- if pdf.isEncrypted {
- let dic = [
- CPDFDocumentWriteOption.userPasswordOption : password,
- CPDFDocumentWriteOption.ownerPasswordOption : password
- ]
- isSuccessfully = pdf.write(to: pdf.documentURL, withOptions: dic)
- } else {
- isSuccessfully = pdf.write(to: pdf.documentURL)
- }
- if !isSuccessfully {
- if let data = pdf.dataRepresentation() {
- isSuccessfully = NSData(data: data).write(to: pdf.documentURL, atomically: true)
- }
- }
-
- DispatchQueue.main.sync {
- if isSuccessfully {
- let workspace = NSWorkspace.shared
- let url = URL(fileURLWithPath: pdf.documentURL?.path ?? "")
- workspace.activateFileViewerSelecting([url])
- } else {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = NSLocalizedString("Failed to insert page(s)!", comment: "")
- alert.runModal()
- }
- }
- }
- }
-
- // MARK: Private Methods
- func refreshUI() -> Void {
- homeButtonVC?.updateUI()
- pdfToolsButtonVC?.updateUI()
- cloudDocumentsButtonVC?.updateUI()
- }
-
- func refreshAIUI() -> Void {
- self.aiHomeBox.fillColor = .clear
- self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
- self.aiTranslationBox.fillColor = .clear
- self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
- self.aiRewritingBox.fillColor = .clear
- self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
- self.aiErrorCorrectionBox.fillColor = .clear
- self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
- rightFullBox.isHidden = true
- rightTopBox.isHidden = true
- rightBottomBox.isHidden = true
- switch self.aiHomeState {
- case .Home:
- self.aiHomeBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
- self.aiHomeLabel.font = NSFont.SFProTextSemiboldFont(16.0)
-
- self.rightTopBox.isHidden = false
- self.rightBottomBox.isHidden = false
- self.rightTopBox.contentView = self.aiOpenPDFFilesViewController.view
- self.rightBottomBox.contentView = self.historyFileViewController.view
- self.rightFullBox.contentView = nil
-
- self.rightTopBoxHeightConstraint.constant = 388.0
-
- self.dragView.isHidden = false
- break
- case .AITranslation:
- self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
- self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
- self.aiTranslationLabel.font = NSFont.SFProTextSemiboldFont(16.0)
- self.rightFullBox.isHidden = false
- self.rightTopBox.contentView = nil
- self.rightBottomBox.contentView = nil
- self.rightFullBox.contentView = self.aiTranslationViewController.view
-
- self.dragView.isHidden = false
- break
- case .AIRewriting:
- self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
- self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
- self.aiRewritingLabel.font = NSFont.SFProTextSemiboldFont(16.0)
- self.rightFullBox.isHidden = false
- self.rightTopBox.contentView = nil
- self.rightBottomBox.contentView = nil
- self.rightFullBox.contentView = self.aiRewritingViewController.view
- // self.aiRewritingViewController.state = .AIRewriting
- self.aiRewritingViewController.initLocalization()
- self.aiRewritingViewController.acquisition_uiState()
-
- self.dragView.isHidden = true
- break
- case .AIErrorCorrection:
- self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
- self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
- self.aiErrorCorrectionLabel.font = NSFont.SFProTextSemiboldFont(16.0)
- self.rightFullBox.isHidden = false
- self.rightTopBox.contentView = nil
- self.rightBottomBox.contentView = nil
- self.rightFullBox.contentView = self.aiRewritingViewController.view
- // self.aiRewritingViewController.state = .AIErrorCorrection
- self.aiRewritingViewController.initLocalization()
- self.aiRewritingViewController.acquisition_uiState()
-
- self.dragView.isHidden = true
- break
- default:
- break
- }
- }
-
- func fetchDifferentFilePath(filePath: String) -> String {
- var resultFilePath = filePath
- var index: Int = 0
- while (FileManager.default.fileExists(atPath: resultFilePath)) {
- index += 1
- let path = NSString(string: filePath).deletingPathExtension + "(" + String(index) + ")"
- resultFilePath = NSString(string: path).appendingPathExtension(NSString(string: filePath).pathExtension)!
- }
-
- return resultFilePath;
- }
-
- func showProgressWindow() {
- let progress = SKProgressController()
- progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
- progress.window?.contentView?.wantsLayer = true
- progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
- progress.progressField.textColor = NSColor.white
- progress.message = NSLocalizedString("Translating...", comment: "")
- progress.closeBlock = { [unowned self] in
-
- }
-
- self.progressController = progress
- self.view.window?.beginSheet(progress.window!)
- }
-
- func hiddenProgressWindow() {
- DispatchQueue.main.async {
- self.progressController?.doubleValue = 100.0
- }
- self.stopTimer()
- if (self.progressController != nil) {
- self.view.window?.endSheet((self.progressController?.window)!)
- self.progressController = nil
- }
- }
-
- func isFileGreaterThan10MB(atPath filePath: String) -> Bool {
- let fileManager = FileManager.default
- do {
- let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
- if let fileSize = fileAttributes[.size] as? UInt64 {
- let megabyteSize = fileSize / (1024 * 1024)
- return megabyteSize >= 10
- }
- } catch {
- KMPrint("Error: \(error)")
- }
- return false
- }
-
- func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
- let url = URL(fileURLWithPath: filePath)
- guard let document = PDFDocument(url: url) else {
- return false
- }
-
- let pageCount = document.pageCount
- return pageCount > 30
- }
-
- @objc func timerTick() {
- timerCounter += 1.0
- self.progressController?.increment(by: 1.0)
-
- if timerCounter >= 95 {
- stopTimer()
- }
- }
-
- func stopTimer() {
- timer?.invalidate()
- timer = nil
- }
- // MARK: Common methods
-
- func workSpaceOpenUrl(_ url: NSString) {
- let httpUrl: NSURL = NSURL.init(string: url as String)!
- let tWorkSpace: NSWorkspace = NSWorkspace.shared
- if !tWorkSpace.open(httpUrl as URL) {
- tWorkSpace.open(httpUrl as URL)
- }
- }
- }
- //MARK: Open Creat PDF
- extension KMHomeViewController: NSPopoverDelegate {
- }
- extension KMHomeViewController {
- func openPDFAction(_ sender: KMBox) {
- if needShowTabbingHintWindow() {
- showTabbingHintWindow()
- return
- }
- let openPanel = NSOpenPanel()
- openPanel.allowedFileTypes = ["pdf", "PDF"]
- openPanel.allowsMultipleSelection = false
- openPanel.beginSheetModal(for: self.view.window!) { (result) in
- if result == NSApplication.ModalResponse.OK {
- NSDocumentController.shared.km_safe_limit_openDocument(withContentsOf: openPanel.url!, display: true) { (document, documentWasAlreadyOpen, error) in
-
- }
- }
- }
- }
-
- func needShowTabbingHintWindow() -> Bool {
- let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController
- if controll?.browser?.tabCount() ?? 0 > 1 && !IAPProductsManager.default().isAvailableAllFunction() {
- return true
- }
- return false
- }
-
- func showTabbingHintWindow(){
- if !KMDataManager.default.isTabbingWin{
- KMDataManager.default.isTabbingWin = true
- let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
- tabbingWin.selectCallBack = { [weak self] continueOrNot in
- KMDataManager.default.isTabbingWin = false
- if continueOrNot {
- self?.reopenDocument(forPaths: nil)
- } else {
-
- }
- }
- self.km_beginSheet(windowC: tabbingWin)
- }
- }
-
- func creatPDFAction(_ sender: KMBox) {
- let popViewDataArr: [String] = [NSLocalizedString("New Blank Page", comment: ""),
- NSLocalizedString("New From Images", comment: ""),
- NSLocalizedString("New From Web Page", comment: ""),
- NSLocalizedString("Import From Camera", comment: ""),
- NSLocalizedString("Import From Scanner", comment: "")]
- let vc: KMHomePopViewController = KMHomePopViewController().initWithPopViewDataArr(popViewDataArr)
- vc.background = KMAppearance.Layout.bgColor()
- vc.textColor = KMAppearance.Layout.h0Color()
- vc.enterFillColor = KMAppearance.Interactive.s0Color()
- let createFilePopover: NSPopover = NSPopover.init()
- createFilePopover.contentViewController = vc
- createFilePopover.delegate = self
- createFilePopover.animates = true
- createFilePopover.behavior = .semitransient
- createFilePopover.setValue(true, forKey: "shouldHideAnchor")
- createFilePopover.show(relativeTo: CGRect(x: sender.bounds.origin.x, y: 10, width: sender.bounds.size.width, height: sender.bounds.size.height), of: sender, preferredEdge: .minY)
-
- vc.downCallback = { [unowned self] (downEntered: Bool, count: String) -> Void in
- if count == NSLocalizedString("New Blank Page", comment: "") {
- self.openBlankPage()
- } else if count == NSLocalizedString("Import From Camera", comment: "") {
- self.importFromCamera()
- } else if count == NSLocalizedString("Import From Scanner", comment: "") {
- self.importFromScanner()
- } else if count == NSLocalizedString("New From Web Page", comment: "") {
- self.importFromWebPage()
- } else if count == NSLocalizedString("New From Images", comment: "") {
- self.newFromImages()
- }
- createFilePopover.close()
- }
- }
-
- func openBlankPage() {
- let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
- let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
- let filePath = savePath.deletingLastPathComponent
- if FileManager.default.fileExists(atPath: filePath) == false {
- try?FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false)
- }
-
- let pdfDocument = CPDFDocument()
- pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
- pdfDocument?.write(to: URL(fileURLWithPath: savePath))
- NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
- if error != nil {
- NSApp.presentError(error!)
- } else {
- if document is KMMainDocument {
- let newDocument = document
- (newDocument as! KMMainDocument).isNewCreated = true
- }
- }
- // self.homeContentView?.reloadData()
- }
- }
-
- func importFromWebPage() {
- self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
-
- self.urlToPDFWindowController?.beginSheetModalForWindow(NSWindow.currentWindow(), completionHandler: { filePath in
- if FileManager.default.fileExists(atPath: filePath) {
- NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
- if error != nil {
- NSApp.presentError(error!)
- } else {
- if document is KMMainDocument {
- (document as! KMMainDocument).isNewCreated = true
- }
- }
- // self.homeContentView.reloadData()
- }
- }
- })
- }
-
- func importFromScanner() {
- let vc = KMDeviceBrowserWindowController.shared
- vc.type = .scanner
- vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
- self?.openFile(withFilePath: url as URL)
- }
- vc.showWindow(NSApp.mainWindow)
- }
-
- func importFromCamera() {
- let vc = KMDeviceBrowserWindowController.shared
- vc.type = .camera
- vc.importCameraFileCallback = { [weak self] (url: NSURL) -> Void in
- self?.openFile(withFilePath: url as URL)
- }
- vc.showWindow(NSApp.mainWindow)
- }
-
- func newFromImages() {
- fastTool_ImageToPDF()
- // let openPanel = NSOpenPanel()
- // openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
- // if IAPProductsManager.defaultManager().isAvailableAllFunction {
- // openPanel.allowsMultipleSelection = true
- // } else {
- // openPanel.allowsMultipleSelection = false
- // }
- // openPanel.message = NSLocalizedString("Select images to create a new document. To select multiple files press cmd ⌘ button on the keyboard and click on the target files one by one.", comment: "")
- // openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
- // if result == .OK {
- // DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
- // debugPrint("缺少图片转PDF")
- // let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
- // var arr: [KMBatchOperateFile] = []
- // for url in openPanel.urls {
- // let file = KMBatchOperateFile(filePath: url.path, type: .createPDF)
- // arr.append(file)
- // }
- //
- // if #available(macOS 10.13, *) {
- // baseWindowController.window?.makeKeyAndOrderFront(nil)
- // } else {
- // baseWindowController.showWindow(nil)
- // }
- // baseWindowController.checkNeedPasswordSwitch(toOperateType: .createPDF, files: arr)
- // if #available(macOS 10.13, *) {
- // baseWindowController.release()
- // }
- // }
- // }
- // }
- }
-
- //MARK: Purchase
- @objc func purchaseStateUpdateNoti() {
- if IAPProductsManager.default().isAvailableAllFunction() {
- self.advertisementShowView.isHidden = true
- }
- }
-
- //MARK: - AI
-
- func showAITypeChooseView() -> Void {
- let windowVC: AINewConfigWindowController = AINewConfigWindowController.currentWC()
- windowVC.chooseCurFileHandle = {[unowned self] windowVC in
- if AIChatInfoManager.defaultManager.currentFilePath.isEmpty == false {
- let documentArray = NSDocumentController.shared.documents
- var didFileEdit: Bool = false
- var curDoc: KMMainDocument!
- for document in documentArray {
- if document.fileURL?.path == AIChatInfoManager.defaultManager.currentFilePath {
- didFileEdit = document.isDocumentEdited
- curDoc = document as! KMMainDocument
- break
- }
- }
- if didFileEdit {
- let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(AIChatInfoManager.defaultManager.currentFilePath.lastPathComponent)
- if FileManager.default.fileExists(atPath: tempFileURL.path) {
- do {
- try FileManager.default.removeItem(at: tempFileURL)
-
- } catch {
-
- }
- }
- if curDoc != nil {
- curDoc.mainViewController?.SaveTempPDFDocumentToURLPath(tempPath: tempFileURL.path)
- }
- }
- windowVC.window?.becomeMain()
- }
- }
- windowVC.window?.center()
- windowVC.eventLabel = "AITools_Onboard"
- windowVC.showWindow(nil)
- }
-
- func loadAITipIconGuide() {
- if KMGuideInfoWindowController.availableShow(.aiTipIconInfo) {
- let guideWC = KMGuideInfoWindowController.currentWC()
- guideWC.type = .aiTipIconInfo
-
- guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
- guideWC.finishHandle = { [weak self] windowVC, type in
-
- }
- if self.view.window != nil {
- var rect = self.view.window?.frame
- rect!.size.height -= 20
- guideWC.window?.setFrame(rect!, display: true)
- guideWC.window?.minSize = rect!.size
- guideWC.window?.maxSize = rect!.size
- self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
- guideWC.show()
- }
- }
- }
-
-
- //MARK: - 引导
- func loadFunctionGuide() -> Void {
-
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
- self.loadNewUserGuide()
- }
- }
-
- // MARK: - what's New
-
- func loadNewUserGuide() -> Void {
- if KMFunctionGuideWindowController.availableShow(.functionMultiAIGuide) {
- let guideWindowVC = KMFunctionGuideWindowController.init(windowNibName: "KMFunctionGuideWindowController")
- guideWindowVC.type = .functionMulti
- guideWindowVC.showWindow(nil)
- guideWindowVC.window?.orderFront(nil)
-
- KMFunctionGuideWindowController.setDidShowFor(.functionMultiAIGuide)
- }
- }
-
- func checkRepeatTrialExpiredController() -> Void {
- //试用过期提示比较表弹窗
- if didTrialExpiredLoad == true {
- return
- }
- didTrialExpiredLoad = true
- let singleTon = KMPurchaseCompareDMGWindowController.init()
- singleTon.showWindow(nil)
- if singleTon.className == KMPurchaseCompareDMGWindowController.className() {
- singleTon.updateTitle(NSLocalizedString("Trial Expired, Upgrade to Pro Version", comment: ""), andColor: NSColor(red: 1, green: 59/255, blue: 47/255, alpha: 1))
- }
- }
-
- func checkRepeatTrialAlertController() -> Void {
- //允许二次试用时弹出二次试用引导弹窗
- if repeatTrialAlertLoad == true {
- return
- }
- repeatTrialAlertLoad = true
- let vc = KMVerificationWindowController.verification(with:.repeatTrialGuide)
- vc?.showWindow(nil)
- }
-
-
- // MARK: - Noti Actions
- func deviceVerifyFinishNotification(_ sender: Notification) {
- #if VERSION_DMG
- if KMVerificationWindowController.allowsShowExpired() {
- self.checkRepeatTrialExpiredController()
- } else if KMVerificationWindowController.allowRepeatTrialAlertShow() {
- self.checkRepeatTrialAlertController()
- }
- #endif
- }
-
- @objc func aiTipIconViewShowStateChangeNoti() {
-
- }
- }
|