KMPDFEditViewController.swift 49 KB

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