KMHomeViewController.swift 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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. self?.advertisementShowView.inputData = data!.advertisement
  198. self?.advertisementShowView.didSelect = { view, item in
  199. let string = KMAdvertisementModelTransition.transitionLanguage(langeuage: item.linkURL)
  200. if string.count != 0 {
  201. NSWorkspace.shared.open(URL.init(string: string)!)
  202. }
  203. guard let firebaseInfo = item.firebase else {
  204. return
  205. }
  206. KMAdvertisementModelTransition.sendFireBaseEvent(firebase: firebaseInfo)
  207. }
  208. if KMAdvertisementManager.manager.infoDict.allKeys.count > 0 {
  209. if let adsInfo = KMAdvertisementManager.manager.infoDict["adsInfo"] {
  210. let infoDict: NSDictionary = KMAdvertisementManager.manager.infoDict["adsInfo"] as! NSDictionary
  211. let array: [[String: Any]] = infoDict["content"] as! [[String : Any]]
  212. let arrM = NSMutableArray.init()
  213. for dict in array {
  214. let adsInfo = KMAdsInfo.init()
  215. let mutableDictionary = NSMutableDictionary(dictionary: dict)
  216. adsInfo.infoDict = mutableDictionary
  217. arrM.add(adsInfo)
  218. }
  219. KMAdsInfoManager.shareInstance.adsInfoArrM = arrM
  220. }
  221. if let couponInfo = KMAdvertisementManager.manager.infoDict["couponContent"] {
  222. let infoDict: NSDictionary = KMAdvertisementManager.manager.infoDict["couponContent"] as! NSDictionary
  223. let array: [[String: Any]] = infoDict["content"] as! [[String : Any]]
  224. if array.isEmpty == false {
  225. let dict = array[0]
  226. let adsInfo = KMCouponInfo.init()
  227. let mutableDictionary = NSMutableDictionary(dictionary: dict)
  228. adsInfo.infoDict = mutableDictionary
  229. KMAdsInfoManager.shareInstance.couponInfo = adsInfo
  230. }
  231. }
  232. self?.checkTrialEndCouponInfo()
  233. }
  234. }
  235. }
  236. }
  237. func setup() {
  238. //creatPDF
  239. self.creatPDFView.openPDFAction = { [unowned self] view, sender in
  240. self.openPDFAction(sender)
  241. }
  242. self.creatPDFView.creatPDFAction = { [unowned self] view, sender in
  243. self.creatPDFAction(sender)
  244. }
  245. //history
  246. self.homeContentView.historyDidSelect = { [unowned self] view, item in
  247. self.openHistoryFilePath(url: item.url!)
  248. }
  249. self.homeContentView.historyRemoveFileAction = { [unowned self] view, item in
  250. self.historyFile(deleteDocuments: [ item.url!])
  251. }
  252. self.homeContentView.historyShowPathAction = { [unowned self] view, item in
  253. if FileManager.default.fileExists(atPath: item.url!.path) {
  254. NSWorkspace.shared.activateFileViewerSelecting([item.url!])
  255. }
  256. }
  257. self.homeContentView.historyRemoveAllFileAction = { [unowned self] view in
  258. let alert = NSAlert()
  259. alert.alertStyle = .critical
  260. alert.messageText = String(format: "%@?", NSLocalizedString("Clear All Recents", comment: ""))
  261. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  262. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  263. alert.beginSheetModal(for: self.view.window!) { response in
  264. if response == .alertFirstButtonReturn {
  265. let urls: Array<URL> = NSDocumentController.shared.recentDocumentURLs
  266. self.historyFileDeleteAction(urls)
  267. }
  268. }
  269. }
  270. //quciktools
  271. self.homeContentView.qucikToolsDidSelect = { [unowned self] view, item in
  272. self.fastToolItemAction(item.type!)
  273. }
  274. self.homeContentView.qucikToolsAddAction = { [unowned self] view, item in
  275. KMBatchQuickActionManager.defaultManager.actionType = .add
  276. self.fastToolItemAction(item.type!)
  277. }
  278. self.homeContentView.qucikToolsRemoveAction = { [unowned self] view, item in
  279. KMBatchQuickActionManager.defaultManager.actionType = .remove
  280. self.fastToolItemAction(item.type!)
  281. }
  282. if IAPProductsManager.default().isAvailableAllFunction() {
  283. self.advertisementShowView.isHidden = true
  284. } else {
  285. self.advertisementShowView.isHidden = false
  286. }
  287. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "KMIAPProductPurchasedNotification"), object: nil)
  288. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "kDeviceActivateNotification"), object: nil)
  289. }
  290. // MARK: Init
  291. func initializeUI() {
  292. rightTopBox.fillColor = .white
  293. rightBottomBox.fillColor = .white
  294. rightFullBox.fillColor = .white
  295. self.refreshRightBoxUI(.Home)
  296. fastToolViewController.delete = self
  297. historyFileViewController.delete = self
  298. pdfToolsViewController.delete = self
  299. dragView.delete = self
  300. }
  301. func initLocalization() {
  302. // self.favoriteDocumentsLabel.stringValue = NSLocalizedString("Favorite Documents", comment: "")
  303. homeButtonVC?.stringValue = NSLocalizedString("Home", comment: "")
  304. pdfToolsButtonVC?.stringValue = NSLocalizedString("PDF Tools", comment: "")
  305. cloudDocumentsButtonVC?.stringValue = NSLocalizedString("Cloud Documents", comment: "")
  306. openPDFButtonVC?.stringValue = NSLocalizedString("Open File", comment: "")
  307. // openPDFBox.toolTip = NSLocalizedString("Open PDF", comment: "")
  308. createPDFButtonVC?.stringValue = NSLocalizedString("Create PDF", comment: "")
  309. // createPDFBox.toolTip = NSLocalizedString("Create PDF", comment: "")
  310. pdfSeriesButtonVC?.stringValue = NSLocalizedString("PDF Pro Series", comment: "")
  311. pdfOthersButtonVC?.stringValue = NSLocalizedString("Others", comment: "")
  312. }
  313. // MARK: Action
  314. func initializeUI_DMG() -> Void {
  315. rightTopBox.fillColor = .white
  316. rightBottomBox.fillColor = .white
  317. rightFullBox.fillColor = .white
  318. self.aiHomeBox.fillColor = .clear
  319. self.aiHomeBox.cornerRadius = 8.0
  320. self.aiHomeImageView.image = NSImage(named: "icon_home")
  321. self.aiHomeLabel.stringValue = NSLocalizedString("Home", comment: "")
  322. self.aiHomeLabel.textColor = NSColor.km_init(hex: "#252629")
  323. self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
  324. self.aiHomeBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  325. if aiHomeState != .Home {
  326. if mouseEntered {
  327. self.aiHomeBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  328. } else {
  329. self.aiHomeBox.fillColor = .clear
  330. }
  331. }
  332. }
  333. self.aiHomeBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  334. if aiHomeState != .Home {
  335. if downEntered {
  336. self.aiHomeState = .Home
  337. self.refreshAIUI()
  338. }
  339. }
  340. }
  341. self.aiTranslationBox.fillColor = .clear
  342. self.aiTranslationBox.cornerRadius = 8.0
  343. self.aiTranslationImageView.image = NSImage(named: "ic_function_other")
  344. self.aiTranslationLabel.stringValue = NSLocalizedString("AI Translation", comment: "")
  345. self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
  346. self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
  347. self.aiTranslationBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  348. if aiHomeState != .AITranslation {
  349. if mouseEntered {
  350. self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  351. } else {
  352. self.aiTranslationBox.fillColor = .clear
  353. }
  354. }
  355. }
  356. self.aiTranslationBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  357. if aiHomeState != .AITranslation {
  358. if downEntered {
  359. self.aiHomeState = .AITranslation
  360. self.trackEvent_ai(eventName: "AI Translation")
  361. self.refreshAIUI()
  362. }
  363. }
  364. }
  365. self.aiRewritingBox.fillColor = .clear
  366. self.aiRewritingBox.cornerRadius = 8.0
  367. self.aiRewritingImageView.image = NSImage(named: "ic_ai_Rewriting")
  368. self.aiRewritingLabel.stringValue = NSLocalizedString("AI Rewriting", comment: "")
  369. self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
  370. self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
  371. self.aiRewritingBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  372. if aiHomeState != .AIRewriting {
  373. if mouseEntered {
  374. self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  375. } else {
  376. self.aiRewritingBox.fillColor = .clear
  377. }
  378. }
  379. }
  380. self.aiRewritingBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  381. if aiHomeState != .AIRewriting {
  382. if downEntered {
  383. self.aiHomeState = .AIRewriting
  384. self.trackEvent_ai(eventName: "AI Rewriting")
  385. self.refreshAIUI()
  386. }
  387. }
  388. }
  389. self.aiErrorCorrectionBox.fillColor = .clear
  390. self.aiErrorCorrectionBox.cornerRadius = 8.0
  391. self.aiErrorCorrectionImageView.image = NSImage(named: "ic_ai_ErrorCorrection")
  392. self.aiErrorCorrectionLabel.stringValue = NSLocalizedString("AI Error Correction", comment: "")
  393. self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
  394. self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
  395. self.aiErrorCorrectionBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  396. if aiHomeState != .AIErrorCorrection {
  397. if mouseEntered {
  398. self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  399. } else {
  400. self.aiErrorCorrectionBox.fillColor = .clear
  401. }
  402. }
  403. }
  404. self.aiErrorCorrectionBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  405. if aiHomeState != .AIErrorCorrection {
  406. if downEntered {
  407. self.aiHomeState = .AIErrorCorrection
  408. self.trackEvent_ai(eventName: "AI Correction")
  409. self.refreshAIUI()
  410. }
  411. }
  412. }
  413. self.refreshAIUI()
  414. historyFileViewController.delete = self
  415. dragView.delete = self
  416. }
  417. func updateUI() {
  418. self.leftBox.fillColor = KMAppearance.Layout.l0Color()
  419. // self.homeSplitView.backgroundColor(KMAppearance.Layout.l0Color())
  420. }
  421. @objc func changeEffectiveAppearance() {
  422. let isDarkModel = KMAdvertisementConfig.isDarkModel()
  423. if isDarkModel {
  424. self.view.appearance = NSAppearance(named: .darkAqua)
  425. } else {
  426. self.view.appearance = NSAppearance(named: .aqua)
  427. }
  428. self.updateUI()
  429. self.advertisementTableView.reloadData()
  430. }
  431. // MARK: Public Methods
  432. func savePDFDocument(_ pdf: CPDFDocument, password: String) -> Void {
  433. DispatchQueue.global(qos: .`default`).async {
  434. var isSuccessfully = false
  435. if pdf.isEncrypted {
  436. let dic = [
  437. CPDFDocumentWriteOption.userPasswordOption : password,
  438. CPDFDocumentWriteOption.ownerPasswordOption : password
  439. ]
  440. isSuccessfully = pdf.write(to: pdf.documentURL, withOptions: dic)
  441. } else {
  442. isSuccessfully = pdf.write(to: pdf.documentURL)
  443. }
  444. if !isSuccessfully {
  445. if let data = pdf.dataRepresentation() {
  446. isSuccessfully = NSData(data: data).write(to: pdf.documentURL, atomically: true)
  447. }
  448. }
  449. DispatchQueue.main.sync {
  450. if isSuccessfully {
  451. let workspace = NSWorkspace.shared
  452. let url = URL(fileURLWithPath: pdf.documentURL?.path ?? "")
  453. workspace.activateFileViewerSelecting([url])
  454. } else {
  455. let alert = NSAlert()
  456. alert.alertStyle = .critical
  457. alert.messageText = NSLocalizedString("Failed to insert page(s)!", comment: "")
  458. alert.runModal()
  459. }
  460. }
  461. }
  462. }
  463. // MARK: Private Methods
  464. func refreshUI() -> Void {
  465. homeButtonVC?.updateUI()
  466. pdfToolsButtonVC?.updateUI()
  467. cloudDocumentsButtonVC?.updateUI()
  468. }
  469. func refreshAIUI() -> Void {
  470. self.aiHomeBox.fillColor = .clear
  471. self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
  472. self.aiTranslationBox.fillColor = .clear
  473. self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
  474. self.aiRewritingBox.fillColor = .clear
  475. self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
  476. self.aiErrorCorrectionBox.fillColor = .clear
  477. self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
  478. rightFullBox.isHidden = true
  479. rightTopBox.isHidden = true
  480. rightBottomBox.isHidden = true
  481. switch self.aiHomeState {
  482. case .Home:
  483. self.aiHomeBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  484. self.aiHomeLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  485. self.rightTopBox.isHidden = false
  486. self.rightBottomBox.isHidden = false
  487. self.rightTopBox.contentView = self.aiOpenPDFFilesViewController.view
  488. self.rightBottomBox.contentView = self.historyFileViewController.view
  489. self.rightFullBox.contentView = nil
  490. self.rightTopBoxHeightConstraint.constant = 388.0
  491. self.dragView.isHidden = false
  492. break
  493. case .AITranslation:
  494. self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  495. self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
  496. self.aiTranslationLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  497. self.rightFullBox.isHidden = false
  498. self.rightTopBox.contentView = nil
  499. self.rightBottomBox.contentView = nil
  500. self.rightFullBox.contentView = self.aiTranslationViewController.view
  501. self.dragView.isHidden = false
  502. break
  503. case .AIRewriting:
  504. self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  505. self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
  506. self.aiRewritingLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  507. self.rightFullBox.isHidden = false
  508. self.rightTopBox.contentView = nil
  509. self.rightBottomBox.contentView = nil
  510. self.rightFullBox.contentView = self.aiRewritingViewController.view
  511. // self.aiRewritingViewController.state = .AIRewriting
  512. self.aiRewritingViewController.initLocalization()
  513. self.aiRewritingViewController.acquisition_uiState()
  514. self.dragView.isHidden = true
  515. break
  516. case .AIErrorCorrection:
  517. self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  518. self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
  519. self.aiErrorCorrectionLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  520. self.rightFullBox.isHidden = false
  521. self.rightTopBox.contentView = nil
  522. self.rightBottomBox.contentView = nil
  523. self.rightFullBox.contentView = self.aiRewritingViewController.view
  524. // self.aiRewritingViewController.state = .AIErrorCorrection
  525. self.aiRewritingViewController.initLocalization()
  526. self.aiRewritingViewController.acquisition_uiState()
  527. self.dragView.isHidden = true
  528. break
  529. default:
  530. break
  531. }
  532. }
  533. func fetchDifferentFilePath(filePath: String) -> String {
  534. var resultFilePath = filePath
  535. var index: Int = 0
  536. while (FileManager.default.fileExists(atPath: resultFilePath)) {
  537. index += 1
  538. let path = NSString(string: filePath).deletingPathExtension + "(" + String(index) + ")"
  539. resultFilePath = NSString(string: path).appendingPathExtension(NSString(string: filePath).pathExtension)!
  540. }
  541. return resultFilePath;
  542. }
  543. func showProgressWindow() {
  544. let progress = SKProgressController()
  545. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  546. progress.window?.contentView?.wantsLayer = true
  547. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  548. progress.progressField.textColor = NSColor.white
  549. progress.message = NSLocalizedString("Translating...", comment: "")
  550. progress.closeBlock = { [weak self] in
  551. }
  552. self.progressController = progress
  553. self.view.window?.beginSheet(progress.window!)
  554. }
  555. func hiddenProgressWindow() {
  556. DispatchQueue.main.async {
  557. self.progressController?.doubleValue = 100.0
  558. }
  559. self.stopTimer()
  560. if (self.progressController != nil) {
  561. self.view.window?.endSheet((self.progressController?.window)!)
  562. self.progressController = nil
  563. }
  564. }
  565. func isFileGreaterThan10MB(atPath filePath: String) -> Bool {
  566. let fileManager = FileManager.default
  567. do {
  568. let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
  569. if let fileSize = fileAttributes[.size] as? UInt64 {
  570. let megabyteSize = fileSize / (1024 * 1024)
  571. return megabyteSize >= 10
  572. }
  573. } catch {
  574. KMPrint("Error: \(error)")
  575. }
  576. return false
  577. }
  578. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  579. let url = URL(fileURLWithPath: filePath)
  580. guard let document = PDFDocument(url: url) else {
  581. return false
  582. }
  583. let pageCount = document.pageCount
  584. return pageCount > 30
  585. }
  586. @objc func timerTick() {
  587. timerCounter += 1.0
  588. self.progressController?.increment(by: 1.0)
  589. if timerCounter >= 95 {
  590. stopTimer()
  591. }
  592. }
  593. func stopTimer() {
  594. timer?.invalidate()
  595. timer = nil
  596. }
  597. // MARK: Common methods
  598. func workSpaceOpenUrl(_ url: NSString) {
  599. let httpUrl: NSURL = NSURL.init(string: url as String)!
  600. let tWorkSpace: NSWorkspace = NSWorkspace.shared
  601. if !tWorkSpace.open(httpUrl as URL) {
  602. tWorkSpace.open(httpUrl as URL)
  603. }
  604. }
  605. }
  606. //MARK: Open Creat PDF
  607. extension KMHomeViewController: NSPopoverDelegate {
  608. }
  609. extension KMHomeViewController {
  610. func openPDFAction(_ sender: KMBox) {
  611. if needShowTabbingHintWindow() {
  612. showTabbingHintWindow()
  613. return
  614. }
  615. let openPanel = NSOpenPanel()
  616. openPanel.allowedFileTypes = ["pdf", "PDF"]
  617. openPanel.allowsMultipleSelection = false
  618. openPanel.beginSheetModal(for: self.view.window!) { (result) in
  619. if result == NSApplication.ModalResponse.OK {
  620. let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController
  621. if controll?.browser?.tabCount() ?? 0 > 1 && KMPreference.shared.openDocumentType == .newWindow{
  622. self.reopenDocument(forPaths: openPanel.url!)
  623. }else {
  624. NSDocumentController.shared.km_safe_limit_openDocument(withContentsOf: openPanel.url!, display: true) { (document, documentWasAlreadyOpen, error) in
  625. }
  626. }
  627. }
  628. }
  629. }
  630. func needShowTabbingHintWindow() -> Bool {
  631. let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController
  632. if controll?.browser?.tabCount() ?? 0 > 1 && !IAPProductsManager.default().isAvailableAllFunction() {
  633. return true
  634. }
  635. return false
  636. }
  637. func showTabbingHintWindow(){
  638. if !KMDataManager.default.isTabbingWin{
  639. KMDataManager.default.isTabbingWin = true
  640. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  641. tabbingWin.selectCallBack = { [weak self] continueOrNot in
  642. KMDataManager.default.isTabbingWin = false
  643. if continueOrNot {
  644. self?.reopenDocument(forPaths: nil)
  645. } else {
  646. }
  647. }
  648. self.km_beginSheet(windowC: tabbingWin)
  649. }
  650. }
  651. func creatPDFAction(_ sender: KMBox) {
  652. let popViewDataArr: [String] = [NSLocalizedString("New Blank Page", comment: ""),
  653. NSLocalizedString("New From Images", comment: ""),
  654. NSLocalizedString("New From Web Page", comment: ""),
  655. NSLocalizedString("Import From Camera", comment: ""),
  656. NSLocalizedString("Import From Scanner", comment: "")]
  657. let vc: KMHomePopViewController = KMHomePopViewController().initWithPopViewDataArr(popViewDataArr)
  658. vc.background = KMAppearance.Layout.bgColor()
  659. vc.textColor = KMAppearance.Layout.h0Color()
  660. vc.enterFillColor = KMAppearance.Interactive.s0Color()
  661. let createFilePopover: NSPopover = NSPopover.init()
  662. createFilePopover.contentViewController = vc
  663. createFilePopover.delegate = self
  664. createFilePopover.animates = true
  665. createFilePopover.behavior = .semitransient
  666. createFilePopover.setValue(true, forKey: "shouldHideAnchor")
  667. 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)
  668. vc.downCallback = { [unowned self] (downEntered: Bool, count: String) -> Void in
  669. if count == NSLocalizedString("New Blank Page", comment: "") {
  670. self.openBlankPage()
  671. } else if count == NSLocalizedString("Import From Camera", comment: "") {
  672. self.importFromCamera()
  673. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  674. self.importFromScanner()
  675. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  676. self.importFromWebPage()
  677. } else if count == NSLocalizedString("New From Images", comment: "") {
  678. self.newFromImages()
  679. }
  680. createFilePopover.close()
  681. }
  682. }
  683. func openBlankPage() {
  684. NSApplication.newBlankDocument()
  685. }
  686. func importFromWebPage() {
  687. self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
  688. self.urlToPDFWindowController?.beginSheetModalForWindow(NSWindow.currentWindow(), completionHandler: { filePath in
  689. if FileManager.default.fileExists(atPath: filePath) {
  690. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  691. if error != nil {
  692. NSApp.presentError(error!)
  693. } else {
  694. if document is KMMainDocument {
  695. (document as! KMMainDocument).isNewCreated = true
  696. }
  697. }
  698. // self.homeContentView.reloadData()
  699. }
  700. }
  701. })
  702. }
  703. func importFromScanner() {
  704. let vc = KMDeviceBrowserWindowController.shared
  705. vc.type = .scanner
  706. vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  707. self?.openFile(withFilePath: url as URL)
  708. }
  709. vc.showWindow(NSApp.mainWindow)
  710. }
  711. func importFromCamera() {
  712. let vc = KMDeviceBrowserWindowController.shared
  713. vc.type = .camera
  714. vc.importCameraFileCallback = { [weak self] (url: NSURL) -> Void in
  715. self?.openFile(withFilePath: url as URL)
  716. }
  717. vc.showWindow(NSApp.mainWindow)
  718. }
  719. func newFromImages() {
  720. fastTool_ImageToPDF()
  721. // let openPanel = NSOpenPanel()
  722. // openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  723. // if IAPProductsManager.defaultManager().isAvailableAllFunction {
  724. // openPanel.allowsMultipleSelection = true
  725. // } else {
  726. // openPanel.allowsMultipleSelection = false
  727. // }
  728. // 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: "")
  729. // openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  730. // if result == .OK {
  731. // DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  732. // debugPrint("缺少图片转PDF")
  733. // let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  734. // var arr: [KMBatchOperateFile] = []
  735. // for url in openPanel.urls {
  736. // let file = KMBatchOperateFile(filePath: url.path, type: .createPDF)
  737. // arr.append(file)
  738. // }
  739. //
  740. // if #available(macOS 10.13, *) {
  741. // baseWindowController.window?.makeKeyAndOrderFront(nil)
  742. // } else {
  743. // baseWindowController.showWindow(nil)
  744. // }
  745. // baseWindowController.checkNeedPasswordSwitch(toOperateType: .createPDF, files: arr)
  746. // if #available(macOS 10.13, *) {
  747. // baseWindowController.release()
  748. // }
  749. // }
  750. // }
  751. // }
  752. }
  753. //MARK: Purchase
  754. @objc func purchaseStateUpdateNoti() {
  755. if IAPProductsManager.default().isAvailableAllFunction() {
  756. self.advertisementShowView.isHidden = true
  757. let content = self.advertisementTableView.inputData
  758. let item = content?.recommondContentPDFPro
  759. var infos: [KMAdvertisementItemInfo] = []
  760. for info in item?.content ?? [] {
  761. if info.version == "recommondPDF-PDFtoOfficePack" {
  762. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() == false {
  763. infos.append(info)
  764. }
  765. } else {
  766. infos.append(info)
  767. }
  768. }
  769. item?.content = infos
  770. self.advertisementTableView.inputData = content
  771. }
  772. }
  773. //MARK: - AI
  774. func showAITypeChooseView() -> Void {
  775. let windowVC: AINewConfigWindowController = AINewConfigWindowController.currentWC()
  776. windowVC.chooseCurFileHandle = {[unowned self] windowVC in
  777. if AIChatInfoManager.defaultManager.currentFilePath.isEmpty == false {
  778. let documentArray = NSDocumentController.shared.documents
  779. var didFileEdit: Bool = false
  780. var curDoc: KMMainDocument!
  781. for document in documentArray {
  782. if document.fileURL?.path == AIChatInfoManager.defaultManager.currentFilePath {
  783. didFileEdit = document.isDocumentEdited
  784. curDoc = document as! KMMainDocument
  785. break
  786. }
  787. }
  788. if didFileEdit {
  789. let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(AIChatInfoManager.defaultManager.currentFilePath.lastPathComponent)
  790. if FileManager.default.fileExists(atPath: tempFileURL.path) {
  791. do {
  792. try FileManager.default.removeItem(at: tempFileURL)
  793. } catch {
  794. }
  795. }
  796. if curDoc != nil {
  797. curDoc.mainViewController?.SaveTempPDFDocumentToURLPath(tempPath: tempFileURL.path)
  798. }
  799. }
  800. windowVC.window?.becomeMain()
  801. }
  802. }
  803. if windowVC.window?.isVisible == true && windowVC.didSetOriginFrame == true {
  804. } else {
  805. windowVC.window?.center()
  806. windowVC.didSetOriginFrame = true
  807. }
  808. windowVC.eventLabel = "AITools_Onboard"
  809. windowVC.showWindow(nil)
  810. }
  811. func loadAITipIconGuide() {
  812. if KMGuideInfoWindowController.availableShow(.aiTipIconInfo) {
  813. let guideWC = KMGuideInfoWindowController.currentWC()
  814. guideWC.type = .aiTipIconInfo
  815. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  816. guideWC.finishHandle = { [weak self] windowVC, type in
  817. }
  818. if self.view.window != nil {
  819. var rect = self.view.window?.frame
  820. rect!.size.height -= 20
  821. guideWC.window?.setFrame(rect!, display: true)
  822. guideWC.window?.minSize = rect!.size
  823. guideWC.window?.maxSize = rect!.size
  824. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  825. guideWC.show()
  826. }
  827. }
  828. }
  829. //MARK: - 引导
  830. func loadFunctionGuide() -> Void {
  831. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  832. self.loadNewUserGuide()
  833. }
  834. }
  835. // MARK: - what's New
  836. func loadNewUserGuide() -> Void {
  837. if KMFunctionGuideWindowController.availableShow(.functionMultiAIGuide) {
  838. guideWindowVC = KMFunctionGuideWindowController.init(windowNibName: "KMFunctionGuideWindowController")
  839. guideWindowVC.type = .functionMulti
  840. guideWindowVC.showWindow(nil)
  841. guideWindowVC.window?.orderFront(nil)
  842. KMFunctionGuideWindowController.setDidShowFor(.functionMultiAIGuide)
  843. }
  844. }
  845. func checkRepeatTrialExpiredController() -> Void {
  846. //试用过期提示比较表弹窗
  847. if didTrialExpiredLoad == true {
  848. return
  849. }
  850. didTrialExpiredLoad = true
  851. let singleTon = KMPurchaseCompareDMGWindowController.init()
  852. singleTon.showWindow(nil)
  853. if singleTon.className == KMPurchaseCompareDMGWindowController.className() {
  854. singleTon.updateTitle(NSLocalizedString("Trial Expired, Upgrade to Pro Version", comment: ""), andColor: NSColor(red: 1, green: 59/255, blue: 47/255, alpha: 1))
  855. }
  856. }
  857. func checkRepeatTrialAlertController() -> Void {
  858. //允许二次试用时弹出二次试用引导弹窗
  859. if repeatTrialAlertLoad == true {
  860. return
  861. }
  862. repeatTrialAlertLoad = true
  863. let vc = KMVerificationWindowController.verification(with:.repeatTrialGuide)
  864. vc?.showWindow(nil)
  865. }
  866. //MARK: 试用到期优惠券弹窗
  867. func checkTrialEndCouponInfo() {
  868. KMRequestServerManager.manager.getDeviceRetensionCoupon {[weak self] success, result in
  869. if success == true {
  870. if result != nil {
  871. guard let dataDict = result!["data"] as? NSDictionary else {
  872. return
  873. }
  874. // if dataDict!["pop_up"] as? Bool == true {
  875. let discount = dataDict["discount"] as? Int
  876. let coupon_code = dataDict["coupon_code"] as? String
  877. let end_up_at = dataDict["end_up_at"] as? String
  878. let pop_up = dataDict["pop_up"] as? Bool
  879. if pop_up == true {
  880. if let versionKey = KMAdsInfoManager.shareInstance.couponInfo?.versionKey {
  881. if KMAdsInfoManager.shareInstance.couponInfo?.show == true {
  882. if (UserDefaults.standard.object(forKey: versionKey) != nil) {
  883. } else {
  884. UserDefaults.standard.set("Show", forKey: versionKey)
  885. UserDefaults.standard.synchronize()
  886. self?.showCouponInfoWindow(discount: discount, couponCode: coupon_code, endUpAt: end_up_at)
  887. }
  888. }
  889. }
  890. }
  891. }
  892. } else {
  893. #if VERSION_DMG
  894. if KMVerificationWindowController.allowsShowExpired() {
  895. self?.checkRepeatTrialExpiredController()
  896. } else if KMVerificationWindowController.allowRepeatTrialAlertShow() {
  897. self?.checkRepeatTrialAlertController()
  898. }
  899. #endif
  900. }
  901. }
  902. }
  903. func showCouponInfoWindow(discount: Int?, couponCode: String?, endUpAt: String?) {
  904. if self.couponDueWindowVC == nil {
  905. self.couponDueWindowVC = KMCouponDueWindowController(windowNibName: "KMCouponDueWindowController")
  906. }
  907. self.couponDueWindowVC.disCount = discount ?? 20
  908. self.couponDueWindowVC.couponCode = couponCode ?? ""
  909. self.couponDueWindowVC.endUpAt = endUpAt ?? ""
  910. self.couponDueWindowVC.showWindow(nil)
  911. self.couponDueWindowVC.reloadData()
  912. }
  913. // MARK: - Noti Actions
  914. func deviceVerifyFinishNotification(_ sender: Notification) {
  915. #if VERSION_DMG
  916. #endif
  917. }
  918. @objc func aiTipIconViewShowStateChangeNoti() {
  919. }
  920. }