KMPDFInsertWindowController.swift 18 KB

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