KMHomeViewController.swift 33 KB

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