KMBaseViewController.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. //
  2. // KMBaseViewController.swift
  3. // PDF Master
  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. override func viewDidLoad() {
  21. super.viewDidLoad()
  22. if (self.needMenu) {
  23. self.addMenu(to: self.view)
  24. } else {
  25. self.removeMenu(to: self.view)
  26. }
  27. }
  28. func km_add_office_multi(fileUrls: [URL], completionBlock:@escaping ([String])->Void) -> Void {
  29. var fileUrlStrings: [String] = []
  30. let dispatchGroup = Dispatch.DispatchGroup()
  31. for (index, fileUrl) in fileUrls.enumerated() {
  32. let filePath = fileUrl.path
  33. let folderPath = "convertToPDF_\(index).pdf"
  34. let savePath = folderPath.kUrlToPDFFolderPath()
  35. if (savePath == nil) {
  36. continue
  37. }
  38. dispatchGroup.enter()
  39. KMConvertPDFManagerOC.convertFile(filePath, savePath: savePath!) { success, errorDic in
  40. if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) {
  41. dispatchGroup.leave()
  42. if FileManager.default.fileExists(atPath: savePath!) {
  43. try?FileManager.default.removeItem(atPath: savePath!)
  44. }
  45. let alert = NSAlert.init()
  46. alert.alertStyle = .critical
  47. var infoString = ""
  48. if errorDic != nil {
  49. for key in (errorDic! as Dictionary).keys {
  50. infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg)
  51. }
  52. }
  53. alert.informativeText = NSLocalizedString("Please install Microsoft Office to create PDFs from Office files", comment: "")
  54. alert.messageText = NSLocalizedString("Failed to Create PDF", comment: "")
  55. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  56. alert.runModal()
  57. return
  58. }
  59. if !savePath!.isPDFValid() {
  60. dispatchGroup.leave()
  61. let alert = NSAlert()
  62. alert.alertStyle = .critical
  63. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  64. alert.runModal()
  65. return
  66. }
  67. fileUrlStrings.append(savePath!)
  68. dispatchGroup.leave()
  69. }
  70. }
  71. dispatchGroup.notify(queue: DispatchQueue.main) {
  72. completionBlock(fileUrlStrings)
  73. }
  74. }
  75. // MARK: - Open Password Files
  76. private var lockedFiles: [URL] = []
  77. func km_open_pdf_multi(type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  78. NSPanel.km_open_pdf_multi_success(self.view.window!, panel: nil) { urls in
  79. self.km_add_pdf_multi(fileUrls: urls, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
  80. }
  81. }
  82. func km_open_file_multi(type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  83. NSPanel.km_open_multi_success(self.view.window!) { panel in
  84. var array: [String] = []
  85. for fileType in KMConvertPDFManagerOC.supportFileType() {
  86. if let string = fileType as? String {
  87. array.append(string)
  88. }
  89. }
  90. panel.allowedFileTypes = KMTools.pdfExtensions + array
  91. } completion: { urls in
  92. self.km_add_file_multi(fileUrls: urls, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
  93. }
  94. }
  95. func km_add_pdf_multi(fileUrlStrings: [String] ,type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  96. var urls: [URL] = []
  97. for string in fileUrlStrings {
  98. urls.append(URL(fileURLWithPath: string))
  99. }
  100. self.km_add_pdf_multi(fileUrls: urls, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
  101. }
  102. func km_add_pdf_multi(fileUrls: [URL] ,type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  103. var results: [CPDFDocument] = []
  104. self.lockedFiles.removeAll()
  105. for url in fileUrls {
  106. let document = CPDFDocument(url: url)
  107. if (document!.isLocked) {
  108. self.lockedFiles.append(url)
  109. continue
  110. }
  111. if let _document = document {
  112. results.append(_document)
  113. }
  114. }
  115. if (self.lockedFiles.count == 0) {
  116. completionBlock(results)
  117. return
  118. }
  119. if let _callback = progressBlock {
  120. _callback(0, results)
  121. }
  122. var index = 0
  123. self._openPasswordWindow_loop(fileUrl: self.lockedFiles.first!, type: type) { params in
  124. index += 1
  125. if (params.count <= 2) { // 参数错误
  126. if let _callback = progressBlock { // 回调进度
  127. _callback(index)
  128. }
  129. return
  130. }
  131. let fileUrl = params[0] as! URL
  132. let result = params[1] as! KMPasswordInputWindowResult
  133. let password = params[2] as? String
  134. if (result == .cancel) {
  135. if let _callback = progressBlock { // 回调进度
  136. _callback(index, fileUrl, result)
  137. }
  138. return
  139. }
  140. let document = CPDFDocument(url: fileUrl)
  141. if let _password = password { // 将文档进行解密
  142. document?.unlock(withPassword: _password)
  143. }
  144. if let _callback = progressBlock { // 回调进度
  145. _callback(index, document as Any, fileUrl, result, password as Any)
  146. }
  147. // 将文档加入返回数据
  148. if let _document = document {
  149. results.append(_document)
  150. }
  151. } completionBlock: {
  152. completionBlock(results)
  153. }
  154. }
  155. func km_add_file_multi(fileUrls: [URL] ,type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  156. var pdfUrls: [URL] = []
  157. var imageUrls: [URL] = []
  158. var officeUrls: [URL] = []
  159. for url in fileUrls {
  160. let type = url.pathExtension.lowercased()
  161. if (KMTools.isPDFType(type)) {
  162. pdfUrls.append(url)
  163. }
  164. if (KMTools.isImageType(type)) {
  165. imageUrls.append(url)
  166. }
  167. if (KMTools.isOfficeType(type)) {
  168. officeUrls.append(url)
  169. }
  170. }
  171. if (officeUrls.count == 0) {
  172. self.km_add_pdf_multi(fileUrls: pdfUrls, type: type, progressBlock: progressBlock) { documents in
  173. var index = documents.count
  174. var _documents: [CPDFDocument] = []
  175. for imageUrl in imageUrls {
  176. index += 1
  177. let document = CPDFDocument()
  178. let image = NSImage(contentsOfFile: imageUrl.path)
  179. document?.insertPage(image!.size, withImage: imageUrl.path, at: 0)
  180. _documents.append(document!)
  181. if let _callback = progressBlock { // 回调进度
  182. _callback(index, document as Any, imageUrl)
  183. }
  184. }
  185. completionBlock(documents + _documents)
  186. }
  187. return
  188. }
  189. self.km_add_office_multi(fileUrls: officeUrls) { [unowned self] fileUrlStrings in
  190. var officeDocuments: [CPDFDocument] = []
  191. var index = 0
  192. for fileUrlString in fileUrlStrings {
  193. index += 1
  194. let document = CPDFDocument(url: URL(fileURLWithPath: fileUrlString))
  195. officeDocuments.append(document!)
  196. if let _callback = progressBlock { // 回调进度
  197. _callback(index, document as Any, URL(fileURLWithPath: fileUrlString))
  198. }
  199. }
  200. self.km_add_pdf_multi(fileUrls: pdfUrls) { documents in
  201. var index = documents.count + officeDocuments.count
  202. var _documents: [CPDFDocument] = []
  203. for imageUrl in imageUrls {
  204. index += 1
  205. let document = CPDFDocument()
  206. let image = NSImage(contentsOfFile: imageUrl.path)
  207. document?.insertPage(image!.size, withImage: imageUrl.path, at: 0)
  208. _documents.append(document!)
  209. if let _callback = progressBlock { // 回调进度
  210. _callback(index, document as Any, imageUrl)
  211. }
  212. }
  213. completionBlock(officeDocuments + documents + _documents)
  214. }
  215. }
  216. }
  217. // MARK: - Open Password Window
  218. // 留意:
  219. // -会直接弹密码弹窗,不会判断文档是否加密
  220. // -在使用前最好判断下文件是否已加密
  221. func openPasswordWindow(fileUrlString: String, type: KMPasswordInputWindowType = .open, completionBlock:@escaping (KMPasswordInputWindowResult, String?)->Void) {
  222. self.openPasswordWindow(fileUrl: URL(fileURLWithPath: fileUrlString), type: type, completionBlock: completionBlock)
  223. }
  224. func openPasswordWindow(fileUrl: URL, type: KMPasswordInputWindowType = .open, completionBlock:@escaping (KMPasswordInputWindowResult, String?)->Void) {
  225. KMPasswordInputWindow.openWindow(window: self.view.window!, type: type, url: fileUrl, callback: completionBlock)
  226. }
  227. func openPasswordWindow_success(fileUrlString: String, type: KMPasswordInputWindowType = .open, completionBlock:@escaping (String)->Void) {
  228. self.openPasswordWindow_success(fileUrl: URL(fileURLWithPath: fileUrlString), type: type, completionBlock: completionBlock)
  229. }
  230. func openPasswordWindow_success(fileUrl: URL, type: KMPasswordInputWindowType = .open, completionBlock:@escaping (String)->Void) {
  231. KMPasswordInputWindow.success_openWindow(window: self.view.window!, url: fileUrl, callback: completionBlock)
  232. }
  233. fileprivate func _openPasswordWindow_loop(fileUrl: URL, type: KMPasswordInputWindowType, progressBlock: ((_ params: Any...)->Void)?, completionBlock:@escaping ()->Void) {
  234. KMPasswordInputWindow.openWindow(window: self.view.window!, type: type, url: fileUrl) { [weak self] result, password in
  235. // 将结果返回
  236. if let _callback = progressBlock {
  237. _callback(fileUrl, result, password as Any)
  238. }
  239. // 进行下一个
  240. self?.lockedFiles.removeFirst()
  241. if let _fileUrl = self?.lockedFiles.first {
  242. self?._openPasswordWindow_loop(fileUrl: _fileUrl, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
  243. } else {
  244. completionBlock()
  245. }
  246. }
  247. }
  248. // MARK: - Progress Window
  249. var progressC: SKProgressController?
  250. func showProgressWindow(message: String = "") {
  251. if (self.progressC != nil) {
  252. self.hiddenProgressWindow()
  253. }
  254. let progressC = SKProgressController()
  255. progressC.showClose = false
  256. progressC.message = message
  257. progressC.window?.backgroundColor = NSColor(hex: "#36383B")
  258. progressC.window?.contentView?.wantsLayer = true
  259. progressC.window?.contentView?.layer?.backgroundColor = NSColor(hex: "#36383B").cgColor
  260. progressC.progressField.textColor = NSColor.white
  261. self.progressC = progressC
  262. self.view.window?.beginSheet(progressC.window!)
  263. }
  264. func hiddenProgressWindow() {
  265. if let _progressC = self.progressC {
  266. if let _window = _progressC.window {
  267. self.view.window?.endSheet(_window)
  268. }
  269. self.progressC = nil
  270. }
  271. }
  272. // MARK: - Menu Add & Remove
  273. public func addMenu(to view: NSView?) {
  274. if let menuView = view {
  275. self.addMenu(to: menuView)
  276. return
  277. }
  278. self.addMenu(to: self.view)
  279. }
  280. public func removeMenu(to view: NSView?) {
  281. if let menuView = view {
  282. self.removeMenu(to: menuView)
  283. return
  284. }
  285. self.removeMenu(to: self.view)
  286. }
  287. private func addMenu(to view: NSView) {
  288. // 先移除
  289. self.removeMenu(to: view)
  290. let menu = NSMenu()
  291. menu.delegate = self
  292. view.menu = menu
  293. }
  294. private func removeMenu(to view: NSView) {
  295. view.menu?.delegate = nil
  296. view.menu = nil
  297. }
  298. }
  299. extension KMBaseViewController: NSMenuDelegate, NSMenuItemValidation {
  300. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  301. return true
  302. }
  303. func menuNeedsUpdate(_ menu: NSMenu) {
  304. menu.removeAllItems()
  305. }
  306. }