KMHomeViewController.swift 33 KB

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