KMMergeWindowController.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. //
  2. // KMMergeWindowController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lizhe on 2023/11/8.
  6. //
  7. import Cocoa
  8. typealias KMMergeWindowControllerCancelAction = (_ controller: KMMergeWindowController) -> Void
  9. typealias KMMergeWindowControllerAddFilesAction = (_ controller: KMMergeWindowController) -> Void
  10. typealias KMMergeWindowControllerMergeAction = (_ controller: KMMergeWindowController, _ filePath: String) -> Void
  11. typealias KMMergeWindowControllerClearAction = (_ controller: KMMergeWindowController) -> Void
  12. class KMMergeWindowController: KMBaseWindowController {
  13. @IBOutlet weak var mergeView: KMMergeView!
  14. // var cancelAction: KMMergeWindowControllerCancelAction?
  15. var oldPDFDocument: PDFDocument = PDFDocument()
  16. var password: String = ""
  17. var oriDucumentUrl: URL? {
  18. didSet {
  19. oldPDFDocument = PDFDocument(url: oriDucumentUrl!)!
  20. oldPDFDocument.unlock(withPassword: self.password)
  21. }
  22. }
  23. var type: KMMergeViewType = .add
  24. var pageIndex: Int?
  25. var mergeAction: KMMergeWindowControllerMergeAction?
  26. convenience init(document: PDFDocument, password: String) {
  27. self.init(windowNibName: "KMMergeWindowController")
  28. self.password = password
  29. }
  30. override func windowDidLoad() {
  31. super.windowDidLoad()
  32. self.window!.title = NSLocalizedString("Merge PDF Files", comment: "");
  33. // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
  34. self.mergeView.type = self.type
  35. mergeView.addFilesAction = { [weak self] view in
  36. guard let self = self else { return }
  37. self.addFile()
  38. }
  39. mergeView.clearAction = { view in
  40. }
  41. mergeView.mergeAction = { [weak self] view, files, size in
  42. guard let self = self else { return }
  43. self.mergeFiles(files: files, size: size)
  44. }
  45. mergeView.cancelAction = { [weak self] view in
  46. guard let self = self else { return }
  47. self._clearImageData()
  48. self.cancelAction?(self)
  49. }
  50. }
  51. }
  52. extension KMMergeWindowController {
  53. func addFile() {
  54. var size = 0.0
  55. let files = self.mergeView.files
  56. for file in files {
  57. size = size + file.fileSize
  58. }
  59. if !IAPProductsManager.default().isAvailableAllFunction() && (files.count >= 2 || size > 20 * 1024 * 1024) {
  60. let winC = KMPurchaseCompareWindowController.sharedInstance()
  61. if self.kEventTag == 1 {
  62. winC?.kEventName = "Onbrd_Merge_BuyNow"
  63. } else {
  64. winC?.kEventName = "Reading_Merge_BuyNow"
  65. }
  66. winC?.showWindow(nil)
  67. return
  68. }
  69. let openPanel = NSOpenPanel()
  70. openPanel.allowedFileTypes = KMTools.imageExtensions + KMTools.pdfExtensions
  71. if KMPurchaseManager.manager.state == .subscription {
  72. openPanel.allowsMultipleSelection = true
  73. openPanel.message = NSLocalizedString("Select files to merge. To select multiple files press cmd ⌘ button on keyboard and click on the target files one by one.", comment: "")
  74. } else {
  75. openPanel.allowsMultipleSelection = false
  76. openPanel.message = NSLocalizedString("Select files to merge, only one file can be selected at a time.", comment: "")
  77. }
  78. openPanel.beginSheetModal(for: self.window!) { (result) in
  79. if result == NSApplication.ModalResponse.OK {
  80. var array: [URL] = []
  81. for fileURL in openPanel.urls {
  82. if KMTools.isImageType(fileURL.pathExtension) {
  83. if let image = NSImage(contentsOf: fileURL) {
  84. if let page = PDFPage(image: image) {
  85. let document = PDFDocument()
  86. document.insert(page, at: 0)
  87. var path = self._saveImagePath() + "/" + fileURL.deletingPathExtension().lastPathComponent + ".pdf"
  88. path = KMTools.getUniqueFilePath(filePath: path)
  89. let result = document.write(toFile: path)
  90. if result {
  91. let file = KMFileAttribute()
  92. file.filePath = path
  93. file.oriFilePath = fileURL.path
  94. file.myPDFDocument = document
  95. let attribe = try?FileManager.default.attributesOfItem(atPath: fileURL.path)
  96. let fileSize = attribe?[FileAttributeKey.size] as? CGFloat ?? 0
  97. size = fileSize + size
  98. if !IAPProductsManager.default().isAvailableAllFunction() && (files.count >= 2 || size > 20 * 1024 * 1024) {
  99. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  100. return
  101. }
  102. self.mergeView.files.append(file)
  103. }
  104. }
  105. } else {
  106. Task {
  107. _ = await KMAlertTool.runModel(message: NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: ""))
  108. }
  109. }
  110. } else {
  111. array.append(fileURL)
  112. }
  113. }
  114. let attribe = try?FileManager.default.attributesOfItem(atPath: openPanel.urls.first!.path)
  115. let fileSize = attribe?[FileAttributeKey.size] as? CGFloat ?? 0
  116. size = fileSize + size
  117. if !IAPProductsManager.default().isAvailableAllFunction() && (files.count >= 2 || size > 20 * 1024 * 1024) {
  118. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  119. return
  120. }
  121. self.mergeView.addFilePaths(urls: array)
  122. }
  123. }
  124. }
  125. private func _saveImagePath() -> String {
  126. let rootPath = KMDataManager.fetchAppSupportOfBundleIdentifierDirectory()
  127. let path = rootPath.appendingPathComponent("Merge").path
  128. if FileManager.default.fileExists(atPath: path) == false {
  129. try?FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: false)
  130. }
  131. return path
  132. }
  133. private func _clearImageData() {
  134. let path = self._saveImagePath()
  135. if FileManager.default.fileExists(atPath: path) {
  136. try?FileManager.default.removeItem(atPath: path)
  137. }
  138. }
  139. func mergeFiles(files: [KMFileAttribute], size: CGSize = .zero) {
  140. var size = 0.0
  141. for file in files {
  142. size = size + file.fileSize
  143. }
  144. if !IAPProductsManager.default().isAvailableAllFunction() && (files.count >= 2 || size > 20 * 1024 * 1024) {
  145. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  146. return
  147. }
  148. var filesCount = 1
  149. if self.oriDucumentUrl != nil {
  150. filesCount = 0
  151. }
  152. if files.count <= filesCount {
  153. let alert = NSAlert.init()
  154. alert.alertStyle = .critical
  155. alert.messageText = NSLocalizedString("To start merging, please select at least 2 files.", comment: "")
  156. alert.runModal()
  157. return
  158. }
  159. var rootPDFOutlineArray: [PDFOutline] = []
  160. var allPage = true //只有是全部才支持大纲的合并
  161. for file in files {
  162. if file.fetchSelectPages().count == 0 {
  163. let alert = NSAlert.init()
  164. alert.alertStyle = .critical
  165. alert.messageText = "\(file.filePath.lastPathComponent) + \(NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
  166. alert.runModal()
  167. return
  168. }
  169. allPage = file.bAllPage
  170. /*防止文件被地址变换后crash*/
  171. guard let tDocument = PDFDocument(url: NSURL(fileURLWithPath: file.filePath) as URL) else {
  172. print("文件不存在")
  173. let alert = NSAlert.init()
  174. alert.alertStyle = .critical
  175. alert.messageText = "\(file.filePath.lastPathComponent) + \(NSLocalizedString("Failed to merge!", comment: ""))"
  176. alert.runModal()
  177. return
  178. }
  179. var outlineArray: [PDFOutline] = []
  180. tDocument.unlock(withPassword: file.password)
  181. if tDocument.outlineRoot != nil {
  182. rootPDFOutlineArray.append((tDocument.outlineRoot)!)
  183. self.fetchAllOfChildren((tDocument.outlineRoot)!, containerArray: &outlineArray)
  184. outlineArray.removeObject((tDocument.outlineRoot)!)
  185. } else {
  186. let rootOutline = PDFOutline.init()
  187. tDocument.outlineRoot = rootOutline
  188. if tDocument.outlineRoot != nil {
  189. rootPDFOutlineArray.append(tDocument.outlineRoot!)
  190. }
  191. }
  192. for number in file.fetchSelectPages() {
  193. let page = tDocument.page(at: number - 1)
  194. self.oldPDFDocument.insert(page!, at: self.oldPDFDocument.pageCount)
  195. }
  196. }
  197. var theFilepath = files.first?.filePath
  198. if let filepath = files.first?.oriFilePath {
  199. theFilepath = filepath
  200. }
  201. let fileName = (theFilepath?.deletingPathExtension.lastPathComponent ?? "") + "_Merged"
  202. DispatchQueue.main.async {
  203. if self.oldPDFDocument.outlineRoot == nil {
  204. self.oldPDFDocument.outlineRoot = PDFOutline.init()
  205. }
  206. var insertIndex = 0
  207. for i in 0..<rootPDFOutlineArray.count {
  208. let rootOutline = rootPDFOutlineArray[i]
  209. for j in 0..<rootOutline.numberOfChildren {
  210. self.oldPDFDocument.outlineRoot?.insertChild(rootOutline.child(at: j)!, at: insertIndex)
  211. insertIndex = insertIndex + 1
  212. }
  213. }
  214. self.handleReDraw()
  215. if self.oriDucumentUrl != nil {
  216. let newPath = self.oldPDFDocument.documentURL!.path
  217. var options: [PDFDocumentWriteOption : Any] = [:]
  218. var success = false
  219. let password = self.password
  220. let pdf = self.oldPDFDocument
  221. let savePanelAccessoryViewController = KMSavePanelAccessoryController.init()
  222. let savePanel = NSSavePanel()
  223. savePanel.nameFieldStringValue = fileName
  224. savePanel.allowedFileTypes = ["pdf"]
  225. savePanel.accessoryView = savePanelAccessoryViewController.view
  226. savePanel.beginSheetModal(for: self.window!) { result in
  227. if result == .OK {
  228. self._clearImageData()
  229. self.cancelAction?()
  230. var outputSavePanel = savePanel.url?.path ?? ""
  231. DispatchQueue.main.async {
  232. var success = false
  233. if pdf.isEncrypted {
  234. options.updateValue(password, forKey: .userPasswordOption)
  235. options.updateValue(password, forKey: .ownerPasswordOption)
  236. success = pdf.write(toFile: outputSavePanel, withOptions: options)
  237. } else {
  238. success = pdf.write(toFile: outputSavePanel)
  239. }
  240. if success {
  241. if savePanelAccessoryViewController.needOpen {
  242. NSDocumentController.shared.openDocument(withContentsOf: savePanel.url!, display: true) { document, open, error in
  243. }
  244. } else {
  245. NSWorkspace.shared.activateFileViewerSelecting([NSURL(fileURLWithPath: outputSavePanel) as URL])
  246. }
  247. } else {
  248. let alert = NSAlert.init()
  249. alert.alertStyle = .critical
  250. alert.messageText = "\(String(describing: files.first?.filePath.lastPathComponent)) + \(NSLocalizedString("Failed to merge!", comment: ""))"
  251. alert.runModal()
  252. }
  253. }
  254. }
  255. }
  256. } else {
  257. let savePanelAccessoryViewController = KMSavePanelAccessoryController.init()
  258. let savePanel = NSSavePanel()
  259. savePanel.nameFieldStringValue = fileName
  260. savePanel.allowedFileTypes = ["pdf"]
  261. savePanel.accessoryView = savePanelAccessoryViewController.view
  262. savePanel.beginSheetModal(for: self.window!) { result in
  263. if result == .OK {
  264. self._clearImageData()
  265. self.cancelAction?()
  266. var outputSavePanel = savePanel.url?.path
  267. DispatchQueue.main.async {
  268. var success = self.oldPDFDocument.write(toFile: outputSavePanel!)
  269. if !success {
  270. success = ((try?self.oldPDFDocument.dataRepresentation()?.write(to: URL(string: outputSavePanel!)!)) != nil)
  271. }
  272. if success {
  273. if savePanelAccessoryViewController.needOpen {
  274. NSDocumentController.shared.openDocument(withContentsOf: savePanel.url!, display: true) { document, open, error in
  275. }
  276. } else {
  277. NSWorkspace.shared.activateFileViewerSelecting([NSURL(fileURLWithPath: outputSavePanel!) as URL])
  278. }
  279. } else {
  280. let alert = NSAlert.init()
  281. alert.alertStyle = .critical
  282. alert.messageText = "\(String(describing: files.first?.filePath.lastPathComponent)) + \(NSLocalizedString("Failed to merge!", comment: ""))"
  283. alert.runModal()
  284. }
  285. }
  286. }
  287. }
  288. }
  289. }
  290. }
  291. func fetchAllOfChildren(_ aOutline: PDFOutline, containerArray aMArray: inout [PDFOutline]) {
  292. if !aMArray.contains(aOutline) {
  293. aMArray.append(aOutline)
  294. }
  295. for i in 0..<aOutline.numberOfChildren {
  296. if let childOutline = aOutline.child(at: i) {
  297. aMArray.append(childOutline)
  298. fetchAllOfChildren(childOutline, containerArray: &aMArray)
  299. }
  300. }
  301. }
  302. func handleReDraw() {
  303. if mergeView.originalSizeButton.state == .on {
  304. } else {
  305. let size = self.mergeView.newPageSize
  306. if size.width < 0 {
  307. return
  308. }
  309. var pagesArray: [PDFPage] = []
  310. let pageCount = self.oldPDFDocument.pageCount
  311. for i in 0..<pageCount {
  312. pagesArray.append(self.oldPDFDocument.page(at: 0)!)
  313. self.oldPDFDocument.removePage(at: 0)
  314. }
  315. for i in 0..<pageCount {
  316. let page: KMMergePDFPage = KMMergePDFPage.init()
  317. page.setBounds(NSMakeRect(0, 0, size.width, size.height), for: .mediaBox)
  318. page.drawingPage = pagesArray[i]
  319. self.oldPDFDocument.insert(page, at: i)
  320. }
  321. if self.oldPDFDocument.outlineRoot != nil {
  322. let childCount = self.oldPDFDocument.outlineRoot?.numberOfChildren
  323. var outlineArray: [PDFOutline] = []
  324. for i in 0..<childCount! {
  325. outlineArray.append((self.oldPDFDocument.outlineRoot?.child(at: i))!)
  326. }
  327. for outline in outlineArray {
  328. outline.removeFromParent()
  329. }
  330. }
  331. }
  332. }
  333. }
  334. class KMMergePDFPage: PDFPage {
  335. var drawingPage: PDFPage?
  336. override func draw(with box: PDFDisplayBox, to context: CGContext) {
  337. super.draw(with: box, to: context)
  338. let pageSize = self.bounds(for: .cropBox).size
  339. self.drawPage(with: context, page: self.drawingPage!, pageSize: pageSize)
  340. }
  341. func drawPage(with context: CGContext, page: PDFPage, pageSize: CGSize) {
  342. var originalSize = page.bounds(for: .cropBox).size
  343. // 如果页面的旋转角度为90或者270,宽高交换
  344. if page.rotation % 180 != 0 {
  345. originalSize = CGSize(width: originalSize.height, height: originalSize.width)
  346. }
  347. let wRatio = pageSize.width / originalSize.width
  348. let hRatio = pageSize.height / originalSize.height
  349. let ratio = min(wRatio, hRatio)
  350. context.saveGState()
  351. let xTransform = (pageSize.width - originalSize.width * ratio) / 2
  352. let yTransform = (pageSize.height - originalSize.height * ratio) / 2
  353. context.translateBy(x: xTransform, y: yTransform)
  354. context.scaleBy(x: ratio, y: ratio)
  355. if #available(macOS 10.12, *) {
  356. page.draw(with: .cropBox, to: context)
  357. page.transformContext(for: .cropBox)
  358. } else {
  359. NSGraphicsContext.saveGraphicsState()
  360. NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: false)
  361. page.draw(with: .cropBox)
  362. NSGraphicsContext.restoreGraphicsState()
  363. page.transformContext(for: .cropBox)
  364. }
  365. context.restoreGState()
  366. }
  367. }