KMPDFEditViewController.swift 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  1. //
  2. // KMPDFEditViewController.swift
  3. // PDF Master
  4. //
  5. // Created by tangchao on 2023/1/6.
  6. //
  7. class KMPDFEditViewController: KMPDFThumbViewBaseController {
  8. @IBOutlet weak var topBarBox: NSBox!
  9. @IBOutlet weak var contentBox: NSBox!
  10. var toolBar = KMPDFEditToolbar(frame: NSZeroRect)
  11. override var thumbnailView: KMPDFThumbnailView {
  12. get {
  13. if (super.thumbnailView is KMPageEditThumbnailView) {
  14. return super.thumbnailView
  15. }
  16. super.thumbnailView = KMPageEditThumbnailView()
  17. return super.thumbnailView
  18. }
  19. set {
  20. super.thumbnailView = newValue
  21. }
  22. }
  23. var pageEditThumbnailView: KMPageEditThumbnailView {
  24. get {
  25. return self.thumbnailView as! KMPageEditThumbnailView
  26. }
  27. }
  28. override var menuItems: [[KMPDFThumbViewMenu.Item]] {
  29. get {
  30. return [[.copy, .cut, .paste, .delete], [.insert, .extract, .replace, .split, .reverse],
  31. [.rightRotate, .leftRotate], [.showPageSize], [.print]]
  32. }
  33. }
  34. private var pdfDocument: CPDFDocument?
  35. var listView: CPDFView?
  36. var pageIsUpdate: Bool = true
  37. var selectedPages: [Int] = []
  38. private let defaultItemSize = NSMakeSize(218 + 12 * 2, 292 + 24)
  39. var itemSize: NSSize = NSMakeSize(218 + 12 * 2, 292 + 24)
  40. // index=1 双击退出;index=2 打印
  41. var itemClick: KMCommonClickBlock?
  42. var documentEditedCallback: KMCommonBlock?
  43. internal var viewFirstAppear = true
  44. private var _listViewCurrentIndex: Int = 0
  45. var listViewCurrentIndex: Int {
  46. get {
  47. return self._listViewCurrentIndex
  48. }
  49. }
  50. override var canPayFunction: Bool {
  51. didSet {
  52. self.thumbnailView.limit = !self.canPayFunction
  53. }
  54. }
  55. required init?(coder: NSCoder) {
  56. super.init(coder: coder)
  57. }
  58. init(_ document: CPDFDocument) {
  59. super.init(nibName: "KMPDFEditViewController", bundle: nil)
  60. self.pdfDocument = document
  61. self.kmUndoManager = UndoManager()
  62. }
  63. override func viewDidAppear() {
  64. super.viewDidAppear()
  65. if (self.pdfDocument?.isLocked == false && self.viewFirstAppear) {
  66. self.viewFirstAppear = false
  67. self.thumbnailView.document = self.pdfDocument!
  68. self.thumbnailView.reloadData()
  69. }
  70. if let view = self.listView { // 存储阅读视图的当前页面索引
  71. self._listViewCurrentIndex = view.currentPageIndex
  72. }
  73. if (self.selectedPages.isEmpty) {
  74. var index: Int = 0
  75. if (self.listView != nil) {
  76. index = self.listView!.currentPageIndex
  77. }
  78. self.selectPages(indexs: IndexSet(integer: index))
  79. self.toolBar.setPageRangeString("\(index+1)")
  80. } else {
  81. var indexs: IndexSet = []
  82. for pageIndex in self.selectedPages {
  83. if (pageIndex < 0 || pageIndex >= (self.listView?.document.pageCount)!) {
  84. continue
  85. }
  86. indexs.insert(pageIndex)
  87. }
  88. self.selectPages(indexs: indexs)
  89. self.toolBar.setPageRangeString(KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs.sorted()))
  90. }
  91. self.view.window?.makeFirstResponder(self)
  92. }
  93. override func viewDidLoad() {
  94. super.viewDidLoad()
  95. self.thumbnailView.collectionView.backgroundColor(NSColor(hex: "#CED0D4"))
  96. var allowedFileTypes: [String] = []
  97. if let _types = KMConvertPDFManagerOC.supportFileType() as? [String] {
  98. allowedFileTypes = KMTools.pdfExtensions + _types
  99. } else {
  100. allowedFileTypes = KMTools.pdfExtensions + KMTools.imageExtensions
  101. }
  102. self.thumbnailView.kmAllowedFileTypes = allowedFileTypes
  103. let toolBar = self.toolBar
  104. self.topBarBox.contentView = toolBar
  105. self.topBarBox.fillColor = NSColor(hex: "#F7F8FA")
  106. toolBar.itemClick = { [unowned self] item, index in
  107. guard let type = KMPageEditType(rawValue: index) else {
  108. if (index == KMPageEditType.insert_files) {
  109. self.insertFileAction()
  110. } else if (index == KMPageEditType.insert_blank_page) {
  111. self.insertBlankPageAction()
  112. } else if (index == KMPageEditType.insert_custom_page) {
  113. self.item_insertCustomPage(sender: nil)
  114. }
  115. return
  116. }
  117. if (type == .leftRotate) {
  118. self.leftRotateAction()
  119. } else if (type == .rightRotate) {
  120. self.rightRotateAction()
  121. } else if (type == .zoomOut) {
  122. self.zoomOutButtonAction(sender: item?.zoomOutButton)
  123. } else if (type == .zoomIn) {
  124. self.zoomInButtonAction(sender: item?.zoomInButton)
  125. } else if (type == .extract) {
  126. self.extractAction()
  127. } else if (type == .replace) {
  128. self.replaceAction()
  129. } else if (type == .split) {
  130. self.splitAction()
  131. } else if (type == .reverse) {
  132. self.reverseAction()
  133. } else if (type == .delete) {
  134. self.deleteAction()
  135. } else if (type == .pageRange) {
  136. self.km_comboBoxSelectionDidChange((item?.pageRangeView)!)
  137. } else if (type == .insert) {
  138. self.trackEvent(type: .insert)
  139. }
  140. }
  141. toolBar.pageRangeValueDidChange = { [unowned self] value, _ in
  142. self.km_controlTextDidEndEditing(self.toolBar.pageRangeView!)
  143. }
  144. let view = self.thumbnailView
  145. self.contentBox.contentView?.addSubview(view)
  146. view.frame = self.contentBox.contentView!.bounds
  147. view.autoresizingMask = [.width, .height]
  148. self.pageEditThumbnailView.delegate = self
  149. self.pageEditThumbnailView.selectionDidChange = { [unowned self] selectedIndexs in
  150. self.view.window?.makeFirstResponder(self)
  151. let enabled = (selectedIndexs.count > 0)
  152. for i in 0 ..< self.toolBar.toolBar.items.count {
  153. let item: KMToolBoxItem = self.toolBar.toolBar.items[i]
  154. if (item.itemIdentifier == KMToolbarPageEditExtractItemIdentifier ||
  155. item.itemIdentifier == KMToolbarPageEditLeftRotateItemIdentifier ||
  156. item.itemIdentifier == KMToolbarPageEditRightRotateItemIdentifier ||
  157. item.itemIdentifier == KMToolbarPageEditReplaceItemIdentifier) {
  158. item.unEnabled = !enabled
  159. } else if (item.itemIdentifier == KMToolbarPageEditReverseItemIdentifier) {
  160. item.unEnabled = !(selectedIndexs.count > 1)
  161. } else if (item.itemIdentifier == KMToolbarPageEditDeleteItemIdentifier) {
  162. item.unEnabled = !self.canDelete()
  163. }
  164. }
  165. if (self.pageIsUpdate == false) {
  166. self.pageIsUpdate = true
  167. return
  168. }
  169. var indexs: Array<Int> = []
  170. for indexPath in selectedIndexs {
  171. indexs.append(indexPath.item)
  172. }
  173. indexs.sort(){$0 < $1}
  174. self.toolBar.setPageRangeString(KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs))
  175. }
  176. }
  177. // MARK: Private Methods
  178. private func getSelecteIndex() -> Int {
  179. let index = self.getPasteIndex()
  180. if (index != NSNotFound) {
  181. return index
  182. }
  183. return 0
  184. }
  185. private func getSelectedPage() -> CPDFPage {
  186. return (self.pdfDocument!.page(at: UInt(getSelecteIndex())))!
  187. }
  188. private func selectPages(indexs: IndexSet) {
  189. var indexpaths: Set<IndexPath> = []
  190. for index in indexs {
  191. indexpaths.insert(IndexPath(item: index, section: 0))
  192. }
  193. self.selectPages(indexpaths: indexpaths)
  194. }
  195. private func km_becomeFirstResponder() {
  196. DispatchQueue.main.async {
  197. self.view.window?.makeFirstResponder(self)
  198. }
  199. }
  200. fileprivate func dealPdfDocumentDidEditCallback(type: KMPageEditType = .none) {
  201. // 提醒外面文档已编辑
  202. guard let callback = self.documentEditedCallback else {
  203. return
  204. }
  205. callback(type)
  206. }
  207. // MARK: - 清空选择
  208. private func clearSelectPages() {
  209. self.selectPages(indexs: IndexSet())
  210. }
  211. override func refreshUI(indexpaths: Set<IndexPath> = [], keepSelected: Bool = false) {
  212. super.refreshUI(indexpaths: indexpaths, keepSelected: keepSelected)
  213. self.listView?.layoutDocumentView()
  214. }
  215. override func cutAction() {
  216. if (self.thumbnailView.selectionIndexPaths.count == (self.listView?.document.pageCount)!) {
  217. let _ = CustomAlertView(message: NSLocalizedString("Unable to delete all pages", comment: ""), from: self.thumbnailView, with: .blue)
  218. return
  219. }
  220. super.cutAction()
  221. }
  222. override func copyAction() {
  223. self.trackEvent_copy()
  224. super.copyAction()
  225. }
  226. override func deleteAction() {
  227. self.trackEvent(type: .delete)
  228. super.deleteAction()
  229. self.toolBar.unSelectItem(for: KMToolbarPageEditDeleteItemIdentifier)
  230. }
  231. override func deleteIndexPaths(indexpaths: Set<IndexPath>) {
  232. guard let pageCount = self.listView?.document.pageCount else {
  233. KMPrint("pageCount invalid.")
  234. return
  235. }
  236. if (indexpaths.count == pageCount) {
  237. let _ = CustomAlertView(message: NSLocalizedString("Unable to delete all pages", comment: ""), from: self.thumbnailView, with: .blue)
  238. return
  239. }
  240. self.dealPdfDocumentDidEditCallback(type: .delete)
  241. super.deleteIndexPaths(indexpaths: indexpaths)
  242. }
  243. override func leftRotateAction() {
  244. self.trackEvent(type: .leftRotate)
  245. super.leftRotateAction()
  246. // self.toolBar.unSelectItem(for: KMToolbarPageEditLeftRotateItemIdentifier)
  247. }
  248. override func leftRotateIndexpaths(indexpaths: Set<IndexPath>) {
  249. if (!self.indexpathsIsValid(indexpaths: indexpaths) || !self.canRotate()) {
  250. return
  251. }
  252. super.leftRotateIndexpaths(indexpaths: indexpaths)
  253. self.dealPdfDocumentDidEditCallback(type: .leftRotate)
  254. }
  255. override func rightRotateAction() {
  256. self.trackEvent(type: .rightRotate)
  257. super.rightRotateAction()
  258. // self.toolBar.unSelectItem(for: KMToolbarPageEditRightRotateItemIdentifier)
  259. }
  260. override func rightRotateIndexpaths(indexpaths: Set<IndexPath>) {
  261. if (!self.indexpathsIsValid(indexpaths: indexpaths) || !self.canRotate()) {
  262. return
  263. }
  264. super.rightRotateIndexpaths(indexpaths: indexpaths)
  265. self.dealPdfDocumentDidEditCallback(type: .rightRotate)
  266. }
  267. override func insertPages(pages: Array<CPDFPage>, at indexs: IndexSet) {
  268. super.insertPages(pages: pages, at: indexs)
  269. if (!indexs.isEmpty) {
  270. self.selectPages(indexs: indexs)
  271. self.dealPdfDocumentDidEditCallback(type: .insert)
  272. }
  273. }
  274. override func pasteAction() {
  275. if (self.canPaste()) {
  276. super.pasteAction()
  277. self.dealPdfDocumentDidEditCallback(type: .paste)
  278. }
  279. }
  280. override func extractAction() {
  281. self.trackEvent(type: .extract)
  282. super.extractAction()
  283. DispatchQueue.main.async {
  284. self.toolBar.unSelectItem(for: KMToolbarPageEditExtractItemIdentifier)
  285. }
  286. }
  287. override func replaceAction() {
  288. self.trackEvent(type: .replace)
  289. super.replaceAction()
  290. DispatchQueue.main.async {
  291. self.toolBar.unSelectItem(for: KMToolbarPageEditReplaceItemIdentifier)
  292. }
  293. }
  294. override func getInsertIndex() -> Int {
  295. var index = 0
  296. if let pageCount = self.thumbnailView.document?.pageCount, pageCount > 0 {
  297. // 默认为最后一页
  298. index = Int(pageCount-1)
  299. }
  300. // 在当前选中item之后插入
  301. // 多选时,则取最后一页
  302. for indexpath in self.thumbnailView.selectionIndexPaths.sorted() {
  303. index = indexpath.item
  304. }
  305. return index
  306. }
  307. override func splitAction() {
  308. self.trackEvent(type: .split)
  309. Task { @MainActor in
  310. self.toolBar.unSelectItem(for: KMToolbarPageEditSplitItemIdentifier)
  311. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  312. let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, type: .split) { isSubscribeSuccess, isWaterMarkExport, isClose in
  313. if (isClose) {
  314. return
  315. }
  316. if (isSubscribeSuccess) {
  317. self._showSplitWindow()
  318. return
  319. }
  320. if (isWaterMarkExport) {
  321. self._showSplitWindow(limit: true)
  322. return
  323. }
  324. }
  325. return
  326. }
  327. self._showSplitWindow()
  328. }
  329. }
  330. override func reverseAction() {
  331. self.trackEvent(type: .reverse)
  332. Task { @MainActor in
  333. self.toolBar.unSelectItem(for: KMToolbarPageEditReverseItemIdentifier)
  334. self.reverseMenuAction(sender: nil)
  335. }
  336. }
  337. fileprivate func _showSplitWindow(limit: Bool = false) {
  338. let model = KMPageEditSplitSettingModel()
  339. model.documentURL = self.listView?.document.documentURL
  340. if let pagecnt = self.thumbnailView.document?.pageCount {
  341. model.pageCount = Int(pagecnt)
  342. }
  343. model.fileName = model.documentURL.lastPathComponent
  344. model.pathExtension = model.fileName.components(separatedBy: ".").last
  345. if (self.thumbnailView.selectionIndexPaths.count > 0) {
  346. model.type = 2
  347. model.pageRangeType = 2
  348. var selectedIndexs: Array<Int> = []
  349. for indexpath in self.thumbnailView.selectionIndexPaths {
  350. selectedIndexs.append(indexpath.item)
  351. }
  352. model.pageRangeString = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: selectedIndexs)
  353. } else {
  354. model.type = 0
  355. }
  356. let windowController = KMPageEditSplitWindowController(model)
  357. self.km_beginSheet(windowC: windowController)
  358. windowController.itemClick = { [weak self] index, value in
  359. if (index == 1) { /// 取消
  360. self?.km_endSheet()
  361. return
  362. }
  363. guard let _windowC = self?.currentWindowC as? KMPageEditSplitWindowController else {
  364. self?.km_endSheet()
  365. return
  366. }
  367. // if self?.canPayFunction == false {
  368. // let _ = KMSubscribeWaterMarkWindowController.show(window: windowController.window!, isContinue: true, type: .split) { isSubscribeSuccess, isWaterMarkExport, isClose in
  369. // var limit = true
  370. // if (isClose) {
  371. // return
  372. // }
  373. // if (isSubscribeSuccess) {
  374. // limit = false
  375. // }
  376. // if (isWaterMarkExport) {
  377. //
  378. // }
  379. //
  380. // /// 拆分
  381. // let outputModel = _windowC.model! as! KMPageEditSplitSettingModel
  382. // self?.km_endSheet()
  383. //
  384. // let panel = NSOpenPanel()
  385. // panel.canChooseFiles = false
  386. // panel.canChooseDirectories = true
  387. // panel.canCreateDirectories = true
  388. // panel.beginSheetModal(for: (self?.view.window)!) { response in
  389. // if (response == .cancel) {
  390. // return
  391. // }
  392. //
  393. // let file_indexs = outputModel.getSplitIndexSets
  394. // if (file_indexs == nil || file_indexs!.count <= 0) {
  395. // return
  396. // }
  397. //
  398. // DispatchQueue.main.async {
  399. // self?.showProgressWindow(message: NSLocalizedString("Spliting...", comment: ""))
  400. // self?.progressC?.maxValue = Double(file_indexs!.count)
  401. // let _document: CPDFDocument = (self?.listView?.document)!
  402. //
  403. // let filePath = "\(panel.url!.path)/\(_document.documentURL.deletingPathExtension().lastPathComponent)"
  404. // let uniqueFilePath = KMTools.getUniqueFilePath(filePath: filePath)
  405. // // Swift.debugPrint(uniqueFilePath)
  406. // if (!FileManager.default.fileExists(atPath: uniqueFilePath)) {
  407. // try?FileManager.default.createDirectory(atPath: uniqueFilePath, withIntermediateDirectories: true)
  408. // }
  409. //
  410. // var filepaths: [String] = []
  411. // for i in 0 ..< file_indexs!.count {
  412. // let indexs = file_indexs![i]
  413. // if (indexs.isEmpty) {
  414. // continue
  415. // }
  416. // let filepath = String(format: "%@/%@.pdf", uniqueFilePath, model.getNewOutputFileName(index: i+1))
  417. // filepaths.append(filepath)
  418. //
  419. // let newDocument = CPDFDocument()
  420. // newDocument?.importPages(indexs, from: _document, at: 0)
  421. // self?.progressC?.increment(by: 1.0)
  422. // if (limit) {
  423. // let _ = KMTools.saveWatermarkDocument(document: newDocument!, to: URL(fileURLWithPath: filepath))
  424. // } else {
  425. // newDocument?.write(to: URL(fileURLWithPath: filepath))
  426. // }
  427. // }
  428. // self?.hiddenProgressWindow()
  429. // if let _urlString = filepaths.first?.deletingLastPathComponent {
  430. // NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: _urlString)])
  431. // }
  432. // }
  433. // }
  434. // }
  435. // }
  436. /// 拆分
  437. let outputModel = _windowC.model! as! KMPageEditSplitSettingModel
  438. self?.km_endSheet()
  439. let panel = NSOpenPanel()
  440. panel.canChooseFiles = false
  441. panel.canChooseDirectories = true
  442. panel.canCreateDirectories = true
  443. panel.beginSheetModal(for: (self?.view.window)!) { response in
  444. if (response == .cancel) {
  445. return
  446. }
  447. let file_indexs = outputModel.getSplitIndexSets
  448. if (file_indexs == nil || file_indexs!.count <= 0) {
  449. return
  450. }
  451. DispatchQueue.main.async {
  452. self?.showProgressWindow(message: NSLocalizedString("Spliting...", comment: ""))
  453. self?.progressC?.maxValue = Double(file_indexs!.count)
  454. let _document: CPDFDocument = (self?.listView?.document)!
  455. let filePath = "\(panel.url!.path)/\(_document.documentURL.deletingPathExtension().lastPathComponent)"
  456. let uniqueFilePath = KMTools.getUniqueFilePath(filePath: filePath)
  457. // Swift.debugPrint(uniqueFilePath)
  458. if (!FileManager.default.fileExists(atPath: uniqueFilePath)) {
  459. try?FileManager.default.createDirectory(atPath: uniqueFilePath, withIntermediateDirectories: true)
  460. }
  461. var filepaths: [String] = []
  462. for i in 0 ..< file_indexs!.count {
  463. let indexs = file_indexs![i]
  464. if (indexs.isEmpty) {
  465. continue
  466. }
  467. let filepath = String(format: "%@/%@.pdf", uniqueFilePath, model.getNewOutputFileName(index: i+1))
  468. filepaths.append(filepath)
  469. let newDocument = CPDFDocument()
  470. newDocument?.importPages(indexs, from: _document, at: 0)
  471. self?.progressC?.increment(by: 1.0)
  472. if (limit) {
  473. let _ = KMTools.saveWatermarkDocument(document: newDocument!, to: URL(fileURLWithPath: filepath))
  474. } else {
  475. newDocument?.write(to: URL(fileURLWithPath: filepath))
  476. }
  477. }
  478. self?.hiddenProgressWindow()
  479. if let _urlString = filepaths.first?.deletingLastPathComponent {
  480. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: _urlString)])
  481. }
  482. }
  483. }
  484. }
  485. }
  486. // MARK: Undo / Redo
  487. @objc private func reversePages(indexs: IndexSet) {
  488. KMPageEditTools.reverse((self.listView?.document)!, indexs
  489. ) { result, error in
  490. if (result) {
  491. self.refreshUI(indexpaths: self.indexsToIndexpaths(indexs: indexs), keepSelected: true)
  492. self.kmUndoManager?.registerUndo(withTarget: self, selector: #selector(self.reversePages), object: indexs)
  493. }
  494. }
  495. }
  496. @objc private func dragPages(_ indexs: IndexSet, _ toIndex: Int, dp: NSCollectionView.DropOperation, reversed: Bool = false) {
  497. if (indexs.count <= 0) {
  498. return
  499. }
  500. self.listViewCurrentPageUpdateForDrag(indexs: indexs, toIndex: toIndex)
  501. // 插入位置偏移量
  502. var toIndexOffset: Int = 0
  503. // 需要移动的页面index数组
  504. var newPages: [CPDFPage] = []
  505. var currentPage: CPDFPage?
  506. var originalIndex = self.listViewCurrentIndex
  507. // 从后面往前删除
  508. for index in indexs.reversed() {
  509. let newPage = (self.listView?.document.page(at: UInt(index)))?.copy() as? CPDFPage
  510. if (newPage == nil) {
  511. continue
  512. }
  513. newPages.insert(newPage!, at: 0)
  514. self.listView?.document.removePage(at: UInt(index))
  515. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  516. toIndexOffset += 1
  517. }
  518. if (currentPage == nil) && (originalIndex == index) {
  519. currentPage = newPage
  520. }
  521. }
  522. if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
  523. toIndexOffset -= 1
  524. }
  525. let insertIndex = max(0, toIndex-toIndexOffset)
  526. var selectIndexs: IndexSet = []
  527. for (index, page) in newPages.enumerated() {
  528. self.listView?.document.insertPageObject(page, at: UInt(insertIndex+index))
  529. selectIndexs.insert(insertIndex+index)
  530. if (currentPage?.pageIndex() == page.pageIndex()) {
  531. // self._listViewCurrentIndex = insertIndex+index
  532. }
  533. }
  534. // 新增 undo
  535. self.kmUndoManager?.registerUndo(withTarget: self) { target in
  536. target.clearSelectPages()
  537. target.dragPages_reversed(indexs, toIndex, newPages, dp: dp)
  538. }
  539. // 刷新UI
  540. self.refreshUI()
  541. if (reversed == false) {
  542. self.selectPages(indexs: selectIndexs)
  543. }
  544. }
  545. @objc private func dragPages_reversed(_ indexs: IndexSet, _ toIndex: Int, _ pages: [CPDFPage], dp: NSCollectionView.DropOperation) {
  546. if (indexs.count <= 0) {
  547. return
  548. }
  549. // 插入位置偏移量
  550. var toIndexOffset: Int = 0
  551. for index in indexs {
  552. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  553. toIndexOffset += 1
  554. }
  555. }
  556. if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
  557. toIndexOffset -= 1
  558. }
  559. let insertIndex = max(0, toIndex-toIndexOffset)
  560. // 需要移动的页面index数组
  561. var datas: [Int] = []
  562. for index in insertIndex ..< (insertIndex + indexs.count) {
  563. datas.append(index)
  564. }
  565. // 从后面开始删除
  566. for index in datas.reversed() {
  567. self.listView?.document.removePage(at: UInt(index))
  568. }
  569. // 再插入到对应的位置
  570. for (index,value) in indexs.enumerated() {
  571. var page: CPDFPage?
  572. if (index < pages.count) {
  573. page = pages[index]
  574. }
  575. if (page != nil) {
  576. self.listView?.document.insertPageObject(page!, at: UInt(value))
  577. }
  578. }
  579. // 新增 undo
  580. self.kmUndoManager?.registerUndo(withTarget: self) { target in
  581. target.dragPages(indexs, toIndex, dp: dp, reversed: true)
  582. }
  583. // 刷新UI
  584. self.refreshUI()
  585. }
  586. // MARK: topBar 事件
  587. @objc func zoomOutButtonAction(sender: NSButton?) {
  588. if (self.itemSize.width > self.defaultItemSize.width) {
  589. return
  590. }
  591. if (self.itemSize.width < self.defaultItemSize.width) {
  592. self.itemSize = self.defaultItemSize
  593. } else if (self.itemSize.width == self.defaultItemSize.width) {
  594. self.itemSize = NSSize(width: self.defaultItemSize.width*1.5, height: self.defaultItemSize.height*1.5)
  595. }
  596. self.toolBar.zoomInButton?.isEnabled = true
  597. if (self.itemSize.width > self.defaultItemSize.width) {
  598. sender?.isEnabled = false
  599. }
  600. self.pageEditThumbnailView.zoomOut()
  601. }
  602. @objc func zoomInButtonAction(sender: NSButton?) {
  603. if (self.itemSize.width < self.defaultItemSize.width) {
  604. return
  605. }
  606. if (self.itemSize.width > self.defaultItemSize.width) {
  607. self.itemSize = self.defaultItemSize
  608. } else if (self.itemSize.width == self.defaultItemSize.width) {
  609. self.itemSize = NSSize(width: self.defaultItemSize.width*0.5, height: self.defaultItemSize.height*0.5)
  610. }
  611. self.toolBar.zoomOutButton?.isEnabled = true
  612. if (self.itemSize.width < self.defaultItemSize.width) {
  613. sender?.isEnabled = false
  614. }
  615. self.pageEditThumbnailView.zoomIn()
  616. }
  617. // MARK: menu 菜单事件
  618. @objc func item_insertCustomPage(sender: NSMenuItem?) {
  619. Task { @MainActor in
  620. let windowController = KMPageEditInsertCustomPageWindowController()
  621. if (self.thumbnailView.selectionIndexPaths.count > 0) {
  622. let page = self.getSelectedPage()
  623. let width = page.bounds.size.width * 210 / 595
  624. let height = page.bounds.size.height * 297 / 842
  625. windowController.selectedPageSize = NSSize(width: width, height: height)
  626. // windowController.selectedPageSize = self.getSelectedPage().bounds.size
  627. }
  628. self.km_beginSheet(windowC: windowController)
  629. windowController.itemClick = { [weak self] index in
  630. if (index == 1) { /// 取消
  631. self?.km_endSheet()
  632. return
  633. }
  634. /// 插入
  635. guard let windowC = self?.currentWindowC as? KMPageEditInsertCustomPageWindowController else {
  636. self?.km_endSheet()
  637. return
  638. }
  639. guard let _insertIndex = self?.getInsertIndex() else {
  640. self?.km_endSheet()
  641. return
  642. }
  643. /// 样式
  644. // let type = windowC.typeIndex
  645. // mm 单位的大小
  646. let pageSize = windowC.pageSize
  647. let direction = windowC.direction
  648. var _pageSize = KMPageEditTools.sizeUnitToBoundSize(unit: .mm, pageSize: pageSize)
  649. if (direction == 0) { // 纵向
  650. if (_pageSize.width > _pageSize.height) { // 需要交换
  651. let tmp = _pageSize.width
  652. _pageSize.width = _pageSize.height
  653. _pageSize.height = tmp
  654. } else {
  655. // no things.
  656. }
  657. } else { // 横向
  658. if (_pageSize.width > _pageSize.height) {
  659. // no things.
  660. } else { // 需要交换
  661. let tmp = _pageSize.width
  662. _pageSize.width = _pageSize.height
  663. _pageSize.height = tmp
  664. }
  665. }
  666. /// 插入位置
  667. // if (type == 1) { /// 空白页
  668. let document = CPDFDocument()
  669. document?.insertPage(_pageSize, at: 0)
  670. if let page: CPDFPage = (document?.page(at: 0)) {
  671. self?.insertPages(pages: [page], at: IndexSet(integer: _insertIndex+1))
  672. }
  673. // } else {
  674. // let document = CPDFDocument()
  675. // var imageName = "plaid"
  676. // if (type == 2) {
  677. // imageName = "horizontal_line"
  678. // } else if (type == 3) {
  679. // imageName = "five_line_score"
  680. // }
  681. // let imagePath = Bundle.main.pathForImageResource(imageName)
  682. // document?.insertPage(pageSize, withImage: imagePath, at: 0)
  683. // let page: CPDFPage = (document?.page(at: 0))!
  684. // if (direction == 0) { /// 纵向
  685. // page.rotation = 90
  686. // }
  687. //
  688. // self?.insertPagesForDescSort(pages: [page], indexs: IndexSet(integer: _insertIndex+1))
  689. // }
  690. self?.km_endSheet()
  691. }
  692. }
  693. }
  694. // MARK: toolBar 菜单事件
  695. @objc func reverseMenuAction(sender: AnyObject?) {
  696. let selectedIndexs = self.thumbnailView.selectionIndexPaths
  697. if (selectedIndexs.count < 2 ) {
  698. let alertView = CustomAlertView(message: NSLocalizedString("Please select at least two pages for editing first", comment: ""), from: self.thumbnailView, with: .blue)
  699. alertView?.layer?.backgroundColor = NSColor(hex: "#36383B").cgColor
  700. alertView?.layer?.cornerRadius = 4
  701. return
  702. }
  703. var indexs: IndexSet = []
  704. for indexpath in selectedIndexs {
  705. indexs.insert(indexpath.item)
  706. }
  707. self.reversePages(indexs: indexs)
  708. self.dealPdfDocumentDidEditCallback(type: .reverse)
  709. }
  710. override func addMenuItem(menu: NSMenu, item: KMPDFThumbViewMenu.Item) -> NSMenuItem? {
  711. var item_: NSMenuItem?
  712. if (item.sel == KMPDFThumbViewMenu.insertSelector) {
  713. if (self.thumbnailView.selectionIndexPaths.count == 1) {
  714. item_ = menu.addItem(withTitle: NSLocalizedString("Insert", comment: ""), action: nil, target: self)
  715. let subMenu = NSMenu()
  716. subMenu.addItem(withTitle: NSLocalizedString("Insert a Blank Page", comment: ""), action: #selector(insertPageItemAction), target: self, tag:0)
  717. subMenu.addItem(withTitle: NSLocalizedString("Insert Custom Page", comment: ""), action: #selector(insertPageItemAction), target: self, tag:1)
  718. subMenu.addItem(withTitle: NSLocalizedString("Insert File", comment: ""), action: #selector(insertPageItemAction), target: self, tag:2)
  719. item_?.submenu = subMenu
  720. }
  721. } else if (item.sel == KMPDFThumbViewMenu.splitSelector) {
  722. if (self.thumbnailView.selectionIndexPaths.count > 1) {
  723. item_ = menu.addItem(withTitle: NSLocalizedString("Split", comment: ""), action: KMPDFThumbViewMenu.splitSelector, target: self)
  724. }
  725. } else if (item.sel == KMPDFThumbViewMenu.reverseSelector) {
  726. if (self.thumbnailView.selectionIndexPaths.count > 1) {
  727. item_ = menu.addItem(withTitle: NSLocalizedString("Reverse", comment: ""), action: KMPDFThumbViewMenu.reverseSelector, target: self)
  728. }
  729. } else {
  730. return super.addMenuItem(menu: menu, item: item)
  731. }
  732. return item_
  733. }
  734. }
  735. extension KMPDFEditViewController {
  736. //MARK: menu Action
  737. @objc func insertPageItemAction(menu:NSMenuItem) {
  738. if (menu.tag == 0) {
  739. self.insertBlankPageAction()
  740. } else if (menu.tag == 1) {
  741. self.item_insertCustomPage(sender: nil)
  742. } else if (menu.tag == 2) {
  743. self.insertFileAction()
  744. }
  745. }
  746. @objc func sharePageItemAction(menu:NSMenuItem) {
  747. let item = menu.parent!
  748. let index = (item.representedObject as! IndexSet).first ?? -1
  749. if Int(index) >= 0 {
  750. let doucument = self.pdfDocument!
  751. let page = doucument.page(at: UInt(index))
  752. let filename : String = doucument.documentURL.lastPathComponent
  753. let folderPath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(filename))!
  754. try? FileManager.default.removeItem(atPath: folderPath)
  755. let pdfdocument = CPDFDocument()
  756. let ret = pdfdocument!.importPages((item.representedObject as! IndexSet), from: self.thumbnailView.document, at: 0)
  757. let url = URL(fileURLWithPath: folderPath)
  758. if ret {
  759. let success = pdfdocument!.write(to:url)
  760. if success {
  761. let workspace = NSWorkspace.shared
  762. workspace.activateFileViewerSelecting([url])
  763. }
  764. }
  765. let represent : NSSharingService = menu.representedObject as! NSSharingService
  766. represent.perform(withItems: [url])
  767. }
  768. }
  769. @objc func showPageSizeItemAction(menu: NSMenuItem) {
  770. self.thumbnailView.isShowPageSize = !self.thumbnailView.isShowPageSize
  771. self.refreshUIForKeepSelecteds()
  772. }
  773. @objc func printItemAction(menu:NSMenuItem) {
  774. var datas: [Int] = []
  775. for indexpath in self.thumbnailView.selectionIndexPaths {
  776. datas.append(indexpath.item)
  777. }
  778. guard let callback = self.itemClick else {
  779. return
  780. }
  781. callback(2, datas.sorted())
  782. }
  783. }
  784. extension KMPDFEditViewController {
  785. override func menuItemAction_print(_ sender: Any?) {
  786. self.printItemAction(menu: sender as! NSMenuItem)
  787. }
  788. override func menuItemAction_showPageSize(_ sender: Any?) {
  789. self.showPageSizeItemAction(menu: sender as! NSMenuItem)
  790. }
  791. }
  792. // MARK: - KMSelectPopButtonDelegate
  793. extension KMPDFEditViewController {
  794. func km_comboBoxSelectionDidChange(_ obj: KMDesignSelect) {
  795. self.pageIsUpdate = false
  796. let index: Int = obj.indexOfSelectedItem
  797. var indexpaths: Set<IndexPath> = []
  798. var type: KMPageRange?
  799. if (index <= 0) { /// 全部页面
  800. type = .all
  801. } else if (index == 1) { /// 奇数页
  802. type = .odd
  803. } else if (index == 2) { /// 偶数页
  804. type = .even
  805. } else if (index == 3) { /// 横向页
  806. type = .horizontal
  807. } else if (index == 4) { /// 纵向页
  808. type = .vertical
  809. } else { /// 自定义
  810. type = .custom
  811. }
  812. for i in 0 ..< (self.pdfDocument?.pageCount)! {
  813. if (type == .all) {
  814. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  815. } else if (type == .odd) {
  816. if (i % 2 == 1) {
  817. continue
  818. }
  819. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  820. } else if (type == .even) {
  821. if (i % 2 == 0) {
  822. continue
  823. }
  824. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  825. } else if (type == .horizontal) {
  826. let page = self.pdfDocument?.page(at: i)
  827. guard let isVertical = page?.isVertical(), !isVertical else {
  828. continue
  829. }
  830. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  831. } else if (type == .vertical) {
  832. let page = self.pdfDocument?.page(at: i)
  833. guard let isHorizontal = page?.isHorizontal(), !isHorizontal else {
  834. continue
  835. }
  836. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  837. }
  838. }
  839. obj.editable = type == .custom
  840. if (type == .custom) {
  841. self.clearSelectPages()
  842. DispatchQueue.main.async {
  843. self.toolBar.pageRangeView?.stringValue = ""
  844. self.view.window?.makeFirstResponder(self.toolBar.pageRangeView?.textField)
  845. }
  846. } else {
  847. self.pageEditThumbnailView.selectPages(at: indexpaths)
  848. }
  849. }
  850. func km_controlTextDidEndEditing(_ obj: KMDesignSelect) {
  851. self.view.window?.makeFirstResponder(self)
  852. for index in 0 ..< obj.numberOfItems {
  853. if (obj.items[index] == obj.stringValue) {
  854. return
  855. }
  856. }
  857. let pages = KMPageRangeTools.findSelectPage(pageRangeString: self.toolBar.pageRangeView!.stringValue, pageCount: Int((self.listView?.document.pageCount)!))
  858. if (pages.isEmpty) {
  859. let alert = NSAlert()
  860. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  861. alert.runModal()
  862. self.toolBar.setPageRangeString("")
  863. DispatchQueue.main.async {
  864. self.view.window?.makeFirstResponder(self.toolBar.pageRangeView?.textField)
  865. }
  866. return
  867. }
  868. var indexpaths: Set<IndexPath> = []
  869. for page in pages {
  870. if (page >= 1) {
  871. indexpaths.insert(IndexPath(item: page-1, section: 0))
  872. }
  873. }
  874. self.pageIsUpdate = false
  875. self.pageEditThumbnailView.selectPages(at: indexpaths)
  876. }
  877. }
  878. // MARK: -
  879. // MARK: KMThumbnailViewDelegate
  880. extension KMPDFEditViewController: KMThumbnailViewDelegate {
  881. func thumbnailView(thumbanView: KMThumbnailView, shouldAcceptDrop draggingInfo: NSDraggingInfo, indexPath: IndexPath, dropOperation: NSCollectionView.DropOperation) -> Bool {
  882. return true
  883. }
  884. func thumbnailView(thumbanView: KMThumbnailView, didDragAddFiles files: [URL], indexpath: IndexPath) {
  885. self.km_add_file_multi(fileUrls: files) { index, params in
  886. if (self.fetchProgressBlockParamsIsPasswordFile(params: params)) { // 加密文档进度回调
  887. return
  888. }
  889. let _fileUrl = self.fetchProgressBlockParamsForFileUrl(params: params)
  890. if let exn = _fileUrl?.pathExtension, KMTools.isPDFType(exn) {
  891. if (_fileUrl!.path.isPDFValid() == false) {
  892. let alert = NSAlert()
  893. alert.alertStyle = .critical
  894. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  895. alert.runModal()
  896. }
  897. }
  898. } completionBlock: { [unowned self] documents in
  899. var insertIndex: Int = indexpath.item
  900. var pages: Array<CPDFPage> = []
  901. var indexs = IndexSet()
  902. for document in documents {
  903. for i in 0 ..< document.pageCount {
  904. let page = document.page(at: i)
  905. pages.append(page!)
  906. indexs.insert(insertIndex)
  907. insertIndex += 1
  908. }
  909. }
  910. self.insertPages(pages: pages, at: indexs)
  911. }
  912. }
  913. func thumbnailView(thumbanView: KMThumbnailView, didDrag dragedIndexPaths: [IndexPath], indexpath: IndexPath, dragInfo: [KMThumbnailViewDragInfoKey.RawValue : Any]) {
  914. let toIndex = max(0, indexpath.item)
  915. var indexs = IndexSet()
  916. for indexpath in dragedIndexPaths {
  917. indexs.insert(indexpath.item)
  918. }
  919. var dp = NSCollectionView.DropOperation.on
  920. if let _dp = dragInfo[KMThumbnailViewDragInfoKey.dropOperation.rawValue] as? NSCollectionView.DropOperation {
  921. dp = _dp
  922. }
  923. self.dragPages(indexs, toIndex, dp: dp)
  924. if (dragedIndexPaths.count > 0) {
  925. self.dealPdfDocumentDidEditCallback()
  926. }
  927. }
  928. func thumbnailView(thumbanView: KMThumbnailView, shouldPasteboardWriterForItemAt indexPath: IndexPath) -> Bool {
  929. return true
  930. }
  931. func thumbnailView(thumbanView: KMThumbnailView, insetForSectionAt section: Int) -> NSEdgeInsets {
  932. return NSEdgeInsets(top: 16, left: 16, bottom: 0, right: 32)
  933. }
  934. func thumbnailView(thumbanView: KMThumbnailView, sizeForItemAt indexpath: IndexPath) -> NSSize {
  935. self.thumbnailView.thumbnailSzie = CGSize(width: 120, height: 155)
  936. if (!self.thumbnailView.isShowPageSize) {
  937. return NSMakeSize(self.itemSize.width, self.itemSize.height+26)
  938. }
  939. return self.itemSize
  940. }
  941. func thumbnailView(thumbanView: KMThumbnailView, numberOfItemsInSection section: Int) -> Int {
  942. if let count = self.pdfDocument?.pageCount {
  943. return Int(count)
  944. }
  945. return 0
  946. }
  947. func thumbnailView(thumbanView: KMThumbnailView, itemForRepresentedObjectAt indexpath: IndexPath) -> NSCollectionViewItem {
  948. let cellView: KMPageEditThumbnailItem = thumbanView.collectionView.makeItem(withIdentifier: KMPageEditThumbnailItem.km_identifier, for: indexpath) as! KMPageEditThumbnailItem
  949. cellView.isShowPageSize = self.thumbnailView.isShowPageSize
  950. cellView.page = (self.pdfDocument?.page(at: UInt(indexpath.item)))!
  951. cellView.setPage(page: (self.pdfDocument?.page(at: UInt(indexpath.item)))!)
  952. cellView.doubleClickAction = { [unowned self] _ in
  953. guard let callback = self.itemClick else {
  954. return
  955. }
  956. callback(1, indexpath.item)
  957. }
  958. cellView.mouseDownAction = { [unowned self] _ in
  959. let selectionIndexPaths = self.thumbnailView.selectionIndexPaths
  960. if (selectionIndexPaths.count == 1 && selectionIndexPaths.first?.item == indexpath.item) {
  961. return
  962. }
  963. self.selectPages(indexs: IndexSet.init(integer: indexpath.item))
  964. }
  965. cellView.rightMouseDownAction = { [unowned self] _ in
  966. self.selectPages(indexs: IndexSet.init(integer: indexpath.item))
  967. }
  968. return cellView
  969. }
  970. }
  971. // MARK: - 系统菜单栏
  972. extension KMPDFEditViewController {
  973. override func undo(_ sender: Any?) {
  974. super.undo(sender)
  975. self.km_becomeFirstResponder()
  976. }
  977. override func redo(_ sender: Any?) {
  978. super.redo(sender)
  979. self.km_becomeFirstResponder()
  980. }
  981. }
  982. // MARK: - KMExtensions
  983. extension KMPDFEditViewController {
  984. override func deleteAfter(indexpaths: Set<IndexPath>) {
  985. self.clearSelectPages()
  986. self.km_becomeFirstResponder()
  987. }
  988. override func copyAfter(indexpaths: Set<IndexPath>) {
  989. self.km_becomeFirstResponder()
  990. }
  991. override func pasteAfter(at index: Int) {
  992. self.km_becomeFirstResponder()
  993. }
  994. override func cutAfter(indexpaths: Set<IndexPath>) {
  995. self.clearSelectPages()
  996. self.km_becomeFirstResponder()
  997. }
  998. override func leftRotateAfter(indexpaths: Set<IndexPath>) {
  999. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMPDFViewRotatePage"), object: self.thumbnailView.document)
  1000. self.km_becomeFirstResponder()
  1001. }
  1002. override func rightRotateAfter(indexpaths: Set<IndexPath>) {
  1003. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMPDFViewRotatePage"), object: self.thumbnailView.document)
  1004. self.km_becomeFirstResponder()
  1005. }
  1006. override func replaceAfter(of targetIndexs: IndexSet, with pages: [CPDFPage], at index: Int) {
  1007. var indexpaths = Set<IndexPath>()
  1008. var insertIndex = index
  1009. for _ in pages {
  1010. indexpaths.insert(IndexPath(item: insertIndex, section: 0))
  1011. insertIndex += 1
  1012. }
  1013. self.thumbnailView.selectionIndexPaths = indexpaths
  1014. self.dealPdfDocumentDidEditCallback(type: .replace)
  1015. }
  1016. override func insertBlankPageAfter(size: NSSize, at index: Int) {
  1017. self.selectPages(indexs: IndexSet(integer: index))
  1018. self.dealPdfDocumentDidEditCallback(type: .insert)
  1019. }
  1020. func listViewCurrentPageUpdateForDrag(indexs: IndexSet, toIndex: Int) {
  1021. if (indexs.isEmpty) {
  1022. return
  1023. }
  1024. // listView 当前页面 被拖拽
  1025. if (indexs.contains(self._listViewCurrentIndex)) {
  1026. // let idx = indexs.firstIndex(of: self._listViewCurrentIndex)
  1027. var idx: Int = 0
  1028. for index in indexs {
  1029. if (index == self._listViewCurrentIndex) {
  1030. break
  1031. }
  1032. idx += 1
  1033. }
  1034. // 插入位置偏移量
  1035. var toIndexOffset: Int = 0
  1036. // 从后面往前删除
  1037. for index in indexs.reversed() {
  1038. let newPage = (self.listView?.document.page(at: UInt(index)))?.copy() as? CPDFPage
  1039. if (newPage == nil) {
  1040. continue
  1041. }
  1042. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  1043. toIndexOffset += 1
  1044. }
  1045. }
  1046. if (indexs.last! < toIndex) { // 往后拖拽
  1047. toIndexOffset -= 1
  1048. }
  1049. let insertIndex = max(0, toIndex-toIndexOffset)
  1050. self._listViewCurrentIndex = insertIndex+idx
  1051. } else {
  1052. var forwardCnt = 0
  1053. var nextCnt = 0
  1054. for index in indexs {
  1055. if (index > self._listViewCurrentIndex) {
  1056. nextCnt += 1
  1057. } else {
  1058. forwardCnt += 1
  1059. }
  1060. }
  1061. if (self._listViewCurrentIndex > toIndex) { // 插入到目标前面, 前面不管,只管后面的格式
  1062. self._listViewCurrentIndex += nextCnt
  1063. } else if (self._listViewCurrentIndex < toIndex) { // 插入到目标后面, 后面不管,只管前面的格式
  1064. self._listViewCurrentIndex = max(0, self._listViewCurrentIndex - forwardCnt)
  1065. } else { // 插入到目标位置 [跟插入到目标后面一样]
  1066. self._listViewCurrentIndex = max(0, self._listViewCurrentIndex - forwardCnt)
  1067. }
  1068. }
  1069. }
  1070. }
  1071. // MARK: - Analytics (埋点)
  1072. extension KMPDFEditViewController {
  1073. func trackEvent(type: KMPageEditType) -> Void {
  1074. if (type == .insert) {
  1075. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Insert", parameters: [
  1076. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1077. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1078. } else if (type == .extract) {
  1079. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Extract", parameters: [
  1080. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1081. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1082. } else if (type == .leftRotate || type == .rightRotate) {
  1083. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Rotate", parameters: [
  1084. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1085. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1086. } else if (type == .replace) {
  1087. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Replace", parameters: [
  1088. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1089. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1090. } else if (type == .split) {
  1091. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Split", parameters: [
  1092. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1093. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1094. } else if (type == .reverse) {
  1095. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Reverse", parameters: [
  1096. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1097. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1098. } else if (type == .delete) {
  1099. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Delete", parameters: [
  1100. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1101. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1102. }
  1103. }
  1104. func trackEvent_copy() -> Void {
  1105. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Copy", parameters: [
  1106. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1107. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1108. }
  1109. }