KMHomeViewController.swift 45 KB

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