KMPDFEditViewController.swift 51 KB

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