KMBaseViewController.swift 19 KB

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