KMHomeViewController.swift 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  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. NSDocumentController.shared.km_safe_limit_openDocument(withContentsOf: openPanel.url!, display: true) { (document, documentWasAlreadyOpen, error) in
  581. }
  582. }
  583. }
  584. }
  585. func needShowTabbingHintWindow() -> Bool {
  586. let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController
  587. if controll?.browser?.tabCount() ?? 0 > 1 && !IAPProductsManager.default().isAvailableAllFunction() {
  588. return true
  589. }
  590. return false
  591. }
  592. func showTabbingHintWindow(){
  593. if !KMDataManager.default.isTabbingWin{
  594. KMDataManager.default.isTabbingWin = true
  595. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  596. tabbingWin.selectCallBack = { [weak self] continueOrNot in
  597. KMDataManager.default.isTabbingWin = false
  598. if continueOrNot {
  599. self?.reopenDocument(forPaths: nil)
  600. } else {
  601. }
  602. }
  603. self.km_beginSheet(windowC: tabbingWin)
  604. }
  605. }
  606. func creatPDFAction(_ sender: KMBox) {
  607. let popViewDataArr: [String] = [NSLocalizedString("New Blank Page", comment: ""),
  608. NSLocalizedString("New From Images", comment: ""),
  609. NSLocalizedString("New From Web Page", comment: ""),
  610. NSLocalizedString("Import From Camera", comment: ""),
  611. NSLocalizedString("Import From Scanner", comment: "")]
  612. let vc: KMHomePopViewController = KMHomePopViewController().initWithPopViewDataArr(popViewDataArr)
  613. vc.background = KMAppearance.Layout.bgColor()
  614. vc.textColor = KMAppearance.Layout.h0Color()
  615. vc.enterFillColor = KMAppearance.Interactive.s0Color()
  616. let createFilePopover: NSPopover = NSPopover.init()
  617. createFilePopover.contentViewController = vc
  618. createFilePopover.delegate = self
  619. createFilePopover.animates = true
  620. createFilePopover.behavior = .semitransient
  621. createFilePopover.setValue(true, forKey: "shouldHideAnchor")
  622. 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)
  623. vc.downCallback = { [unowned self] (downEntered: Bool, count: String) -> Void in
  624. if count == NSLocalizedString("New Blank Page", comment: "") {
  625. self.openBlankPage()
  626. } else if count == NSLocalizedString("Import From Camera", comment: "") {
  627. self.importFromCamera()
  628. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  629. self.importFromScanner()
  630. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  631. self.importFromWebPage()
  632. } else if count == NSLocalizedString("New From Images", comment: "") {
  633. self.newFromImages()
  634. }
  635. createFilePopover.close()
  636. }
  637. }
  638. func openBlankPage() {
  639. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  640. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
  641. let filePath = savePath.deletingLastPathComponent
  642. if FileManager.default.fileExists(atPath: filePath) == false {
  643. try?FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false)
  644. }
  645. let pdfDocument = CPDFDocument()
  646. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  647. pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  648. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  649. if error != nil {
  650. NSApp.presentError(error!)
  651. } else {
  652. if document is KMMainDocument {
  653. let newDocument = document
  654. (newDocument as! KMMainDocument).isNewCreated = true
  655. }
  656. }
  657. // self.homeContentView?.reloadData()
  658. }
  659. }
  660. func importFromWebPage() {
  661. self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
  662. self.urlToPDFWindowController?.beginSheetModalForWindow(NSWindow.currentWindow(), completionHandler: { filePath in
  663. if FileManager.default.fileExists(atPath: filePath) {
  664. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  665. if error != nil {
  666. NSApp.presentError(error!)
  667. } else {
  668. if document is KMMainDocument {
  669. (document as! KMMainDocument).isNewCreated = true
  670. }
  671. }
  672. // self.homeContentView.reloadData()
  673. }
  674. }
  675. })
  676. }
  677. func importFromScanner() {
  678. let vc = KMDeviceBrowserWindowController.shared
  679. vc.type = .scanner
  680. vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  681. self?.openFile(withFilePath: url as URL)
  682. }
  683. vc.showWindow(NSApp.mainWindow)
  684. }
  685. func importFromCamera() {
  686. let vc = KMDeviceBrowserWindowController.shared
  687. vc.type = .camera
  688. vc.importCameraFileCallback = { [weak self] (url: NSURL) -> Void in
  689. self?.openFile(withFilePath: url as URL)
  690. }
  691. vc.showWindow(NSApp.mainWindow)
  692. }
  693. func newFromImages() {
  694. fastTool_ImageToPDF()
  695. // let openPanel = NSOpenPanel()
  696. // openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  697. // if IAPProductsManager.defaultManager().isAvailableAllFunction {
  698. // openPanel.allowsMultipleSelection = true
  699. // } else {
  700. // openPanel.allowsMultipleSelection = false
  701. // }
  702. // 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: "")
  703. // openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  704. // if result == .OK {
  705. // DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  706. // debugPrint("缺少图片转PDF")
  707. // let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  708. // var arr: [KMBatchOperateFile] = []
  709. // for url in openPanel.urls {
  710. // let file = KMBatchOperateFile(filePath: url.path, type: .createPDF)
  711. // arr.append(file)
  712. // }
  713. //
  714. // if #available(macOS 10.13, *) {
  715. // baseWindowController.window?.makeKeyAndOrderFront(nil)
  716. // } else {
  717. // baseWindowController.showWindow(nil)
  718. // }
  719. // baseWindowController.checkNeedPasswordSwitch(toOperateType: .createPDF, files: arr)
  720. // if #available(macOS 10.13, *) {
  721. // baseWindowController.release()
  722. // }
  723. // }
  724. // }
  725. // }
  726. }
  727. //MARK: Purchase
  728. @objc func purchaseStateUpdateNoti() {
  729. if IAPProductsManager.default().isAvailableAllFunction() {
  730. self.advertisementShowView.isHidden = true
  731. }
  732. }
  733. //MARK: - AI
  734. func showAITypeChooseView() -> Void {
  735. let windowVC: AINewConfigWindowController = AINewConfigWindowController.currentWC()
  736. windowVC.chooseCurFileHandle = {[unowned self] windowVC in
  737. if AIChatInfoManager.defaultManager.currentFilePath.isEmpty == false {
  738. let documentArray = NSDocumentController.shared.documents
  739. var didFileEdit: Bool = false
  740. var curDoc: KMMainDocument!
  741. for document in documentArray {
  742. if document.fileURL?.path == AIChatInfoManager.defaultManager.currentFilePath {
  743. didFileEdit = document.isDocumentEdited
  744. curDoc = document as! KMMainDocument
  745. break
  746. }
  747. }
  748. if didFileEdit {
  749. let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(AIChatInfoManager.defaultManager.currentFilePath.lastPathComponent)
  750. if FileManager.default.fileExists(atPath: tempFileURL.path) {
  751. do {
  752. try FileManager.default.removeItem(at: tempFileURL)
  753. } catch {
  754. }
  755. }
  756. if curDoc != nil {
  757. curDoc.mainViewController?.SaveTempPDFDocumentToURLPath(tempPath: tempFileURL.path)
  758. }
  759. }
  760. windowVC.window?.becomeMain()
  761. }
  762. }
  763. if windowVC.window?.isVisible == true && windowVC.didSetOriginFrame == true {
  764. } else {
  765. windowVC.window?.center()
  766. windowVC.didSetOriginFrame = true
  767. }
  768. windowVC.eventLabel = "AITools_Onboard"
  769. windowVC.showWindow(nil)
  770. }
  771. func loadAITipIconGuide() {
  772. if KMGuideInfoWindowController.availableShow(.aiTipIconInfo) {
  773. let guideWC = KMGuideInfoWindowController.currentWC()
  774. guideWC.type = .aiTipIconInfo
  775. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  776. guideWC.finishHandle = { [weak self] windowVC, type in
  777. }
  778. if self.view.window != nil {
  779. var rect = self.view.window?.frame
  780. rect!.size.height -= 20
  781. guideWC.window?.setFrame(rect!, display: true)
  782. guideWC.window?.minSize = rect!.size
  783. guideWC.window?.maxSize = rect!.size
  784. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  785. guideWC.show()
  786. }
  787. }
  788. }
  789. //MARK: - 引导
  790. func loadFunctionGuide() -> Void {
  791. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  792. self.loadNewUserGuide()
  793. }
  794. }
  795. // MARK: - what's New
  796. func loadNewUserGuide() -> Void {
  797. if KMFunctionGuideWindowController.availableShow(.functionMultiAIGuide) {
  798. let guideWindowVC = KMFunctionGuideWindowController.init(windowNibName: "KMFunctionGuideWindowController")
  799. guideWindowVC.type = .functionMulti
  800. guideWindowVC.showWindow(nil)
  801. guideWindowVC.window?.orderFront(nil)
  802. KMFunctionGuideWindowController.setDidShowFor(.functionMultiAIGuide)
  803. }
  804. }
  805. func checkRepeatTrialExpiredController() -> Void {
  806. //试用过期提示比较表弹窗
  807. if didTrialExpiredLoad == true {
  808. return
  809. }
  810. didTrialExpiredLoad = true
  811. let singleTon = KMPurchaseCompareDMGWindowController.init()
  812. singleTon.showWindow(nil)
  813. if singleTon.className == KMPurchaseCompareDMGWindowController.className() {
  814. singleTon.updateTitle(NSLocalizedString("Trial Expired, Upgrade to Pro Version", comment: ""), andColor: NSColor(red: 1, green: 59/255, blue: 47/255, alpha: 1))
  815. }
  816. }
  817. func checkRepeatTrialAlertController() -> Void {
  818. //允许二次试用时弹出二次试用引导弹窗
  819. if repeatTrialAlertLoad == true {
  820. return
  821. }
  822. repeatTrialAlertLoad = true
  823. let vc = KMVerificationWindowController.verification(with:.repeatTrialGuide)
  824. vc?.showWindow(nil)
  825. }
  826. // MARK: - Noti Actions
  827. func deviceVerifyFinishNotification(_ sender: Notification) {
  828. #if VERSION_DMG
  829. if KMVerificationWindowController.allowsShowExpired() {
  830. self.checkRepeatTrialExpiredController()
  831. } else if KMVerificationWindowController.allowRepeatTrialAlertShow() {
  832. self.checkRepeatTrialAlertController()
  833. }
  834. #endif
  835. }
  836. @objc func aiTipIconViewShowStateChangeNoti() {
  837. }
  838. }