KMHomeViewController.swift 31 KB

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