KMHomeViewController.swift 34 KB

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