KMPDFEditInsertPageWindow.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  110. // PasswordWindowController *passwordVC = [[PasswordWindowController alloc] initWithWindowNibName:@"PasswordWindowController"];
  111. // passwordVC.fileURL = [self.pdfDocument documentURL];
  112. //
  113. // [passwordVC beginSheetModalForWindow:self.window completionHandler:^(NSString *password) {
  114. // if (password) {
  115. // [_pdfDocument unlockWithPassword:password];
  116. // self.password = password;
  117. //
  118. // _pageCountLabel.stringValue = [NSString stringWithFormat:@"/%ld",_pdfDocument.pageCount];
  119. // _byPageStepper.minValue = 1.0;
  120. // _byPageStepper.maxValue = _pdfDocument.pageCount;
  121. //
  122. // }
  123. // }];
  124. // [passwordVC release];
  125. // });
  126. } else {
  127. self.byPageStepper.minValue = 1.0
  128. self.byPageStepper.maxValue = Double(self.pdfDocument?.pageCount ?? 0)
  129. self.pageCountLabel.stringValue = String(format: "/%ld", self.pdfDocument?.pageCount ?? 0)
  130. }
  131. if (self.insertLocation == 2) {
  132. self.locationLastButton.state = .on
  133. } else if (self.insertLocation == 3) {
  134. self.rangeButton.state = .on
  135. self.locationRangePopUpButton.isEnabled = true
  136. self.pagesText.isEditable = true
  137. self.byPageStepper.isEnabled = true
  138. } else {
  139. self.locationFirstButton.state = .on
  140. }
  141. self.pagesText.stringValue = String(format: "%ld", self.currentPage)
  142. self.byPageStepper.integerValue = Int(self.pagesText.stringValue) ?? 0
  143. }
  144. @IBAction func byPageStepperAction(_ sender: AnyObject) {
  145. self.pagesText.stringValue = "\(self.byPageStepper.integerValue)"
  146. }
  147. @IBAction func buttonItemClicked_Location(_ sender: NSButton) {
  148. if (sender == self.rangeButton) {
  149. self.pagesText.isEditable = true
  150. self.locationRangePopUpButton.isEnabled = true
  151. self.byPageStepper.isEnabled = true
  152. } else {
  153. self.pagesText.isEditable = false
  154. self.locationRangePopUpButton.isEnabled = false
  155. self.byPageStepper.isEnabled = false
  156. }
  157. }
  158. @IBAction func buttonItemClicked_Cancel(_ sender: AnyObject) {
  159. self.pdfDocument = nil
  160. guard let block = self.callback else {
  161. return
  162. }
  163. block(nil, nil, nil, 0)
  164. }
  165. @IBAction func buttonItemClicked_Insert(_ sender: AnyObject) {
  166. if (self.insertDocument == nil) {
  167. return
  168. }
  169. let fromDocument = CPDFDocument(url: self.fromFilePath)
  170. if (fromDocument!.isLocked) {
  171. fromDocument?.unlock(withPassword: self._fromFilePassword)
  172. }
  173. self.progress.isHidden = false
  174. self.cancelButton.isEnabled = false
  175. self.insertButton.isEnabled = false
  176. self.progress.startAnimation(nil)
  177. var pages: [CPDFPage] = []
  178. if self.outputFolderText.stringValue == "" || self.outputFolderText.stringValue.isEmpty {
  179. let alert = NSAlert()
  180. alert.alertStyle = .critical
  181. alert.messageText = KMLocalizedString("Select a File", nil)
  182. alert.runModal()
  183. self.progress.isHidden = true
  184. self.cancelButton.isEnabled = true
  185. self.insertButton.isEnabled = true
  186. self.progress.stopAnimation(nil)
  187. return
  188. }
  189. let fileAttribute = KMFileAttribute()
  190. fileAttribute.filePath = self.outputFolderText.stringValue
  191. if ((0 == self._selectPagesIndex)) {
  192. fileAttribute.bAllPage = true
  193. } else if(1 == self._selectPagesIndex){
  194. fileAttribute.bAllPage = false
  195. let tDocument = CPDFDocument(url: URL(fileURLWithPath: fileAttribute.filePath))
  196. var tPagesString = ""
  197. for i in 0 ..< tDocument!.pageCount {
  198. if (i%2 == 0) {
  199. if (tPagesString.isEmpty) {
  200. tPagesString.append("\(i+1)")
  201. }else{
  202. tPagesString.append(",\(i+1)")
  203. }
  204. }
  205. }
  206. fileAttribute.pagesString = tPagesString
  207. } else if (2 == self._selectPagesIndex){
  208. fileAttribute.bAllPage = false
  209. let tDocument = CPDFDocument(url: URL(fileURLWithPath: fileAttribute.filePath))
  210. var tPagesString = ""
  211. for i in 0 ..< tDocument!.pageCount {
  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.pagesString = self.rangeTextField.stringValue
  224. }
  225. if (fileAttribute.fetchSelectPages().isEmpty) {
  226. let alert = NSAlert()
  227. alert.alertStyle = .critical
  228. alert.messageText = String(format: "%@ %@", fileAttribute.filePath.lastPathComponent, KMLocalizedString("Invalid page range or the page number is out of range. Please try again.", nil))
  229. alert.runModal()
  230. self.progress.isHidden = true
  231. self.cancelButton.isEnabled = true
  232. self.insertButton.isEnabled = true
  233. self.progress.stopAnimation(nil)
  234. return
  235. } else {
  236. for number in fileAttribute.fetchSelectPages() {
  237. let page = self.insertDocument?.page(at: UInt(number.intValue-1)).copy()
  238. pages.append(page as! CPDFPage)
  239. }
  240. }
  241. var index = 0
  242. if (self.locationFirstButton.state == .on) {
  243. index = 0
  244. } else if (self.locationLastButton.state == .on) {
  245. index = Int(self.pdfDocument?.pageCount ?? 0)
  246. } else {
  247. index = Int(self.pagesText.stringValue) ?? 0
  248. if ((1 == self.locationRangePopUpButton.indexOfSelectedItem)) {
  249. index = index - 1
  250. }
  251. }
  252. for page in pages {
  253. self._insertPages.append(page)
  254. }
  255. self._insertPageIndex = index
  256. self.progress.isHidden = true
  257. self.cancelButton.isEnabled = true
  258. self.insertButton.isEnabled = true
  259. self.progress.stopAnimation(nil)
  260. guard let block = self.callback else {
  261. return
  262. }
  263. block(self.pdfDocument, self._password as NSString, self._insertPages, self._insertPageIndex)
  264. }
  265. @IBAction func buttonItemClicked_OutputFolder(_ sender: AnyObject) {
  266. let openPanel = NSOpenPanel()
  267. openPanel.allowedFileTypes = ["pdf"]
  268. openPanel.beginSheetModal(for: self.window!) { result in
  269. // }
  270. // [openPanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result){
  271. if (result == .OK) {
  272. for fileURL in openPanel.urls {
  273. // for (NSURL * in [openPanel URLs]) {
  274. // PDFDocument *pdfDoc = [[PDFDocument alloc] initWithURL:fileURL];
  275. // if ([pdfDoc isLocked]) {
  276. // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  277. // PasswordWindowController *com = [[PasswordWindowController alloc] initWithWindowNibName:@"PasswordWindowController"];
  278. // com.fileURL = fileURL;
  279. //
  280. // [com beginSheetModalForWindow:self.window completionHandler:^(NSString *password) {
  281. // if (password) {
  282. // self.password = password;
  283. // self.fromFilePath = fileURL;
  284. // self.insertDocument = [[[PDFDocument alloc] initWithURL:fileURL] autorelease];
  285. // if([self.insertDocument isLocked]) {
  286. // [self.insertDocument unlockWithPassword:password];
  287. // }
  288. // self.customTextField.stringValue = [NSString stringWithFormat:@"/ %ld",self.insertDocument.pageCount];
  289. // _outputFolderText.stringValue = [_fromFilePath path];
  290. //
  291. // [self.window makeFirstResponder:self];
  292. // _pagesText.stringValue = [NSString stringWithFormat:@"%d",1];
  293. // [_insertButton setEnabled:YES];
  294. //
  295. // }
  296. // }];
  297. // [com release];
  298. // });
  299. // } else {
  300. self.fromFilePath = fileURL
  301. self.outputFolderText.stringValue = self.fromFilePath!.path
  302. self.insertDocument = CPDFDocument(url: fileURL)
  303. self.customTextField.stringValue = String(format: "/ %ld", self.insertDocument?.pageCount ?? 0)
  304. self.window?.makeFirstResponder(self)
  305. self.pagesText.stringValue = "1"
  306. self.insertButton.isEnabled = true
  307. // }
  308. // [pdfDoc release];
  309. }
  310. }
  311. }
  312. }
  313. @IBAction func customPageButton_Action(_ sender: NSButton) {
  314. self.allPageButton.state = .off
  315. self.singlePageButton.state = .off
  316. self.doublePageButton.state = .off
  317. self.customPageButton.state = .off
  318. sender.state = .on
  319. self.rangeTextField.isEnabled = false
  320. self.customTextField.textColor = NSColor.disabledControlTextColor
  321. self._selectPagesIndex = sender.tag
  322. if (sender.tag == 3) {
  323. self.rangeTextField.isEnabled = true
  324. self.customTextField.textColor = NSColor.labelColor
  325. self.window?.makeFirstResponder(self.rangeTextField)
  326. if(self.rangeTextField.stringValue.isEmpty) {
  327. return
  328. }
  329. }
  330. }
  331. override func keyDown(with event: NSEvent) {
  332. super.keyDown(with: event)
  333. self.window?.makeFirstResponder(nil)
  334. }
  335. @IBAction func after_Action(_ sender: AnyObject?) {
  336. }
  337. @IBAction func before_Action(_ sender: AnyObject?) {
  338. }
  339. }
  340. extension KMPDFEditInsertPageWindow: NSTextFieldDelegate {
  341. func controlTextDidChange(_ obj: Notification) {
  342. let textField = obj.object as? NSTextField
  343. if (self.pagesText.isEqual(to: textField)) {
  344. if let data = Int(textField!.stringValue), data <= 0 {
  345. self.pagesText.stringValue = "1"
  346. self.byPageStepper.integerValue = 1
  347. } else if let data = textField?.stringValue.stringToCGFloat(), data > self.byPageStepper.maxValue {
  348. self.pagesText.stringValue = String(format: "%.0f", self.byPageStepper.maxValue)
  349. self.byPageStepper.integerValue = Int(self.byPageStepper.maxValue)
  350. } else {
  351. self.byPageStepper.integerValue = Int(self.pagesText.stringValue) ?? 0
  352. }
  353. }
  354. }
  355. }
  356. // MARK: - Private Methods
  357. extension KMPDFEditInsertPageWindow {
  358. /*
  359. #pragma mark Private methor
  360. - (void)viewFileAtFinder:(NSString *)filePath
  361. {
  362. NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
  363. NSURL *url = [NSURL fileURLWithPath:filePath];
  364. [workspace activateFileViewerSelectingURLs:[NSArray arrayWithObject:url]];
  365. }
  366. */
  367. }