KMExtractImageWindowController.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. //
  2. // KMExtractImageWindowController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by liujiajie on 2023/11/17.
  6. //
  7. import Cocoa
  8. class KMExtractImageWindowController: KMNBaseWindowController, PDFConvertObjectDelegate,NSTextFieldDelegate{
  9. var docPath: String = ""
  10. var password: String = ""
  11. var currentPage: Int = 0
  12. var maskView: KMBookletMaskView?
  13. @IBOutlet var rangeTipLabel: NSTextField!
  14. @IBOutlet var rangeTextField: NSTextField!
  15. @IBOutlet var allPageButton: NSButton!
  16. @IBOutlet var currentPageButton: NSButton!
  17. @IBOutlet var singlePageButton: NSButton!
  18. @IBOutlet var doublePageButton: NSButton!
  19. @IBOutlet var customPageButton: NSButton!
  20. @IBOutlet var extractImageButton: NSButton!
  21. @IBOutlet var cancelButton: NSButton!
  22. @IBOutlet var customTextField: NSTextField!
  23. @IBOutlet var totalImagesTextField: NSTextField!
  24. lazy var pdfDocument: CPDFDocument? = {
  25. var pdfDoc = CPDFDocument(url: URL(fileURLWithPath: self.docPath))
  26. if (self.password.count > 0){
  27. pdfDoc?.unlock(withPassword: self.password)
  28. }
  29. return pdfDoc
  30. }()
  31. var selectPagesIndex: Int = 0
  32. lazy var pdfConverter: PDFConvertObject? = {
  33. let conerter = PDFConvertObject()
  34. return conerter
  35. }()
  36. @IBOutlet var currentPageTextField: NSTextField!
  37. @IBOutlet var pageCountTextField: NSTextField!
  38. @IBOutlet var pdfViewBG: NSView!
  39. var preViewPDFView: CPDFView!
  40. private var fileAttri_: KMFileAttribute?
  41. deinit {
  42. NotificationCenter.default.removeObserver(self)
  43. }
  44. override func windowDidLoad() {
  45. super.windowDidLoad()
  46. let preView: CPDFView = CPDFView(frame: self.pdfViewBG.bounds)
  47. self.pdfViewBG.addSubview(preView)
  48. self.preViewPDFView = preView
  49. configUI()
  50. }
  51. func configUI() {
  52. if !self.docPath.isEmpty && self.docPath.count > 0 {
  53. let url = URL(fileURLWithPath: docPath)
  54. let document = CPDFDocument(url: url)
  55. if self.password.count > 0 {
  56. document?.unlock(withPassword: password)
  57. }
  58. self.preViewPDFView.document = document
  59. self.preViewPDFView.autoScales = true
  60. self.preViewPDFView.layoutDocumentView()
  61. self.preViewPDFView.go(toPageIndex: self.currentPage, animated: true)
  62. self.fileAttri_ = KMFileAttribute()
  63. self.fileAttri_?.filePath = url.path
  64. }
  65. self.allPageButton.title = KMLocalizedString("All Pages", comment: "")
  66. self.singlePageButton.title = KMLocalizedString("Odd Pages Only", comment: "")
  67. self.doublePageButton.title = KMLocalizedString("Even Pages Only", comment: "")
  68. self.currentPageButton.title = KMLocalizedString("Current Page", comment: "")
  69. self.extractImageButton.title = KMLocalizedString("Extract", comment: "")
  70. self.cancelButton.title = KMLocalizedString("Cancel", comment: "")
  71. self.rangeTextField.placeholderString = KMLocalizedString("e.g. 1,3-5,10", comment: "")
  72. self.rangeTipLabel.stringValue = KMLocalizedString("Page Range", comment: "")
  73. self.currentPageTextField.stringValue = "\(self.currentPage + 1)"
  74. self.pageCountTextField.stringValue = "/ \(self.pdfDocument?.pageCount ?? 0)"
  75. self.customTextField.stringValue = self.pageCountTextField.stringValue
  76. self.selectPagesIndex = 0
  77. self.rangeTextField.isEnabled = false
  78. self.customTextField.isEnabled = false
  79. self.allPageButton.state = NSControl.StateValue.on
  80. if self.pdfDocument?.pageCount ?? 0 < 2 {
  81. self.doublePageButton.isEnabled = false
  82. } else {
  83. self.doublePageButton.isEnabled = true
  84. }
  85. self.preViewPDFView.setDisplay(.singlePage)
  86. self.preViewPDFView.layoutDocumentView()
  87. NotificationCenter.default.addObserver(self, selector: #selector(pageChangeNotification(notification:)), name: NSNotification.Name.PDFViewPageChanged, object: self.preViewPDFView)
  88. }
  89. func selectCurrentPageBtn() {
  90. self.customPageButton_Action(self.currentPageButton)
  91. }
  92. @IBAction func customPageButton_Action(_ sender: NSButton) {
  93. self.allPageButton.state = NSControl.StateValue.off
  94. self.currentPageButton.state = NSControl.StateValue.off
  95. self.singlePageButton.state = NSControl.StateValue.off
  96. self.doublePageButton.state = NSControl.StateValue.off
  97. self.customPageButton.state = NSControl.StateValue.off
  98. sender.state = NSControl.StateValue.on
  99. self.rangeTextField.isEnabled = false
  100. self.customTextField.textColor = NSColor.disabledControlTextColor
  101. self.selectPagesIndex = sender.tag
  102. if sender.tag == 3 {
  103. self.rangeTextField.isEnabled = true
  104. self.customTextField.textColor = NSColor.labelColor
  105. self.window?.makeFirstResponder(self.rangeTextField)
  106. if self.rangeTextField.stringValue.isEmpty {
  107. return
  108. }
  109. }
  110. }
  111. @IBAction func extractImageButton_Action(_ sender: Any) {
  112. if KMMemberInfo.shared.isLogin == false {
  113. KMLoginWindowsController.shared.showWindow(nil)
  114. return
  115. }
  116. startExtracting()
  117. }
  118. @IBAction func cancleButton_Action(_ sender: Any) {
  119. self.window?.sheetParent?.endSheet(self.window!)
  120. }
  121. @IBAction func nextPage_Action(_ sender: Any) {
  122. if self.preViewPDFView.canGoToNextPage() {
  123. self.preViewPDFView.goToNextPage(sender)
  124. }
  125. let index = self.preViewPDFView.document.index(for: self.preViewPDFView.currentPage())
  126. self.currentPageTextField.stringValue = "\(index + 1)"
  127. }
  128. @IBAction func previousPage_Action(_ sender: Any) {
  129. if self.preViewPDFView.canGoToPreviousPage() {
  130. self.preViewPDFView.goToPreviousPage(sender)
  131. }
  132. let index = self.preViewPDFView.document.index(for: self.preViewPDFView.currentPage())
  133. self.currentPageTextField.stringValue = "\(index + 1)"
  134. }
  135. override func close() {
  136. if ((self.window?.isSheet) != nil) {
  137. self.window?.sheetParent?.endSheet(self.window!)
  138. } else {
  139. super.close()
  140. }
  141. }
  142. func startExtracting() {
  143. let indeSet = self.selectIndexSet()
  144. if indeSet.count == 0 { return }
  145. let lastPathName = self.pdfDocument?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  146. var tFileName = (String(format: "%@_Extract Images", lastPathName))
  147. let outputSavePanel = NSSavePanel()
  148. if let data = outputSavePanel.directoryURL?.appendingPathComponent(tFileName) {
  149. let fileUrl = self.fetchUniquePath(data.path)
  150. tFileName = fileUrl.lastPathComponent
  151. }
  152. outputSavePanel.title = KMLocalizedString("Save as PDF", comment: "")
  153. outputSavePanel.allowsOtherFileTypes = true
  154. outputSavePanel.isExtensionHidden = true
  155. outputSavePanel.canCreateDirectories = true
  156. outputSavePanel.nameFieldStringValue = tFileName
  157. outputSavePanel.beginSheetModal(for: self.window!) {(result) in
  158. if result == NSApplication.ModalResponse.OK {
  159. self.showWaitting()
  160. DispatchQueue.main.async {
  161. let tDestFile = outputSavePanel.url?.path ?? ""
  162. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  163. self.pdfConverter?.extractResourcesFromPDF(at: self.docPath, pdfPassword: self.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  164. self.extractOK(tDestFile)
  165. }
  166. }
  167. }
  168. }
  169. func fetchUniquePath(_ originalPath: String) -> String {
  170. var path = originalPath
  171. let dManager = FileManager.default
  172. if !dManager.fileExists(atPath: path) {
  173. if path.extension.count < 1 {
  174. path = path.stringByAppendingPathExtension("pdf")
  175. }
  176. return path
  177. } else {
  178. let originalFullFileName = path.lastPathComponent
  179. let originalFileName = originalFullFileName
  180. let startIndex: Int = 0
  181. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  182. let fileLocatePath = originalPath.substring(to: endIndex)
  183. var i = 1
  184. while (1 != 0) {
  185. let newName = String(format: "%@(%ld)", originalFileName, i)
  186. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  187. if !dManager.fileExists(atPath: newPath) {
  188. return newPath
  189. } else {
  190. i+=1
  191. continue
  192. }
  193. }
  194. }
  195. }
  196. func extractOK(_ folder: String) {
  197. self.hideWaitting()
  198. self.close()
  199. if FileManager.default.fileExists(atPath: folder) {
  200. let workspace = NSWorkspace.shared
  201. let url = URL(fileURLWithPath: folder)
  202. workspace.activateFileViewerSelecting([url])
  203. }
  204. }
  205. func selectIndexSet() -> NSMutableIndexSet {
  206. let pageCount = self.pdfDocument?.pageCount
  207. let indeSet = NSMutableIndexSet()
  208. if self.selectPagesIndex == 0 {
  209. for i in 0..<(pageCount ?? 0) {
  210. indeSet.add(IndexSet(integer: IndexSet.Element(i)))
  211. }
  212. } else if self.selectPagesIndex == 1 {
  213. for i in 0..<(pageCount ?? 0) {
  214. if i % 2 == 0 {
  215. indeSet.add(IndexSet(integer: IndexSet.Element(i)))
  216. }
  217. }
  218. } else if self.selectPagesIndex == 2 {
  219. for i in 0..<(pageCount ?? 0) {
  220. if i % 2 != 0 {
  221. indeSet.add(IndexSet(integer: IndexSet.Element(i)))
  222. }
  223. }
  224. } else if self.selectPagesIndex == 4 {
  225. if let index = self.preViewPDFView.document?.index(for: self.preViewPDFView.currentPage()!) {
  226. indeSet.add(IndexSet(integer: IndexSet.Element(index)))
  227. }
  228. } else {
  229. var fileAttribute = self.fileAttri_
  230. if fileAttribute == nil {
  231. self.fileAttri_ = KMFileAttribute()
  232. self.fileAttri_?.filePath = self.preViewPDFView.document?.documentURL?.path ?? ""
  233. fileAttribute = self.fileAttri_
  234. }
  235. fileAttribute?.bAllPage = false
  236. if (self.customPageButton.state == .on){
  237. fileAttribute?.pagesType = .custom
  238. }
  239. fileAttribute?.pagesString = self.rangeTextField.stringValue
  240. if let data = fileAttribute?.fetchSelectPages().isEmpty, data {
  241. let alert = NSAlert()
  242. alert.alertStyle = .critical
  243. alert.messageText = "\(fileAttribute?.filePath.lastPathComponent ?? "") \(KMLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
  244. alert.runModal()
  245. return indeSet
  246. }
  247. for num in fileAttribute?.fetchSelectPages() ?? [] {
  248. indeSet.add(num-1)
  249. }
  250. }
  251. return indeSet
  252. }
  253. class func createDestFolder(path: String, isUnique: Bool) -> String {
  254. var tUniqueName: String? = nil
  255. let tFileManager = FileManager.default
  256. if isUnique {
  257. tUniqueName = getUniqueFilePath(filePath: path)
  258. } else {
  259. tUniqueName = path
  260. }
  261. if !tFileManager.fileExists(atPath: tUniqueName!) {
  262. do {
  263. try tFileManager.createDirectory(atPath: tUniqueName!, withIntermediateDirectories: true, attributes: nil)
  264. } catch {
  265. }
  266. }
  267. return tUniqueName!
  268. }
  269. class func getUniqueFilePath(filePath: String) -> String {
  270. var i = 0
  271. var isDirectory = ObjCBool(false)
  272. var uniqueFilePath = filePath
  273. let filemanager = FileManager.default
  274. filemanager.fileExists(atPath: uniqueFilePath, isDirectory: &isDirectory)
  275. if isDirectory.boolValue {
  276. while filemanager.fileExists(atPath: uniqueFilePath) {
  277. i += 1
  278. uniqueFilePath = "\(filePath)(\(i))"
  279. }
  280. } else {
  281. while filemanager.fileExists(atPath: uniqueFilePath) {
  282. i += 1
  283. let path = "\(filePath.deletingPathExtension)(\(i))"
  284. uniqueFilePath = path.stringByAppendingPathExtension(filePath.customPathExtension)
  285. }
  286. }
  287. return uniqueFilePath
  288. }
  289. @objc func pageChangeNotification(notification: Notification) {
  290. self.currentPageTextField.stringValue = self.preViewPDFView.currentPage().label ?? ""
  291. }
  292. func controlTextDidEndEditing(_ obj: Notification) {
  293. if obj.object as? NSTextField == self.currentPageTextField {
  294. if let intValue = Int(self.currentPageTextField.stringValue), intValue > (self.preViewPDFView.document?.pageCount ?? 0) {
  295. let alert = NSAlert()
  296. alert.alertStyle = .critical
  297. alert.messageText = String(format: "%@%@", self.preViewPDFView.document.documentURL.lastPathComponent.lastPathComponent,KMLocalizedString("Invalid page range or the page number is out of range. Please try again."))
  298. alert.beginSheetModal(for: NSApp.mainWindow!, completionHandler: nil)
  299. return
  300. }
  301. self.preViewPDFView.go(to: self.preViewPDFView.document?.page(at: UInt((Int(self.currentPageTextField.stringValue) ?? 0) - 1)))
  302. } else if obj.object as? NSTextField == self.rangeTextField {
  303. if !checkPageRangeValidate(self.rangeTextField.stringValue) {
  304. let alert = NSAlert()
  305. alert.alertStyle = .critical
  306. alert.messageText = String(format: "%@%@", self.preViewPDFView.document.documentURL.lastPathComponent.lastPathComponent,KMLocalizedString("Invalid page range or the page number is out of range. Please try again."))
  307. alert.beginSheetModal(for: NSApp.mainWindow!, completionHandler: nil)
  308. return
  309. }
  310. }
  311. }
  312. func checkPageRangeValidate(_ pageRangeString: String) -> Bool {
  313. var fileAttribute = self.fileAttri_
  314. if fileAttribute == nil {
  315. self.fileAttri_ = KMFileAttribute()
  316. self.fileAttri_?.filePath = self.preViewPDFView.document?.documentURL?.path ?? ""
  317. fileAttribute = self.fileAttri_
  318. }
  319. fileAttribute?.bAllPage = false
  320. fileAttribute?.pagesString = self.rangeTextField.stringValue
  321. let isEmpty = fileAttribute?.fetchSelectPages().isEmpty ?? true
  322. let cnt = fileAttribute?.fetchSelectPages().count ?? 0
  323. if isEmpty || cnt < 1{
  324. return false
  325. }
  326. return true
  327. }
  328. override func mouseDown(with event: NSEvent) {
  329. super.mouseDown(with: event)
  330. self.window?.makeFirstResponder(nil)
  331. }
  332. @objc func pageChangeNotification(_ notification: Notification) {
  333. self.currentPageTextField.stringValue = self.preViewPDFView.currentPage().label ?? ""
  334. }
  335. func PDFConvertObject2(_ converter: PDFConvertObject, didEndConversion error: Error?) {
  336. self.hideWaitting()
  337. self.window?.sheetParent?.endSheet(self.window!)
  338. }
  339. func showWaitting() {
  340. if self.maskView == nil {
  341. self.maskView = KMBookletMaskView(frame: CGRect(x: 0, y: 0, width: self.window?.frame.size.width ?? 0, height: self.window?.frame.size.height ?? 0))
  342. }
  343. self.window?.contentView?.addSubview(self.maskView!)
  344. }
  345. func hideWaitting() {
  346. self.maskView?.removeFromSuperview()
  347. }
  348. func beginSheetModal(for window: NSWindow, completionHandler handler: ((NSInteger) -> Void)?) {
  349. self.window?.beginSheet(window, completionHandler: { returnCode in
  350. NSApp.endSheet(self.window!, returnCode: NSApplication.ModalResponse.abort.rawValue)
  351. if let handler = handler {
  352. handler(returnCode.rawValue)
  353. }
  354. })
  355. }
  356. }