KMHomeViewController.swift 44 KB

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