KMHomeViewController.swift 45 KB

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