KMCompressWindowController.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. //
  2. // KMCompressWindowController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2022/11/25.
  6. //
  7. import Cocoa
  8. typealias KMCompressWindowControllerItemClick = (Int)->()
  9. typealias KMCompressWindowControllerResultCallback = (_ result: Bool,_ openDocuemt: Bool, _ fileURL: URL, _ error: String)->()
  10. class KMCompressWindowController: NSWindowController {
  11. @IBOutlet weak var titleLabel: NSTextField!
  12. @IBOutlet weak var largeBox: NSBox!
  13. @IBOutlet weak var standardBox: NSBox!
  14. @IBOutlet weak var smallBox: NSBox!
  15. @IBOutlet weak var minimumBox: NSBox!
  16. @IBOutlet weak var batchButton: NSButton!
  17. @IBOutlet weak var cancelBox: NSBox!
  18. @IBOutlet weak var compressBox: NSBox!
  19. var documentURL: URL!
  20. var password: String!
  21. private var datas: [String] = []
  22. var selectIndex = 2
  23. var limit = true
  24. var oriDocumentUrl: URL?
  25. var itemClick : KMCompressWindowControllerItemClick!
  26. var resultCallback : KMCompressWindowControllerResultCallback!
  27. var largeVC : KMDesignButton!
  28. var standardVC : KMDesignButton!
  29. var smallVC : KMDesignButton!
  30. var minimumVC : KMDesignButton!
  31. var cancelVC : KMDesignButton!
  32. var compressVC : KMDesignButton!
  33. deinit {
  34. KMPrint("KMCompressWindowController 已释放")
  35. }
  36. override func windowDidLoad() {
  37. super.windowDidLoad()
  38. // self.window?.appearance = NSAppearance(named: .aqua)
  39. largeVC = KMDesignButton.init(withType: .RadioButton)
  40. standardVC = KMDesignButton.init(withType: .RadioButton)
  41. smallVC = KMDesignButton.init(withType: .RadioButton)
  42. minimumVC = KMDesignButton.init(withType: .RadioButton)
  43. cancelVC = KMDesignButton.init(withType: .Text)
  44. compressVC = KMDesignButton.init(withType: .Text)
  45. largeBox.fillColor = .clear
  46. largeBox.contentView = largeVC.view
  47. standardBox.fillColor = .clear
  48. standardBox.contentView = standardVC.view
  49. smallBox.fillColor = .clear
  50. smallBox.contentView = smallVC.view
  51. minimumBox.fillColor = .clear
  52. minimumBox.contentView = minimumVC.view
  53. cancelBox.fillColor = .clear
  54. cancelBox.contentView = cancelVC.view
  55. compressBox.fillColor = .clear
  56. compressBox.contentView = compressVC.view
  57. titleLabel.stringValue = NSLocalizedString("Compress", comment: "")
  58. batchButton.isBordered = false
  59. batchButton.title = NSLocalizedString("Batch", comment: "")
  60. batchButton.wantsLayer = true
  61. batchButton.layer?.borderWidth = 1
  62. batchButton.layer?.borderColor = NSColor.black.cgColor
  63. batchButton.layer?.cornerRadius = 4
  64. batchButton.target = self
  65. batchButton.action = #selector(batchButtonAction)
  66. batchButton.isHidden = true
  67. cancelVC.target = self
  68. cancelVC.action = #selector(cancelButtonAction)
  69. cancelVC.stringValue = NSLocalizedString("Cancel", comment: "")
  70. cancelVC.button(type: .Sec, size: .m)
  71. cancelVC.button.keyEquivalent = KMKeyEquivalent.esc.string()
  72. compressVC.target = self
  73. compressVC.action = #selector(compressButtonAction)
  74. compressVC.stringValue = NSLocalizedString("Compress", comment: "")
  75. compressVC.button(type: .Cta, size: .m)
  76. compressVC.button.keyEquivalent = KMKeyEquivalent.enter
  77. largeVC.target = self
  78. largeVC.action = #selector(self.radioButtonAction(_:))
  79. largeVC.stringValue = NSLocalizedString("Large File Size", comment: "")
  80. largeVC.checkbox_radio()
  81. standardVC.target = self
  82. standardVC.action = #selector(self.radioButtonAction(_:))
  83. standardVC.stringValue = NSLocalizedString("Standard File Size", comment: "")
  84. standardVC.checkbox_radio()
  85. smallVC.target = self
  86. smallVC.action = #selector(self.radioButtonAction(_:))
  87. smallVC.stringValue = NSLocalizedString("Small File Size", comment: "")
  88. smallVC.checkbox_radio()
  89. minimumVC.target = self
  90. minimumVC.action = #selector(self.radioButtonAction(_:))
  91. minimumVC.stringValue = NSLocalizedString("Minimum File Size", comment: "")
  92. minimumVC.checkbox_radio()
  93. self.initUIProperty()
  94. smallVC.state = .Checked
  95. Task { @MainActor in
  96. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  97. self.limit = true
  98. } else {
  99. self.limit = false
  100. }
  101. }
  102. }
  103. private func initUIProperty() {
  104. self.titleLabel.textColor = NSColor.titleColor()
  105. self.titleLabel.font = .SFProTextSemiboldFont(16)
  106. self.batchButton.setTitleColor(color: NSColor.buttonTitleColor())
  107. self.batchButton.layer?.borderColor = NSColor.buttonBorderColor().cgColor
  108. self.batchButton.font = .SFProTextRegularFont(14)
  109. }
  110. @objc func radioButtonAction(_ sender: NSButton) {
  111. largeVC.state = .Norm
  112. standardVC.state = .Norm
  113. smallVC.state = .Norm
  114. minimumVC.state = .Norm
  115. if (largeVC.button == sender) {
  116. largeVC.state = .Checked
  117. self.selectIndex = 0
  118. } else if (standardVC.button == sender) {
  119. standardVC.state = .Checked
  120. self.selectIndex = 1
  121. } else if (smallVC.button == sender) {
  122. smallVC.state = .Checked
  123. self.selectIndex = 2
  124. } else if (minimumVC.button == sender) {
  125. minimumVC.state = .Checked
  126. self.selectIndex = 3
  127. }
  128. }
  129. @objc func batchButtonAction() {
  130. guard let callback = itemClick else {
  131. return
  132. }
  133. callback(1)
  134. }
  135. @objc func cancelButtonAction() {
  136. self._clearData()
  137. guard let callback = itemClick else {
  138. return
  139. }
  140. callback(2)
  141. }
  142. @objc func compressButtonAction() {
  143. if documentURL == nil {
  144. return
  145. }
  146. Task { @MainActor in
  147. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  148. let _ = KMSubscribeWaterMarkWindowController.show(window: self.window!) { isSubscribeSuccess, isWaterMarkExport, isClose in
  149. if (isClose) {
  150. return
  151. }
  152. if (isSubscribeSuccess) {
  153. self._compressButtonAction()
  154. }
  155. if (isWaterMarkExport) {
  156. self._compressButtonAction(limit: true)
  157. }
  158. }
  159. return
  160. }
  161. self._compressButtonAction()
  162. }
  163. }
  164. func getUniqueFilePath(filePath: String) -> String {
  165. var i: Int = 0
  166. var isDirectory: ObjCBool = false
  167. var uniqueFilePath = filePath
  168. let fileManager = FileManager.default
  169. fileManager.fileExists(atPath: uniqueFilePath, isDirectory: &isDirectory)
  170. if isDirectory.boolValue {
  171. var path: String = ""
  172. while fileManager.fileExists(atPath: uniqueFilePath) {
  173. i += 1
  174. path = filePath
  175. path.append("(\(i))")
  176. uniqueFilePath = path
  177. }
  178. } else {
  179. let fileURL = URL(fileURLWithPath: filePath)
  180. var path: String = ""
  181. while fileManager.fileExists(atPath: uniqueFilePath) {
  182. i += 1
  183. path = fileURL.deletingPathExtension().path
  184. path.append("(\(i))")
  185. path.append(".")
  186. path.append(fileURL.pathExtension)
  187. uniqueFilePath = path
  188. }
  189. }
  190. return uniqueFilePath
  191. }
  192. private func _compressButtonAction(limit: Bool = false) {
  193. DispatchQueue.main.async {
  194. NSPanel.savePanel(self.window!, true) { panel in
  195. var url: URL = self.documentURL
  196. if (self.oriDocumentUrl != nil) {
  197. url = self.oriDocumentUrl!
  198. }
  199. panel.nameFieldStringValue = ""+url.deletingPathExtension().lastPathComponent+"_Compressed"
  200. panel.allowedFileTypes = ["pdf"]
  201. } completion: { response, url, isOpen in
  202. if (response == .cancel) {
  203. return
  204. }
  205. self.beginLoading()
  206. DispatchQueue.global().async {
  207. let docuemt = CPDFDocument.init(url: self.documentURL)
  208. if (docuemt?.isLocked)! && self.password != nil {
  209. docuemt?.unlock(withPassword: self.password)
  210. }
  211. var option = 60
  212. if self.selectIndex == 0 {
  213. option = 120
  214. } else if self.selectIndex == 1 {
  215. option = 90
  216. } else if self.selectIndex == 2 {
  217. option = 60
  218. } else if self.selectIndex == 3 {
  219. option = 30
  220. }
  221. //
  222. var result = false
  223. if (limit) {
  224. if let _document = docuemt, let _ = KMTools.saveWatermarkDocumentForCompress(document: _document, to: url!, imageQuality: option) {
  225. result = true
  226. }
  227. } else {
  228. if let data = docuemt?.writeOptimize(to: url, withOptions: [.imageQualityOption : option]) {
  229. result = data
  230. }
  231. }
  232. if (result) {
  233. self._clearData()
  234. }
  235. DispatchQueue.main.async {
  236. self.endLoading()
  237. guard let callback = self.resultCallback else {
  238. if (result) {
  239. if isOpen { /// 开启文档
  240. NSDocumentController.shared.km_safe_openDocument(withContentsOf: url!, display: true) { _, _, _ in
  241. }
  242. } else {
  243. NSWorkspace.shared.activateFileViewerSelecting([url!])
  244. }
  245. }
  246. return
  247. }
  248. callback(result, isOpen, url!, "")
  249. }
  250. }
  251. }
  252. }
  253. }
  254. private func _clearData() {
  255. if let _ = self.oriDocumentUrl {
  256. if let data = self.documentURL?.path, FileManager.default.fileExists(atPath: data) {
  257. try?FileManager.default.removeItem(atPath: data)
  258. }
  259. }
  260. }
  261. }
  262. extension KMCompressWindowController: NSTableViewDataSource {
  263. func numberOfRows(in tableView: NSTableView) -> Int {
  264. datas.count
  265. }
  266. }
  267. extension KMCompressWindowController: KMLoadingProtocol {
  268. func beginLoading() {
  269. self.window?.contentView?.beginLoading()
  270. }
  271. func endLoading() {
  272. self.window?.contentView?.endLoading()
  273. }
  274. }