KMHomeViewController.swift 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  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. self.homeContentView.reloadData()
  91. }
  92. override func viewWillDisappear() {
  93. super.viewWillDisappear()
  94. // self.homeContentView.reloadData()
  95. }
  96. override func viewDidLoad() {
  97. super.viewDidLoad()
  98. // Do view setup here.
  99. openPDFButtonVC = KMDesignButton.init(withType: .Text)
  100. createPDFButtonVC = KMDesignButton.init(withType: .Text)
  101. createPDFImage = KMDesignButton.init(withType: .Image)
  102. createPDFAddButtonVC = KMDesignButton.init(withType: .Image)
  103. homeButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  104. pdfToolsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  105. cloudDocumentsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  106. pdfSeriesButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  107. pdfOthersButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  108. self.homeSplitView.setPosition(270.0, ofDividerAt: 0)
  109. self.leftBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
  110. self.rightBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
  111. NSEvent.addLocalMonitorForEvents(matching: .leftMouseDown) { (aEvent) -> NSEvent? in
  112. self.otherMouseDown(with: aEvent)
  113. return aEvent
  114. }
  115. self.initNetworkingData()
  116. // self.initLocalization()
  117. // self.initializeUI()
  118. self.initializeUI_DMG()
  119. self.setup()
  120. // refreshUI()
  121. self.updateUI()
  122. self.changeEffectiveAppearance()
  123. NotificationCenter.default.addObserver(self, selector: #selector(homeFileRectChange(_:)), name: Notification.Name("KMHomeFileRectChange"), object: nil)
  124. NotificationCenter.default.addObserver(self, selector: #selector(changeEffectiveAppearance), name: NSNotification.Name(rawValue: "kEffectiveAppearance"), object: nil)
  125. // setAppearance(isDarkMode: KMAdvertisementConfig.isDarkModel())
  126. // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name(NSApplication.didUpdateNotification.rawValue), object: nil)
  127. // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name(NSWindow.didBecomeMainNotification.rawValue), object: nil)
  128. // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name("AppleInterfaceThemeChangedNotification"), object: nil)
  129. NotificationCenter.default.addObserver(self, selector: #selector(openNewWindowAlertV), name: Notification.Name("KMCTTableChangeShowAlertView"), object: nil)
  130. #if VERSION_DMG
  131. NotificationCenter.default.addObserver(self, selector: #selector(deviceVerifyFinishNotification), name: Notification.Name.init(NSNotification.Name.deviceVerifyFinish.rawValue), object: nil)
  132. #endif
  133. NotificationCenter.default.addObserver(self, selector: #selector(importFromCamera), name: Notification.Name("kDeviceCameraMenuItemNotification"), object: nil)
  134. NotificationCenter.default.addObserver(self, selector: #selector(importFromScanner), name: Notification.Name("kDeviceScannerMenuItemNotification"), object: nil)
  135. self.loadFunctionGuide()
  136. }
  137. override func viewDidAppear() {
  138. super.viewDidAppear()
  139. refreshScrollView()
  140. }
  141. override func viewDidLayout() {
  142. super.viewDidLayout()
  143. refreshScrollView()
  144. // self.loadAITipIconGuide()
  145. }
  146. func initNetworkingData() {
  147. }
  148. func setup() {
  149. //creatPDF
  150. self.creatPDFView.openPDFAction = { [unowned self] view, sender in
  151. self.openPDFAction(sender)
  152. }
  153. self.creatPDFView.creatPDFAction = { [unowned self] view, sender in
  154. self.creatPDFAction(sender)
  155. }
  156. //history
  157. self.homeContentView.historyDidSelect = { [unowned self] view, item in
  158. self.openHistoryFilePath(url: item.url!)
  159. }
  160. self.homeContentView.historyRemoveFileAction = { [unowned self] view, item in
  161. self.historyFile(deleteDocuments: [ item.url!])
  162. }
  163. self.homeContentView.historyShowPathAction = { [unowned self] view, item in
  164. if FileManager.default.fileExists(atPath: item.url!.path) {
  165. NSWorkspace.shared.activateFileViewerSelecting([item.url!])
  166. }
  167. }
  168. self.homeContentView.historyRemoveAllFileAction = { [unowned self] view in
  169. let alert = NSAlert()
  170. alert.alertStyle = .critical
  171. alert.messageText = String(format: "%@?", NSLocalizedString("Clear All Recents", comment: ""))
  172. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  173. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  174. alert.beginSheetModal(for: self.view.window!) { response in
  175. if response == .alertFirstButtonReturn {
  176. let urls: Array<URL> = NSDocumentController.shared.recentDocumentURLs
  177. self.historyFileDeleteAction(urls)
  178. }
  179. }
  180. }
  181. //quciktools
  182. self.homeContentView.qucikToolsDidSelect = { [unowned self] view, item in
  183. self.fastToolItemAction(item.type!)
  184. }
  185. self.homeContentView.qucikToolsAddAction = { [unowned self] view, item in
  186. KMBatchQuickActionManager.defaultManager.actionType = .add
  187. self.fastToolItemAction(item.type!)
  188. }
  189. self.homeContentView.qucikToolsRemoveAction = { [unowned self] view, item in
  190. KMBatchQuickActionManager.defaultManager.actionType = .remove
  191. self.fastToolItemAction(item.type!)
  192. }
  193. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "KMIAPProductPurchasedNotification"), object: nil)
  194. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "kDeviceActivateNotification"), object: nil)
  195. }
  196. // MARK: Init
  197. func initializeUI() {
  198. rightTopBox.fillColor = .white
  199. rightBottomBox.fillColor = .white
  200. rightFullBox.fillColor = .white
  201. self.refreshRightBoxUI(.Home)
  202. fastToolViewController.delete = self
  203. historyFileViewController.delete = self
  204. pdfToolsViewController.delete = self
  205. dragView.delete = self
  206. }
  207. func initLocalization() {
  208. // self.favoriteDocumentsLabel.stringValue = NSLocalizedString("Favorite Documents", comment: "")
  209. homeButtonVC?.stringValue = NSLocalizedString("Home", comment: "")
  210. pdfToolsButtonVC?.stringValue = NSLocalizedString("PDF Tools", comment: "")
  211. cloudDocumentsButtonVC?.stringValue = NSLocalizedString("Cloud Documents", comment: "")
  212. openPDFButtonVC?.stringValue = NSLocalizedString("Open File", comment: "")
  213. // openPDFBox.toolTip = NSLocalizedString("Open PDF", comment: "")
  214. createPDFButtonVC?.stringValue = NSLocalizedString("Create PDF", comment: "")
  215. // createPDFBox.toolTip = NSLocalizedString("Create PDF", comment: "")
  216. pdfSeriesButtonVC?.stringValue = NSLocalizedString("PDF Pro Series", comment: "")
  217. pdfOthersButtonVC?.stringValue = NSLocalizedString("Others", comment: "")
  218. }
  219. // MARK: Action
  220. func initializeUI_DMG() -> Void {
  221. rightTopBox.fillColor = .white
  222. rightBottomBox.fillColor = .white
  223. rightFullBox.fillColor = .white
  224. self.aiHomeBox.fillColor = .clear
  225. self.aiHomeBox.cornerRadius = 8.0
  226. self.aiHomeImageView.image = NSImage(named: "icon_home")
  227. self.aiHomeLabel.stringValue = NSLocalizedString("Home", comment: "")
  228. self.aiHomeLabel.textColor = NSColor.km_init(hex: "#252629")
  229. self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
  230. self.aiHomeBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  231. if aiHomeState != .Home {
  232. if mouseEntered {
  233. self.aiHomeBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  234. } else {
  235. self.aiHomeBox.fillColor = .clear
  236. }
  237. }
  238. }
  239. self.aiHomeBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  240. if aiHomeState != .Home {
  241. if downEntered {
  242. self.aiHomeState = .Home
  243. self.refreshAIUI()
  244. }
  245. }
  246. }
  247. self.aiTranslationBox.fillColor = .clear
  248. self.aiTranslationBox.cornerRadius = 8.0
  249. self.aiTranslationImageView.image = NSImage(named: "ic_function_other")
  250. self.aiTranslationLabel.stringValue = NSLocalizedString("AI Translation", comment: "")
  251. self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
  252. self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
  253. self.aiTranslationBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  254. if aiHomeState != .AITranslation {
  255. if mouseEntered {
  256. self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  257. } else {
  258. self.aiTranslationBox.fillColor = .clear
  259. }
  260. }
  261. }
  262. self.aiTranslationBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  263. if aiHomeState != .AITranslation {
  264. if downEntered {
  265. self.aiHomeState = .AITranslation
  266. self.trackEvent_ai(eventName: "AI Translation")
  267. self.refreshAIUI()
  268. }
  269. }
  270. }
  271. self.aiRewritingBox.fillColor = .clear
  272. self.aiRewritingBox.cornerRadius = 8.0
  273. self.aiRewritingImageView.image = NSImage(named: "ic_ai_Rewriting")
  274. self.aiRewritingLabel.stringValue = NSLocalizedString("AI Rewriting", comment: "")
  275. self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
  276. self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
  277. self.aiRewritingBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  278. if aiHomeState != .AIRewriting {
  279. if mouseEntered {
  280. self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  281. } else {
  282. self.aiRewritingBox.fillColor = .clear
  283. }
  284. }
  285. }
  286. self.aiRewritingBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  287. if aiHomeState != .AIRewriting {
  288. if downEntered {
  289. self.aiHomeState = .AIRewriting
  290. self.trackEvent_ai(eventName: "AI Rewriting")
  291. self.refreshAIUI()
  292. }
  293. }
  294. }
  295. self.aiErrorCorrectionBox.fillColor = .clear
  296. self.aiErrorCorrectionBox.cornerRadius = 8.0
  297. self.aiErrorCorrectionImageView.image = NSImage(named: "ic_ai_ErrorCorrection")
  298. self.aiErrorCorrectionLabel.stringValue = NSLocalizedString("AI Error Correction", comment: "")
  299. self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
  300. self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
  301. self.aiErrorCorrectionBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  302. if aiHomeState != .AIErrorCorrection {
  303. if mouseEntered {
  304. self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  305. } else {
  306. self.aiErrorCorrectionBox.fillColor = .clear
  307. }
  308. }
  309. }
  310. self.aiErrorCorrectionBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  311. if aiHomeState != .AIErrorCorrection {
  312. if downEntered {
  313. self.aiHomeState = .AIErrorCorrection
  314. self.trackEvent_ai(eventName: "AI Correction")
  315. self.refreshAIUI()
  316. }
  317. }
  318. }
  319. self.refreshAIUI()
  320. historyFileViewController.delete = self
  321. dragView.delete = self
  322. }
  323. func updateUI() {
  324. self.leftBox.fillColor = KMAppearance.Layout.l0Color()
  325. // self.homeSplitView.backgroundColor(KMAppearance.Layout.l0Color())
  326. }
  327. @objc func changeEffectiveAppearance() {
  328. let isDarkModel = NSView.isDarkModel()
  329. if isDarkModel {
  330. self.view.appearance = NSAppearance(named: .darkAqua)
  331. } else {
  332. self.view.appearance = NSAppearance(named: .aqua)
  333. }
  334. self.updateUI()
  335. }
  336. // MARK: Public Methods
  337. func savePDFDocument(_ pdf: CPDFDocument, password: String) -> Void {
  338. DispatchQueue.global(qos: .`default`).async {
  339. var isSuccessfully = false
  340. if pdf.isEncrypted {
  341. let dic = [
  342. CPDFDocumentWriteOption.userPasswordOption : password,
  343. CPDFDocumentWriteOption.ownerPasswordOption : password
  344. ]
  345. isSuccessfully = pdf.write(to: pdf.documentURL, withOptions: dic)
  346. } else {
  347. isSuccessfully = pdf.write(to: pdf.documentURL)
  348. }
  349. if !isSuccessfully {
  350. if let data = pdf.dataRepresentation() {
  351. isSuccessfully = NSData(data: data).write(to: pdf.documentURL, atomically: true)
  352. }
  353. }
  354. DispatchQueue.main.sync {
  355. if isSuccessfully {
  356. let workspace = NSWorkspace.shared
  357. let url = URL(fileURLWithPath: pdf.documentURL?.path ?? "")
  358. workspace.activateFileViewerSelecting([url])
  359. } else {
  360. let alert = NSAlert()
  361. alert.alertStyle = .critical
  362. alert.messageText = NSLocalizedString("Failed to insert page(s)!", comment: "")
  363. alert.runModal()
  364. }
  365. }
  366. }
  367. }
  368. // MARK: Private Methods
  369. func refreshUI() -> Void {
  370. homeButtonVC?.updateUI()
  371. pdfToolsButtonVC?.updateUI()
  372. cloudDocumentsButtonVC?.updateUI()
  373. }
  374. func refreshAIUI() -> Void {
  375. self.aiHomeBox.fillColor = .clear
  376. self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
  377. self.aiTranslationBox.fillColor = .clear
  378. self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
  379. self.aiRewritingBox.fillColor = .clear
  380. self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
  381. self.aiErrorCorrectionBox.fillColor = .clear
  382. self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
  383. rightFullBox.isHidden = true
  384. rightTopBox.isHidden = true
  385. rightBottomBox.isHidden = true
  386. switch self.aiHomeState {
  387. case .Home:
  388. self.aiHomeBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  389. self.aiHomeLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  390. self.rightTopBox.isHidden = false
  391. self.rightBottomBox.isHidden = false
  392. self.rightTopBox.contentView = self.aiOpenPDFFilesViewController.view
  393. self.rightBottomBox.contentView = self.historyFileViewController.view
  394. self.rightFullBox.contentView = nil
  395. self.rightTopBoxHeightConstraint.constant = 388.0
  396. self.dragView.isHidden = false
  397. break
  398. case .AITranslation:
  399. self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  400. self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
  401. self.aiTranslationLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  402. self.rightFullBox.isHidden = false
  403. self.rightTopBox.contentView = nil
  404. self.rightBottomBox.contentView = nil
  405. self.rightFullBox.contentView = self.aiTranslationViewController.view
  406. self.dragView.isHidden = false
  407. break
  408. case .AIRewriting:
  409. self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  410. self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
  411. self.aiRewritingLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  412. self.rightFullBox.isHidden = false
  413. self.rightTopBox.contentView = nil
  414. self.rightBottomBox.contentView = nil
  415. self.rightFullBox.contentView = self.aiRewritingViewController.view
  416. // self.aiRewritingViewController.state = .AIRewriting
  417. self.aiRewritingViewController.initLocalization()
  418. self.aiRewritingViewController.acquisition_uiState()
  419. self.dragView.isHidden = true
  420. break
  421. case .AIErrorCorrection:
  422. self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  423. self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
  424. self.aiErrorCorrectionLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  425. self.rightFullBox.isHidden = false
  426. self.rightTopBox.contentView = nil
  427. self.rightBottomBox.contentView = nil
  428. self.rightFullBox.contentView = self.aiRewritingViewController.view
  429. // self.aiRewritingViewController.state = .AIErrorCorrection
  430. self.aiRewritingViewController.initLocalization()
  431. self.aiRewritingViewController.acquisition_uiState()
  432. self.dragView.isHidden = true
  433. break
  434. default:
  435. break
  436. }
  437. }
  438. func fetchDifferentFilePath(filePath: String) -> String {
  439. var resultFilePath = filePath
  440. var index: Int = 0
  441. while (FileManager.default.fileExists(atPath: resultFilePath)) {
  442. index += 1
  443. let path = NSString(string: filePath).deletingPathExtension + "(" + String(index) + ")"
  444. resultFilePath = NSString(string: path).appendingPathExtension(NSString(string: filePath).pathExtension)!
  445. }
  446. return resultFilePath;
  447. }
  448. func showProgressWindow() {
  449. let progress = SKProgressController()
  450. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  451. progress.window?.contentView?.wantsLayer = true
  452. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  453. progress.progressField.textColor = NSColor.white
  454. progress.message = NSLocalizedString("Translating...", comment: "")
  455. progress.closeBlock = { [unowned self] in
  456. }
  457. self.progressController = progress
  458. self.view.window?.beginSheet(progress.window!)
  459. }
  460. func hiddenProgressWindow() {
  461. DispatchQueue.main.async {
  462. self.progressController?.doubleValue = 100.0
  463. }
  464. self.stopTimer()
  465. if (self.progressController != nil) {
  466. self.view.window?.endSheet((self.progressController?.window)!)
  467. self.progressController = nil
  468. }
  469. }
  470. func isFileGreaterThan10MB(atPath filePath: String) -> Bool {
  471. let fileManager = FileManager.default
  472. do {
  473. let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
  474. if let fileSize = fileAttributes[.size] as? UInt64 {
  475. let megabyteSize = fileSize / (1024 * 1024)
  476. return megabyteSize >= 10
  477. }
  478. } catch {
  479. KMPrint("Error: \(error)")
  480. }
  481. return false
  482. }
  483. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  484. let url = URL(fileURLWithPath: filePath)
  485. guard let document = PDFDocument(url: url) else {
  486. return false
  487. }
  488. let pageCount = document.pageCount
  489. return pageCount > 30
  490. }
  491. @objc func timerTick() {
  492. timerCounter += 1.0
  493. self.progressController?.increment(by: 1.0)
  494. if timerCounter >= 95 {
  495. stopTimer()
  496. }
  497. }
  498. func stopTimer() {
  499. timer?.invalidate()
  500. timer = nil
  501. }
  502. // MARK: Common methods
  503. func workSpaceOpenUrl(_ url: NSString) {
  504. let httpUrl: NSURL = NSURL.init(string: url as String)!
  505. let tWorkSpace: NSWorkspace = NSWorkspace.shared
  506. if !tWorkSpace.open(httpUrl as URL) {
  507. tWorkSpace.open(httpUrl as URL)
  508. }
  509. }
  510. }
  511. //MARK: Open Creat PDF
  512. extension KMHomeViewController: NSPopoverDelegate {
  513. }
  514. extension KMHomeViewController {
  515. func openPDFAction(_ sender: KMBox) {
  516. if needShowTabbingHintWindow() {
  517. showTabbingHintWindow()
  518. return
  519. }
  520. let openPanel = NSOpenPanel()
  521. openPanel.allowedFileTypes = ["pdf", "PDF"]
  522. openPanel.allowsMultipleSelection = false
  523. openPanel.beginSheetModal(for: self.view.window!) { (result) in
  524. if result == NSApplication.ModalResponse.OK {
  525. let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController
  526. if controll?.browser?.tabCount() ?? 0 > 1 && KMPreference.shared.openDocumentType == .newWindow{
  527. self.reopenDocument(forPaths: openPanel.url!)
  528. }else {
  529. NSDocumentController.shared.km_safe_limit_openDocument(withContentsOf: openPanel.url!, display: true) { (document, documentWasAlreadyOpen, error) in
  530. }
  531. }
  532. }
  533. }
  534. }
  535. func needShowTabbingHintWindow() -> Bool {
  536. let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController
  537. if controll?.browser?.tabCount() ?? 0 > 1 && !IAPProductsManager.default().isAvailableAllFunction() {
  538. return true
  539. }
  540. return false
  541. }
  542. func showTabbingHintWindow(){
  543. if !KMDataManager.default.isTabbingWin{
  544. KMDataManager.default.isTabbingWin = true
  545. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  546. tabbingWin.selectCallBack = { [weak self] continueOrNot in
  547. KMDataManager.default.isTabbingWin = false
  548. if continueOrNot {
  549. self?.reopenDocument(forPaths: nil)
  550. } else {
  551. }
  552. }
  553. self.km_beginSheet(windowC: tabbingWin)
  554. }
  555. }
  556. func creatPDFAction(_ sender: KMBox) {
  557. let popViewDataArr: [String] = [NSLocalizedString("New Blank Page", comment: ""),
  558. NSLocalizedString("New From Images", comment: ""),
  559. NSLocalizedString("New From Web Page", comment: ""),
  560. NSLocalizedString("Import From Camera", comment: ""),
  561. NSLocalizedString("Import From Scanner", comment: "")]
  562. let vc: KMHomePopViewController = KMHomePopViewController().initWithPopViewDataArr(popViewDataArr)
  563. vc.background = KMAppearance.Layout.bgColor()
  564. vc.textColor = KMAppearance.Layout.h0Color()
  565. vc.enterFillColor = KMAppearance.Interactive.s0Color()
  566. let createFilePopover: NSPopover = NSPopover.init()
  567. createFilePopover.contentViewController = vc
  568. createFilePopover.delegate = self
  569. createFilePopover.animates = true
  570. createFilePopover.behavior = .semitransient
  571. createFilePopover.setValue(true, forKey: "shouldHideAnchor")
  572. 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)
  573. vc.downCallback = { [unowned self] (downEntered: Bool, count: String) -> Void in
  574. if count == NSLocalizedString("New Blank Page", comment: "") {
  575. self.openBlankPage()
  576. } else if count == NSLocalizedString("Import From Camera", comment: "") {
  577. self.importFromCamera()
  578. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  579. self.importFromScanner()
  580. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  581. self.importFromWebPage()
  582. } else if count == NSLocalizedString("New From Images", comment: "") {
  583. self.newFromImages()
  584. }
  585. createFilePopover.close()
  586. }
  587. }
  588. func openBlankPage() {
  589. // let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  590. // let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
  591. // let filePath = savePath.deletingLastPathComponent
  592. // if FileManager.default.fileExists(atPath: filePath) == false {
  593. // try?FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false)
  594. // }
  595. //
  596. // let pdfDocument = CPDFDocument()
  597. // pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  598. // pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  599. // let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController
  600. // if controll?.browser?.tabCount() ?? 0 > 1 && KMPreference.shared.openDocumentType == .newWindow{
  601. // self.reopenDocument(forPaths: URL(fileURLWithPath: savePath))
  602. // }else {
  603. // NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  604. // if error != nil {
  605. // NSApp.presentError(error!)
  606. // } else {
  607. // if document is KMMainDocument {
  608. // let newDocument = document
  609. // (newDocument as! KMMainDocument).isNewCreated = true
  610. // }
  611. // }
  612. // // self.homeContentView?.reloadData()
  613. // }
  614. // }
  615. NSApplication.newBlankDocument()
  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. //
  757. // KMFunctionGuideWindowController.setDidShowFor(.functionMultiAIGuide)
  758. // }
  759. }
  760. func checkRepeatTrialExpiredController() -> Void {
  761. //试用过期提示比较表弹窗
  762. if didTrialExpiredLoad == true {
  763. return
  764. }
  765. didTrialExpiredLoad = true
  766. let singleTon = KMPurchaseCompareDMGWindowController.init()
  767. singleTon.showWindow(nil)
  768. if singleTon.className == KMPurchaseCompareDMGWindowController.className() {
  769. singleTon.updateTitle(NSLocalizedString("Trial Expired, Upgrade to Pro Version", comment: ""), andColor: NSColor(red: 1, green: 59/255, blue: 47/255, alpha: 1))
  770. }
  771. }
  772. func checkRepeatTrialAlertController() -> Void {
  773. //允许二次试用时弹出二次试用引导弹窗
  774. if repeatTrialAlertLoad == true {
  775. return
  776. }
  777. repeatTrialAlertLoad = true
  778. let vc = KMVerificationWindowController.verification(with:.repeatTrialGuide)
  779. vc?.showWindow(nil)
  780. }
  781. //MARK: 试用到期优惠券弹窗
  782. func checkTrialEndCouponInfo() {
  783. KMRequestServerManager.manager.getDeviceRetensionCoupon {[weak self] success, result in
  784. if success == true {
  785. if result != nil {
  786. guard let dataDict = result!["data"] as? NSDictionary else {
  787. return
  788. }
  789. // if dataDict!["pop_up"] as? Bool == true {
  790. let discount = dataDict["discount"] as? Int
  791. let coupon_code = dataDict["coupon_code"] as? String
  792. let end_up_at = dataDict["end_up_at"] as? String
  793. let pop_up = dataDict["pop_up"] as? Bool
  794. if pop_up == true {
  795. if let versionKey = KMAdsInfoManager.shareInstance.couponInfo?.versionKey {
  796. if KMAdsInfoManager.shareInstance.couponInfo?.show == true {
  797. if (UserDefaults.standard.object(forKey: versionKey) != nil) {
  798. } else {
  799. UserDefaults.standard.set("Show", forKey: versionKey)
  800. UserDefaults.standard.synchronize()
  801. self?.showCouponInfoWindow(discount: discount, couponCode: coupon_code, endUpAt: end_up_at)
  802. }
  803. }
  804. }
  805. }
  806. }
  807. } else {
  808. #if VERSION_DMG
  809. if KMVerificationWindowController.allowsShowExpired() {
  810. self?.checkRepeatTrialExpiredController()
  811. } else if KMVerificationWindowController.allowRepeatTrialAlertShow() {
  812. self?.checkRepeatTrialAlertController()
  813. }
  814. #endif
  815. }
  816. }
  817. }
  818. func showCouponInfoWindow(discount: Int?, couponCode: String?, endUpAt: String?) {
  819. }
  820. // MARK: - Noti Actions
  821. func deviceVerifyFinishNotification(_ sender: Notification) {
  822. #if VERSION_DMG
  823. #endif
  824. }
  825. @objc func aiTipIconViewShowStateChangeNoti() {
  826. }
  827. }