KMPDFEditViewController.swift 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665
  1. //
  2. // KMPDFEditViewController.swift
  3. // PDF Master
  4. //
  5. // Created by tangchao on 2023/1/6.
  6. //
  7. import Cocoa
  8. enum KMPageEditType: Int {
  9. case pageRange = 1
  10. case leftRotate = 2
  11. case rightRotate = 3
  12. case insert = 4
  13. case extract = 5
  14. case replace = 6
  15. case split = 7
  16. case reverse = 8
  17. case delete = 9
  18. }
  19. class KMPDFEditViewController: NSViewController {
  20. @IBOutlet weak var topBarBox: NSBox!
  21. @IBOutlet weak var contentBox: NSBox!
  22. var pageRangeView: KMDesignSelect?
  23. var pageRangeViewItems = [NSLocalizedString("All Pages", comment: ""),
  24. NSLocalizedString("Odd Pages", comment: ""),
  25. NSLocalizedString("Even Pages", comment: ""),
  26. NSLocalizedString("Horizontal Pages", comment: ""),
  27. NSLocalizedString("Vertical Pages", comment: ""),
  28. NSLocalizedString("Customized", comment: "")]
  29. var toolBar = KMToolbar()
  30. private var zoomOutButton: NSButton?
  31. private var zoomInButton: NSButton?
  32. lazy var rightItemView: NSView = {
  33. let view = NSView()
  34. let size: CGFloat = 28
  35. let y: CGFloat = 6
  36. let zoomOutButton = NSButton()
  37. view.addSubview(zoomOutButton)
  38. zoomOutButton.frame = NSMakeRect(0, y, size, size)
  39. zoomOutButton.isBordered = false
  40. zoomOutButton.image = NSImage(named: "KMImageNamePageEditZoomOut")
  41. zoomOutButton.target = self
  42. zoomOutButton.action = #selector(zoomOutButtonAction)
  43. self.zoomOutButton = zoomOutButton
  44. let zoomInButton = NSButton()
  45. view.addSubview(zoomInButton)
  46. zoomInButton.frame = NSMakeRect(size+7, y, size, size)
  47. zoomInButton.isBordered = false
  48. zoomInButton.image = NSImage(named: "KMImageNamePageEditZoomIn")
  49. zoomInButton.target = self
  50. zoomInButton.action = #selector(zoomInButtonAction)
  51. self.zoomInButton = zoomInButton
  52. return view
  53. }()
  54. var thumbnailView = KMPageEditThumbnailView()
  55. private var pdfDocument: CPDFDocument?
  56. var listView: CPDFView?
  57. var windowController: NSWindowController?
  58. var pageIsUpdate: Bool = true
  59. /// 临时存储 document
  60. private var documentCaches: [CPDFDocument] = []
  61. var selectedPages: [Int] = []
  62. var copysPages: Array<CPDFPage> = []
  63. private let defaultItemSize = NSMakeSize(218 + 12 * 2, 292 + 24)
  64. var itemSize: NSSize = NSMakeSize(218 + 12 * 2, 292 + 24)
  65. private var lockedFiles: Array<URL> = []
  66. private var undoRedoManager: UndoManager = UndoManager()
  67. // index=1 双击退出;index=2 打印
  68. var itemClick: KMCommonClickBlock?
  69. var documentEditedCallback: KMCommonBlock?
  70. internal var viewFirstAppear = true
  71. required init?(coder: NSCoder) {
  72. super.init(coder: coder)
  73. }
  74. init(_ document: CPDFDocument) {
  75. super.init(nibName: "KMPDFEditViewController", bundle: nil)
  76. self.pdfDocument = document
  77. }
  78. override func viewDidAppear() {
  79. super.viewDidAppear()
  80. if (self.pdfDocument?.isLocked == false && self.viewFirstAppear) {
  81. self.viewFirstAppear = false
  82. self.thumbnailView.document = self.pdfDocument!
  83. self.thumbnailView.reloadData()
  84. }
  85. if (self.selectedPages.isEmpty) {
  86. var index: Int = 0
  87. if (self.listView != nil) {
  88. index = self.listView!.currentPageIndex
  89. }
  90. self.selectPages(indexs: IndexSet(integer: index))
  91. self.pageRangeView?.stringValue = "\(index+1)"
  92. self.pageRangeView?.editable = true
  93. } else {
  94. var indexs: IndexSet = []
  95. for pageIndex in self.selectedPages {
  96. if (pageIndex < 0 || pageIndex >= (self.listView?.document.pageCount)!) {
  97. continue
  98. }
  99. indexs.insert(pageIndex)
  100. }
  101. self.selectPages(indexs: indexs)
  102. self.pageRangeView?.editable = true
  103. self.pageRangeView?.stringValue = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs.sorted())
  104. }
  105. self.view.window?.makeFirstResponder(self)
  106. }
  107. override func viewDidLoad() {
  108. super.viewDidLoad()
  109. self.thumbnailView.collectionView.backgroundColor(NSColor(hex: "#CED0D4"))
  110. let toolBar = self.toolBar
  111. self.topBarBox.contentView?.addSubview(toolBar)
  112. toolBar.frame = self.topBarBox.contentView!.bounds
  113. toolBar.autoresizingMask = [.width, .height]
  114. toolBar.delegate = self
  115. self.topBarBox.fillColor = NSColor(hex: "#F7F8FA")
  116. let rightItemView = self.rightItemView
  117. self.topBarBox.contentView?.addSubview(rightItemView)
  118. rightItemView.frame = NSMakeRect(NSWidth(self.topBarBox.contentView!.frame)-80, 0, 80, NSHeight(self.topBarBox.contentView!.frame))
  119. rightItemView.autoresizingMask = [.minXMargin]
  120. let view = self.thumbnailView
  121. self.contentBox.contentView?.addSubview(view)
  122. view.frame = self.contentBox.contentView!.bounds
  123. view.autoresizingMask = [.width, .height]
  124. self.thumbnailView.delegate = self
  125. self.thumbnailView.selectionDidChange = { [weak self] selectedIndexs in
  126. self?.view.window?.makeFirstResponder(self)
  127. var replaceEnable: Bool = false
  128. if (selectedIndexs.count == 1) { /// 替换item 置灰
  129. replaceEnable = true
  130. }
  131. var enabled: Bool = false
  132. if (selectedIndexs.count > 0) {
  133. enabled = true
  134. }
  135. if (self?.toolBar.items == nil) {
  136. return
  137. }
  138. var replaceItem: KMToolBoxItem?
  139. for i in 0 ..< (self?.toolBar.items.count)! {
  140. let item: KMToolBoxItem = (self?.toolBar.items[i])!
  141. if (item.itemIdentifier == KMToolbarPageEditReplaceItemIdentifier) {
  142. replaceItem = item
  143. }
  144. if (item.itemIdentifier == KMToolbarPageEditExtractItemIdentifier ||
  145. item.itemIdentifier == KMToolbarPageEditReverseItemIdentifier ||
  146. item.itemIdentifier == KMToolbarPageEditDeleteItemIdentifier ||
  147. item.itemIdentifier == KMToolbarPageEditLeftRotateItemIdentifier ||
  148. item.itemIdentifier == KMToolbarPageEditRightRotateItemIdentifier) {
  149. item.unEnabled = !enabled
  150. }
  151. }
  152. if (replaceItem != nil) {
  153. replaceItem?.unEnabled = !replaceEnable
  154. }
  155. if (self!.pageIsUpdate == false) {
  156. self?.pageIsUpdate = true
  157. return
  158. }
  159. var indexs: Array<Int> = []
  160. for indexPath in selectedIndexs {
  161. indexs.append(indexPath.item)
  162. }
  163. indexs.sort(){$0 < $1}
  164. self?.pageRangeView?.editable = true;
  165. self?.pageRangeView?.stringValue = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs)
  166. }
  167. let menu = NSMenu()
  168. menu.delegate = self
  169. self.view.menu = menu
  170. }
  171. // MARK: Private Methods
  172. private func copyPages(with indexs: IndexSet) {
  173. Task { @MainActor in
  174. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  175. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  176. return
  177. }
  178. if indexs.count > 0 {
  179. self.copysPages = []
  180. for i in indexs {
  181. let page = self.thumbnailView.document.page(at: UInt(i)).copy() as? CPDFPage
  182. if (page == nil) {
  183. continue
  184. }
  185. self.copysPages.append(page!)
  186. }
  187. }
  188. }
  189. }
  190. private func cutPages(with indexs: IndexSet) {
  191. Task { @MainActor in
  192. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  193. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  194. return
  195. }
  196. if indexs.count > 0 {
  197. if (indexs.count == (self.listView?.document.pageCount)!) {
  198. let _ = CustomAlertView(message: NSLocalizedString("Unable to delete all pages", comment: ""), from: self.thumbnailView, with: .blue)
  199. return
  200. }
  201. self.copysPages = []
  202. for i in indexs {
  203. let page = self.thumbnailView.document.page(at: UInt(i)).copy() as? CPDFPage
  204. if (page == nil) {
  205. continue
  206. }
  207. self.copysPages.append(page!)
  208. }
  209. self.clearSelectPages()
  210. self.deletePages(indexs: indexs)
  211. // 提醒外面文档已编辑
  212. if (self.documentEditedCallback != nil) {
  213. self.documentEditedCallback!()
  214. }
  215. }
  216. }
  217. }
  218. private func pastePages(at index: Int) {
  219. Task { @MainActor in
  220. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  221. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  222. return
  223. }
  224. if (index >= 0 && self.copysPages.count > 0) {
  225. var indexs: IndexSet = IndexSet()
  226. for (i, _) in self.copysPages.enumerated() {
  227. indexs.insert(index+i+1)
  228. }
  229. self.insertPagesForDescSort(pages: self.copysPages, indexs: indexs)
  230. // 提醒外面文档已编辑
  231. if (self.documentEditedCallback != nil) {
  232. self.documentEditedCallback!()
  233. }
  234. var indexpaths: Set<IndexPath> = []
  235. indexpaths.insert(IndexPath(item: index, section: 0))
  236. self.thumbnailView.collectionView.animator().scrollToItems(at: indexpaths, scrollPosition: .top)
  237. }
  238. }
  239. }
  240. private func getSelecteIndex() -> Int {
  241. var index: Int = 0
  242. for indexpath in self.thumbnailView.selectionIndexPaths {
  243. index = indexpath.item
  244. }
  245. return index
  246. }
  247. private func getSelectedPage() -> CPDFPage {
  248. return (self.pdfDocument!.page(at: UInt(getSelecteIndex())))!
  249. }
  250. private func showPasswordWindow(_ insertIndex: Int) {
  251. if (self.lockedFiles.count > 0) {
  252. let fileURL = self.lockedFiles.first
  253. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .open, url: fileURL!) { result, password in
  254. if (result == .cancel) { /// 取消
  255. self.lockedFiles.removeFirst()
  256. if (self.lockedFiles.count > 0) {
  257. self.showPasswordWindow(insertIndex)
  258. }
  259. return
  260. }
  261. /// 解密成功
  262. let document = CPDFDocument(url: fileURL)
  263. document?.unlock(withPassword: password)
  264. var newInsertIndex: Int = insertIndex
  265. var pages: [CPDFPage] = []
  266. var indexs: IndexSet = IndexSet()
  267. for i in 0 ..< document!.pageCount {
  268. let page = document?.page(at: i)
  269. pages.append(page!)
  270. indexs.insert(newInsertIndex)
  271. newInsertIndex += 1
  272. }
  273. self.insertPagesForDescSort(pages: pages, indexs: indexs)
  274. self.lockedFiles.removeFirst()
  275. if (self.lockedFiles.count > 0) {
  276. self.showPasswordWindow(newInsertIndex)
  277. }
  278. }
  279. }
  280. }
  281. @objc private func insertPagesForDescSort(pages: Array<CPDFPage>, indexs: IndexSet) {
  282. self.insertPages(pages: pages, indexs: indexs)
  283. /// 选中插入的页面
  284. self.selectPages(indexs: indexs)
  285. }
  286. private func selectPages(indexs: IndexSet) {
  287. var indexpaths: Set<IndexPath> = []
  288. for index in indexs {
  289. indexpaths.insert(IndexPath(item: index, section: 0))
  290. }
  291. self.thumbnailView.selectPages(at: indexpaths)
  292. }
  293. // MARK: -
  294. // MARK: - 清空选择
  295. private func clearSelectPages() {
  296. self.selectPages(indexs: IndexSet())
  297. }
  298. private func refreshUI(indexs: IndexSet = []) {
  299. if (Thread.isMainThread) {
  300. self.listView?.layoutDocumentView()
  301. var indexpaths: Set<IndexPath> = []
  302. for index in indexs {
  303. indexpaths.insert(IndexPath(item: index, section: 0))
  304. }
  305. self.thumbnailView.refreshUI(indexs: indexpaths)
  306. } else {
  307. DispatchQueue.main.async {
  308. self.listView?.layoutDocumentView()
  309. var indexpaths: Set<IndexPath> = []
  310. for index in indexs {
  311. indexpaths.insert(IndexPath(item: index, section: 0))
  312. }
  313. self.thumbnailView.refreshUI(indexs: indexpaths)
  314. }
  315. }
  316. }
  317. private func refreshUIForKeepSelecteds(indexs: IndexSet = []) {
  318. let indexpaths = self.thumbnailView.selectionIndexPaths
  319. self.refreshUI(indexs: indexs)
  320. self.thumbnailView.selectPages(at: indexpaths)
  321. }
  322. // MARK: Undo / Redo
  323. @objc private func leftRotate(indexs: IndexSet) {
  324. Task { @MainActor in
  325. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  326. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  327. return
  328. }
  329. if (indexs.count <= 0) {
  330. return
  331. }
  332. // 提醒外面文档已编辑
  333. if (self.documentEditedCallback != nil) {
  334. self.documentEditedCallback!()
  335. }
  336. for i in 0 ..< (self.listView?.document.pageCount)! {
  337. if (indexs.contains(IndexSet.Element(i))) {
  338. let page = self.listView?.document.page(at: i)
  339. if (page == nil) {
  340. continue
  341. }
  342. page!.rotation = (page!.rotation-90)%360
  343. }
  344. }
  345. self.undoRedoManager.registerUndo(withTarget: self, selector: #selector(rightRotate), object: indexs)
  346. self.refreshUIForKeepSelecteds(indexs: indexs)
  347. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMPDFViewRotatePage"), object: self.listView?.document)
  348. }
  349. }
  350. @objc private func rightRotate(indexs: IndexSet) {
  351. Task { @MainActor in
  352. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  353. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  354. return
  355. }
  356. if (indexs.count <= 0) {
  357. return
  358. }
  359. // 提醒外面文档已编辑
  360. if (self.documentEditedCallback != nil) {
  361. self.documentEditedCallback!()
  362. }
  363. for i in 0 ..< (self.listView?.document.pageCount)! {
  364. if (indexs.contains(IndexSet.Element(i))) {
  365. let page = self.listView?.document.page(at: i)
  366. if (page == nil) {
  367. continue
  368. }
  369. page!.rotation = (page!.rotation+90)%360
  370. }
  371. }
  372. self.undoRedoManager.registerUndo(withTarget: self, selector: #selector(leftRotate), object: indexs)
  373. self.refreshUIForKeepSelecteds(indexs: indexs)
  374. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMPDFViewRotatePage"), object: self.listView?.document)
  375. }
  376. }
  377. @objc private func insertPages(pages: Array<CPDFPage>, indexs: IndexSet) {
  378. var count: Int = 0
  379. for index in indexs {
  380. if (count >= pages.count) {
  381. break
  382. }
  383. if (index > (self.listView?.document.pageCount)!) {
  384. break
  385. }
  386. let newPage = pages[count]
  387. self.listView?.document.insertPageObject(newPage, at: UInt(index))
  388. count += 1
  389. }
  390. self.undoRedoManager.registerUndo(withTarget: self, selector: #selector(deletePages), object: indexs)
  391. self.refreshUI()
  392. }
  393. @objc private func deletePages(indexs: IndexSet) {
  394. if (indexs.count <= 0) {
  395. return
  396. }
  397. if (indexs.count == (self.listView?.document.pageCount)!) {
  398. let _ = CustomAlertView(message: NSLocalizedString("Unable to delete all pages", comment: ""), from: self.thumbnailView, with: .blue)
  399. return
  400. }
  401. // 提醒外面文档已编辑
  402. if (self.documentEditedCallback != nil) {
  403. self.documentEditedCallback!()
  404. }
  405. var array: Array<CPDFPage> = []
  406. for i in indexs {
  407. let page = self.listView?.document.page(at: UInt(i)).copy() as? CPDFPage
  408. if (page != nil) {
  409. array.append(page!)
  410. }
  411. }
  412. self.listView?.document.removePage(at: indexs)
  413. self.undoRedoManager.registerUndo(withTarget: self) { target in
  414. target.insertPages(pages: array, indexs: indexs)
  415. }
  416. self.refreshUI()
  417. }
  418. @objc private func reversePages(indexs: IndexSet) {
  419. KMPageEditTools.reverse((self.listView?.document)!, indexs
  420. ) { result, error in
  421. if (result) {
  422. self.refreshUI()
  423. self.undoRedoManager.registerUndo(withTarget: self, selector: #selector(self.reversePages), object: indexs)
  424. }
  425. }
  426. }
  427. @objc private func dragPages(_ indexs: IndexSet, _ toIndex: Int, reversed: Bool = false) {
  428. if (indexs.count <= 0) {
  429. return
  430. }
  431. // 插入位置偏移量
  432. var toIndexOffset: Int = 0
  433. // 需要移动的页面index数组
  434. var newPages: [CPDFPage] = []
  435. // 从后面往前删除
  436. for index in indexs.reversed() {
  437. let newPage = (self.listView?.document.page(at: UInt(index)))?.copy() as? CPDFPage
  438. if (newPage == nil) {
  439. continue
  440. }
  441. newPages.insert(newPage!, at: 0)
  442. self.listView?.document.removePage(at: UInt(index))
  443. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  444. toIndexOffset += 1
  445. }
  446. }
  447. if (indexs.last! < toIndex) { // 往后拖拽
  448. toIndexOffset -= 1
  449. }
  450. let insertIndex = max(0, toIndex-toIndexOffset)
  451. var selectIndexs: IndexSet = []
  452. for (index, page) in newPages.enumerated() {
  453. self.listView?.document.insertPageObject(page, at: UInt(insertIndex+index))
  454. selectIndexs.insert(insertIndex+index)
  455. }
  456. // 新增 undo
  457. self.undoRedoManager.registerUndo(withTarget: self) { target in
  458. target.clearSelectPages()
  459. target.dragPages_reversed(indexs, toIndex, newPages)
  460. }
  461. // 刷新UI
  462. self.refreshUI()
  463. if (reversed == false) {
  464. self.selectPages(indexs: selectIndexs)
  465. }
  466. }
  467. @objc private func dragPages_reversed(_ indexs: IndexSet, _ toIndex: Int, _ pages: [CPDFPage]) {
  468. if (indexs.count <= 0) {
  469. return
  470. }
  471. // 插入位置偏移量
  472. var toIndexOffset: Int = 0
  473. for index in indexs {
  474. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  475. toIndexOffset += 1
  476. }
  477. }
  478. if (indexs.last! < toIndex) { // 往后拖拽
  479. toIndexOffset -= 1
  480. }
  481. let insertIndex = max(0, toIndex-toIndexOffset)
  482. // 需要移动的页面index数组
  483. var datas: [Int] = []
  484. for index in insertIndex ..< (insertIndex + indexs.count) {
  485. datas.append(index)
  486. }
  487. // 从后面开始删除
  488. for index in datas.reversed() {
  489. self.listView?.document.removePage(at: UInt(index))
  490. }
  491. // 再插入到对应的位置
  492. for (index,value) in indexs.enumerated() {
  493. var page: CPDFPage?
  494. if (index < pages.count) {
  495. page = pages[index]
  496. }
  497. if (page != nil) {
  498. self.listView?.document.insertPageObject(page!, at: UInt(value))
  499. }
  500. }
  501. // 新增 undo
  502. self.undoRedoManager.registerUndo(withTarget: self) { target in
  503. target.dragPages(indexs, toIndex, reversed: true)
  504. }
  505. // 刷新UI
  506. self.refreshUI()
  507. }
  508. // MARK: topBar 事件
  509. @objc func zoomOutButtonAction(sender: NSButton) {
  510. if (self.itemSize.width > self.defaultItemSize.width) {
  511. return
  512. }
  513. if (self.itemSize.width < self.defaultItemSize.width) {
  514. self.itemSize = self.defaultItemSize
  515. } else if (self.itemSize.width == self.defaultItemSize.width) {
  516. self.itemSize = NSSize(width: self.defaultItemSize.width*1.5, height: self.defaultItemSize.height*1.5)
  517. }
  518. self.zoomInButton?.isEnabled = true
  519. if (self.itemSize.width > self.defaultItemSize.width) {
  520. sender.isEnabled = false
  521. }
  522. self.thumbnailView.zoomOut()
  523. }
  524. @objc func zoomInButtonAction(sender: NSButton) {
  525. if (self.itemSize.width < self.defaultItemSize.width) {
  526. return
  527. }
  528. if (self.itemSize.width > self.defaultItemSize.width) {
  529. self.itemSize = self.defaultItemSize
  530. } else if (self.itemSize.width == self.defaultItemSize.width) {
  531. self.itemSize = NSSize(width: self.defaultItemSize.width*0.5, height: self.defaultItemSize.height*0.5)
  532. }
  533. self.zoomOutButton?.isEnabled = true
  534. if (self.itemSize.width < self.defaultItemSize.width) {
  535. sender.isEnabled = false
  536. }
  537. self.thumbnailView.zoomIn()
  538. }
  539. // MARK: menu 菜单事件
  540. @objc func item_insertFile(sender: NSMenuItem?) {
  541. let panel = NSOpenPanel()
  542. panel.allowedFileTypes = ["pdf"]
  543. panel.allowsMultipleSelection = true
  544. panel.beginSheetModal(for: self.view.window!) { [weak self] response in
  545. if (response == .cancel) {
  546. return
  547. }
  548. /// 处理page
  549. var insertIndex: Int = (self?.getSelecteIndex())!
  550. self!.lockedFiles.removeAll()
  551. var pages: Array<CPDFPage> = []
  552. self?.documentCaches.removeAll()
  553. var indexs = IndexSet()
  554. for fileURL in panel.urls {
  555. let document = CPDFDocument(url: fileURL)
  556. if ((document?.isLocked)!) {
  557. self?.lockedFiles.append(fileURL)
  558. continue
  559. }
  560. self?.documentCaches.append(document!)
  561. for i in 0 ..< document!.pageCount {
  562. let page = document?.page(at: i)
  563. pages.append(page!)
  564. insertIndex += 1
  565. indexs.insert(insertIndex)
  566. }
  567. }
  568. self?.insertPagesForDescSort(pages: pages, indexs: indexs)
  569. if ((self?.lockedFiles.count)! <= 0) {
  570. self?.refreshUI()
  571. return
  572. }
  573. self?.refreshUI()
  574. self!.showPasswordWindow(insertIndex)
  575. }
  576. }
  577. @objc func item_insertBlankPage(sender: NSMenuItem?) {
  578. let index = self.getSelecteIndex()
  579. let page = self.listView?.document.page(at: UInt(index))
  580. self.documentCaches.removeAll()
  581. let document = CPDFDocument()
  582. document?.insertPage((page?.bounds.size)!, at: 0)
  583. self.documentCaches.append(document!)
  584. let newPage: CPDFPage = (document?.page(at: 0))!
  585. self.insertPagesForDescSort(pages: [newPage], indexs: IndexSet(integer: index+1))
  586. }
  587. @objc func item_insertCustomPage(sender: NSMenuItem?) {
  588. let windowController = KMPageEditInsertCustomPageWindowController(windowNibName: "KMPageEditInsertCustomPageWindowController")
  589. if (self.thumbnailView.selectionIndexPaths.count > 0) {
  590. windowController.selectedPageSize = self.getSelectedPage().bounds.size
  591. }
  592. self.windowController = windowController
  593. self.view.window?.beginSheet(windowController.window!, completionHandler: { response in})
  594. windowController.itemClick = {
  595. [weak self] (index: Int) in
  596. if (index == 1) { /// 取消
  597. self?.view.window?.endSheet((self!.windowController?.window)!)
  598. self?.windowController = nil
  599. return
  600. }
  601. /// 插入
  602. /// 样式
  603. let windowController_Insert: KMPageEditInsertCustomPageWindowController = self?.windowController as! KMPageEditInsertCustomPageWindowController
  604. let type = windowController_Insert.typeIndex
  605. /// 页面大小
  606. let pageSize = windowController_Insert.pageSize
  607. /// 方向
  608. let direction = windowController_Insert.direction
  609. /// 插入位置
  610. let insertIndex: Int = (self?.getSelecteIndex())!
  611. if (type == 1) { /// 空白页
  612. let document = CPDFDocument()
  613. document?.insertPage(pageSize, at: 0)
  614. let page: CPDFPage = (document?.page(at: 0))!
  615. if (direction == 0) { /// 纵向
  616. page.rotation = 90
  617. }
  618. self?.insertPagesForDescSort(pages: [page], indexs: IndexSet(integer: insertIndex+1))
  619. } else {
  620. let document = CPDFDocument()
  621. var imageName = "plaid"
  622. if (type == 2) {
  623. imageName = "horizontal_line"
  624. } else if (type == 3) {
  625. imageName = "five_line_score"
  626. }
  627. let imagePath = Bundle.main.pathForImageResource(imageName)
  628. document?.insertPage(pageSize, withImage: imagePath, at: 0)
  629. let page: CPDFPage = (document?.page(at: 0))!
  630. if (direction == 0) { /// 纵向
  631. page.rotation = 90
  632. }
  633. self?.insertPagesForDescSort(pages: [page], indexs: IndexSet(integer: insertIndex+1))
  634. }
  635. self?.view.window?.endSheet((self?.windowController?.window)!)
  636. self?.windowController = nil
  637. }
  638. }
  639. // MARK: toolBar 菜单事件
  640. @objc func pageRangeMenuAction(sender: KMToolbarClickButton) {
  641. }
  642. @objc func leftRotateMenuAction(sender: KMToolbarClickButton?) {
  643. let selectedIndexs = self.thumbnailView.selectionIndexPaths
  644. var indexs: IndexSet = []
  645. for indexpath in selectedIndexs {
  646. indexs.insert(indexpath.item)
  647. }
  648. self.leftRotate(indexs: indexs)
  649. }
  650. @objc func rightRotateMenuAction(sender: KMToolbarClickButton?) {
  651. let selectedIndexs = self.thumbnailView.selectionIndexPaths
  652. var indexs: IndexSet = []
  653. for indexpath in selectedIndexs {
  654. indexs.insert(indexpath.item)
  655. }
  656. self.rightRotate(indexs: indexs)
  657. }
  658. @objc func insertMenuAction(sender: KMToolbarClickButton) {
  659. let menu = NSMenu()
  660. let insertFileItem = NSMenuItem(title: "Insert File", action: #selector(item_insertFile), target: self)
  661. menu.addItem(insertFileItem!)
  662. let insertBlankPageItem = NSMenuItem(title: "Insert a blank page", action: #selector(item_insertBlankPage), target: self)
  663. menu.addItem(insertBlankPageItem!)
  664. let insertCustomPageItem = NSMenuItem(title: "Insert custom page", action: #selector(item_insertCustomPage), target: self)
  665. menu.addItem(insertCustomPageItem!)
  666. menu.popUp(positioning: nil, at: NSPoint(x: 0, y: 40), in: sender)
  667. }
  668. @objc func extractMenuAction(sender: KMToolbarClickButton?) {
  669. if (self.thumbnailView.selectionIndexPaths.count == 0) {
  670. let alert = NSAlert()
  671. alert.messageText = "请选择需要提取的页面"
  672. alert.runModal()
  673. return
  674. }
  675. let windowController = KMPageEditExtractWindowController(windowNibName: "KMPageEditSettingBaseWindowController")
  676. self.view.window?.beginSheet(windowController.window!)
  677. self.windowController = windowController
  678. windowController.itemClick = { [weak self] index, value in
  679. if (index == 1) { /// 取消
  680. self?.view.window?.endSheet((self?.windowController?.window)!)
  681. self?.windowController = nil
  682. return
  683. }
  684. let windowController_extract: KMPageEditExtractWindowController = self?.windowController as! KMPageEditExtractWindowController
  685. /// 提取设置项
  686. let settingView: KMPageEditExtractSettingView = windowController_extract.settingView! as! KMPageEditExtractSettingView
  687. let oneDocumentPerPage: Bool = settingView.independentPerPageCheck.state != .on
  688. let extractAfterDelete: Bool = settingView.extractAfterDeletePageCheck.state == .on
  689. self?.view.window?.endSheet((self?.windowController!.window)!)
  690. self?.windowController = nil
  691. // /// 提取的页面
  692. let indexpaths = self?.thumbnailView.selectionIndexPaths
  693. var indexs: IndexSet = []
  694. var extractPages: Array<CPDFPage> = []
  695. for indexpath in indexpaths! {
  696. let page = self?.listView?.document.page(at: UInt(indexpath.item))
  697. if (page != nil) {
  698. extractPages.append(page!)
  699. }
  700. indexs.insert(indexpath.item)
  701. }
  702. KMPageEditTools.extract((self?.listView?.document)!, indexs, oneDocumentPerPage, (self?.view.window)!) { result, urls, error in
  703. if (result == false) {
  704. return
  705. }
  706. if (extractAfterDelete) {
  707. var indexs: IndexSet = IndexSet()
  708. for page in extractPages {
  709. let indexPage: Int = Int((self?.listView?.document.index(for: page))!)
  710. indexs.insert(indexPage)
  711. }
  712. self?.deletePages(indexs: indexs)
  713. }
  714. }
  715. }
  716. }
  717. @objc func replaceMenuAction(sender: KMToolbarClickButton?) {
  718. let panel = NSOpenPanel()
  719. panel.allowedFileTypes = ["pdf"]
  720. panel.allowsMultipleSelection = true
  721. panel.beginSheetModal(for: self.view.window!) { [weak self] response in
  722. if (response == .cancel) {
  723. return
  724. }
  725. /// 处理page
  726. var pages: Array<CPDFPage> = []
  727. let selectedIndex: Int = (self?.getSelecteIndex())!
  728. self?.listView?.document.removePage(at: UInt(selectedIndex))
  729. var insertIndex: Int = selectedIndex
  730. self?.lockedFiles.removeAll()
  731. for fileURL in panel.urls {
  732. let document = CPDFDocument(url: fileURL)
  733. if ((document?.isLocked)!) {
  734. self?.lockedFiles.append(fileURL)
  735. continue
  736. }
  737. for i in 0 ..< document!.pageCount {
  738. let page = document?.page(at: i)
  739. pages.append(page!)
  740. self!.listView?.document.insertPageObject(page, at:UInt(insertIndex))
  741. insertIndex += 1
  742. }
  743. }
  744. if ((self?.lockedFiles.count)! <= 0) {
  745. self?.refreshUI()
  746. return
  747. }
  748. self?.refreshUI()
  749. self!.showPasswordWindow(insertIndex)
  750. }
  751. }
  752. @objc func splitMenuAction(sender: KMToolbarClickButton) {
  753. let model = KMPageEditSplitSettingModel()
  754. model.documentURL = self.listView?.document.documentURL
  755. model.fileName = model.documentURL.lastPathComponent
  756. model.pathExtension = model.fileName.components(separatedBy: ".").last
  757. if (self.thumbnailView.selectionIndexPaths.count > 0) {
  758. model.type = 2
  759. model.pageRangeType = 2
  760. var selectedIndexs: Array<Int> = []
  761. for indexpath in self.thumbnailView.selectionIndexPaths {
  762. selectedIndexs.append(indexpath.item)
  763. }
  764. model.pageRangeString = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: selectedIndexs)
  765. } else {
  766. model.type = 0
  767. }
  768. let windowController = KMPageEditSplitWindowController(model)
  769. self.view.window?.beginSheet(windowController.window!)
  770. self.windowController = windowController
  771. windowController.itemClick = { [weak self] index, value in
  772. if (index == 1) { /// 取消
  773. self?.view.window?.endSheet((self?.windowController!.window)!)
  774. self?.windowController = nil
  775. return
  776. }
  777. /// 拆分
  778. let windowController_split: KMPageEditSplitWindowController = self?.windowController as! KMPageEditSplitWindowController
  779. let outputModel: KMPageEditSplitSettingModel = windowController_split.model! as! KMPageEditSplitSettingModel
  780. self?.view.window?.endSheet((self?.windowController!.window)!)
  781. self?.windowController = nil
  782. let panel = NSOpenPanel()
  783. panel.canChooseFiles = false
  784. panel.canChooseDirectories = true
  785. panel.canCreateDirectories = true
  786. let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  787. button.state = .off
  788. panel.accessoryView = button
  789. panel.beginSheetModal(for: (self?.view.window)!) { response in
  790. if (response == .cancel) {
  791. return
  792. }
  793. KMPageEditTools.split((self?.listView?.document)!, outputModel, panel.url!.path, outputModel.outputFileNameDeletePathExtension) { result, outputFilepaths, error in
  794. if (result) {
  795. if (button.state == .on) {
  796. for filepath in outputFilepaths! {
  797. if !filepath.isPDFValid() {
  798. let alert = NSAlert()
  799. alert.alertStyle = .critical
  800. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  801. alert.runModal()
  802. } else {
  803. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filepath), display: true) { document, alreadyOpen, error in
  804. }
  805. }
  806. }
  807. } else {
  808. var urls: [URL] = []
  809. for filepath in outputFilepaths! {
  810. urls.append(URL(fileURLWithPath: filepath))
  811. }
  812. NSWorkspace.shared.activateFileViewerSelecting(urls)
  813. }
  814. }
  815. }
  816. }
  817. }
  818. }
  819. @objc func reverseMenuAction(sender: KMToolbarClickButton) {
  820. let selectedIndexs = self.thumbnailView.selectionIndexPaths
  821. if (selectedIndexs.count < 2 ) {
  822. let _ = CustomAlertView(message: "请先选择至少两个页面进行编辑操作", from: self.thumbnailView, with: .blue)
  823. return
  824. }
  825. var indexs: IndexSet = []
  826. for indexpath in selectedIndexs {
  827. indexs.insert(indexpath.item)
  828. }
  829. self.reversePages(indexs: indexs)
  830. }
  831. @objc func deleteMenuAction(sender: KMToolbarClickButton) {
  832. Task { @MainActor in
  833. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  834. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  835. return
  836. }
  837. var indexs: IndexSet = IndexSet()
  838. for indexPath in self.thumbnailView.selectionIndexPaths {
  839. indexs.insert(indexPath.item)
  840. }
  841. self.clearSelectPages()
  842. self.deletePages(indexs: indexs)
  843. }
  844. }
  845. }
  846. // MARK: -
  847. // MARK: KMNewToolbarDelegate
  848. extension KMPDFEditViewController: KMNewToolbarDelegate {
  849. func toolbarDefaultItemIdentifiers(_ toolbar: KMToolbar!) -> [String]! {
  850. return [KMToolbarPageEditPageRangeItemIdentifier,
  851. KMToolbarPageEditLeftRotateItemIdentifier,
  852. KMToolbarPageEditRightRotateItemIdentifier,
  853. // KMToolbarDividerItemIdentifier,
  854. // KMToolbarPageEditInsetItemIdentifier,
  855. // KMToolbarPageEditExtractItemIdentifier,
  856. // KMToolbarPageEditReplaceItemIdentifier,
  857. // KMToolbarPageEditSplitItemIdentifier,
  858. // KMToolbarPageEditReverseItemIdentifier,
  859. KMToolbarDividerItemIdentifier,
  860. KMToolbarPageEditDeleteItemIdentifier]
  861. }
  862. func toolbar(_ toolbar: KMToolbar!, itemForItemIdentifier identifier: String!) -> KMToolBoxItem! {
  863. let item = KMToolBoxItem(itemIdentifier: identifier)
  864. if (identifier == KMToolbarPageEditPageRangeItemIdentifier) {
  865. // item?.image = NSImage(named: "KMImageNameMainToolbarrRight")
  866. item?.alternateImage = NSImage(named: "KMImageNameMainToolbarrRight")
  867. item?.target = self
  868. item?.btnTag = KMPageEditType.pageRange.rawValue
  869. // item?.toolTip = NSLocalizedString("pageRange", comment: "")
  870. item?.titleName = NSLocalizedString("pageRange ", comment: "")
  871. item?.boxImagePosition = KMToolBoxImagePosition.left
  872. item?.btnAction = #selector(pageRangeMenuAction)
  873. let view = NSView()
  874. item?.addSubview(view)
  875. view.frame = item!.bounds
  876. view.autoresizingMask = [.width,.height]
  877. view.wantsLayer = true
  878. view.layer?.backgroundColor = NSColor(hex: "#F7F8FA").cgColor
  879. let comBoxView = KMDesignSelect(withType: .Combox)
  880. view.addSubview(comBoxView.view)
  881. comBoxView.view.frame = NSMakeRect(0, 8, NSWidth(view.frame), 24)
  882. comBoxView.view.autoresizingMask = [.width]
  883. comBoxView.removeAllItems()
  884. comBoxView.addItems(withObjectValues: self.pageRangeViewItems)
  885. comBoxView.selectItem(at: 0)
  886. comBoxView.placeholderString = NSLocalizedString("eg .1,3-5,10", comment: "")
  887. comBoxView.editable = false
  888. comBoxView.delete = self
  889. pageRangeView = comBoxView
  890. let menuItem = NSMenuItem.init(title: "pageRange", action: #selector(pageRangeMenuAction), target: self)
  891. item?.menuFormRepresentation = menuItem
  892. } else if (identifier == KMToolbarPageEditLeftRotateItemIdentifier) {
  893. item?.image = NSImage(named: "KMImageNameMainToolPageLeftRotate")
  894. item?.alternateImage = NSImage(named: "KMImageNameMainToolPageLeftRotate")
  895. item?.target = self
  896. item?.btnTag = KMPageEditType.leftRotate.rawValue
  897. item?.toolTip = NSLocalizedString("Rotate Left", comment: "")
  898. item?.titleName = NSLocalizedString("", comment: "")
  899. item?.boxImagePosition = KMToolBoxImagePosition.left
  900. item?.btnAction = #selector(leftRotateMenuAction)
  901. let menuItem = NSMenuItem.init(title: "", action: #selector(leftRotateMenuAction), target: self)
  902. item?.menuFormRepresentation = menuItem
  903. } else if (identifier == KMToolbarPageEditRightRotateItemIdentifier) {
  904. item?.image = NSImage(named: "KMImageNameMainToolPageRightRotate")
  905. item?.alternateImage = NSImage(named: "KMImageNameMainToolPageRightRotate")
  906. item?.target = self
  907. item?.btnTag = KMPageEditType.rightRotate.rawValue
  908. item?.toolTip = NSLocalizedString("Rotate Right", comment: "")
  909. item?.titleName = NSLocalizedString("", comment: "")
  910. item?.boxImagePosition = KMToolBoxImagePosition.left
  911. item?.btnAction = #selector(rightRotateMenuAction)
  912. let menuItem = NSMenuItem.init(title: "", action: #selector(rightRotateMenuAction), target: self)
  913. item?.menuFormRepresentation = menuItem
  914. } else if (identifier == KMToolbarPageEditInsetItemIdentifier) {
  915. item?.image = NSImage(named: "KMImageNameMainToolPageInsert")
  916. item?.alternateImage = NSImage(named: "KMImageNameMainToolPageInsert")
  917. item?.target = self
  918. item?.btnTag = KMPageEditType.insert.rawValue
  919. item?.toolTip = NSLocalizedString("Insert", comment: "")
  920. item?.titleName = NSLocalizedString("Insert", comment: "")
  921. item?.boxImagePosition = KMToolBoxImagePosition.left
  922. item?.btnAction = #selector(insertMenuAction)
  923. let menuItem = NSMenuItem.init(title: "Insert", action: #selector(insertMenuAction), target: self)
  924. item?.menuFormRepresentation = menuItem
  925. } else if (identifier == KMToolbarPageEditExtractItemIdentifier) {
  926. item?.image = NSImage(named: "KMImageNameMainToolPageExtract")
  927. item?.alternateImage = NSImage(named: "KMImageNameMainToolPageExtract")
  928. item?.target = self
  929. item?.btnTag = KMPageEditType.extract.rawValue
  930. item?.toolTip = NSLocalizedString("Extract", comment: "")
  931. item?.titleName = NSLocalizedString("Extract", comment: "")
  932. item?.boxImagePosition = KMToolBoxImagePosition.left
  933. item?.btnAction = #selector(extractMenuAction)
  934. let menuItem = NSMenuItem.init(title: "Extract", action: #selector(extractMenuAction), target: self)
  935. item?.menuFormRepresentation = menuItem
  936. } else if (identifier == KMToolbarPageEditReplaceItemIdentifier) {
  937. item?.image = NSImage(named: "KMImageNameMainToolPageReplace")
  938. item?.alternateImage = NSImage(named: "KMImageNameMainToolPageReplace")
  939. item?.target = self
  940. item?.btnTag = KMPageEditType.replace.rawValue
  941. item?.toolTip = NSLocalizedString("Replace", comment: "")
  942. item?.titleName = NSLocalizedString("Replace", comment: "")
  943. item?.boxImagePosition = KMToolBoxImagePosition.left
  944. item?.btnAction = #selector(replaceMenuAction)
  945. let menuItem = NSMenuItem.init(title: "Replace", action: #selector(replaceMenuAction), target: self)
  946. item?.menuFormRepresentation = menuItem
  947. } else if (identifier == KMToolbarPageEditSplitItemIdentifier) {
  948. item?.image = NSImage(named: "KMImageNameMainToolPageSplit")
  949. item?.alternateImage = NSImage(named: "KMImageNameMainToolPageSplit")
  950. item?.target = self
  951. item?.btnTag = KMPageEditType.split.rawValue
  952. item?.toolTip = NSLocalizedString("Split the PDF into multiple files", comment: "")
  953. item?.titleName = NSLocalizedString("Split", comment: "")
  954. item?.boxImagePosition = KMToolBoxImagePosition.left
  955. item?.btnAction = #selector(splitMenuAction)
  956. let menuItem = NSMenuItem.init(title: "Split", action: #selector(splitMenuAction), target: self)
  957. item?.menuFormRepresentation = menuItem
  958. } else if (identifier == KMToolbarPageEditReverseItemIdentifier) {
  959. item?.image = NSImage(named: "KMImageNameMainToolPageReverse")
  960. item?.alternateImage = NSImage(named: "KMImageNameMainToolPageReverse")
  961. item?.target = self
  962. item?.btnTag = KMPageEditType.reverse.rawValue
  963. item?.toolTip = NSLocalizedString("Reverse", comment: "")
  964. item?.titleName = NSLocalizedString("Reverse", comment: "")
  965. item?.boxImagePosition = KMToolBoxImagePosition.left
  966. item?.btnAction = #selector(reverseMenuAction)
  967. let menuItem = NSMenuItem.init(title: "Reverse", action: #selector(reverseMenuAction), target: self)
  968. item?.menuFormRepresentation = menuItem
  969. } else if (identifier == KMToolbarPageEditDeleteItemIdentifier) {
  970. item?.image = NSImage(named: "KMImageNameMainToolPageDelete")
  971. item?.alternateImage = NSImage(named: "KMImageNameMainToolPageDelete")
  972. item?.target = self
  973. item?.btnTag = KMPageEditType.delete.rawValue
  974. item?.toolTip = NSLocalizedString("Delete", comment: "")
  975. item?.titleName = NSLocalizedString("", comment: "")
  976. item?.boxImagePosition = KMToolBoxImagePosition.left
  977. item?.btnAction = #selector(deleteMenuAction)
  978. let menuItem = NSMenuItem.init(title: "Delete", action: #selector(deleteMenuAction), target: self)
  979. item?.menuFormRepresentation = menuItem
  980. }
  981. return item
  982. }
  983. //MARK: menu Action
  984. @objc func insertPageItemAction(menu:NSMenuItem) {
  985. if (menu.tag == 0) {
  986. self.item_insertFile(sender: nil)
  987. } else if (menu.tag == 1) {
  988. self.item_insertBlankPage(sender: nil)
  989. } else if (menu.tag == 2) {
  990. self.item_insertCustomPage(sender: nil)
  991. }
  992. }
  993. @objc func rotatePageItemAction(menu:NSMenuItem) {
  994. rightRotateMenuAction(sender: nil)
  995. }
  996. @objc func leftRotatePageItemAction(menu:NSMenuItem) {
  997. leftRotateMenuAction(sender: nil)
  998. }
  999. @objc func extractPageItemAction(menu:NSMenuItem) {
  1000. extractMenuAction(sender: nil)
  1001. }
  1002. @objc func replacePageItemAction(menu:NSMenuItem) {
  1003. replaceMenuAction(sender: nil)
  1004. }
  1005. @objc func deletePageItemAction(menu:NSMenuItem) {
  1006. Task { @MainActor in
  1007. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1008. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1009. return
  1010. }
  1011. let indexs = menu.representedObject as! IndexSet
  1012. if indexs.count > 0 {
  1013. self.clearSelectPages()
  1014. self.deletePages(indexs: indexs)
  1015. }
  1016. }
  1017. }
  1018. @objc func sharePageItemAction(menu:NSMenuItem) {
  1019. let item = menu.parent!
  1020. let index = (item.representedObject as! IndexSet).first ?? -1
  1021. if Int(index) >= 0 {
  1022. let doucument = self.thumbnailView.document
  1023. let page = doucument.page(at: UInt(index))
  1024. let filename : String = doucument.documentURL.lastPathComponent
  1025. let folderPath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(filename))!
  1026. try? FileManager.default.removeItem(atPath: folderPath)
  1027. let pdfdocument = CPDFDocument()
  1028. let ret = pdfdocument!.importPages((item.representedObject as! IndexSet), from: self.thumbnailView.document, at: 0)
  1029. let url = URL(fileURLWithPath: folderPath)
  1030. if ret {
  1031. let success = pdfdocument!.write(to:url)
  1032. if success {
  1033. let workspace = NSWorkspace.shared
  1034. workspace.activateFileViewerSelecting([url])
  1035. }
  1036. }
  1037. let represent : NSSharingService = menu.representedObject as! NSSharingService
  1038. represent.perform(withItems: [url])
  1039. }
  1040. }
  1041. @objc func copyItemAction(menu:NSMenuItem) {
  1042. let indexs = menu.representedObject as! IndexSet
  1043. self.copyPages(with: indexs)
  1044. }
  1045. @objc func cutItemAction(menu:NSMenuItem) {
  1046. let indexs = menu.representedObject as! IndexSet
  1047. self.cutPages(with: indexs)
  1048. }
  1049. @objc func pastePageItemAction(menu:NSMenuItem) {
  1050. var index = (menu.representedObject as! IndexSet).last ?? -1
  1051. self.pastePages(at: index)
  1052. }
  1053. @objc func showPageSizeItemAction(menu: NSMenuItem) {
  1054. self.thumbnailView.isShowPageSize = !self.thumbnailView.isShowPageSize
  1055. self.refreshUIForKeepSelecteds()
  1056. }
  1057. @objc func printItemAction(menu:NSMenuItem) {
  1058. var datas: [Int] = []
  1059. for indexpath in self.thumbnailView.selectionIndexPaths {
  1060. datas.append(indexpath.item)
  1061. }
  1062. guard let callback = self.itemClick else {
  1063. return
  1064. }
  1065. callback(2, datas.sorted())
  1066. }
  1067. }
  1068. // MARK: -
  1069. // MARK: NSMenuDelegate,NSMenuItemValidation
  1070. extension KMPDFEditViewController : NSMenuDelegate,NSMenuItemValidation {
  1071. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  1072. let action = menuItem.action
  1073. if action == #selector(insertPageItemAction) ||
  1074. action == #selector(insertPageItemAction) ||
  1075. action == #selector(deletePageItemAction) ||
  1076. action == #selector(replacePageItemAction) ||
  1077. action == #selector(rotatePageItemAction) ||
  1078. action == #selector(leftRotatePageItemAction) ||
  1079. action == #selector(copyItemAction) ||
  1080. action == #selector(cutItemAction) ||
  1081. action == #selector(pastePageItemAction) ||
  1082. action == #selector(printItemAction) ||
  1083. action == #selector(sharePageItemAction) ||
  1084. action == #selector(extractPageItemAction) ||
  1085. action == #selector(showPageSizeItemAction) {
  1086. let row = self.thumbnailView.collectionView.selectionIndexes
  1087. if row.count > 0 {
  1088. if (row.count > 1 && action == #selector(replacePageItemAction)) {
  1089. return false
  1090. }
  1091. return true
  1092. }
  1093. return false
  1094. }
  1095. if (action == #selector(cut)) {
  1096. return self.thumbnailView.collectionView.selectionIndexes.count > 0
  1097. }
  1098. if (action == NSSelectorFromString("copy:")) {
  1099. return self.thumbnailView.collectionView.selectionIndexes.count > 0
  1100. }
  1101. if (action == #selector(paste)) {
  1102. return self.copysPages.count > 0
  1103. }
  1104. if (action == #selector(undo)) {
  1105. return self.undoRedoManager.canUndo
  1106. }
  1107. if (action == #selector(redo)) {
  1108. return self.undoRedoManager.canRedo
  1109. }
  1110. if (action == #selector(delete)) {
  1111. return self.thumbnailView.collectionView.selectionIndexes.count > 0
  1112. }
  1113. return true
  1114. }
  1115. func menuNeedsUpdate(_ menu: NSMenu) {
  1116. menu.removeAllItems()
  1117. let row = self.thumbnailView.collectionView.selectionIndexes
  1118. // let point = self.thumbnailView.collectionView.convert(NSEvent.mouseLocation, to: nil)
  1119. // let indexpaths = self.thumbnailView.collectionView.indexPathForItem(at: point)
  1120. if (row.isEmpty) {
  1121. return
  1122. }
  1123. var item = NSMenuItem()
  1124. // if (row.count == 1) {
  1125. // item = menu.addItem(withTitle: NSLocalizedString("Insert", comment: ""), action: nil, target: self)
  1126. // item.representedObject = row
  1127. //
  1128. // var subMenu = NSMenu()
  1129. // var subitem = NSMenuItem()
  1130. // subitem = subMenu.addItem(withTitle: NSLocalizedString("Insert File", comment: ""), action: #selector(insertPageItemAction), target: self, tag:0)
  1131. // subitem.representedObject = row
  1132. // subitem = subMenu.addItem(withTitle: NSLocalizedString("Insert blank page", comment: ""), action: #selector(insertPageItemAction), target: self, tag:1)
  1133. // subitem.representedObject = row
  1134. // subitem = subMenu.addItem(withTitle: NSLocalizedString("Insert page", comment: ""), action: #selector(insertPageItemAction), target: self, tag:2)
  1135. // subitem.representedObject = row
  1136. // item.submenu = subMenu
  1137. // }
  1138. // item = menu.addItem(withTitle: NSLocalizedString("Extract", comment: ""), action: #selector(extractPageItemAction), target: self)
  1139. // item.representedObject = row
  1140. // if (row.count == 1) {
  1141. // item = menu.addItem(withTitle: NSLocalizedString("Replace Page", comment: ""), action: #selector(replacePageItemAction), target: self)
  1142. // item.representedObject = row
  1143. // }
  1144. item = menu.addItem(withTitle: NSLocalizedString("Delete Page", comment: ""), action: #selector(deletePageItemAction), target: self)
  1145. item.keyEquivalent = String(Unicode.Scalar(NSBackspaceCharacter)!)
  1146. item.keyEquivalentModifierMask = []
  1147. item.representedObject = row
  1148. menu.addItem(NSMenuItem.separator())
  1149. item = menu.addItem(withTitle: NSLocalizedString("Rotate Clockwise", comment: ""), action: #selector(rotatePageItemAction), target: self)
  1150. item.representedObject = row
  1151. item = menu.addItem(withTitle: NSLocalizedString("Rotate Counterclockwise", comment: ""), action: #selector(leftRotatePageItemAction), target: self)
  1152. item.representedObject = row
  1153. menu.addItem(NSMenuItem.separator())
  1154. item = menu.addItem(withTitle: NSLocalizedString("Copy", comment: ""), action: #selector(copyItemAction), target: self)
  1155. item.representedObject = row
  1156. item.keyEquivalent = "c"
  1157. item.keyEquivalentModifierMask = [.command]
  1158. item = menu.addItem(withTitle: NSLocalizedString("Cut", comment: ""), action: #selector(cutItemAction), target: self)
  1159. item.representedObject = row
  1160. item.keyEquivalent = "x"
  1161. item = menu.addItem(withTitle: NSLocalizedString("Paste", comment: ""), action: #selector(pastePageItemAction), target: self)
  1162. item.representedObject = row
  1163. item.keyEquivalent = "v"
  1164. menu.addItem(NSMenuItem.separator())
  1165. if (!self.thumbnailView.isShowPageSize) {
  1166. item = menu.addItem(withTitle: NSLocalizedString("Hide Page Size", comment: ""), action: #selector(showPageSizeItemAction), target: self)
  1167. item.representedObject = row
  1168. } else {
  1169. item = menu.addItem(withTitle: NSLocalizedString("Display Page Size", comment: ""), action: #selector(showPageSizeItemAction), target: self)
  1170. item.representedObject = row
  1171. }
  1172. menu.addItem(NSMenuItem.separator())
  1173. item = menu.addItem(withTitle: NSLocalizedString("Print", comment: ""), action: #selector(printItemAction), target: self)
  1174. item.representedObject = row
  1175. // if (row.count <= 1) {
  1176. // item = menu.addItem(withTitle: NSLocalizedString("Share", comment: ""), action: nil, target: self)
  1177. // item.representedObject = row
  1178. // item.submenu = NSSharingServicePicker.menu(forSharingItems: [self.listView!.document.documentURL ?? ""], subjectContext: "", withTarget: self, selector: #selector(sharePageItemAction), serviceDelegate: nil)
  1179. // }
  1180. }
  1181. }
  1182. // MARK: -
  1183. // MARK: KMSelectPopButtonDelegate
  1184. extension KMPDFEditViewController: KMSelectPopButtonDelegate {
  1185. func km_comboBoxSelectionDidChange(_ obj: KMDesignSelect) {
  1186. let index: Int = self.pageRangeView!.indexOfSelectedItem
  1187. var indexpaths: Set<IndexPath> = []
  1188. if (index <= 0) { /// 全部页面
  1189. self.pageRangeView?.editable = false
  1190. for i in 0 ..< (self.listView?.document.pageCount)! {
  1191. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1192. }
  1193. self.pageIsUpdate = false
  1194. self.thumbnailView.selectPages(at: indexpaths)
  1195. } else if (index == 1) { /// 奇数页
  1196. self.pageRangeView?.editable = false
  1197. for i in 0 ..< (self.listView?.document.pageCount)! {
  1198. if (i % 2 == 1) {
  1199. continue
  1200. }
  1201. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1202. }
  1203. self.pageIsUpdate = false
  1204. self.thumbnailView.selectPages(at: indexpaths)
  1205. } else if (index == 2) { /// 偶数页
  1206. self.pageRangeView?.editable = false
  1207. for i in 0 ..< (self.listView?.document.pageCount)! {
  1208. if (i % 2 == 0) {
  1209. continue
  1210. }
  1211. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1212. }
  1213. self.pageIsUpdate = false
  1214. self.thumbnailView.selectPages(at: indexpaths)
  1215. } else if (index == 3) { /// 横向页
  1216. self.pageRangeView?.editable = false
  1217. for i in 0 ..< (self.listView?.document.pageCount)! {
  1218. let page = self.listView?.document.page(at: i)
  1219. if (page?.rotation == 0 || page?.rotation == 180 || page?.rotation == -180) {
  1220. continue
  1221. }
  1222. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1223. }
  1224. self.pageIsUpdate = false
  1225. self.thumbnailView.selectPages(at: indexpaths)
  1226. } else if (index == 4) { /// 纵向页
  1227. self.pageRangeView?.editable = false
  1228. for i in 0 ..< (self.listView?.document.pageCount)! {
  1229. let page = self.listView?.document.page(at: i)
  1230. if (page?.rotation == 90 || page?.rotation == 270 || page?.rotation == -90 || page?.rotation == -270) {
  1231. continue
  1232. }
  1233. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1234. }
  1235. self.pageIsUpdate = false
  1236. self.thumbnailView.selectPages(at: indexpaths)
  1237. } else { /// 自定义
  1238. self.pageIsUpdate = false
  1239. self.pageRangeView?.editable = true
  1240. self.clearSelectPages()
  1241. DispatchQueue.main.async {
  1242. self.pageRangeView?.stringValue = ""
  1243. }
  1244. }
  1245. }
  1246. func km_controlTextDidChange(_ obj: KMDesignSelect) {
  1247. }
  1248. func km_controlTextDidEndEditing(_ obj: KMDesignSelect) {
  1249. self.view.window?.makeFirstResponder(self)
  1250. for index in 0 ..< self.pageRangeView!.numberOfItems {
  1251. if (self.pageRangeViewItems[index] == self.pageRangeView!.stringValue) {
  1252. return
  1253. }
  1254. }
  1255. let pages = KMPageRangeTools.findSelectPage(pageRangeString: self.pageRangeView!.stringValue, pageCount: Int((self.listView?.document.pageCount)!))
  1256. if (pages.isEmpty) {
  1257. let alert = NSAlert()
  1258. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  1259. alert.runModal()
  1260. return
  1261. }
  1262. var indexpaths: Set<IndexPath> = []
  1263. for page in pages {
  1264. if (page >= 1) {
  1265. indexpaths.insert(IndexPath(item: page-1, section: 0))
  1266. }
  1267. }
  1268. self.pageIsUpdate = false
  1269. self.thumbnailView.selectPages(at: indexpaths)
  1270. }
  1271. }
  1272. // MARK: -
  1273. // MARK: KMPDFThumbnailViewDelegate
  1274. extension KMPDFEditViewController: KMPDFThumbnailViewDelegate {
  1275. func thumbnailView(thumbanView: KMPDFThumbnailView, didDragAddFiles files: [URL], indexpath: IndexPath) {
  1276. /// 处理page
  1277. // var insertIndex: Int = indexpath.item
  1278. // self.lockedFiles.removeAll()
  1279. // var pages: Array<CPDFPage> = []
  1280. // self.documentCaches.removeAll()
  1281. // var indexs = IndexSet()
  1282. // for fileURL in files {
  1283. // let document = CPDFDocument(url: fileURL)
  1284. // if ((document?.isLocked)!) {
  1285. // self.lockedFiles.append(fileURL)
  1286. // continue
  1287. // }
  1288. //
  1289. // self.documentCaches.append(document!)
  1290. // for i in 0 ..< document!.pageCount {
  1291. // let page = document?.page(at: i)
  1292. // pages.append(page!)
  1293. // indexs.insert(insertIndex)
  1294. // insertIndex += 1
  1295. // }
  1296. // }
  1297. // self.insertPagesForDescSort(pages: pages, indexs: indexs)
  1298. //
  1299. // if (self.lockedFiles.count <= 0) {
  1300. // self.refreshUI()
  1301. // return
  1302. // }
  1303. //
  1304. // self.refreshUI()
  1305. // self.showPasswordWindow(insertIndex)
  1306. }
  1307. func thumbnailView(thumbanView: KMPDFThumbnailView, didDragPages pages: [Int], indexpath: IndexPath) {
  1308. let toIndex = max(0, indexpath.item)
  1309. var indexs = IndexSet()
  1310. for page in pages {
  1311. indexs.insert(page)
  1312. }
  1313. self.dragPages(indexs, toIndex)
  1314. if (pages.count > 0) {
  1315. // 提醒外面文档已编辑
  1316. if (self.documentEditedCallback != nil) {
  1317. self.documentEditedCallback!()
  1318. }
  1319. }
  1320. }
  1321. // MARK: thumbanView layout
  1322. func thumbnailView(thumbanView: KMPDFThumbnailView, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  1323. return 0.01
  1324. }
  1325. func thumbnailView(thumbanView: KMPDFThumbnailView, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  1326. return 0.01
  1327. }
  1328. func thumbnailView(thumbanView: KMPDFThumbnailView, insetForSectionAt section: Int) -> NSEdgeInsets {
  1329. return NSEdgeInsets(top: 16, left: 16, bottom: 0, right: 32)
  1330. }
  1331. func thumbnailView(thumbanView: KMPDFThumbnailView, sizeForItemAt indexpath: IndexPath) -> NSSize {
  1332. self.thumbnailView.thumbnailSzie = CGSize(width: 120, height: 155)
  1333. if (!self.thumbnailView.isShowPageSize) {
  1334. return NSMakeSize(self.itemSize.width, self.itemSize.height+26)
  1335. }
  1336. return self.itemSize
  1337. }
  1338. func thumbnailView(thumbanView: KMPDFThumbnailView, itemForRepresentedObjectAt indexpath: IndexPath) -> NSCollectionViewItem {
  1339. let cellView: KMPageEditThumbnailItem = thumbanView.collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMPageEditThumbnailItem"), for: indexpath) as! KMPageEditThumbnailItem
  1340. cellView.isShowPageSize = self.thumbnailView.isShowPageSize
  1341. cellView.page = self.thumbnailView.document.page(at: UInt(indexpath.item))
  1342. cellView.setPage(page: self.thumbnailView.document.page(at: UInt(indexpath.item)))
  1343. cellView.doubleClickAction = { [unowned self] _ in
  1344. guard let callback = self.itemClick else {
  1345. return
  1346. }
  1347. callback(1, indexpath.item)
  1348. }
  1349. cellView.mouseDownAction = { [unowned self] _ in
  1350. let selectionIndexPaths = self.thumbnailView.selectionIndexPaths
  1351. if (selectionIndexPaths.count == 1 && selectionIndexPaths.first?.item == indexpath.item) {
  1352. return
  1353. }
  1354. self.selectPages(indexs: IndexSet.init(integer: indexpath.item))
  1355. }
  1356. cellView.rightMouseDownAction = { [unowned self] _ in
  1357. self.selectPages(indexs: IndexSet.init(integer: indexpath.item))
  1358. }
  1359. return cellView
  1360. }
  1361. }
  1362. // MARK: -
  1363. // MARK: 系统菜单栏
  1364. extension KMPDFEditViewController: KMEditMenuProtocol {
  1365. @IBAction func cut(_ sender: Any) {
  1366. self.cutPages(with: self.thumbnailView.collectionView.selectionIndexes)
  1367. }
  1368. @IBAction func copy(_ sender: Any) {
  1369. self.copyPages(with: self.thumbnailView.collectionView.selectionIndexes)
  1370. }
  1371. @IBAction func paste(_ sender: Any) {
  1372. var index: Int = Int(self.thumbnailView.document.pageCount-1)
  1373. let indexSet = self.thumbnailView.collectionView.selectionIndexes
  1374. if (indexSet.isEmpty == false) {
  1375. index = indexSet.last!
  1376. }
  1377. self.pastePages(at: index)
  1378. }
  1379. @IBAction func delete(_ sender: Any) {
  1380. Task { @MainActor in
  1381. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1382. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1383. return
  1384. }
  1385. let selectedIndexs = self.thumbnailView.collectionView.selectionIndexPaths
  1386. var indexs: IndexSet = IndexSet()
  1387. for indexPath in selectedIndexs {
  1388. indexs.insert(indexPath.item)
  1389. }
  1390. self.clearSelectPages()
  1391. self.deletePages(indexs: indexs)
  1392. }
  1393. }
  1394. @IBAction func undo(_ sender: Any) {
  1395. if (self.undoRedoManager.canUndo) {
  1396. self.undoRedoManager.undo()
  1397. }
  1398. }
  1399. @IBAction func redo(_ sender: Any) {
  1400. if (self.undoRedoManager.canRedo) {
  1401. self.undoRedoManager.redo()
  1402. }
  1403. }
  1404. }