KMHomeViewController.swift 29 KB

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