KMHomeViewController.swift 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  1. //
  2. // KMHomeViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/10/13.
  6. //
  7. import Cocoa
  8. @objc enum KMHomeToolState : Int {
  9. case OpenPDF = 0
  10. case CreatePDF
  11. case Home
  12. case PDFTools
  13. case FavoriteDocuments
  14. case CloudDocuments
  15. }
  16. @objc enum KMAIHomeToolState : Int {
  17. case Home = 0
  18. case AITranslation
  19. case AIRewriting
  20. case AIErrorCorrection
  21. }
  22. @objcMembers class KMHomeViewController: NSViewController {
  23. @IBOutlet weak var leftBox: NSBox!
  24. @IBOutlet weak var rightBox: NSBox!
  25. @IBOutlet weak var homeSplitView: NSSplitView!
  26. @IBOutlet weak var homeRightScrollViewView: NSScrollView!
  27. @IBOutlet weak var rightTopBox: NSBox!
  28. @IBOutlet weak var rightBottomBox: NSBox!
  29. @IBOutlet weak var rightFullBox: NSBox!
  30. @IBOutlet weak var rightTopBoxHeightConstraint: NSLayoutConstraint!
  31. @IBOutlet var fastToolViewController: KMHomeFastToolViewController!
  32. @IBOutlet var historyFileViewController: KMHomeHistoryFileViewController!
  33. @IBOutlet var pdfToolsViewController: KMPDFToolsViewController!
  34. @IBOutlet var cloudDocumentsViewController: KMCloudDocumentsViewController!
  35. @IBOutlet weak var dragView: KMHomeDragView!
  36. // AI 临时UI
  37. @IBOutlet weak var aiHomeBox: KMBox!
  38. @IBOutlet weak var aiHomeImageView: NSImageView!
  39. @IBOutlet weak var aiHomeLabel: NSTextField!
  40. @IBOutlet weak var aiTranslationBox: KMBox!
  41. @IBOutlet weak var aiTranslationImageView: NSImageView!
  42. @IBOutlet weak var aiTranslationLabel: NSTextField!
  43. @IBOutlet weak var aiRewritingBox: KMBox!
  44. @IBOutlet weak var aiRewritingImageView: NSImageView!
  45. @IBOutlet weak var aiRewritingLabel: NSTextField!
  46. @IBOutlet weak var aiErrorCorrectionBox: KMBox!
  47. @IBOutlet weak var aiErrorCorrectionImageView: NSImageView!
  48. @IBOutlet weak var aiErrorCorrectionLabel: NSTextField!
  49. @IBOutlet var aiOpenPDFFilesViewController: KMAIOpenPDFFilesVC!
  50. @IBOutlet var aiTranslationViewController: KMAITranslationVC!
  51. @IBOutlet var aiRewritingViewController: KMAIRewritingVC!
  52. @IBOutlet weak var creatPDFView: KMCreatPDFView!
  53. //HomeContentView
  54. @IBOutlet weak var homeContentView: KMHomeContentView!
  55. //广告 互推
  56. @IBOutlet weak var advertisementTableView: KMAdvertisementTableView!
  57. @IBOutlet weak var advertisementTableViewHeightConstraint: NSLayoutConstraint!
  58. @IBOutlet weak var advertisementShowView: KMAdvertisementShowView!
  59. //合并
  60. var mergeWindowController: KMMergeWindowController?
  61. var aiHomeState: KMAIHomeToolState = .Home
  62. let ScrollerViewWidget: CGFloat = 15.0
  63. var homeWindowController : MainWindowController!
  64. var isShowQuickTour: Bool = false
  65. weak var myDocument: NSDocument?
  66. var currentWindowController: NSWindowController?
  67. var homeState: KMHomeToolState = .Home
  68. var urlToPDFWindowController: KMURLToPDFWindowController?
  69. var openPDFButtonVC: KMDesignButton?
  70. var createPDFButtonVC: KMDesignButton?
  71. var createPDFImage: KMDesignButton?
  72. var createPDFAddButtonVC: KMDesignButton?
  73. var homeButtonVC: KMTextImageButtonVC?
  74. var pdfToolsButtonVC: KMTextImageButtonVC?
  75. var cloudDocumentsButtonVC: KMTextImageButtonVC?
  76. var pdfSeriesButtonVC: KMTextImageButtonVC?
  77. var pdfOthersButtonVC: KMTextImageButtonVC?
  78. var popover: NSPopover?
  79. var deviceBrowserWC: KMDeviceBrowserWindowController?
  80. var progressController: SKProgressController?
  81. var timer: Timer?
  82. var timerCounter = 0.0
  83. //AI相关
  84. //试用相关
  85. var didTrialExpiredLoad: Bool = false
  86. var repeatTrialAlertLoad: Bool = false
  87. var guideWindowVC: KMFunctionGuideWindowController!
  88. var showCoupon: Bool = true
  89. var couponDueWindowVC: KMCouponDueWindowController!
  90. var homeVC: KMNHomeViewController = KMNHomeViewController()
  91. @IBOutlet weak var rightBottonHeight: NSLayoutConstraint!
  92. var currentController: NSWindowController?
  93. deinit {
  94. NotificationCenter.default.removeObserver(self)
  95. }
  96. override func viewWillAppear() {
  97. super.viewWillAppear()
  98. if !KMLightMemberManager.manager.isLogin() {
  99. KMLightMemberManager.manager.canShowAdvancedView = true
  100. }
  101. self.homeContentView.reloadData()
  102. #if VERSION_DMG
  103. let kDMGFirstInstallKey = "DMGFirstInstallKey"
  104. if KMDataManager.ud_object(forKey: kDMGFirstInstallKey) == nil {
  105. KMDataManager.ud_set("Show", forKey: kDMGFirstInstallKey)
  106. KMTools.openURL(urlString: "http://www.pdfreaderpro.com/thank-you-for-installation")
  107. }
  108. #else
  109. // [self loadAIInfo];
  110. #endif
  111. }
  112. override func viewWillDisappear() {
  113. super.viewWillDisappear()
  114. // self.homeContentView.reloadData()
  115. }
  116. override func viewDidLoad() {
  117. super.viewDidLoad()
  118. // Do view setup here.
  119. openPDFButtonVC = KMDesignButton.init(withType: .Text)
  120. createPDFButtonVC = KMDesignButton.init(withType: .Text)
  121. createPDFImage = KMDesignButton.init(withType: .Image)
  122. createPDFAddButtonVC = KMDesignButton.init(withType: .Image)
  123. homeButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  124. pdfToolsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  125. cloudDocumentsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  126. pdfSeriesButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  127. pdfOthersButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  128. self.homeSplitView.setPosition(270.0, ofDividerAt: 0)
  129. self.leftBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
  130. self.rightBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
  131. NSEvent.addLocalMonitorForEvents(matching: .leftMouseDown) { (aEvent) -> NSEvent? in
  132. self.otherMouseDown(with: aEvent)
  133. return aEvent
  134. }
  135. self.initNetworkingData()
  136. // self.initLocalization()
  137. // self.initializeUI()
  138. self.initializeUI_DMG()
  139. self.setup()
  140. // refreshUI()
  141. self.updateUI()
  142. self.changeEffectiveAppearance()
  143. NotificationCenter.default.addObserver(self, selector: #selector(homeFileRectChange(_:)), name: Notification.Name("KMHomeFileRectChange"), object: nil)
  144. NotificationCenter.default.addObserver(self, selector: #selector(changeEffectiveAppearance), name: NSNotification.Name(rawValue: "kEffectiveAppearance"), object: nil)
  145. // setAppearance(isDarkMode: KMAdvertisementConfig.isDarkModel())
  146. // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name(NSApplication.didUpdateNotification.rawValue), object: nil)
  147. // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name(NSWindow.didBecomeMainNotification.rawValue), object: nil)
  148. // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name("AppleInterfaceThemeChangedNotification"), object: nil)
  149. NotificationCenter.default.addObserver(self, selector: #selector(openNewWindowAlertV), name: Notification.Name("KMCTTableChangeShowAlertView"), object: nil)
  150. #if VERSION_DMG
  151. NotificationCenter.default.addObserver(self, selector: #selector(deviceVerifyFinishNotification), name: Notification.Name.init(NSNotification.Name.deviceVerifyFinish.rawValue), object: nil)
  152. #endif
  153. NotificationCenter.default.addObserver(self, selector: #selector(importFromCamera), name: Notification.Name("kDeviceCameraMenuItemNotification"), object: nil)
  154. NotificationCenter.default.addObserver(self, selector: #selector(importFromScanner), name: Notification.Name("kDeviceScannerMenuItemNotification"), object: nil)
  155. self.loadFunctionGuide()
  156. self.homeRightScrollViewView.isHidden = true
  157. self.homeContentView.isHidden = true
  158. self.homeVC.view.frame = self.view.bounds
  159. self.homeVC.view.wantsLayer = true
  160. self.homeVC.view.layer?.backgroundColor = NSColor.white.cgColor
  161. self.homeVC.view.autoresizingMask = [.width, .height]
  162. self.rightBox.addSubview(self.homeVC.view)
  163. }
  164. override func viewDidAppear() {
  165. super.viewDidAppear()
  166. refreshScrollView()
  167. }
  168. override func viewDidLayout() {
  169. super.viewDidLayout()
  170. refreshScrollView()
  171. // self.loadAITipIconGuide()
  172. }
  173. func initNetworkingData() {
  174. // KMAdvertisementManager.manager.fetchDataWithResponseObject { [weak self] data, responseObject, error in
  175. // KMPrint("获取广告数据成功")
  176. // if data != nil {
  177. // let content = data!.recommondContent
  178. // let item = content?.recommondContentPDFPro
  179. // var infos: [KMAdvertisementItemInfo] = []
  180. // for info in item?.content ?? [] {
  181. // if info.version == "recommondPDF-PDFtoOfficePack" {
  182. // if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() == false {
  183. // infos.append(info)
  184. // }
  185. // } else {
  186. // infos.append(info)
  187. // }
  188. // }
  189. // item?.content = infos
  190. // self?.advertisementTableView.inputData = content
  191. // self?.advertisementTableView.didSelect = { view, item in
  192. // let string = KMAdvertisementModelTransition.transitionLanguage(langeuage: item.linkURL)
  193. // if string.count != 0 {
  194. // NSWorkspace.shared.open(URL.init(string: string)!)
  195. // }
  196. // }
  197. //
  198. // self?.advertisementShowView.inputData = data!.advertisement
  199. // self?.advertisementShowView.didSelect = { view, item in
  200. // let string = KMAdvertisementModelTransition.transitionLanguage(langeuage: item.linkURL)
  201. // if string.count != 0 {
  202. // NSWorkspace.shared.open(URL.init(string: string)!)
  203. // }
  204. //
  205. // guard let firebaseInfo = item.firebase else {
  206. // return
  207. // }
  208. // KMAdvertisementModelTransition.sendFireBaseEvent(firebase: firebaseInfo)
  209. //
  210. // }
  211. //
  212. // if KMAdvertisementManager.manager.infoDict.allKeys.count > 0 {
  213. // if let adsInfo = KMAdvertisementManager.manager.infoDict["adsInfo"] {
  214. // let infoDict: NSDictionary = KMAdvertisementManager.manager.infoDict["adsInfo"] as! NSDictionary
  215. // let array: [[String: Any]] = infoDict["content"] as! [[String : Any]]
  216. //
  217. // let arrM = NSMutableArray.init()
  218. // for dict in array {
  219. // let adsInfo = KMAdsInfo.init()
  220. // let mutableDictionary = NSMutableDictionary(dictionary: dict)
  221. // adsInfo.infoDict = mutableDictionary
  222. // arrM.add(adsInfo)
  223. // }
  224. // KMAdsInfoManager.shareInstance.adsInfoArrM = arrM
  225. // }
  226. //
  227. // if let couponInfo = KMAdvertisementManager.manager.infoDict["couponContent"] {
  228. // let infoDict: NSDictionary = KMAdvertisementManager.manager.infoDict["couponContent"] as! NSDictionary
  229. // let array: [[String: Any]] = infoDict["content"] as! [[String : Any]]
  230. // if array.isEmpty == false {
  231. // let dict = array[0]
  232. // let adsInfo = KMCouponInfo.init()
  233. // let mutableDictionary = NSMutableDictionary(dictionary: dict)
  234. // adsInfo.infoDict = mutableDictionary
  235. // KMAdsInfoManager.shareInstance.couponInfo = adsInfo
  236. // }
  237. // }
  238. // self?.checkTrialEndCouponInfo()
  239. // }
  240. // }
  241. // }
  242. }
  243. func setup() {
  244. //creatPDF
  245. self.creatPDFView.openPDFAction = { [unowned self] view, sender in
  246. self.openPDFAction(sender)
  247. }
  248. self.creatPDFView.creatPDFAction = { [unowned self] view, sender in
  249. self.creatPDFAction(sender)
  250. }
  251. //history
  252. self.homeContentView.historyDidSelect = { [unowned self] view, item in
  253. self.openHistoryFilePath(url: item.url!)
  254. }
  255. self.homeContentView.historyRemoveFileAction = { [unowned self] view, item in
  256. self.historyFile(deleteDocuments: [ item.url!])
  257. }
  258. self.homeContentView.historyShowPathAction = { [unowned self] view, item in
  259. if FileManager.default.fileExists(atPath: item.url!.path) {
  260. NSWorkspace.shared.activateFileViewerSelecting([item.url!])
  261. }
  262. }
  263. self.homeContentView.historyRemoveAllFileAction = { [unowned self] view in
  264. let alert = NSAlert()
  265. alert.alertStyle = .critical
  266. alert.messageText = String(format: "%@?", NSLocalizedString("Clear All Recents", comment: ""))
  267. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  268. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  269. alert.beginSheetModal(for: self.view.window!) { response in
  270. if response == .alertFirstButtonReturn {
  271. let urls: Array<URL> = NSDocumentController.shared.recentDocumentURLs
  272. self.historyFileDeleteAction(urls)
  273. }
  274. }
  275. }
  276. //quciktools
  277. self.homeContentView.qucikToolsDidSelect = { [unowned self] view, item in
  278. self.fastToolItemAction(item.type!)
  279. }
  280. self.homeContentView.qucikToolsAddAction = { [unowned self] view, item in
  281. KMBatchQuickActionManager.defaultManager.actionType = .add
  282. self.fastToolItemAction(item.type!)
  283. }
  284. self.homeContentView.qucikToolsRemoveAction = { [unowned self] view, item in
  285. KMBatchQuickActionManager.defaultManager.actionType = .remove
  286. self.fastToolItemAction(item.type!)
  287. }
  288. if IAPProductsManager.default().isAvailableAllFunction() {
  289. self.advertisementShowView.isHidden = true
  290. } else {
  291. self.advertisementShowView.isHidden = false
  292. }
  293. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "KMIAPProductPurchasedNotification"), object: nil)
  294. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "kDeviceActivateNotification"), object: nil)
  295. }
  296. // MARK: Init
  297. func initializeUI() {
  298. rightTopBox.fillColor = .white
  299. rightBottomBox.fillColor = .white
  300. rightFullBox.fillColor = .white
  301. self.refreshRightBoxUI(.Home)
  302. fastToolViewController.delete = self
  303. historyFileViewController.delete = self
  304. pdfToolsViewController.delete = self
  305. dragView.delete = self
  306. }
  307. func initLocalization() {
  308. // self.favoriteDocumentsLabel.stringValue = NSLocalizedString("Favorite Documents", comment: "")
  309. homeButtonVC?.stringValue = NSLocalizedString("Home", comment: "")
  310. pdfToolsButtonVC?.stringValue = NSLocalizedString("PDF Tools", comment: "")
  311. cloudDocumentsButtonVC?.stringValue = NSLocalizedString("Cloud Documents", comment: "")
  312. openPDFButtonVC?.stringValue = NSLocalizedString("Open File", comment: "")
  313. // openPDFBox.toolTip = NSLocalizedString("Open PDF", comment: "")
  314. createPDFButtonVC?.stringValue = NSLocalizedString("Create PDF", comment: "")
  315. // createPDFBox.toolTip = NSLocalizedString("Create PDF", comment: "")
  316. pdfSeriesButtonVC?.stringValue = NSLocalizedString("PDF Pro Series", comment: "")
  317. pdfOthersButtonVC?.stringValue = NSLocalizedString("Others", comment: "")
  318. }
  319. // MARK: Action
  320. func initializeUI_DMG() -> Void {
  321. rightTopBox.fillColor = .white
  322. rightBottomBox.fillColor = .white
  323. rightFullBox.fillColor = .white
  324. self.aiHomeBox.fillColor = .clear
  325. self.aiHomeBox.cornerRadius = 8.0
  326. self.aiHomeImageView.image = NSImage(named: "icon_home")
  327. self.aiHomeLabel.stringValue = NSLocalizedString("Home", comment: "")
  328. self.aiHomeLabel.textColor = NSColor.km_init(hex: "#252629")
  329. self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
  330. self.aiHomeBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  331. if aiHomeState != .Home {
  332. if mouseEntered {
  333. self.aiHomeBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  334. } else {
  335. self.aiHomeBox.fillColor = .clear
  336. }
  337. }
  338. }
  339. self.aiHomeBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  340. if aiHomeState != .Home {
  341. if downEntered {
  342. self.aiHomeState = .Home
  343. self.refreshAIUI()
  344. }
  345. }
  346. }
  347. self.aiTranslationBox.fillColor = .clear
  348. self.aiTranslationBox.cornerRadius = 8.0
  349. self.aiTranslationImageView.image = NSImage(named: "ic_function_other")
  350. self.aiTranslationLabel.stringValue = NSLocalizedString("AI Translation", comment: "")
  351. self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
  352. self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
  353. self.aiTranslationBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  354. if aiHomeState != .AITranslation {
  355. if mouseEntered {
  356. self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  357. } else {
  358. self.aiTranslationBox.fillColor = .clear
  359. }
  360. }
  361. }
  362. self.aiTranslationBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  363. if aiHomeState != .AITranslation {
  364. if downEntered {
  365. self.aiHomeState = .AITranslation
  366. self.trackEvent_ai(eventName: "AI Translation")
  367. self.refreshAIUI()
  368. }
  369. }
  370. }
  371. self.aiRewritingBox.fillColor = .clear
  372. self.aiRewritingBox.cornerRadius = 8.0
  373. self.aiRewritingImageView.image = NSImage(named: "ic_ai_Rewriting")
  374. self.aiRewritingLabel.stringValue = NSLocalizedString("AI Rewriting", comment: "")
  375. self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
  376. self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
  377. self.aiRewritingBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  378. if aiHomeState != .AIRewriting {
  379. if mouseEntered {
  380. self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  381. } else {
  382. self.aiRewritingBox.fillColor = .clear
  383. }
  384. }
  385. }
  386. self.aiRewritingBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  387. if aiHomeState != .AIRewriting {
  388. if downEntered {
  389. self.aiHomeState = .AIRewriting
  390. self.trackEvent_ai(eventName: "AI Rewriting")
  391. self.refreshAIUI()
  392. }
  393. }
  394. }
  395. self.aiErrorCorrectionBox.fillColor = .clear
  396. self.aiErrorCorrectionBox.cornerRadius = 8.0
  397. self.aiErrorCorrectionImageView.image = NSImage(named: "ic_ai_ErrorCorrection")
  398. self.aiErrorCorrectionLabel.stringValue = NSLocalizedString("AI Error Correction", comment: "")
  399. self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
  400. self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
  401. self.aiErrorCorrectionBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  402. if aiHomeState != .AIErrorCorrection {
  403. if mouseEntered {
  404. self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  405. } else {
  406. self.aiErrorCorrectionBox.fillColor = .clear
  407. }
  408. }
  409. }
  410. self.aiErrorCorrectionBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  411. if aiHomeState != .AIErrorCorrection {
  412. if downEntered {
  413. self.aiHomeState = .AIErrorCorrection
  414. self.trackEvent_ai(eventName: "AI Correction")
  415. self.refreshAIUI()
  416. }
  417. }
  418. }
  419. self.refreshAIUI()
  420. historyFileViewController.delete = self
  421. dragView.delete = self
  422. }
  423. func updateUI() {
  424. self.leftBox.fillColor = KMAppearance.Layout.l0Color()
  425. // self.homeSplitView.backgroundColor(KMAppearance.Layout.l0Color())
  426. }
  427. @objc func changeEffectiveAppearance() {
  428. let isDarkModel = KMAdvertisementConfig.isDarkModel()
  429. if isDarkModel {
  430. self.view.appearance = NSAppearance(named: .darkAqua)
  431. } else {
  432. self.view.appearance = NSAppearance(named: .aqua)
  433. }
  434. self.updateUI()
  435. self.advertisementTableView.reloadData()
  436. }
  437. // MARK: Public Methods
  438. func savePDFDocument(_ pdf: CPDFDocument, password: String) -> Void {
  439. DispatchQueue.global(qos: .`default`).async {
  440. var isSuccessfully = false
  441. if pdf.isEncrypted {
  442. let dic = [
  443. CPDFDocumentWriteOption.userPasswordOption : password,
  444. CPDFDocumentWriteOption.ownerPasswordOption : password
  445. ]
  446. isSuccessfully = pdf.write(to: pdf.documentURL, withOptions: dic)
  447. } else {
  448. isSuccessfully = pdf.write(to: pdf.documentURL)
  449. }
  450. if !isSuccessfully {
  451. if let data = pdf.dataRepresentation() {
  452. isSuccessfully = NSData(data: data).write(to: pdf.documentURL, atomically: true)
  453. }
  454. }
  455. DispatchQueue.main.sync {
  456. if isSuccessfully {
  457. let workspace = NSWorkspace.shared
  458. let url = URL(fileURLWithPath: pdf.documentURL?.path ?? "")
  459. workspace.activateFileViewerSelecting([url])
  460. } else {
  461. let alert = NSAlert()
  462. alert.alertStyle = .critical
  463. alert.messageText = NSLocalizedString("Failed to insert page(s)!", comment: "")
  464. alert.runModal()
  465. }
  466. }
  467. }
  468. }
  469. // MARK: Private Methods
  470. func refreshUI() -> Void {
  471. homeButtonVC?.updateUI()
  472. pdfToolsButtonVC?.updateUI()
  473. cloudDocumentsButtonVC?.updateUI()
  474. }
  475. func refreshAIUI() -> Void {
  476. self.aiHomeBox.fillColor = .clear
  477. self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
  478. self.aiTranslationBox.fillColor = .clear
  479. self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
  480. self.aiRewritingBox.fillColor = .clear
  481. self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
  482. self.aiErrorCorrectionBox.fillColor = .clear
  483. self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
  484. rightFullBox.isHidden = true
  485. rightTopBox.isHidden = true
  486. rightBottomBox.isHidden = true
  487. switch self.aiHomeState {
  488. case .Home:
  489. self.aiHomeBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  490. self.aiHomeLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  491. self.rightTopBox.isHidden = false
  492. self.rightBottomBox.isHidden = false
  493. self.rightTopBox.contentView = self.aiOpenPDFFilesViewController.view
  494. self.rightBottomBox.contentView = self.historyFileViewController.view
  495. self.rightFullBox.contentView = nil
  496. self.rightTopBoxHeightConstraint.constant = 388.0
  497. self.dragView.isHidden = false
  498. break
  499. case .AITranslation:
  500. self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  501. self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
  502. self.aiTranslationLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  503. self.rightFullBox.isHidden = false
  504. self.rightTopBox.contentView = nil
  505. self.rightBottomBox.contentView = nil
  506. self.rightFullBox.contentView = self.aiTranslationViewController.view
  507. self.dragView.isHidden = false
  508. break
  509. case .AIRewriting:
  510. self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  511. self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
  512. self.aiRewritingLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  513. self.rightFullBox.isHidden = false
  514. self.rightTopBox.contentView = nil
  515. self.rightBottomBox.contentView = nil
  516. self.rightFullBox.contentView = self.aiRewritingViewController.view
  517. // self.aiRewritingViewController.state = .AIRewriting
  518. self.aiRewritingViewController.initLocalization()
  519. self.aiRewritingViewController.acquisition_uiState()
  520. self.dragView.isHidden = true
  521. break
  522. case .AIErrorCorrection:
  523. self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  524. self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
  525. self.aiErrorCorrectionLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  526. self.rightFullBox.isHidden = false
  527. self.rightTopBox.contentView = nil
  528. self.rightBottomBox.contentView = nil
  529. self.rightFullBox.contentView = self.aiRewritingViewController.view
  530. // self.aiRewritingViewController.state = .AIErrorCorrection
  531. self.aiRewritingViewController.initLocalization()
  532. self.aiRewritingViewController.acquisition_uiState()
  533. self.dragView.isHidden = true
  534. break
  535. default:
  536. break
  537. }
  538. }
  539. func fetchDifferentFilePath(filePath: String) -> String {
  540. var resultFilePath = filePath
  541. var index: Int = 0
  542. while (FileManager.default.fileExists(atPath: resultFilePath)) {
  543. index += 1
  544. let path = NSString(string: filePath).deletingPathExtension + "(" + String(index) + ")"
  545. resultFilePath = NSString(string: path).appendingPathExtension(NSString(string: filePath).pathExtension)!
  546. }
  547. return resultFilePath;
  548. }
  549. func showProgressWindow() {
  550. let progress = SKProgressController()
  551. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  552. progress.window?.contentView?.wantsLayer = true
  553. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  554. progress.progressField.textColor = NSColor.white
  555. progress.message = NSLocalizedString("Translating...", comment: "")
  556. progress.closeBlock = { [weak self] in
  557. }
  558. self.progressController = progress
  559. self.view.window?.beginSheet(progress.window!)
  560. }
  561. func hiddenProgressWindow() {
  562. DispatchQueue.main.async {
  563. self.progressController?.doubleValue = 100.0
  564. }
  565. self.stopTimer()
  566. if (self.progressController != nil) {
  567. self.view.window?.endSheet((self.progressController?.window)!)
  568. self.progressController = nil
  569. }
  570. }
  571. func isFileGreaterThan10MB(atPath filePath: String) -> Bool {
  572. let fileManager = FileManager.default
  573. do {
  574. let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
  575. if let fileSize = fileAttributes[.size] as? UInt64 {
  576. let megabyteSize = fileSize / (1024 * 1024)
  577. return megabyteSize >= 10
  578. }
  579. } catch {
  580. KMPrint("Error: \(error)")
  581. }
  582. return false
  583. }
  584. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  585. let url = URL(fileURLWithPath: filePath)
  586. guard let document = PDFDocument(url: url) else {
  587. return false
  588. }
  589. let pageCount = document.pageCount
  590. return pageCount > 30
  591. }
  592. @objc func timerTick() {
  593. timerCounter += 1.0
  594. self.progressController?.increment(by: 1.0)
  595. if timerCounter >= 95 {
  596. stopTimer()
  597. }
  598. }
  599. func stopTimer() {
  600. timer?.invalidate()
  601. timer = nil
  602. }
  603. // MARK: Common methods
  604. func workSpaceOpenUrl(_ url: NSString) {
  605. let httpUrl: NSURL = NSURL.init(string: url as String)!
  606. let tWorkSpace: NSWorkspace = NSWorkspace.shared
  607. if !tWorkSpace.open(httpUrl as URL) {
  608. tWorkSpace.open(httpUrl as URL)
  609. }
  610. }
  611. }
  612. //MARK: Open Creat PDF
  613. extension KMHomeViewController: NSPopoverDelegate {
  614. }
  615. extension KMHomeViewController {
  616. func openPDFAction(_ sender: KMBox) {
  617. if needShowTabbingHintWindow() {
  618. showTabbingHintWindow()
  619. return
  620. }
  621. let openPanel = NSOpenPanel()
  622. openPanel.allowedFileTypes = ["pdf", "PDF"]
  623. openPanel.allowsMultipleSelection = false
  624. openPanel.beginSheetModal(for: self.view.window!) { (result) in
  625. if result == NSApplication.ModalResponse.OK {
  626. let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController
  627. if controll?.browser?.tabCount() ?? 0 > 1 && KMPreference.shared.openDocumentType == .newWindow{
  628. self.reopenDocument(forPaths: openPanel.url!)
  629. }else {
  630. NSDocumentController.shared.km_safe_limit_openDocument(withContentsOf: openPanel.url!, display: true) { (document, documentWasAlreadyOpen, error) in
  631. }
  632. }
  633. }
  634. }
  635. }
  636. func needShowTabbingHintWindow() -> Bool {
  637. let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController
  638. if controll?.browser?.tabCount() ?? 0 > 1 && !IAPProductsManager.default().isAvailableAllFunction() {
  639. return true
  640. }
  641. return false
  642. }
  643. func showTabbingHintWindow(){
  644. if !KMDataManager.default.isTabbingWin{
  645. KMDataManager.default.isTabbingWin = true
  646. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  647. tabbingWin.selectCallBack = { [weak self] continueOrNot in
  648. KMDataManager.default.isTabbingWin = false
  649. if continueOrNot {
  650. self?.reopenDocument(forPaths: nil)
  651. } else {
  652. }
  653. }
  654. self.km_beginSheet(windowC: tabbingWin)
  655. }
  656. }
  657. func creatPDFAction(_ sender: KMBox) {
  658. let popViewDataArr: [String] = [NSLocalizedString("New Blank Page", comment: ""),
  659. NSLocalizedString("New From Images", comment: ""),
  660. NSLocalizedString("New From Web Page", comment: ""),
  661. NSLocalizedString("Import From Camera", comment: ""),
  662. NSLocalizedString("Import From Scanner", comment: "")]
  663. let vc: KMHomePopViewController = KMHomePopViewController().initWithPopViewDataArr(popViewDataArr)
  664. vc.background = KMAppearance.Layout.bgColor()
  665. vc.textColor = KMAppearance.Layout.h0Color()
  666. vc.enterFillColor = KMAppearance.Interactive.s0Color()
  667. let createFilePopover: NSPopover = NSPopover.init()
  668. createFilePopover.contentViewController = vc
  669. createFilePopover.delegate = self
  670. createFilePopover.animates = true
  671. createFilePopover.behavior = .semitransient
  672. createFilePopover.setValue(true, forKey: "shouldHideAnchor")
  673. 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)
  674. vc.downCallback = { [unowned self] (downEntered: Bool, count: String) -> Void in
  675. if count == NSLocalizedString("New Blank Page", comment: "") {
  676. self.openBlankPage()
  677. } else if count == NSLocalizedString("Import From Camera", comment: "") {
  678. self.importFromCamera()
  679. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  680. self.importFromScanner()
  681. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  682. self.importFromWebPage()
  683. } else if count == NSLocalizedString("New From Images", comment: "") {
  684. self.newFromImages()
  685. }
  686. createFilePopover.close()
  687. }
  688. }
  689. func openBlankPage() {
  690. NSApplication.newBlankDocument()
  691. }
  692. func importFromWebPage() {
  693. self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
  694. self.urlToPDFWindowController?.beginSheetModalForWindow(NSWindow.currentWindow(), completionHandler: { filePath in
  695. if FileManager.default.fileExists(atPath: filePath) {
  696. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  697. if error != nil {
  698. NSApp.presentError(error!)
  699. } else {
  700. if document is KMMainDocument {
  701. (document as! KMMainDocument).isNewCreated = true
  702. }
  703. }
  704. // self.homeContentView.reloadData()
  705. }
  706. }
  707. })
  708. }
  709. func importFromScanner() {
  710. let vc = KMDeviceBrowserWindowController.shared
  711. vc.type = .scanner
  712. vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  713. self?.openFile(withFilePath: url as URL)
  714. }
  715. vc.showWindow(NSApp.mainWindow)
  716. }
  717. func importFromCamera() {
  718. let vc = KMDeviceBrowserWindowController.shared
  719. vc.type = .camera
  720. vc.importCameraFileCallback = { [weak self] (url: NSURL) -> Void in
  721. self?.openFile(withFilePath: url as URL)
  722. }
  723. vc.showWindow(NSApp.mainWindow)
  724. }
  725. func newFromImages() {
  726. fastTool_ImageToPDF()
  727. }
  728. //MARK: Purchase
  729. @objc func purchaseStateUpdateNoti() {
  730. if IAPProductsManager.default().isAvailableAllFunction() {
  731. self.advertisementShowView.isHidden = true
  732. let content = self.advertisementTableView.inputData
  733. let item = content?.recommondContentPDFPro
  734. var infos: [KMAdvertisementItemInfo] = []
  735. for info in item?.content ?? [] {
  736. if info.version == "recommondPDF-PDFtoOfficePack" {
  737. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() == false {
  738. infos.append(info)
  739. }
  740. } else {
  741. infos.append(info)
  742. }
  743. }
  744. item?.content = infos
  745. self.advertisementTableView.inputData = content
  746. }
  747. }
  748. //MARK: - AI
  749. func showAITypeChooseView() -> Void {
  750. let windowVC: AINewConfigWindowController = AINewConfigWindowController.currentWC()
  751. windowVC.chooseCurFileHandle = {[unowned self] windowVC in
  752. if AIChatInfoManager.defaultManager.currentFilePath.isEmpty == false {
  753. let documentArray = NSDocumentController.shared.documents
  754. var didFileEdit: Bool = false
  755. var curDoc: KMMainDocument!
  756. for document in documentArray {
  757. if document.fileURL?.path == AIChatInfoManager.defaultManager.currentFilePath {
  758. didFileEdit = document.isDocumentEdited
  759. curDoc = document as! KMMainDocument
  760. break
  761. }
  762. }
  763. if didFileEdit {
  764. let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(AIChatInfoManager.defaultManager.currentFilePath.lastPathComponent)
  765. if FileManager.default.fileExists(atPath: tempFileURL.path) {
  766. do {
  767. try FileManager.default.removeItem(at: tempFileURL)
  768. } catch {
  769. }
  770. }
  771. if curDoc != nil {
  772. curDoc.mainViewController?.SaveTempPDFDocumentToURLPath(tempPath: tempFileURL.path)
  773. }
  774. }
  775. windowVC.window?.becomeMain()
  776. }
  777. }
  778. if windowVC.window?.isVisible == true && windowVC.didSetOriginFrame == true {
  779. } else {
  780. windowVC.window?.center()
  781. windowVC.didSetOriginFrame = true
  782. }
  783. windowVC.eventLabel = "AITools_Onboard"
  784. windowVC.showWindow(nil)
  785. }
  786. func loadAITipIconGuide() {
  787. if KMGuideInfoWindowController.availableShow(.aiTipIconInfo) {
  788. let guideWC = KMGuideInfoWindowController.currentWC()
  789. guideWC.type = .aiTipIconInfo
  790. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  791. guideWC.finishHandle = { [weak self] windowVC, type in
  792. }
  793. if self.view.window != nil {
  794. var rect = self.view.window?.frame
  795. rect!.size.height -= 20
  796. guideWC.window?.setFrame(rect!, display: true)
  797. guideWC.window?.minSize = rect!.size
  798. guideWC.window?.maxSize = rect!.size
  799. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  800. guideWC.show()
  801. }
  802. }
  803. }
  804. //MARK: - 引导
  805. func loadFunctionGuide() -> Void {
  806. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  807. self.loadNewUserGuide()
  808. }
  809. }
  810. // MARK: - what's New
  811. func loadNewUserGuide() -> Void {
  812. if KMFunctionGuideWindowController.availableShow(.functionMultiAIGuide) {
  813. guideWindowVC = KMFunctionGuideWindowController.init(windowNibName: "KMFunctionGuideWindowController")
  814. guideWindowVC.type = .functionMulti
  815. guideWindowVC.showWindow(nil)
  816. guideWindowVC.window?.orderFront(nil)
  817. KMFunctionGuideWindowController.setDidShowFor(.functionMultiAIGuide)
  818. }
  819. }
  820. func checkRepeatTrialExpiredController() -> Void {
  821. //试用过期提示比较表弹窗
  822. if didTrialExpiredLoad == true {
  823. return
  824. }
  825. didTrialExpiredLoad = true
  826. let singleTon = KMPurchaseCompareDMGWindowController.init()
  827. singleTon.showWindow(nil)
  828. if singleTon.className == KMPurchaseCompareDMGWindowController.className() {
  829. singleTon.updateTitle(NSLocalizedString("Trial Expired, Upgrade to Pro Version", comment: ""), andColor: NSColor(red: 1, green: 59/255, blue: 47/255, alpha: 1))
  830. }
  831. }
  832. func checkRepeatTrialAlertController() -> Void {
  833. //允许二次试用时弹出二次试用引导弹窗
  834. if repeatTrialAlertLoad == true {
  835. return
  836. }
  837. repeatTrialAlertLoad = true
  838. let vc = KMVerificationWindowController.verification(with:.repeatTrialGuide)
  839. vc?.showWindow(nil)
  840. }
  841. //MARK: 试用到期优惠券弹窗
  842. func checkTrialEndCouponInfo() {
  843. KMRequestServerManager.manager.getDeviceRetensionCoupon {[weak self] success, result in
  844. if success == true {
  845. if result != nil {
  846. guard let dataDict = result!["data"] as? NSDictionary else {
  847. return
  848. }
  849. // if dataDict!["pop_up"] as? Bool == true {
  850. let discount = dataDict["discount"] as? Int
  851. let coupon_code = dataDict["coupon_code"] as? String
  852. let end_up_at = dataDict["end_up_at"] as? String
  853. let pop_up = dataDict["pop_up"] as? Bool
  854. if pop_up == true {
  855. if let versionKey = KMAdsInfoManager.shareInstance.couponInfo?.versionKey {
  856. if KMAdsInfoManager.shareInstance.couponInfo?.show == true {
  857. if (UserDefaults.standard.object(forKey: versionKey) != nil) {
  858. } else {
  859. UserDefaults.standard.set("Show", forKey: versionKey)
  860. UserDefaults.standard.synchronize()
  861. self?.showCouponInfoWindow(discount: discount, couponCode: coupon_code, endUpAt: end_up_at)
  862. }
  863. }
  864. }
  865. }
  866. }
  867. } else {
  868. #if VERSION_DMG
  869. if KMVerificationWindowController.allowsShowExpired() {
  870. self?.checkRepeatTrialExpiredController()
  871. } else if KMVerificationWindowController.allowRepeatTrialAlertShow() {
  872. self?.checkRepeatTrialAlertController()
  873. }
  874. #endif
  875. }
  876. }
  877. }
  878. func showCouponInfoWindow(discount: Int?, couponCode: String?, endUpAt: String?) {
  879. if self.couponDueWindowVC == nil {
  880. self.couponDueWindowVC = KMCouponDueWindowController(windowNibName: "KMCouponDueWindowController")
  881. }
  882. self.couponDueWindowVC.disCount = discount ?? 20
  883. self.couponDueWindowVC.couponCode = couponCode ?? ""
  884. self.couponDueWindowVC.endUpAt = endUpAt ?? ""
  885. self.couponDueWindowVC.showWindow(nil)
  886. self.couponDueWindowVC.reloadData()
  887. }
  888. // MARK: - Noti Actions
  889. func deviceVerifyFinishNotification(_ sender: Notification) {
  890. #if VERSION_DMG
  891. #endif
  892. }
  893. @objc func aiTipIconViewShowStateChangeNoti() {
  894. }
  895. }