KMPDFEditViewController.swift 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  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 = KMConvertPDFManagerOC.supportFileType() as? [String] {
  102. allowedFileTypes = KMTools.pdfExtensions + _types
  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(message: NSLocalizedString("Unable to delete all pages", comment: ""), from: self.thumbnailView, with: .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(message: NSLocalizedString("Unable to delete all pages", comment: ""), from: self.thumbnailView, with: .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: NSWindow.currentWindow()) { 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. self.km_endSheet()
  432. if let _urlString = filepaths.first?.deletingLastPathComponent {
  433. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: _urlString)])
  434. }
  435. }
  436. }
  437. }
  438. }
  439. // MARK: Undo / Redo
  440. @objc private func reversePages(indexs: IndexSet) {
  441. KMPageEditTools.reverse((self.listView?.document)!, indexs
  442. ) { result, error in
  443. if (result) {
  444. self.refreshUI(indexpaths: self.indexsToIndexpaths(indexs: indexs), keepSelected: true)
  445. self.kmUndoManager?.registerUndo(withTarget: self, selector: #selector(self.reversePages), object: indexs)
  446. }
  447. }
  448. }
  449. @objc private func dragPages(_ indexs: IndexSet, _ toIndex: Int, dp: NSCollectionView.DropOperation, reversed: Bool = false) {
  450. if (indexs.count <= 0) {
  451. return
  452. }
  453. self.listViewCurrentPageUpdateForDrag(indexs: indexs, toIndex: toIndex)
  454. // 插入位置偏移量
  455. var toIndexOffset: Int = 0
  456. // 需要移动的页面index数组
  457. var newPages: [CPDFPage] = []
  458. var currentPage: CPDFPage?
  459. var originalIndex = self.listViewCurrentIndex
  460. // 从后面往前删除
  461. for index in indexs.reversed() {
  462. let newPage = (self.listView?.document.page(at: UInt(index)))?.copy() as? CPDFPage
  463. if (newPage == nil) {
  464. continue
  465. }
  466. newPages.insert(newPage!, at: 0)
  467. self.listView?.document.removePage(at: UInt(index))
  468. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  469. toIndexOffset += 1
  470. }
  471. if (currentPage == nil) && (originalIndex == index) {
  472. currentPage = newPage
  473. }
  474. }
  475. if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
  476. toIndexOffset -= 1
  477. }
  478. let insertIndex = max(0, toIndex-toIndexOffset)
  479. var selectIndexs: IndexSet = []
  480. for (index, page) in newPages.enumerated() {
  481. self.listView?.document.insertPageObject(page, at: UInt(insertIndex+index))
  482. selectIndexs.insert(insertIndex+index)
  483. if (currentPage?.pageIndex() == page.pageIndex()) {
  484. // self._listViewCurrentIndex = insertIndex+index
  485. }
  486. }
  487. // 新增 undo
  488. self.kmUndoManager?.registerUndo(withTarget: self) { target in
  489. target.clearSelectPages()
  490. target.dragPages_reversed(indexs, toIndex, newPages, dp: dp)
  491. }
  492. // 刷新UI
  493. self.refreshUI()
  494. if (reversed == false) {
  495. self.selectPages(indexs: selectIndexs)
  496. }
  497. }
  498. @objc private func dragPages_reversed(_ indexs: IndexSet, _ toIndex: Int, _ pages: [CPDFPage], dp: NSCollectionView.DropOperation) {
  499. if (indexs.count <= 0) {
  500. return
  501. }
  502. // 插入位置偏移量
  503. var toIndexOffset: Int = 0
  504. for index in indexs {
  505. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  506. toIndexOffset += 1
  507. }
  508. }
  509. if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
  510. toIndexOffset -= 1
  511. }
  512. let insertIndex = max(0, toIndex-toIndexOffset)
  513. // 需要移动的页面index数组
  514. var datas: [Int] = []
  515. for index in insertIndex ..< (insertIndex + indexs.count) {
  516. datas.append(index)
  517. }
  518. // 从后面开始删除
  519. for index in datas.reversed() {
  520. self.listView?.document.removePage(at: UInt(index))
  521. }
  522. // 再插入到对应的位置
  523. for (index,value) in indexs.enumerated() {
  524. var page: CPDFPage?
  525. if (index < pages.count) {
  526. page = pages[index]
  527. }
  528. if (page != nil) {
  529. self.listView?.document.insertPageObject(page!, at: UInt(value))
  530. }
  531. }
  532. // 新增 undo
  533. self.kmUndoManager?.registerUndo(withTarget: self) { target in
  534. target.dragPages(indexs, toIndex, dp: dp, reversed: true)
  535. }
  536. // 刷新UI
  537. self.refreshUI()
  538. }
  539. // MARK: topBar 事件
  540. @objc func zoomOutButtonAction(sender: NSButton?) {
  541. if (self.itemSize.width > self.defaultItemSize.width) {
  542. return
  543. }
  544. if let _document = self.thumbnailView.document {
  545. for i in 0 ..< _document.pageCount {
  546. let page = _document.page(at: i)
  547. page?.pageEditImage = nil
  548. }
  549. }
  550. if (self.itemSize.width < self.defaultItemSize.width) {
  551. self.itemSize = self.defaultItemSize
  552. } else if (self.itemSize.width == self.defaultItemSize.width) {
  553. self.itemSize = NSSize(width: self.defaultItemSize.width*1.5, height: self.defaultItemSize.height*1.5)
  554. }
  555. self.toolBar.zoomInButton?.isEnabled = true
  556. if (self.itemSize.width > self.defaultItemSize.width) {
  557. sender?.isEnabled = false
  558. }
  559. self.pageEditThumbnailView.zoomOut()
  560. }
  561. @objc func zoomInButtonAction(sender: NSButton?) {
  562. if (self.itemSize.width < self.defaultItemSize.width) {
  563. return
  564. }
  565. if let _document = self.thumbnailView.document {
  566. for i in 0 ..< _document.pageCount {
  567. let page = _document.page(at: i)
  568. page?.pageEditImage = nil
  569. }
  570. }
  571. if (self.itemSize.width > self.defaultItemSize.width) {
  572. self.itemSize = self.defaultItemSize
  573. } else if (self.itemSize.width == self.defaultItemSize.width) {
  574. self.itemSize = NSSize(width: self.defaultItemSize.width*0.5, height: self.defaultItemSize.height*0.5)
  575. }
  576. self.toolBar.zoomOutButton?.isEnabled = true
  577. if (self.itemSize.width < self.defaultItemSize.width) {
  578. sender?.isEnabled = false
  579. }
  580. self.pageEditThumbnailView.zoomIn()
  581. }
  582. // MARK: menu 菜单事件
  583. @objc func item_insertCustomPage(sender: NSMenuItem?) {
  584. Task { @MainActor in
  585. let windowController = KMPageEditInsertCustomPageWindowController()
  586. if (self.thumbnailView.selectionIndexPaths.count > 0) {
  587. let page = self.getSelectedPage()
  588. let width = page.bounds.size.width * 210 / 595
  589. let height = page.bounds.size.height * 297 / 842
  590. windowController.selectedPageSize = NSSize(width: width, height: height)
  591. // windowController.selectedPageSize = self.getSelectedPage().bounds.size
  592. }
  593. self.km_beginSheet(windowC: windowController)
  594. windowController.itemClick = { [weak self] index in
  595. if (index == 1) { /// 取消
  596. self?.km_endSheet()
  597. return
  598. }
  599. /// 插入
  600. guard let windowC = self?.kmCurrentWindowC as? KMPageEditInsertCustomPageWindowController else {
  601. self?.km_endSheet()
  602. return
  603. }
  604. guard let _insertIndex = self?.getInsertIndex() else {
  605. self?.km_endSheet()
  606. return
  607. }
  608. /// 样式
  609. // let type = windowC.typeIndex
  610. // mm 单位的大小
  611. let pageSize = windowC.pageSize
  612. let direction = windowC.direction
  613. var _pageSize = KMPageEditTools.sizeUnitToBoundSize(unit: .mm, pageSize: pageSize)
  614. if (direction == 0) { // 纵向
  615. if (_pageSize.width > _pageSize.height) { // 需要交换
  616. let tmp = _pageSize.width
  617. _pageSize.width = _pageSize.height
  618. _pageSize.height = tmp
  619. } else {
  620. // no things.
  621. }
  622. } else { // 横向
  623. if (_pageSize.width > _pageSize.height) {
  624. // no things.
  625. } else { // 需要交换
  626. let tmp = _pageSize.width
  627. _pageSize.width = _pageSize.height
  628. _pageSize.height = tmp
  629. }
  630. }
  631. /// 插入位置
  632. // if (type == 1) { /// 空白页
  633. let document = CPDFDocument()
  634. document?.insertPage(_pageSize, at: 0)
  635. if let page: CPDFPage = (document?.page(at: 0)) {
  636. self?.insertPages(pages: [page], at: IndexSet(integer: _insertIndex+1))
  637. }
  638. // } else {
  639. // let document = CPDFDocument()
  640. // var imageName = "plaid"
  641. // if (type == 2) {
  642. // imageName = "horizontal_line"
  643. // } else if (type == 3) {
  644. // imageName = "five_line_score"
  645. // }
  646. // let imagePath = Bundle.main.pathForImageResource(imageName)
  647. // document?.insertPage(pageSize, withImage: imagePath, at: 0)
  648. // let page: CPDFPage = (document?.page(at: 0))!
  649. // if (direction == 0) { /// 纵向
  650. // page.rotation = 90
  651. // }
  652. //
  653. // self?.insertPagesForDescSort(pages: [page], indexs: IndexSet(integer: _insertIndex+1))
  654. // }
  655. self?.km_endSheet()
  656. }
  657. }
  658. }
  659. // MARK: toolBar 菜单事件
  660. @objc func reverseMenuAction(sender: AnyObject?) {
  661. let selectedIndexs = self.thumbnailView.selectionIndexPaths
  662. if (selectedIndexs.count < 2 ) {
  663. let alertView = CustomAlertView(message: NSLocalizedString("Please select at least two pages for editing first", comment: ""), from: self.thumbnailView, with: .blue)
  664. alertView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  665. alertView?.layer?.cornerRadius = 4
  666. return
  667. }
  668. var indexs: IndexSet = []
  669. for indexpath in selectedIndexs {
  670. indexs.insert(indexpath.item)
  671. }
  672. self.reversePages(indexs: indexs)
  673. self.dealPdfDocumentDidEditCallback(type: .reverse)
  674. }
  675. override func addMenuItem(menu: NSMenu, item: KMPDFThumbViewMenu.Item) -> NSMenuItem? {
  676. var item_: NSMenuItem?
  677. if (item.sel == KMPDFThumbViewMenu.insertSelector) {
  678. if (self.thumbnailView.selectionIndexPaths.count == 1) {
  679. item_ = menu.addItem(withTitle: NSLocalizedString("Insert", comment: ""), action: nil, target: self)
  680. let subMenu = NSMenu()
  681. subMenu.addItem(withTitle: NSLocalizedString("Insert a Blank Page", comment: ""), action: #selector(insertPageItemAction), target: self, tag:0)
  682. subMenu.addItem(withTitle: NSLocalizedString("Insert Custom Page", comment: ""), action: #selector(insertPageItemAction), target: self, tag:1)
  683. subMenu.addItem(withTitle: NSLocalizedString("Insert File", comment: ""), action: #selector(insertPageItemAction), target: self, tag:2)
  684. item_?.submenu = subMenu
  685. }
  686. } else if (item.sel == KMPDFThumbViewMenu.splitSelector) {
  687. if (self.thumbnailView.selectionIndexPaths.count > 1) {
  688. item_ = menu.addItem(withTitle: NSLocalizedString("Split", comment: ""), action: KMPDFThumbViewMenu.splitSelector, target: self)
  689. }
  690. } else if (item.sel == KMPDFThumbViewMenu.reverseSelector) {
  691. if (self.thumbnailView.selectionIndexPaths.count > 1) {
  692. item_ = menu.addItem(withTitle: NSLocalizedString("Reverse", comment: ""), action: KMPDFThumbViewMenu.reverseSelector, target: self)
  693. }
  694. } else {
  695. return super.addMenuItem(menu: menu, item: item)
  696. }
  697. return item_
  698. }
  699. }
  700. extension KMPDFEditViewController {
  701. //MARK: menu Action
  702. @objc func insertPageItemAction(menu:NSMenuItem) {
  703. if (menu.tag == 0) {
  704. self.insertBlankPageAction()
  705. } else if (menu.tag == 1) {
  706. self.item_insertCustomPage(sender: nil)
  707. } else if (menu.tag == 2) {
  708. self.insertFileAction()
  709. }
  710. }
  711. @objc func sharePageItemAction(menu:NSMenuItem) {
  712. let item = menu.parent!
  713. let index = (item.representedObject as! IndexSet).first ?? -1
  714. if Int(index) >= 0 {
  715. let doucument = self.pdfDocument!
  716. let page = doucument.page(at: UInt(index))
  717. let filename : String = doucument.documentURL.lastPathComponent
  718. let folderPath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(filename))!
  719. try? FileManager.default.removeItem(atPath: folderPath)
  720. let pdfdocument = CPDFDocument()
  721. let ret = pdfdocument!.importPages((item.representedObject as! IndexSet), from: self.thumbnailView.document, at: 0)
  722. let url = URL(fileURLWithPath: folderPath)
  723. if ret {
  724. let success = pdfdocument!.write(to:url)
  725. if success {
  726. let workspace = NSWorkspace.shared
  727. workspace.activateFileViewerSelecting([url])
  728. }
  729. }
  730. let represent : NSSharingService = menu.representedObject as! NSSharingService
  731. represent.perform(withItems: [url])
  732. }
  733. }
  734. @objc func showPageSizeItemAction(menu: NSMenuItem) {
  735. self.thumbnailView.isShowPageSize = !self.thumbnailView.isShowPageSize
  736. self.refreshUIForKeepSelecteds()
  737. }
  738. @objc func printItemAction(menu:NSMenuItem) {
  739. var datas: [Int] = []
  740. for indexpath in self.thumbnailView.selectionIndexPaths {
  741. datas.append(indexpath.item)
  742. }
  743. guard let callback = self.itemClick else {
  744. return
  745. }
  746. callback(2, datas.sorted())
  747. }
  748. }
  749. extension KMPDFEditViewController {
  750. override func menuItemAction_print(_ sender: Any?) {
  751. self.printItemAction(menu: sender as! NSMenuItem)
  752. }
  753. override func menuItemAction_showPageSize(_ sender: Any?) {
  754. self.showPageSizeItemAction(menu: sender as! NSMenuItem)
  755. }
  756. }
  757. // MARK: - KMSelectPopButtonDelegate
  758. extension KMPDFEditViewController {
  759. func km_comboBoxSelectionDidChange(_ obj: KMDesignSelect) {
  760. self.pageIsUpdate = false
  761. let index: Int = obj.indexOfSelectedItem
  762. var indexpaths: Set<IndexPath> = []
  763. var type: KMPageRange?
  764. if (index <= 0) { /// 全部页面
  765. type = .all
  766. } else if (index == 1) { /// 奇数页
  767. type = .odd
  768. } else if (index == 2) { /// 偶数页
  769. type = .even
  770. } else if (index == 3) { /// 横向页
  771. type = .horizontal
  772. } else if (index == 4) { /// 纵向页
  773. type = .vertical
  774. } else { /// 自定义
  775. type = .custom
  776. }
  777. for i in 0 ..< (self.pdfDocument?.pageCount)! {
  778. if (type == .all) {
  779. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  780. } else if (type == .odd) {
  781. if (i % 2 == 1) {
  782. continue
  783. }
  784. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  785. } else if (type == .even) {
  786. if (i % 2 == 0) {
  787. continue
  788. }
  789. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  790. } else if (type == .horizontal) {
  791. let page = self.pdfDocument?.page(at: i)
  792. guard let isVertical = page?.isVertical(), !isVertical else {
  793. continue
  794. }
  795. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  796. } else if (type == .vertical) {
  797. let page = self.pdfDocument?.page(at: i)
  798. guard let isHorizontal = page?.isHorizontal(), !isHorizontal else {
  799. continue
  800. }
  801. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  802. }
  803. }
  804. obj.editable = type == .custom
  805. if (type == .custom) {
  806. self.clearSelectPages()
  807. DispatchQueue.main.async {
  808. self.toolBar.pageRangeView?.stringValue = ""
  809. self.view.window?.makeFirstResponder(self.toolBar.pageRangeView?.textField)
  810. }
  811. } else {
  812. self.pageEditThumbnailView.selectPages(at: indexpaths)
  813. }
  814. }
  815. func km_controlTextDidEndEditing(_ obj: KMDesignSelect) {
  816. self.view.window?.makeFirstResponder(self)
  817. for index in 0 ..< obj.numberOfItems {
  818. if (obj.items[index] == obj.stringValue) {
  819. return
  820. }
  821. }
  822. let pages = KMPageRangeTools.findSelectPage(pageRangeString: self.toolBar.pageRangeView!.stringValue, pageCount: Int((self.listView?.document.pageCount)!))
  823. if (pages.isEmpty) {
  824. let alert = NSAlert()
  825. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  826. alert.runModal()
  827. self.toolBar.setPageRangeString("")
  828. DispatchQueue.main.async {
  829. self.view.window?.makeFirstResponder(self.toolBar.pageRangeView?.textField)
  830. }
  831. return
  832. }
  833. var indexpaths: Set<IndexPath> = []
  834. for page in pages {
  835. if (page >= 1) {
  836. indexpaths.insert(IndexPath(item: page-1, section: 0))
  837. }
  838. }
  839. self.pageIsUpdate = false
  840. self.pageEditThumbnailView.selectPages(at: indexpaths)
  841. }
  842. }
  843. // MARK: -
  844. // MARK: KMThumbnailViewDelegate
  845. extension KMPDFEditViewController: KMThumbnailViewDelegate {
  846. func thumbnailView(thumbanView: KMThumbnailView, shouldAcceptDrop draggingInfo: NSDraggingInfo, indexPath: IndexPath, dropOperation: NSCollectionView.DropOperation) -> Bool {
  847. return true
  848. }
  849. func thumbnailView(thumbanView: KMThumbnailView, didDragAddFiles files: [URL], indexpath: IndexPath) {
  850. self.km_add_file_multi(fileUrls: files) { index, params in
  851. if (self.fetchProgressBlockParamsIsPasswordFile(params: params)) { // 加密文档进度回调
  852. return
  853. }
  854. let _fileUrl = self.fetchProgressBlockParamsForFileUrl(params: params)
  855. if let exn = _fileUrl?.pathExtension, KMTools.isPDFType(exn) {
  856. if (_fileUrl!.path.isPDFValid() == false) {
  857. let alert = NSAlert()
  858. alert.alertStyle = .critical
  859. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  860. alert.runModal()
  861. }
  862. }
  863. } completionBlock: { [unowned self] documents in
  864. var insertIndex: Int = indexpath.item
  865. var pages: Array<CPDFPage> = []
  866. var indexs = IndexSet()
  867. for document in documents {
  868. for i in 0 ..< document.pageCount {
  869. let page = document.page(at: i)
  870. pages.append(page!)
  871. indexs.insert(insertIndex)
  872. insertIndex += 1
  873. }
  874. }
  875. self.insertPages(pages: pages, at: indexs)
  876. }
  877. }
  878. func thumbnailView(thumbanView: KMThumbnailView, didDrag dragedIndexPaths: [IndexPath], indexpath: IndexPath, dragInfo: [KMThumbnailViewDragInfoKey.RawValue : Any]) {
  879. let toIndex = max(0, indexpath.item)
  880. var indexs = IndexSet()
  881. for indexpath in dragedIndexPaths {
  882. indexs.insert(indexpath.item)
  883. }
  884. var dp = NSCollectionView.DropOperation.on
  885. if let _dp = dragInfo[KMThumbnailViewDragInfoKey.dropOperation.rawValue] as? NSCollectionView.DropOperation {
  886. dp = _dp
  887. }
  888. self.dragPages(indexs, toIndex, dp: dp)
  889. if (dragedIndexPaths.count > 0) {
  890. self.dealPdfDocumentDidEditCallback()
  891. }
  892. }
  893. func thumbnailView(thumbanView: KMThumbnailView, shouldPasteboardWriterForItemAt indexPath: IndexPath) -> Bool {
  894. if (!self.canPayFunction) {
  895. return false
  896. }
  897. return true
  898. }
  899. func thumbnailView(thumbanView: KMThumbnailView, insetForSectionAt section: Int) -> NSEdgeInsets {
  900. return NSEdgeInsets(top: 16, left: 16, bottom: 0, right: 32)
  901. }
  902. func thumbnailView(thumbanView: KMThumbnailView, sizeForItemAt indexpath: IndexPath) -> NSSize {
  903. self.thumbnailView.thumbnailSzie = CGSize(width: 120, height: 155)
  904. if (!self.thumbnailView.isShowPageSize) {
  905. return NSMakeSize(self.itemSize.width, self.itemSize.height+26)
  906. }
  907. return self.itemSize
  908. }
  909. func thumbnailView(thumbanView: KMThumbnailView, numberOfItemsInSection section: Int) -> Int {
  910. if let count = self.pdfDocument?.pageCount {
  911. return Int(count)
  912. }
  913. return 0
  914. }
  915. func thumbnailView(thumbanView: KMThumbnailView, itemForRepresentedObjectAt indexpath: IndexPath) -> NSCollectionViewItem {
  916. let cellView: KMPageEditThumbnailItem = thumbanView.collectionView.makeItem(withIdentifier: KMPageEditThumbnailItem.km_identifier, for: indexpath) as! KMPageEditThumbnailItem
  917. cellView.isShowPageSize = self.thumbnailView.isShowPageSize
  918. cellView.setPage(page: (self.pdfDocument?.page(at: UInt(indexpath.item)))!)
  919. cellView.doubleClickAction = { [unowned self] _ in
  920. guard let callback = self.itemClick else {
  921. return
  922. }
  923. callback(1, indexpath.item)
  924. }
  925. cellView.mouseDownAction = { [unowned self] _ in
  926. let selectionIndexPaths = self.thumbnailView.selectionIndexPaths
  927. if (selectionIndexPaths.count == 1 && selectionIndexPaths.first?.item == indexpath.item) {
  928. return
  929. }
  930. self.selectPages(indexs: IndexSet.init(integer: indexpath.item))
  931. }
  932. cellView.rightMouseDownAction = { [unowned self] _ in
  933. self.selectPages(indexs: IndexSet.init(integer: indexpath.item))
  934. }
  935. return cellView
  936. }
  937. }
  938. // MARK: - 系统菜单栏
  939. extension KMPDFEditViewController {
  940. override func undo(_ sender: Any?) {
  941. super.undo(sender)
  942. self.km_becomeFirstResponder()
  943. }
  944. override func redo(_ sender: Any?) {
  945. super.redo(sender)
  946. self.km_becomeFirstResponder()
  947. }
  948. }
  949. // MARK: - KMExtensions
  950. extension KMPDFEditViewController {
  951. override func deleteAfter(indexpaths: Set<IndexPath>) {
  952. self.clearSelectPages()
  953. self.km_becomeFirstResponder()
  954. }
  955. override func copyAfter(indexpaths: Set<IndexPath>) {
  956. self.km_becomeFirstResponder()
  957. }
  958. override func pasteAfter(at index: Int) {
  959. self.km_becomeFirstResponder()
  960. }
  961. override func cutAfter(indexpaths: Set<IndexPath>) {
  962. self.clearSelectPages()
  963. self.km_becomeFirstResponder()
  964. }
  965. override func leftRotateAfter(indexpaths: Set<IndexPath>) {
  966. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMPDFViewRotatePage"), object: self.thumbnailView.document)
  967. self.km_becomeFirstResponder()
  968. }
  969. override func rightRotateAfter(indexpaths: Set<IndexPath>) {
  970. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMPDFViewRotatePage"), object: self.thumbnailView.document)
  971. self.km_becomeFirstResponder()
  972. }
  973. override func replaceAfter(of targetIndexs: IndexSet, with pages: [CPDFPage], at index: Int) {
  974. var indexpaths = Set<IndexPath>()
  975. var insertIndex = index
  976. for _ in pages {
  977. indexpaths.insert(IndexPath(item: insertIndex, section: 0))
  978. insertIndex += 1
  979. }
  980. self.thumbnailView.selectionIndexPaths = indexpaths
  981. self.dealPdfDocumentDidEditCallback(type: .replace)
  982. }
  983. override func insertBlankPageAfter(size: NSSize, at index: Int) {
  984. self.selectPages(indexs: IndexSet(integer: index))
  985. self.dealPdfDocumentDidEditCallback(type: .insert)
  986. }
  987. func listViewCurrentPageUpdateForDrag(indexs: IndexSet, toIndex: Int) {
  988. if (indexs.isEmpty) {
  989. return
  990. }
  991. // listView 当前页面 被拖拽
  992. if (indexs.contains(self._listViewCurrentIndex)) {
  993. // let idx = indexs.firstIndex(of: self._listViewCurrentIndex)
  994. var idx: Int = 0
  995. for index in indexs {
  996. if (index == self._listViewCurrentIndex) {
  997. break
  998. }
  999. idx += 1
  1000. }
  1001. // 插入位置偏移量
  1002. var toIndexOffset: Int = 0
  1003. // 从后面往前删除
  1004. for index in indexs.reversed() {
  1005. let newPage = (self.listView?.document.page(at: UInt(index)))?.copy() as? CPDFPage
  1006. if (newPage == nil) {
  1007. continue
  1008. }
  1009. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  1010. toIndexOffset += 1
  1011. }
  1012. }
  1013. if (indexs.last! < toIndex) { // 往后拖拽
  1014. toIndexOffset -= 1
  1015. }
  1016. let insertIndex = max(0, toIndex-toIndexOffset)
  1017. self._listViewCurrentIndex = insertIndex+idx
  1018. } else {
  1019. var forwardCnt = 0
  1020. var nextCnt = 0
  1021. for index in indexs {
  1022. if (index > self._listViewCurrentIndex) {
  1023. nextCnt += 1
  1024. } else {
  1025. forwardCnt += 1
  1026. }
  1027. }
  1028. if (self._listViewCurrentIndex > toIndex) { // 插入到目标前面, 前面不管,只管后面的格式
  1029. self._listViewCurrentIndex += nextCnt
  1030. } else if (self._listViewCurrentIndex < toIndex) { // 插入到目标后面, 后面不管,只管前面的格式
  1031. self._listViewCurrentIndex = max(0, self._listViewCurrentIndex - forwardCnt)
  1032. } else { // 插入到目标位置 [跟插入到目标后面一样]
  1033. self._listViewCurrentIndex = max(0, self._listViewCurrentIndex - forwardCnt)
  1034. }
  1035. }
  1036. }
  1037. }
  1038. // MARK: - Analytics (埋点)
  1039. extension KMPDFEditViewController {
  1040. func trackEvent(type: KMPageEditType) -> Void {
  1041. if (type == .insert) {
  1042. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Insert", parameters: [
  1043. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1044. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1045. } else if (type == .extract) {
  1046. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Extract", parameters: [
  1047. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1048. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1049. } else if (type == .leftRotate || type == .rightRotate) {
  1050. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Rotate", parameters: [
  1051. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1052. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1053. } else if (type == .replace) {
  1054. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Replace", parameters: [
  1055. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1056. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1057. } else if (type == .split) {
  1058. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Split", parameters: [
  1059. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1060. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1061. } else if (type == .reverse) {
  1062. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Reverse", parameters: [
  1063. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1064. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1065. } else if (type == .delete) {
  1066. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Delete", parameters: [
  1067. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1068. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1069. }
  1070. }
  1071. func trackEvent_copy() -> Void {
  1072. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Copy", parameters: [
  1073. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1074. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1075. }
  1076. }