KMHomeViewController.swift 41 KB

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