KMBaseViewController.swift 18 KB

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