KMBaseViewController.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. var index = 0
  106. for url in fileUrls {
  107. let document = CPDFDocument(url: url)
  108. if (document!.isLocked) {
  109. self.lockedFiles.append(url)
  110. continue
  111. }
  112. if let _document = document {
  113. results.append(_document)
  114. }
  115. index += 1
  116. if let _callback = progressBlock {
  117. _callback(index, ((document != nil) ? document : CPDFDocument()) as Any, url)
  118. }
  119. }
  120. if (self.lockedFiles.count == 0) {
  121. completionBlock(results)
  122. return
  123. }
  124. // if let _callback = progressBlock {
  125. // _callback(0, results)
  126. // }
  127. self._openPasswordWindow_loop(fileUrl: self.lockedFiles.first!, type: type) { params in
  128. index += 1
  129. if (params.count <= 2) { // 参数错误
  130. if let _callback = progressBlock { // 回调进度
  131. _callback(index)
  132. }
  133. return
  134. }
  135. let fileUrl = params[0] as! URL
  136. let result = params[1] as! KMPasswordInputWindowResult
  137. let password = params[2] as? String
  138. if (result == .cancel) {
  139. if let _callback = progressBlock { // 回调进度
  140. _callback(index, CPDFDocument() as Any, fileUrl, result)
  141. }
  142. return
  143. }
  144. let document = CPDFDocument(url: fileUrl)
  145. if let _password = password { // 将文档进行解密
  146. document?.unlock(withPassword: _password)
  147. }
  148. if let _callback = progressBlock { // 回调进度
  149. _callback(index, document as Any, fileUrl, result, password as Any)
  150. }
  151. // 将文档加入返回数据
  152. if let _document = document {
  153. results.append(_document)
  154. }
  155. } completionBlock: {
  156. completionBlock(results)
  157. }
  158. }
  159. func km_add_file_multi(fileUrls: [URL] ,type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  160. var pdfUrls: [URL] = []
  161. var imageUrls: [URL] = []
  162. var officeUrls: [URL] = []
  163. for url in fileUrls {
  164. let type = url.pathExtension.lowercased()
  165. if (KMTools.isPDFType(type)) {
  166. pdfUrls.append(url)
  167. }
  168. if (KMTools.isImageType(type)) {
  169. imageUrls.append(url)
  170. }
  171. if (KMTools.isOfficeType(type)) {
  172. officeUrls.append(url)
  173. }
  174. }
  175. if (officeUrls.count == 0) {
  176. self.km_add_pdf_multi(fileUrls: pdfUrls, type: type, progressBlock: progressBlock) { documents in
  177. var index = documents.count
  178. var _documents: [CPDFDocument] = []
  179. for imageUrl in imageUrls {
  180. index += 1
  181. let document = CPDFDocument()
  182. let image = NSImage(contentsOfFile: imageUrl.path)
  183. document?.insertPage(image!.size, withImage: imageUrl.path, at: 0)
  184. _documents.append(document!)
  185. if let _callback = progressBlock { // 回调进度
  186. _callback(index, document as Any, imageUrl)
  187. }
  188. }
  189. completionBlock(documents + _documents)
  190. }
  191. return
  192. }
  193. self.km_add_office_multi(fileUrls: officeUrls) { [unowned self] fileUrlStrings in
  194. var officeDocuments: [CPDFDocument] = []
  195. var index = 0
  196. for fileUrlString in fileUrlStrings {
  197. index += 1
  198. let document = CPDFDocument(url: URL(fileURLWithPath: fileUrlString))
  199. officeDocuments.append(document!)
  200. if let _callback = progressBlock { // 回调进度
  201. _callback(index, document as Any, URL(fileURLWithPath: fileUrlString))
  202. }
  203. }
  204. self.km_add_pdf_multi(fileUrls: pdfUrls) { documents in
  205. var index = documents.count + officeDocuments.count
  206. var _documents: [CPDFDocument] = []
  207. for imageUrl in imageUrls {
  208. index += 1
  209. let document = CPDFDocument()
  210. let image = NSImage(contentsOfFile: imageUrl.path)
  211. document?.insertPage(image!.size, withImage: imageUrl.path, at: 0)
  212. _documents.append(document!)
  213. if let _callback = progressBlock { // 回调进度
  214. _callback(index, document as Any, imageUrl)
  215. }
  216. }
  217. completionBlock(officeDocuments + documents + _documents)
  218. }
  219. }
  220. }
  221. // MARK: - ProgressBlock Params Fetch
  222. func fetchProgressBlockParamsForDocument(params: Any...) -> CPDFDocument? {
  223. return params.first as? CPDFDocument
  224. }
  225. func fetchProgressBlockParamsForFileUrl(params: Any...) -> URL? {
  226. if (params.count < 2) {
  227. return nil
  228. }
  229. return params[1] as? URL
  230. }
  231. func fetchProgressBlockParamsForResult(params: Any...) -> KMPasswordInputWindowResult? {
  232. if (params.count <= 2) {
  233. return nil
  234. }
  235. return params[2] as? KMPasswordInputWindowResult
  236. }
  237. func fetchProgressBlockParamsForPassword(params: Any...) -> String? {
  238. if (params.count <= 2) {
  239. return nil
  240. }
  241. return params.last as? String
  242. }
  243. func fetchProgressBlockParamsIsPasswordFile(params: Any...) -> Bool {
  244. if (params.count <= 2) {
  245. return false
  246. }
  247. return true
  248. }
  249. // MARK: - Open Password Window
  250. // 留意:
  251. // -会直接弹密码弹窗,不会判断文档是否加密
  252. // -在使用前最好判断下文件是否已加密
  253. func openPasswordWindow(fileUrlString: String, type: KMPasswordInputWindowType = .open, completionBlock:@escaping (KMPasswordInputWindowResult, String?)->Void) {
  254. self.openPasswordWindow(fileUrl: URL(fileURLWithPath: fileUrlString), type: type, completionBlock: completionBlock)
  255. }
  256. func openPasswordWindow(fileUrl: URL, type: KMPasswordInputWindowType = .open, completionBlock:@escaping (KMPasswordInputWindowResult, String?)->Void) {
  257. KMPasswordInputWindow.openWindow(window: self.view.window!, type: type, url: fileUrl, callback: completionBlock)
  258. }
  259. func openPasswordWindow_success(fileUrlString: String, type: KMPasswordInputWindowType = .open, completionBlock:@escaping (String)->Void) {
  260. self.openPasswordWindow_success(fileUrl: URL(fileURLWithPath: fileUrlString), type: type, completionBlock: completionBlock)
  261. }
  262. func openPasswordWindow_success(fileUrl: URL, type: KMPasswordInputWindowType = .open, completionBlock:@escaping (String)->Void) {
  263. KMPasswordInputWindow.success_openWindow(window: self.view.window!, url: fileUrl, callback: completionBlock)
  264. }
  265. fileprivate func _openPasswordWindow_loop(fileUrl: URL, type: KMPasswordInputWindowType, progressBlock: ((_ params: Any...)->Void)?, completionBlock:@escaping ()->Void) {
  266. KMPasswordInputWindow.openWindow(window: self.view.window!, type: type, url: fileUrl) { [weak self] result, password in
  267. // 将结果返回
  268. if let _callback = progressBlock {
  269. _callback(fileUrl, result, password as Any)
  270. }
  271. // 进行下一个
  272. self?.lockedFiles.removeFirst()
  273. if let _fileUrl = self?.lockedFiles.first {
  274. self?._openPasswordWindow_loop(fileUrl: _fileUrl, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
  275. } else {
  276. completionBlock()
  277. }
  278. }
  279. }
  280. // MARK: - Progress Window
  281. var progressC: SKProgressController?
  282. func showProgressWindow(message: String = "") {
  283. if (self.progressC != nil) {
  284. self.hiddenProgressWindow()
  285. }
  286. let progressC = SKProgressController()
  287. progressC.showClose = false
  288. progressC.message = message
  289. progressC.window?.backgroundColor = NSColor(hex: "#36383B")
  290. progressC.window?.contentView?.wantsLayer = true
  291. progressC.window?.contentView?.layer?.backgroundColor = NSColor(hex: "#36383B").cgColor
  292. progressC.progressField.textColor = NSColor.white
  293. self.progressC = progressC
  294. self.view.window?.beginSheet(progressC.window!)
  295. }
  296. func hiddenProgressWindow() {
  297. if let _progressC = self.progressC {
  298. if let _window = _progressC.window {
  299. self.view.window?.endSheet(_window)
  300. }
  301. self.progressC = nil
  302. }
  303. }
  304. // MARK: - Menu Add & Remove
  305. public func addMenu(to view: NSView?) {
  306. if let menuView = view {
  307. self.addMenu(to: menuView)
  308. return
  309. }
  310. self.addMenu(to: self.view)
  311. }
  312. public func removeMenu(to view: NSView?) {
  313. if let menuView = view {
  314. self.removeMenu(to: menuView)
  315. return
  316. }
  317. self.removeMenu(to: self.view)
  318. }
  319. private func addMenu(to view: NSView) {
  320. // 先移除
  321. self.removeMenu(to: view)
  322. let menu = NSMenu()
  323. menu.delegate = self
  324. view.menu = menu
  325. }
  326. private func removeMenu(to view: NSView) {
  327. view.menu?.delegate = nil
  328. view.menu = nil
  329. }
  330. }
  331. extension KMBaseViewController: NSMenuDelegate, NSMenuItemValidation {
  332. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  333. return true
  334. }
  335. func menuNeedsUpdate(_ menu: NSMenu) {
  336. menu.removeAllItems()
  337. }
  338. }