KMHomeViewController.swift 38 KB

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