KMPDFEditInsertPageWindow.swift 17 KB

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