KMPDFEditInsertPageWindow.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. //
  2. // KMPDFEditInsertPageWindow.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2023/11/13.
  6. //
  7. import Cocoa
  8. enum KMPDFEditInsertType: Int {
  9. case management = 1
  10. case pageEdit
  11. }
  12. class KMPDFEditInsertPageWindow: NSWindowController {
  13. var currentPage: Int = 1
  14. var insertLocation: Int = 0
  15. @IBOutlet var progress: NSProgressIndicator!
  16. @IBOutlet var pageCountLabel: NSTextField!
  17. @IBOutlet var pageLabel: NSTextField!
  18. @IBOutlet var pagesText: NSTextField!
  19. @IBOutlet var outputFolderText: NSTextField!
  20. @IBOutlet var locationFirstButton: NSButton!
  21. @IBOutlet var locationLastButton: NSButton!
  22. @IBOutlet var rangeButton: NSButton!
  23. @IBOutlet var insertButton: NSButton!
  24. @IBOutlet var cancelButton: NSButton!
  25. @IBOutlet var selectedPathButton: NSButton!
  26. @IBOutlet var byPageStepper: NSStepper!
  27. @IBOutlet var whereInsertBox: NSBox!
  28. @IBOutlet var insertLabel: NSTextField!
  29. @IBOutlet var whereInsertLabel: NSTextField!
  30. @IBOutlet var locationRangePopUpButton: NSPopUpButton!
  31. @IBOutlet var allPageButton: NSButton!
  32. @IBOutlet var singlePageButton: NSButton!
  33. @IBOutlet var doublePageButton: NSButton!
  34. @IBOutlet var customPageButton: NSButton!
  35. @IBOutlet var customTextField: NSTextField!
  36. @IBOutlet var rangeTextField: NSTextField!
  37. weak var pdfDocument: CPDFDocument?
  38. var insertDocument: CPDFDocument?
  39. var type: KMPDFEditInsertType = .management
  40. var fromFilePath: URL?
  41. private var _insertPages: [CPDFPage] = []
  42. private var _selectPagesIndex: Int = 0
  43. private var _password: String = ""
  44. private var _fromFilePassword: String = ""
  45. private var _insertPageIndex: Int = 0
  46. var callback: ((CPDFDocument?, NSString?, [CPDFPage]?, Int) -> Void)?
  47. var fileAttribute = KMFileAttribute()
  48. convenience init(document: CPDFDocument, path: URL, password: String? = nil) {
  49. self.init(windowNibName: "KMPDFEditInsertPageWindow")
  50. self.insertDocument = CPDFDocument(url: path)
  51. if let data = self.insertDocument?.isLocked, data {
  52. self.insertDocument?.unlock(withPassword: password ?? "")
  53. }
  54. self.fromFilePath = path
  55. self.type = .pageEdit
  56. self.pdfDocument = document
  57. }
  58. convenience init(documentPath: URL) {
  59. self.init(windowNibName: "KMPDFEditInsertPageWindow")
  60. self.type = .management
  61. self.currentPage = 1
  62. self.pdfDocument = CPDFDocument(url: documentPath)
  63. }
  64. override func windowDidLoad() {
  65. super.windowDidLoad()
  66. self._insertPages = []
  67. var viewColor = NSColor.white
  68. var viewborderColor = NSColor(red: 195.0/255.0, green: 195.0/255.0, blue: 195.0/255.0, alpha: 1)
  69. var textColor = NSColor(red: 51.0/255.0, green: 51.0/255.0, blue: 51.0/255.0, alpha: 1)
  70. if KMAppearance.isSupportNewColor() {
  71. if KMAppearance.isDarkMode() {
  72. viewColor = NSColor(red: 101.0/255.0, green: 101.0/255.0, blue: 101.0/255.0, alpha: 1)
  73. viewborderColor = NSColor.clear
  74. textColor = .white
  75. }
  76. }
  77. self.outputFolderText.textColor = textColor
  78. self.selectedPathButton.title = KMLocalizedString("Choose...")
  79. self.whereInsertLabel.stringValue = KMLocalizedString("Where to insert?")
  80. self.pageLabel.stringValue = KMLocalizedString("Page")
  81. self.progress.isHidden = true
  82. self.outputFolderText.isEditable = false
  83. self.pagesText.isEditable = false
  84. self.byPageStepper.isEnabled = false
  85. self.locationFirstButton.title = KMLocalizedString("First")
  86. self.locationLastButton.title = KMLocalizedString("Last")
  87. self.cancelButton.title = KMLocalizedString("Cancel")
  88. self.insertButton.title = KMLocalizedString("Insert")
  89. self.pagesText.formatter = TextFieldFormatter()
  90. self.pagesText.delegate = self
  91. self.allPageButton.title = KMLocalizedString("All Pages")
  92. self.singlePageButton.title = KMLocalizedString("Odd Pages Only")
  93. self.doublePageButton.title = KMLocalizedString("Even Pages Only")
  94. self.rangeTextField.placeholderString = KMLocalizedString("e.g. 1,3-5,10")
  95. self.insertLabel.stringValue = KMLocalizedString("Page Range")
  96. if(self.type == .pageEdit) {
  97. self.customTextField.stringValue = String(format: "/ %ld", self.insertDocument?.pageCount ?? 0)
  98. self.outputFolderText.stringValue = self.fromFilePath?.path ?? ""
  99. }
  100. self._selectPagesIndex = 0
  101. self.rangeTextField.isEnabled = self.customPageButton.state == .on
  102. self.allPageButton.state = .on
  103. let menu = NSMenu()
  104. _ = menu.addItem(title: KMLocalizedString("After"), action: #selector(after_Action), target: self)
  105. _ = menu.addItem(title: KMLocalizedString("Before"), action: #selector(before_Action), target: self)
  106. self.locationRangePopUpButton.menu = menu
  107. self.outputFolderText.placeholderString = KMLocalizedString("Select a File")
  108. self.locationRangePopUpButton.isEnabled = false
  109. if let data = self.pdfDocument?.isLocked, data {
  110. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  111. KMBaseWindowController.checkPassword(url: self.pdfDocument!.documentURL, type: .owner) { success, resultPassword in
  112. if (resultPassword.isEmpty == false) {
  113. self.pdfDocument?.unlock(withPassword: resultPassword)
  114. self._password = resultPassword
  115. self.pageCountLabel.stringValue = String(format: "/%ld", self.pdfDocument?.pageCount ?? 0)
  116. self.byPageStepper.minValue = 1.0
  117. self.byPageStepper.maxValue = Double(self.pdfDocument?.pageCount ?? 0)
  118. }
  119. }
  120. }
  121. } else {
  122. self.byPageStepper.minValue = 1.0
  123. self.byPageStepper.maxValue = Double(self.pdfDocument?.pageCount ?? 0)
  124. self.pageCountLabel.stringValue = String(format: "/%ld", self.pdfDocument?.pageCount ?? 0)
  125. }
  126. if (self.insertLocation == 2) {
  127. self.locationLastButton.state = .on
  128. } else if (self.insertLocation == 3) {
  129. self.rangeButton.state = .on
  130. self.locationRangePopUpButton.isEnabled = true
  131. self.pagesText.isEditable = true
  132. self.byPageStepper.isEnabled = true
  133. } else {
  134. self.locationFirstButton.state = .on
  135. }
  136. self.pagesText.stringValue = String(format: "%ld", self.currentPage)
  137. self.byPageStepper.integerValue = Int(self.pagesText.stringValue) ?? 0
  138. }
  139. @IBAction func byPageStepperAction(_ sender: AnyObject) {
  140. self.pagesText.stringValue = "\(self.byPageStepper.integerValue)"
  141. }
  142. @IBAction func buttonItemClicked_Location(_ sender: NSButton) {
  143. if (sender == self.rangeButton) {
  144. self.pagesText.isEditable = true
  145. self.locationRangePopUpButton.isEnabled = true
  146. self.byPageStepper.isEnabled = true
  147. } else {
  148. self.pagesText.isEditable = false
  149. self.locationRangePopUpButton.isEnabled = false
  150. self.byPageStepper.isEnabled = false
  151. }
  152. }
  153. @IBAction func buttonItemClicked_Cancel(_ sender: AnyObject) {
  154. self.pdfDocument = nil
  155. guard let block = self.callback else {
  156. return
  157. }
  158. block(nil, nil, nil, 0)
  159. }
  160. @IBAction func buttonItemClicked_Insert(_ sender: AnyObject) {
  161. if (self.insertDocument == nil) {
  162. return
  163. }
  164. let fromDocument = CPDFDocument(url: self.fromFilePath)
  165. if let data = (fromDocument?.isLocked), data {
  166. fromDocument?.unlock(withPassword: self.insertDocument?.password ?? "")
  167. }
  168. self.progress.isHidden = false
  169. self.cancelButton.isEnabled = false
  170. self.insertButton.isEnabled = false
  171. self.progress.startAnimation(nil)
  172. var pages: [CPDFPage] = []
  173. if self.outputFolderText.stringValue == "" || self.outputFolderText.stringValue.isEmpty {
  174. let alert = NSAlert()
  175. alert.alertStyle = .critical
  176. alert.messageText = KMLocalizedString("Select a File")
  177. alert.runModal()
  178. self.progress.isHidden = true
  179. self.cancelButton.isEnabled = true
  180. self.insertButton.isEnabled = true
  181. self.progress.stopAnimation(nil)
  182. return
  183. }
  184. let fileAttribute = KMFileAttribute()
  185. self.fileAttribute = fileAttribute
  186. fileAttribute.password = self.insertDocument?.password ?? ""
  187. fileAttribute.filePath = self.outputFolderText.stringValue
  188. if ((0 == self._selectPagesIndex)) {
  189. fileAttribute.bAllPage = true
  190. fileAttribute.pagesType = .all
  191. } else if(1 == self._selectPagesIndex){
  192. fileAttribute.bAllPage = false
  193. fileAttribute.pagesType = .odd
  194. let tDocument = CPDFDocument(url: URL(fileURLWithPath: fileAttribute.filePath))
  195. var tPagesString = ""
  196. for i in 0 ..< (tDocument?.pageCount ?? 0) {
  197. if (i%2 == 0) {
  198. if (tPagesString.isEmpty) {
  199. tPagesString.append("\(i+1)")
  200. }else{
  201. tPagesString.append(",\(i+1)")
  202. }
  203. }
  204. }
  205. fileAttribute.pagesString = tPagesString
  206. } else if (2 == self._selectPagesIndex){
  207. fileAttribute.bAllPage = false
  208. fileAttribute.pagesType = .even
  209. let tDocument = CPDFDocument(url: URL(fileURLWithPath: fileAttribute.filePath))
  210. var tPagesString = ""
  211. for i in 0 ..< (tDocument?.pageCount ?? 0) {
  212. if (i%2 == 1) {
  213. if (tPagesString.isEmpty) {
  214. tPagesString.append("\(i+1)")
  215. }else{
  216. tPagesString.append(",\(i+1)")
  217. }
  218. }
  219. }
  220. fileAttribute.pagesString = tPagesString
  221. } else {
  222. fileAttribute.bAllPage = false
  223. fileAttribute.pagesType = .custom
  224. fileAttribute.pagesString = self.rangeTextField.stringValue
  225. }
  226. if (fileAttribute.fetchSelectPages().isEmpty) {
  227. let alert = NSAlert()
  228. alert.alertStyle = .critical
  229. alert.messageText = String(format: "%@ %@", fileAttribute.filePath.lastPathComponent, KMLocalizedString("Invalid page range or the page number is out of range. Please try again."))
  230. alert.runModal()
  231. self.progress.isHidden = true
  232. self.cancelButton.isEnabled = true
  233. self.insertButton.isEnabled = true
  234. self.progress.stopAnimation(nil)
  235. return
  236. } else {
  237. for number in fileAttribute.fetchSelectPages() {
  238. // let page = self.insertDocument?.page(at: UInt(number.intValue-1)).copy()
  239. // pages.append(page as! CPDFPage)
  240. }
  241. }
  242. var index = 0
  243. if (self.locationFirstButton.state == .on) {
  244. index = 0
  245. } else if (self.locationLastButton.state == .on) {
  246. index = Int(self.pdfDocument?.pageCount ?? 0)
  247. } else {
  248. index = Int(self.pagesText.stringValue) ?? 0
  249. if ((1 == self.locationRangePopUpButton.indexOfSelectedItem)) {
  250. index = index - 1
  251. }
  252. }
  253. for page in pages {
  254. self._insertPages.append(page)
  255. }
  256. self._insertPageIndex = index
  257. self.progress.isHidden = true
  258. self.cancelButton.isEnabled = true
  259. self.insertButton.isEnabled = true
  260. self.progress.stopAnimation(nil)
  261. guard let block = self.callback else {
  262. return
  263. }
  264. block(self.pdfDocument, self._password as NSString, self._insertPages, self._insertPageIndex)
  265. }
  266. @IBAction func buttonItemClicked_OutputFolder(_ sender: AnyObject) {
  267. let openPanel = NSOpenPanel()
  268. openPanel.allowedFileTypes = ["pdf"]
  269. openPanel.beginSheetModal(for: self.window!) { result in
  270. if (result == .OK) {
  271. for fileURL in openPanel.urls {
  272. let pdfDoc = CPDFDocument(url: fileURL)
  273. if let data = pdfDoc?.isLocked, data {
  274. DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
  275. KMBaseWindowController.checkPassword(url: fileURL, type: .owner) { result, pwd in
  276. if (pwd.isEmpty == false) {
  277. self._password = pwd
  278. self.fromFilePath = fileURL
  279. self.insertDocument = CPDFDocument(url: fileURL)
  280. if let data = self.insertDocument?.isLocked, data {
  281. self.insertDocument?.unlock(withPassword: pwd)
  282. }
  283. self.customTextField.stringValue = String(format: "/ %ld", self.insertDocument?.pageCount ?? 0)
  284. self.outputFolderText.stringValue = self.fromFilePath?.path ?? ""
  285. self.window?.makeFirstResponder(self)
  286. self.pagesText.stringValue = "1"
  287. self.insertButton.isEnabled = true
  288. }
  289. }
  290. }
  291. } else {
  292. self.fromFilePath = fileURL
  293. self.outputFolderText.stringValue = self.fromFilePath?.path ?? ""
  294. self.insertDocument = CPDFDocument(url: fileURL)
  295. self.customTextField.stringValue = String(format: "/ %ld", self.insertDocument?.pageCount ?? 0)
  296. self.window?.makeFirstResponder(self)
  297. self.pagesText.stringValue = "1"
  298. self.insertButton.isEnabled = true
  299. }
  300. }
  301. }
  302. }
  303. }
  304. @IBAction func customPageButton_Action(_ sender: NSButton) {
  305. self.allPageButton.state = .off
  306. self.singlePageButton.state = .off
  307. self.doublePageButton.state = .off
  308. self.customPageButton.state = .off
  309. sender.state = .on
  310. self.rangeTextField.isEnabled = false
  311. self.customTextField.textColor = NSColor.disabledControlTextColor
  312. self._selectPagesIndex = sender.tag
  313. if (sender.tag == 3) {
  314. self.rangeTextField.isEnabled = true
  315. self.customTextField.textColor = NSColor.labelColor
  316. self.window?.makeFirstResponder(self.rangeTextField)
  317. if(self.rangeTextField.stringValue.isEmpty) {
  318. return
  319. }
  320. }
  321. }
  322. override func keyDown(with event: NSEvent) {
  323. super.keyDown(with: event)
  324. self.window?.makeFirstResponder(nil)
  325. }
  326. @IBAction func after_Action(_ sender: AnyObject?) {
  327. }
  328. @IBAction func before_Action(_ sender: AnyObject?) {
  329. }
  330. }
  331. extension KMPDFEditInsertPageWindow: NSTextFieldDelegate {
  332. func controlTextDidChange(_ obj: Notification) {
  333. let textField = obj.object as? NSTextField
  334. if (self.pagesText.isEqual(to: textField)) {
  335. if let data = Int(textField!.stringValue), data <= 0 {
  336. self.pagesText.stringValue = "1"
  337. self.byPageStepper.integerValue = 1
  338. } else if let data = textField?.stringValue.stringToCGFloat(), data > self.byPageStepper.maxValue {
  339. self.pagesText.stringValue = String(format: "%.0f", self.byPageStepper.maxValue)
  340. self.byPageStepper.integerValue = Int(self.byPageStepper.maxValue)
  341. } else {
  342. self.byPageStepper.integerValue = Int(self.pagesText.stringValue) ?? 0
  343. }
  344. }
  345. }
  346. }
  347. // MARK: - Private Methods
  348. extension KMPDFEditInsertPageWindow {
  349. /*
  350. #pragma mark Private methor
  351. - (void)viewFileAtFinder:(NSString *)filePath
  352. {
  353. NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
  354. NSURL *url = [NSURL fileURLWithPath:filePath];
  355. [workspace activateFileViewerSelectingURLs:[NSArray arrayWithObject:url]];
  356. }
  357. */
  358. }