KMHomeViewController.swift 31 KB

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