KMPDFInsertWindowController.swift 18 KB

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