KMHomeViewController.swift 41 KB

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