KMHomeViewController.swift 29 KB

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