KMHomeViewController.swift 41 KB

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