KMBaseViewController.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 = folderPath.kUrlToPDFFolderPath()
  72. if (savePath == nil) {
  73. continue
  74. }
  75. dispatchGroup.enter()
  76. KMConvertPDFManagerOC.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 KMConvertPDFManagerOC.supportFileType() {
  123. if let string = fileType as? String {
  124. array.append(string)
  125. }
  126. }
  127. panel.allowedFileTypes = KMTools.pdfExtensions + array
  128. } completion: { urls in
  129. self.km_add_file_multi(fileUrls: urls, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
  130. }
  131. }
  132. func km_add_pdf_multi(fileUrlStrings: [String] ,type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  133. var urls: [URL] = []
  134. for string in fileUrlStrings {
  135. urls.append(URL(fileURLWithPath: string))
  136. }
  137. self.km_add_pdf_multi(fileUrls: urls, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
  138. }
  139. func km_add_pdf_multi(fileUrls: [URL] ,type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  140. var results: [CPDFDocument] = []
  141. self.lockedFiles.removeAll()
  142. var index = 0
  143. for url in fileUrls {
  144. let document = CPDFDocument(url: url)
  145. if (document!.isLocked) {
  146. self.lockedFiles.append(url)
  147. continue
  148. }
  149. if let _document = document {
  150. results.append(_document)
  151. }
  152. index += 1
  153. if let _callback = progressBlock {
  154. _callback(index, ((document != nil) ? document : CPDFDocument()) as Any, url)
  155. }
  156. }
  157. if (self.lockedFiles.count == 0) {
  158. completionBlock(results)
  159. return
  160. }
  161. // if let _callback = progressBlock {
  162. // _callback(0, results)
  163. // }
  164. self._openPasswordWindow_loop(fileUrl: self.lockedFiles.first!, type: type) { params in
  165. index += 1
  166. if (params.count <= 2) { // 参数错误
  167. if let _callback = progressBlock { // 回调进度
  168. _callback(index)
  169. }
  170. return
  171. }
  172. let fileUrl = params[0] as! URL
  173. let result = params[1] as! KMPasswordInputWindowResult
  174. let password = params[2] as? String
  175. if (result == .cancel) {
  176. if let _callback = progressBlock { // 回调进度
  177. _callback(index, CPDFDocument() as Any, fileUrl, result)
  178. }
  179. return
  180. }
  181. let document = CPDFDocument(url: fileUrl)
  182. if let _password = password { // 将文档进行解密
  183. document?.unlock(withPassword: _password)
  184. }
  185. if let _callback = progressBlock { // 回调进度
  186. _callback(index, document as Any, fileUrl, result, password as Any)
  187. }
  188. // 将文档加入返回数据
  189. if let _document = document {
  190. results.append(_document)
  191. }
  192. } completionBlock: {
  193. completionBlock(results)
  194. }
  195. }
  196. func km_add_file_multi(fileUrls: [URL] ,type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  197. var pdfUrls: [URL] = []
  198. var imageUrls: [URL] = []
  199. var officeUrls: [URL] = []
  200. for url in fileUrls {
  201. let type = url.pathExtension.lowercased()
  202. if (KMTools.isPDFType(type)) {
  203. pdfUrls.append(url)
  204. }
  205. if (KMTools.isImageType(type)) {
  206. imageUrls.append(url)
  207. }
  208. if (KMTools.isOfficeType(type)) {
  209. officeUrls.append(url)
  210. }
  211. }
  212. if (officeUrls.count == 0) {
  213. self.km_add_pdf_multi(fileUrls: pdfUrls, type: type, progressBlock: progressBlock) { documents in
  214. var index = documents.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(documents + _documents)
  228. }
  229. return
  230. }
  231. self.km_add_office_multi(fileUrls: officeUrls) { [unowned self] fileUrlStrings in
  232. var officeDocuments: [CPDFDocument] = []
  233. var index = 0
  234. for fileUrlString in fileUrlStrings {
  235. index += 1
  236. let document = CPDFDocument(url: URL(fileURLWithPath: fileUrlString))
  237. officeDocuments.append(document!)
  238. if let _callback = progressBlock { // 回调进度
  239. _callback(index, document as Any, URL(fileURLWithPath: fileUrlString))
  240. }
  241. }
  242. self.km_add_pdf_multi(fileUrls: pdfUrls) { documents in
  243. var index = documents.count + officeDocuments.count
  244. var _documents: [CPDFDocument] = []
  245. for imageUrl in imageUrls {
  246. index += 1
  247. let document = CPDFDocument()
  248. let image = NSImage(contentsOfFile: imageUrl.path)
  249. // document?.insertPage(image!.size, withImage: imageUrl.path, at: 0)
  250. document?.km_insertPage(image!.size, withImage: imageUrl.path, at: 0)
  251. _documents.append(document!)
  252. if let _callback = progressBlock { // 回调进度
  253. _callback(index, document as Any, imageUrl)
  254. }
  255. }
  256. completionBlock(officeDocuments + documents + _documents)
  257. }
  258. }
  259. }
  260. // MARK: - ProgressBlock Params Fetch
  261. func fetchProgressBlockParamsForDocument(params: Any...) -> CPDFDocument? {
  262. return params.first as? CPDFDocument
  263. }
  264. func fetchProgressBlockParamsForFileUrl(params: Any...) -> URL? {
  265. if (params.count < 2) {
  266. return nil
  267. }
  268. return params[1] as? URL
  269. }
  270. func fetchProgressBlockParamsForResult(params: Any...) -> KMPasswordInputWindowResult? {
  271. if (params.count <= 2) {
  272. return nil
  273. }
  274. return params[2] as? KMPasswordInputWindowResult
  275. }
  276. func fetchProgressBlockParamsForPassword(params: Any...) -> String? {
  277. if (params.count <= 2) {
  278. return nil
  279. }
  280. return params.last as? String
  281. }
  282. func fetchProgressBlockParamsIsPasswordFile(params: Any...) -> Bool {
  283. if (params.count <= 2) {
  284. return false
  285. }
  286. return true
  287. }
  288. // MARK: - Open Password Window
  289. // 留意:
  290. // -会直接弹密码弹窗,不会判断文档是否加密
  291. // -在使用前最好判断下文件是否已加密
  292. func openPasswordWindow(fileUrlString: String, type: KMPasswordInputWindowType = .open, completionBlock:@escaping (KMPasswordInputWindowResult, String?)->Void) {
  293. self.openPasswordWindow(fileUrl: URL(fileURLWithPath: fileUrlString), type: type, completionBlock: completionBlock)
  294. }
  295. func openPasswordWindow(fileUrl: URL, type: KMPasswordInputWindowType = .open, completionBlock:@escaping (KMPasswordInputWindowResult, String?)->Void) {
  296. KMPasswordInputWindow.openWindow(window: self.view.window!, type: type, url: fileUrl, callback: completionBlock)
  297. }
  298. func openPasswordWindow_success(fileUrlString: String, type: KMPasswordInputWindowType = .open, completionBlock:@escaping (String)->Void) {
  299. self.openPasswordWindow_success(fileUrl: URL(fileURLWithPath: fileUrlString), type: type, completionBlock: completionBlock)
  300. }
  301. func openPasswordWindow_success(fileUrl: URL, type: KMPasswordInputWindowType = .open, completionBlock:@escaping (String)->Void) {
  302. KMPasswordInputWindow.success_openWindow(window: self.view.window!, url: fileUrl, callback: completionBlock)
  303. }
  304. fileprivate func _openPasswordWindow_loop(fileUrl: URL, type: KMPasswordInputWindowType, progressBlock: ((_ params: Any...)->Void)?, completionBlock:@escaping ()->Void) {
  305. KMPasswordInputWindow.openWindow(window: self.view.window!, type: type, url: fileUrl) { [weak self] result, password in
  306. // 将结果返回
  307. if let _callback = progressBlock {
  308. _callback(fileUrl, result, password as Any)
  309. }
  310. // 进行下一个
  311. self?.lockedFiles.removeFirst()
  312. if let _fileUrl = self?.lockedFiles.first {
  313. self?._openPasswordWindow_loop(fileUrl: _fileUrl, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
  314. } else {
  315. completionBlock()
  316. }
  317. }
  318. }
  319. // MARK: - Progress Window
  320. var progressC: SKProgressController?
  321. func showProgressWindow(message: String = "") {
  322. if (self.progressC != nil) {
  323. self.hiddenProgressWindow()
  324. }
  325. let progressC = SKProgressController()
  326. progressC.showClose = false
  327. progressC.message = message
  328. progressC.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  329. progressC.window?.contentView?.wantsLayer = true
  330. progressC.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  331. progressC.progressField.textColor = NSColor.white
  332. self.progressC = progressC
  333. self.view.window?.beginSheet(progressC.window!)
  334. }
  335. func hiddenProgressWindow() {
  336. if let _progressC = self.progressC {
  337. if let _window = _progressC.window {
  338. self.view.window?.endSheet(_window)
  339. }
  340. self.progressC = nil
  341. }
  342. }
  343. // MARK: - Menu Add & Remove
  344. public func addMenu(to view: NSView?) {
  345. if let menuView = view {
  346. self.addMenu(to: menuView)
  347. return
  348. }
  349. self.addMenu(to: self.view)
  350. }
  351. public func removeMenu(to view: NSView?) {
  352. if let menuView = view {
  353. self.removeMenu(to: menuView)
  354. return
  355. }
  356. self.removeMenu(to: self.view)
  357. }
  358. private func addMenu(to view: NSView) {
  359. // 先移除
  360. self.removeMenu(to: view)
  361. let menu = NSMenu()
  362. menu.delegate = self
  363. view.menu = menu
  364. }
  365. private func removeMenu(to view: NSView) {
  366. view.menu?.delegate = nil
  367. view.menu = nil
  368. }
  369. // MARK: - Document isDocumentEdited
  370. public func setDocumentEditedState(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.setDocumentEditedState(document: _document)
  382. }
  383. public func setDocumentEditedState(url: URL? = nil) {
  384. if let _url = url {
  385. KMTools.setDocumentEditedState(url: _url)
  386. } else {
  387. self.setDocumentEditedState(window: self.view.window)
  388. }
  389. }
  390. public func setDocumentEditedState(document: NSDocument) {
  391. km_synchronized(document) {
  392. if let _document = document as? KMMainDocument {
  393. _document.km_updateChangeCount(.changeDone)
  394. } else {
  395. document.updateChangeCount(.changeDone)
  396. }
  397. }
  398. }
  399. public func clearDocumentEditedState(window: NSWindow? = nil) {
  400. var _win = window
  401. if (_win == nil) {
  402. _win = self.view.window
  403. }
  404. guard let _window = _win else {
  405. return
  406. }
  407. guard let _document = NSDocumentController.shared.document(for: _window) else {
  408. return
  409. }
  410. self.clearDocumentEditedState(document: _document)
  411. }
  412. public func clearDocumentEditedState(url: URL? = nil) {
  413. if let _url = url {
  414. KMTools.clearDocumentEditedState(url: _url)
  415. } else {
  416. self.clearDocumentEditedState(window: self.view.window)
  417. }
  418. }
  419. public func clearDocumentEditedState(document: NSDocument) {
  420. km_synchronized(document) {
  421. if let _document = document as? KMMainDocument {
  422. _document.km_updateChangeCount(.changeCleared)
  423. } else {
  424. document.updateChangeCount(.changeCleared)
  425. }
  426. }
  427. }
  428. }
  429. extension KMBaseViewController: NSMenuDelegate, NSMenuItemValidation {
  430. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  431. return true
  432. }
  433. func menuNeedsUpdate(_ menu: NSMenu) {
  434. menu.removeAllItems()
  435. }
  436. }