KMCompressWindowController.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. //
  2. // KMCompressWindowController.swift
  3. // PDF Master
  4. //
  5. // Created by tangchao on 2022/11/25.
  6. //
  7. import Cocoa
  8. protocol KMLoadingProtocol: NSObjectProtocol {
  9. func beginLoading()
  10. func endLoading()
  11. }
  12. extension NSView: KMLoadingProtocol {
  13. var markViewTag: Int {
  14. get {
  15. return 123456
  16. }
  17. }
  18. func beginLoading() {
  19. self.endLoading()
  20. if (Thread.isMainThread) {
  21. self.beginLoadingInMainThread()
  22. } else {
  23. DispatchQueue.main.async {
  24. self.beginLoadingInMainThread()
  25. }
  26. }
  27. }
  28. func endLoading() {
  29. if (Thread.isMainThread) {
  30. self.endLoadingInMainThread()
  31. } else {
  32. DispatchQueue.main.async {
  33. self.endLoadingInMainThread()
  34. }
  35. }
  36. }
  37. // MARK: exe in main thread
  38. private func beginLoadingInMainThread() {
  39. let maskView = self.createLoadingMaskView()
  40. self.addSubview(maskView)
  41. maskView.frame = self.bounds
  42. maskView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  43. let loadingIndicator = self.createLoadingIndicator()
  44. maskView.addSubview(loadingIndicator)
  45. let size = NSMakeSize(32, 32)
  46. let left: CGFloat = (NSWidth(self.bounds)-size.width) * 0.5
  47. let top: CGFloat = (NSHeight(self.bounds)-size.height) * 0.5
  48. loadingIndicator.frame = NSMakeRect(left, top, size.width, size.height)
  49. loadingIndicator.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  50. loadingIndicator.startAnimation(nil)
  51. }
  52. private func endLoadingInMainThread() {
  53. let maskView = self.viewWithTag(self.markViewTag)
  54. if (maskView == nil) {
  55. return
  56. }
  57. let loadingIndicator = maskView?.subviews.first
  58. if (loadingIndicator is NSProgressIndicator == false) {
  59. return
  60. }
  61. (loadingIndicator as! NSProgressIndicator).stopAnimation(nil)
  62. loadingIndicator?.removeFromSuperview()
  63. maskView?.removeFromSuperview()
  64. }
  65. // MARK: Init View
  66. private func createLoadingMaskView() -> NSButton {
  67. let mask = NSButton()
  68. mask.tag = self.markViewTag
  69. mask.isBordered = false
  70. mask.title = ""
  71. mask.target = self
  72. mask.action = #selector(loadingMask_Click)
  73. return mask
  74. }
  75. private func createLoadingIndicator() -> NSProgressIndicator {
  76. let loading = NSProgressIndicator()
  77. loading.style = .spinning
  78. loading.controlSize = .regular
  79. loading.isIndeterminate = true
  80. return loading
  81. }
  82. @objc private func loadingMask_Click() {}
  83. }
  84. typealias KMCompressWindowControllerItemClick = (Int)->()
  85. typealias KMCompressWindowControllerResultCallback = (_ result: Bool,_ openDocuemt: Bool, _ fileURL: URL, _ error: String)->()
  86. class KMCompressWindowController: NSWindowController {
  87. @IBOutlet weak var titleLabel: NSTextField!
  88. @IBOutlet weak var largeBox: NSBox!
  89. @IBOutlet weak var standardBox: NSBox!
  90. @IBOutlet weak var smallBox: NSBox!
  91. @IBOutlet weak var minimumBox: NSBox!
  92. @IBOutlet weak var batchButton: NSButton!
  93. @IBOutlet weak var cancelBox: NSBox!
  94. @IBOutlet weak var compressBox: NSBox!
  95. var documentURL: URL!
  96. var password: String!
  97. private var datas: [String] = []
  98. var selectIndex = 2
  99. var itemClick : KMCompressWindowControllerItemClick!
  100. var resultCallback : KMCompressWindowControllerResultCallback!
  101. var largeVC : KMDesignButton!
  102. var standardVC : KMDesignButton!
  103. var smallVC : KMDesignButton!
  104. var minimumVC : KMDesignButton!
  105. var cancelVC : KMDesignButton!
  106. var compressVC : KMDesignButton!
  107. deinit {
  108. KMPrint("KMCompressWindowController 已释放")
  109. }
  110. override func windowDidLoad() {
  111. super.windowDidLoad()
  112. self.window?.appearance = NSAppearance(named: .aqua)
  113. largeVC = KMDesignButton.init(withType: .RadioButton)
  114. standardVC = KMDesignButton.init(withType: .RadioButton)
  115. smallVC = KMDesignButton.init(withType: .RadioButton)
  116. minimumVC = KMDesignButton.init(withType: .RadioButton)
  117. cancelVC = KMDesignButton.init(withType: .Text)
  118. compressVC = KMDesignButton.init(withType: .Text)
  119. largeBox.fillColor = .clear
  120. largeBox.contentView = largeVC.view
  121. standardBox.fillColor = .clear
  122. standardBox.contentView = standardVC.view
  123. smallBox.fillColor = .clear
  124. smallBox.contentView = smallVC.view
  125. minimumBox.fillColor = .clear
  126. minimumBox.contentView = minimumVC.view
  127. cancelBox.fillColor = .clear
  128. cancelBox.contentView = cancelVC.view
  129. compressBox.fillColor = .clear
  130. compressBox.contentView = compressVC.view
  131. titleLabel.stringValue = NSLocalizedString("Compress", comment: "")
  132. batchButton.isBordered = false
  133. batchButton.title = NSLocalizedString("Batch", comment: "")
  134. batchButton.wantsLayer = true
  135. batchButton.layer?.borderWidth = 1
  136. batchButton.layer?.borderColor = NSColor.black.cgColor
  137. batchButton.layer?.cornerRadius = 4
  138. batchButton.target = self
  139. batchButton.action = #selector(batchButtonAction)
  140. batchButton.isHidden = true
  141. cancelVC.target = self
  142. cancelVC.action = #selector(cancelButtonAction)
  143. cancelVC.stringValue = NSLocalizedString("Cancel", comment: "")
  144. cancelVC.button(type: .Sec, size: .m)
  145. cancelVC.button.keyEquivalent = KMKeyEquivalent.esc.string()
  146. compressVC.target = self
  147. compressVC.action = #selector(compressButtonAction)
  148. compressVC.stringValue = NSLocalizedString("Compress", comment: "")
  149. compressVC.button(type: .Cta, size: .m)
  150. compressVC.button.keyEquivalent = KMKeyEquivalent.enter
  151. largeVC.target = self
  152. largeVC.action = #selector(self.radioButtonAction(_:))
  153. largeVC.stringValue = NSLocalizedString("Large File Size", comment: "")
  154. largeVC.checkbox_radio()
  155. standardVC.target = self
  156. standardVC.action = #selector(self.radioButtonAction(_:))
  157. standardVC.stringValue = NSLocalizedString("Standard File Size", comment: "")
  158. standardVC.checkbox_radio()
  159. smallVC.target = self
  160. smallVC.action = #selector(self.radioButtonAction(_:))
  161. smallVC.stringValue = NSLocalizedString("Small File Size", comment: "")
  162. smallVC.checkbox_radio()
  163. minimumVC.target = self
  164. minimumVC.action = #selector(self.radioButtonAction(_:))
  165. minimumVC.stringValue = NSLocalizedString("Minimum File Size", comment: "")
  166. minimumVC.checkbox_radio()
  167. self.initUIProperty()
  168. smallVC.state = .Checked
  169. }
  170. private func initUIProperty() {
  171. self.titleLabel.textColor = NSColor.titleColor()
  172. self.titleLabel.font = .SFProTextSemibold(16)
  173. self.batchButton.setTitleColor(NSColor.buttonTitleColor())
  174. self.batchButton.layer?.borderColor = NSColor.buttonBorderColor().cgColor
  175. self.batchButton.font = .SFProTextRegular(14)
  176. }
  177. @objc func radioButtonAction(_ sender: NSButton) {
  178. largeVC.state = .Norm
  179. standardVC.state = .Norm
  180. smallVC.state = .Norm
  181. minimumVC.state = .Norm
  182. if (largeVC.button == sender) {
  183. largeVC.state = .Checked
  184. self.selectIndex = 0
  185. } else if (standardVC.button == sender) {
  186. standardVC.state = .Checked
  187. self.selectIndex = 1
  188. } else if (smallVC.button == sender) {
  189. smallVC.state = .Checked
  190. self.selectIndex = 2
  191. } else if (minimumVC.button == sender) {
  192. minimumVC.state = .Checked
  193. self.selectIndex = 3
  194. }
  195. }
  196. @objc func batchButtonAction() {
  197. guard let callback = itemClick else {
  198. return
  199. }
  200. callback(1)
  201. }
  202. @objc func cancelButtonAction() {
  203. guard let callback = itemClick else {
  204. return
  205. }
  206. callback(2)
  207. }
  208. @objc func compressButtonAction() {
  209. if documentURL == nil {
  210. return
  211. }
  212. NSPanel.savePanel(self.window!, true) { panel in
  213. panel.nameFieldStringValue = ""+self.documentURL.deletingPathExtension().lastPathComponent+"_Compressed"
  214. panel.allowedFileTypes = ["pdf"]
  215. } completion: { response, url, isOpen in
  216. if (response == .cancel) {
  217. return
  218. }
  219. self.beginLoading()
  220. DispatchQueue.main.async {
  221. let docuemt = CPDFDocument.init(url: self.documentURL)
  222. if (docuemt?.isLocked)! && self.password != nil {
  223. docuemt?.unlock(withPassword: self.password)
  224. }
  225. var option = 60
  226. if self.selectIndex == 0 {
  227. option = 120
  228. } else if self.selectIndex == 1 {
  229. option = 90
  230. } else if self.selectIndex == 2 {
  231. option = 60
  232. } else if self.selectIndex == 3 {
  233. option = 30
  234. }
  235. let result = docuemt?.writeOptimize(to: url, withOptions: [.imageQualityOption : option])
  236. self.endLoading()
  237. guard let callback = self.resultCallback else {
  238. if result! {
  239. if isOpen { /// 开启文档
  240. if !url!.path.isPDFValid() {
  241. let alert = NSAlert()
  242. alert.alertStyle = .critical
  243. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  244. alert.runModal()
  245. return
  246. }
  247. NSDocumentController.shared.openDocument(withContentsOf: url!, display: true) { document, alreadyOpen, error in
  248. }
  249. } else {
  250. NSWorkspace.shared.activateFileViewerSelecting([url!])
  251. }
  252. }
  253. return
  254. }
  255. callback(result!, isOpen, url!, "")
  256. }
  257. }
  258. }
  259. func getUniqueFilePath(filePath: String) -> String {
  260. var i: Int = 0
  261. var isDirectory: ObjCBool = false
  262. var uniqueFilePath = filePath
  263. let fileManager = FileManager.default
  264. fileManager.fileExists(atPath: uniqueFilePath, isDirectory: &isDirectory)
  265. if isDirectory.boolValue {
  266. var path: String = ""
  267. while fileManager.fileExists(atPath: uniqueFilePath) {
  268. i += 1
  269. path = filePath
  270. path.append("(\(i))")
  271. uniqueFilePath = path
  272. }
  273. } else {
  274. let fileURL = URL(fileURLWithPath: filePath)
  275. var path: String = ""
  276. while fileManager.fileExists(atPath: uniqueFilePath) {
  277. i += 1
  278. path = fileURL.deletingPathExtension().path
  279. path.append("(\(i))")
  280. path.append(".")
  281. path.append(fileURL.pathExtension)
  282. uniqueFilePath = path
  283. }
  284. }
  285. return uniqueFilePath
  286. }
  287. }
  288. extension KMCompressWindowController: NSTableViewDataSource {
  289. func numberOfRows(in tableView: NSTableView) -> Int {
  290. datas.count
  291. }
  292. }
  293. extension KMCompressWindowController: KMLoadingProtocol {
  294. func beginLoading() {
  295. self.window?.contentView?.beginLoading()
  296. }
  297. func endLoading() {
  298. self.window?.contentView?.endLoading()
  299. }
  300. }