KMNBaseViewController.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. //
  2. // KMNBaseViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2023/5/5.
  6. //
  7. import Cocoa
  8. // 基类 [抽象类]
  9. class KMNBaseViewController: NSViewController {
  10. // 是否需要菜单
  11. var needMenu = false {
  12. didSet {
  13. if (self.needMenu) {
  14. self.addMenu(to: self.view)
  15. } else {
  16. self.removeMenu(to: self.view)
  17. }
  18. }
  19. }
  20. deinit {
  21. KMPrint(self.className + " deinit.")
  22. self.removeNotifations()
  23. }
  24. override func viewDidLoad() {
  25. super.viewDidLoad()
  26. if (self.needMenu) {
  27. self.addMenu(to: self.view)
  28. } else {
  29. self.removeMenu(to: self.view)
  30. }
  31. self.addNotifations()
  32. }
  33. func updateUIThemeColor() {}
  34. // Noti
  35. func addNotifations() { }
  36. func removeNotifations() {
  37. NotificationCenter.default.removeObserver(self)
  38. }
  39. func km_add_office_multi(fileUrls: [URL], completionBlock:@escaping ([String])->Void) -> Void {
  40. var fileUrlStrings: [String] = []
  41. let dispatchGroup = Dispatch.DispatchGroup()
  42. for (index, fileUrl) in fileUrls.enumerated() {
  43. let filePath = fileUrl.path
  44. let folderPath = "convertToPDF_\(index).pdf"
  45. let savePath: String? = folderPath.kUrlToPDFFolderPath() as String
  46. if (savePath == nil) {
  47. continue
  48. }
  49. dispatchGroup.enter()
  50. KMConvertPDFManager.convertFile(filePath, savePath: savePath!) { success, errorDic in
  51. if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) {
  52. dispatchGroup.leave()
  53. if FileManager.default.fileExists(atPath: savePath!) {
  54. try?FileManager.default.removeItem(atPath: savePath!)
  55. }
  56. let alert = NSAlert.init()
  57. alert.alertStyle = .critical
  58. var infoString = ""
  59. if errorDic != nil {
  60. for key in (errorDic! as Dictionary).keys {
  61. infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg)
  62. }
  63. }
  64. alert.informativeText = NSLocalizedString("Please install Microsoft Office to create PDFs from Office files", comment: "")
  65. alert.messageText = NSLocalizedString("Failed to Create PDF", comment: "")
  66. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  67. alert.runModal()
  68. return
  69. }
  70. if !savePath!.isPDFValid() {
  71. dispatchGroup.leave()
  72. let alert = NSAlert()
  73. alert.alertStyle = .critical
  74. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  75. alert.runModal()
  76. return
  77. }
  78. fileUrlStrings.append(savePath!)
  79. dispatchGroup.leave()
  80. }
  81. }
  82. dispatchGroup.notify(queue: DispatchQueue.main) {
  83. completionBlock(fileUrlStrings)
  84. }
  85. }
  86. // MARK: - Open Password Files
  87. private var lockedFiles: [URL] = []
  88. func km_open_pdf_multi(type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  89. NSPanel.km_open_pdf_multi_success(self.view.window!, panel: nil) { urls in
  90. self.km_add_pdf_multi(fileUrls: urls, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
  91. }
  92. }
  93. func km_open_file_multi(type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  94. NSPanel.km_open_multi_success(self.view.window!) { panel in
  95. var array: [String] = []
  96. for fileType in KMConvertPDFManager.supportFileType() {
  97. array.append(fileType)
  98. }
  99. panel.allowedFileTypes = KMTools.pdfExtensions + array
  100. } completion: { urls in
  101. self.km_add_file_multi(fileUrls: urls, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
  102. }
  103. }
  104. func km_add_pdf_multi(fileUrlStrings: [String] ,type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  105. var urls: [URL] = []
  106. for string in fileUrlStrings {
  107. urls.append(URL(fileURLWithPath: string))
  108. }
  109. self.km_add_pdf_multi(fileUrls: urls, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
  110. }
  111. func km_add_pdf_multi(fileUrls: [URL] ,type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  112. var results: [CPDFDocument] = []
  113. self.lockedFiles.removeAll()
  114. var index = 0
  115. for url in fileUrls {
  116. let document = CPDFDocument(url: url)
  117. if (document!.isLocked) {
  118. self.lockedFiles.append(url)
  119. continue
  120. }
  121. if let _document = document {
  122. results.append(_document)
  123. }
  124. index += 1
  125. if let _callback = progressBlock {
  126. _callback(index, ((document != nil) ? document : CPDFDocument()) as Any, url)
  127. }
  128. }
  129. if (self.lockedFiles.count == 0) {
  130. completionBlock(results)
  131. return
  132. }
  133. // if let _callback = progressBlock {
  134. // _callback(0, results)
  135. // }
  136. self._openPasswordWindow_loop(fileUrl: self.lockedFiles.first!, type: type) { params in
  137. index += 1
  138. if (params.count <= 2) { // 参数错误
  139. if let _callback = progressBlock { // 回调进度
  140. _callback(index)
  141. }
  142. return
  143. }
  144. let fileUrl = params[0] as! URL
  145. let result = params[1] as! KMPasswordInputWindowResult
  146. let password = params[2] as? String
  147. if (result == .cancel) {
  148. if let _callback = progressBlock { // 回调进度
  149. _callback(index, CPDFDocument() as Any, fileUrl, result)
  150. }
  151. return
  152. }
  153. let document = CPDFDocument(url: fileUrl)
  154. if let _password = password { // 将文档进行解密
  155. document?.unlock(withPassword: _password)
  156. }
  157. if let _callback = progressBlock { // 回调进度
  158. _callback(index, document as Any, fileUrl, result, password as Any)
  159. }
  160. // 将文档加入返回数据
  161. if let _document = document {
  162. results.append(_document)
  163. }
  164. } completionBlock: {
  165. completionBlock(results)
  166. }
  167. }
  168. func km_add_file_multi(fileUrls: [URL] ,type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  169. var pdfUrls: [URL] = []
  170. var imageUrls: [URL] = []
  171. var officeUrls: [URL] = []
  172. for url in fileUrls {
  173. let type = url.pathExtension.lowercased()
  174. if (KMTools.isPDFType(type)) {
  175. pdfUrls.append(url)
  176. }
  177. if (KMTools.isImageType(type)) {
  178. imageUrls.append(url)
  179. }
  180. if (KMTools.isOfficeType(type)) {
  181. officeUrls.append(url)
  182. }
  183. }
  184. if (officeUrls.count == 0) {
  185. self.km_add_pdf_multi(fileUrls: pdfUrls, type: type, progressBlock: progressBlock) { documents in
  186. var index = documents.count
  187. var _documents: [CPDFDocument] = []
  188. for imageUrl in imageUrls {
  189. index += 1
  190. let document = CPDFDocument()
  191. let image = NSImage(contentsOfFile: imageUrl.path)
  192. // document?.insertPage(image!.size, withImage: imageUrl.path, at: 0)
  193. document?.km_insertPage(image?.size ?? .zero, withImage: imageUrl.path, at: 0)
  194. _documents.append(document!)
  195. if let _callback = progressBlock { // 回调进度
  196. _callback(index, document as Any, imageUrl)
  197. }
  198. }
  199. completionBlock(documents + _documents)
  200. }
  201. return
  202. }
  203. self.km_add_office_multi(fileUrls: officeUrls) { [unowned self] fileUrlStrings in
  204. var officeDocuments: [CPDFDocument] = []
  205. var index = 0
  206. for fileUrlString in fileUrlStrings {
  207. index += 1
  208. let document = CPDFDocument(url: URL(fileURLWithPath: fileUrlString))
  209. officeDocuments.append(document!)
  210. if let _callback = progressBlock { // 回调进度
  211. _callback(index, document as Any, URL(fileURLWithPath: fileUrlString))
  212. }
  213. }
  214. self.km_add_pdf_multi(fileUrls: pdfUrls) { documents in
  215. var index = documents.count + officeDocuments.count
  216. var _documents: [CPDFDocument] = []
  217. for imageUrl in imageUrls {
  218. index += 1
  219. let document = CPDFDocument()
  220. let image = NSImage(contentsOfFile: imageUrl.path)
  221. // document?.insertPage(image!.size, withImage: imageUrl.path, at: 0)
  222. document?.km_insertPage(image!.size, withImage: imageUrl.path, at: 0)
  223. _documents.append(document!)
  224. if let _callback = progressBlock { // 回调进度
  225. _callback(index, document as Any, imageUrl)
  226. }
  227. }
  228. completionBlock(officeDocuments + documents + _documents)
  229. }
  230. }
  231. }
  232. // MARK: - ProgressBlock Params Fetch
  233. func fetchProgressBlockParamsForDocument(params: Any...) -> CPDFDocument? {
  234. return params.first as? CPDFDocument
  235. }
  236. func fetchProgressBlockParamsForFileUrl(params: Any...) -> URL? {
  237. if (params.count < 2) {
  238. return nil
  239. }
  240. return params[1] as? URL
  241. }
  242. func fetchProgressBlockParamsForResult(params: Any...) -> KMPasswordInputWindowResult? {
  243. if (params.count <= 2) {
  244. return nil
  245. }
  246. return params[2] as? KMPasswordInputWindowResult
  247. }
  248. func fetchProgressBlockParamsForPassword(params: Any...) -> String? {
  249. if (params.count <= 2) {
  250. return nil
  251. }
  252. return params.last as? String
  253. }
  254. func fetchProgressBlockParamsIsPasswordFile(params: Any...) -> Bool {
  255. if (params.count <= 2) {
  256. return false
  257. }
  258. return true
  259. }
  260. // MARK: - Open Password Window
  261. // 留意:
  262. // -会直接弹密码弹窗,不会判断文档是否加密
  263. // -在使用前最好判断下文件是否已加密
  264. func openPasswordWindow(fileUrlString: String, type: KMPasswordInputWindowType = .open, completionBlock:@escaping (KMPasswordInputWindowResult, String?)->Void) {
  265. self.openPasswordWindow(fileUrl: URL(fileURLWithPath: fileUrlString), type: type, completionBlock: completionBlock)
  266. }
  267. func openPasswordWindow(fileUrl: URL, type: KMPasswordInputWindowType = .open, completionBlock:@escaping (KMPasswordInputWindowResult, String?)->Void) {
  268. KMPasswordInputWindow.openWindow(window: self.view.window!, type: type, url: fileUrl, callback: completionBlock)
  269. }
  270. func openPasswordWindow_success(fileUrlString: String, type: KMPasswordInputWindowType = .open, completionBlock:@escaping (String)->Void) {
  271. self.openPasswordWindow_success(fileUrl: URL(fileURLWithPath: fileUrlString), type: type, completionBlock: completionBlock)
  272. }
  273. func openPasswordWindow_success(fileUrl: URL, type: KMPasswordInputWindowType = .open, completionBlock:@escaping (String)->Void) {
  274. KMPasswordInputWindow.success_openWindow(window: self.view.window!, url: fileUrl, callback: completionBlock)
  275. }
  276. fileprivate func _openPasswordWindow_loop(fileUrl: URL, type: KMPasswordInputWindowType, progressBlock: ((_ params: Any...)->Void)?, completionBlock:@escaping ()->Void) {
  277. KMPasswordInputWindow.openWindow(window: self.view.window!, type: type, url: fileUrl) { [weak self] result, password in
  278. // 将结果返回
  279. if let _callback = progressBlock {
  280. _callback(fileUrl, result, password as Any)
  281. }
  282. // 进行下一个
  283. self?.lockedFiles.removeFirst()
  284. if let _fileUrl = self?.lockedFiles.first {
  285. self?._openPasswordWindow_loop(fileUrl: _fileUrl, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
  286. } else {
  287. completionBlock()
  288. }
  289. }
  290. }
  291. // MARK: - Progress Window
  292. var progressC: SKProgressController?
  293. func showProgressWindow(message: String = "") {
  294. if (self.progressC != nil) {
  295. self.hiddenProgressWindow()
  296. }
  297. let progressC = SKProgressController()
  298. progressC.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  299. progressC.window?.contentView?.wantsLayer = true
  300. progressC.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  301. progressC.progressField.textColor = NSColor.white
  302. progressC.showClose = false
  303. progressC.message = message
  304. self.progressC = progressC
  305. self.view.window?.beginSheet(progressC.window!)
  306. }
  307. func hiddenProgressWindow() {
  308. if let _progressC = self.progressC {
  309. if let _window = _progressC.window {
  310. self.view.window?.endSheet(_window)
  311. }
  312. self.progressC = nil
  313. }
  314. }
  315. // MARK: - Menu Add & Remove
  316. public func addMenu(to view: NSView?) {
  317. if let menuView = view {
  318. self.addMenu(to: menuView)
  319. return
  320. }
  321. self.addMenu(to: self.view)
  322. }
  323. public func removeMenu(to view: NSView?) {
  324. if let menuView = view {
  325. self.removeMenu(to: menuView)
  326. return
  327. }
  328. self.removeMenu(to: self.view)
  329. }
  330. private func addMenu(to view: NSView) {
  331. // 先移除
  332. self.removeMenu(to: view)
  333. let menu = NSMenu()
  334. menu.delegate = self
  335. view.menu = menu
  336. }
  337. private func removeMenu(to view: NSView) {
  338. view.menu?.delegate = nil
  339. view.menu = nil
  340. }
  341. // MARK: - Document isDocumentEdited
  342. public func setDocumentEditedState(window: NSWindow? = nil) {
  343. var _win = window
  344. if (_win == nil) {
  345. _win = self.view.window
  346. }
  347. guard let _window = _win else {
  348. return
  349. }
  350. guard let _document = NSDocumentController.shared.document(for: _window) else {
  351. return
  352. }
  353. self.setDocumentEditedState(document: _document)
  354. }
  355. public func setDocumentEditedState(url: URL? = nil) {
  356. if let _url = url {
  357. KMTools.setDocumentEditedState(url: _url)
  358. } else {
  359. self.setDocumentEditedState(window: self.view.window)
  360. }
  361. }
  362. public func setDocumentEditedState(document: NSDocument) {
  363. km_synchronized(document) {
  364. if let _document = document as? KMMainDocument {
  365. _document.km_updateChangeCount(.changeDone)
  366. } else {
  367. document.updateChangeCount(.changeDone)
  368. }
  369. }
  370. }
  371. public func clearDocumentEditedState(window: NSWindow? = nil) {
  372. var _win = window
  373. if (_win == nil) {
  374. _win = self.view.window
  375. }
  376. guard let _window = _win else {
  377. return
  378. }
  379. guard let _document = NSDocumentController.shared.document(for: _window) else {
  380. return
  381. }
  382. self.clearDocumentEditedState(document: _document)
  383. }
  384. public func clearDocumentEditedState(url: URL? = nil) {
  385. if let _url = url {
  386. KMTools.clearDocumentEditedState(url: _url)
  387. } else {
  388. self.clearDocumentEditedState(window: self.view.window)
  389. }
  390. }
  391. public func clearDocumentEditedState(document: NSDocument) {
  392. km_synchronized(document) {
  393. if let _document = document as? KMMainDocument {
  394. _document.km_updateChangeCount(.changeCleared)
  395. } else {
  396. document.updateChangeCount(.changeCleared)
  397. }
  398. }
  399. }
  400. }
  401. extension KMNBaseViewController: NSMenuDelegate, NSMenuItemValidation {
  402. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  403. return true
  404. }
  405. func menuNeedsUpdate(_ menu: NSMenu) {
  406. menu.removeAllItems()
  407. }
  408. }