KMHomeViewController.swift 28 KB

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