KMHomeViewController.swift 31 KB

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