12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132 |
- //
- // KMPDFEditViewController.swift
- // PDF Reader Pro
- //
- // Created by tangchao on 2023/1/6.
- //
- typealias KMPDFEditViewControllerSelectionDidChange = (_ selectedIndexs: Set<IndexPath>) -> ()
- typealias KMIndexChooseBlock = (_ index: Int) -> Void
- class KMPDFEditViewController: KMPDFThumbViewBaseController {
-
- static let kNoPagesSelectedTipMessage = "No pages selected. Please select one or more pages first to organize."
-
- @IBOutlet weak var topBarBox: NSBox!
- @IBOutlet weak var contentBox: NSBox!
-
- @IBOutlet weak var thumbnailSizeView: NSView!
- @IBOutlet weak var zoomInButton: NSButton!
- @IBOutlet weak var zoomOutButton: NSButton!
- @IBOutlet weak var lineBoxView: NSView!
-
-
- var toolBar = KMPDFEditToolbar(frame: NSZeroRect)
- override var thumbnailView: KMPDFThumbnailView {
- get {
- if (super.thumbnailView is KMPageEditThumbnailView) {
- return super.thumbnailView
- }
-
- super.thumbnailView = KMPageEditThumbnailView()
- return super.thumbnailView
- }
- set {
- super.thumbnailView = newValue
- }
- }
-
- var pageEditThumbnailView: KMPageEditThumbnailView {
- get {
- return self.thumbnailView as! KMPageEditThumbnailView
- }
- }
-
- override var menuItems: [[KMPDFThumbViewMenu.Item]] {
- get {
- return [[.insert ,.extract], [.leftRotate, .rightRotate, .copy, .paste, .reverse],
- [.delete], [.share]]
- }
- }
-
- private var pdfDocument: CPDFDocument?
- var listView: CPDFView?
-
- var pageIsUpdate: Bool = true
- var selectedPages: [Int] = []
-
- private let defaultItemSize = NSMakeSize(215, 250)
- var itemSize: NSSize = NSMakeSize(215, 250)
-
- // index=1 双击退出;index=2 打印
- var itemClick: KMCommonClickBlock?
- private var _isEdited = false
- var isEdited: Bool {
- return self._isEdited
- }
- var documentEditedCallback: KMCommonBlock?
- var selectionDidChange: KMPDFEditViewControllerSelectionDidChange?
-
- internal var viewFirstAppear = true
- private var _listViewCurrentIndex: Int = 0
- var listViewCurrentIndex: Int {
- get {
- return self._listViewCurrentIndex
- }
- }
-
- private var fileAttri_: KMFileAttribute?
- private var popOver_: NSPopover?
-
- deinit {
-
- }
-
- required init?(coder: NSCoder) {
- super.init(coder: coder)
- }
-
- init(_ document: CPDFDocument) {
- super.init(nibName: "KMPDFEditViewController", bundle: nil)
-
- self.pdfDocument = document
- self.kmUndoManager = UndoManager()
- self.fileAttri_ = KMFileAttribute()
- self.fileAttri_?.password = document.password ?? ""
- self.fileAttri_?.filePath = document.documentURL.path
- }
-
- override func viewDidAppear() {
- super.viewDidAppear()
-
- let isLocked = self.pdfDocument?.isLocked ?? false
- let first = self.viewFirstAppear
- if (isLocked == false && self.viewFirstAppear) {
- self.viewFirstAppear = false
- if let doc = self.pdfDocument {
- self.thumbnailView.document = doc
- }
- self.thumbnailView.reloadData()
- }
-
- if let view = self.listView { // 存储阅读视图的当前页面索引
- self._listViewCurrentIndex = view.currentPageIndex
- }
- var item: Int = 0
- if (self.selectedPages.isEmpty) {
- let index = self.listView?.currentPageIndex ?? 0
- self.selectPages(indexs: IndexSet(integer: index))
- self.toolBar.setPageRangeString("\(index+1)")
- item = index
- } else {
- var indexs: IndexSet = []
- for pageIndex in self.selectedPages {
- let pageCnt = self.listView?.document?.pageCount ?? 0
- if (pageIndex < 0 || pageIndex >= pageCnt) {
- continue
- }
-
- indexs.insert(pageIndex)
- }
-
- self.selectPages(indexs: indexs)
- self.toolBar.setPageRangeString(KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs.sorted()))
- item = indexs.sorted().last ?? 0
- }
- if first {
- let cnt = self.thumbnailView.document?.pageCount ?? 0
- if cnt > 0 {
- var ips = Set<IndexPath>()
- ips.insert(IndexPath(item: item, section: 0))
- self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .bottom)
- }
- }
-
- self.view.window?.makeFirstResponder(self)
- self._showPDFEditDetails()
- }
-
- override func viewDidLoad() {
- super.viewDidLoad()
-
- self._isEdited = false
- // 显示拖放移动动效
- // self.thumbnailView.dragMoveEffectAnimated = true
- // self.thumbnailView.collectionView.backgroundColor(NSColor.km_init(hex: "#CED0D4"))
- self.thumbnailView.collectionView.wantsLayer = true
- // self.thumbnailView.collectionView.layer?.backgroundColor = KMAppearance.PDFViewBackgroundColor().cgColor
- if KMAppearance.isDarkMode() {
- self.thumbnailView.collectionView.layer?.backgroundColor = NSColor.km_init(hex: "#5F5F60").cgColor
- } else {
- self.thumbnailView.collectionView.layer?.backgroundColor = NSColor.km_init(hex: "#DADBDE").cgColor
- }
-
- self.thumbnailSizeView.wantsLayer = true
- self.thumbnailSizeView.layer?.backgroundColor = KMAppearance.Layout.b80Color().cgColor
- self.lineBoxView.wantsLayer = true
- self.lineBoxView.layer?.backgroundColor = KMAppearance.Layout.h2Color().cgColor
-
-
- var allowedFileTypes: [String] = []
- // if let _types = KMConvertPDFManager.supportFileType() {
- allowedFileTypes = KMTools.pdfExtensions + KMConvertPDFManager.supportFileType()
- // } else {
- // allowedFileTypes = KMTools.pdfExtensions + KMTools.imageExtensions
- // }
- self.thumbnailView.kmAllowedFileTypes = allowedFileTypes
-
- let toolBar = self.toolBar
- self.topBarBox.contentView = toolBar
- self.topBarBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
- toolBar.itemClick = { [unowned self] item, index in
- guard let type = KMPageEditType(rawValue: index) else {
- if (index == KMPageEditType.insert_files) {
- self.insertFileAction()
- self.trackEvent(type: .insert, index: index)
- } else if (index == KMPageEditType.insert_blank_page) {
- self.insertBlankPageAction()
- self.trackEvent(type: .insert, index: index)
- } else if (index == KMPageEditType.insert_custom_page) {
- self.item_insertCustomPage(sender: nil)
- self.trackEvent(type: .insert, index: index)
- } else if (index == KMPageEditType.insert_fromImage) {
- self.item_insertFromImage(sender: nil)
- self.trackEvent(type: .insert, index: index)
- } else if (index == KMPageEditType.insert_fromClipboard) {
- self.item_insertFromClipboard(sender: nil)
- self.trackEvent(type: .insert, index: index)
- } else if (index == KMPageEditType.insert_fromScanner) {
- self.item_insertFromScanner(sender: nil)
- self.trackEvent(type: .insert, index: index)
- } else if (index == KMPageEditType.extract_selected_pages) {
- self.extractSelectPageItemAction()
- } else if (index == KMPageEditType.split_selected_pages) {
- self.splitMenuAction()
- }
- return
- }
-
- if (type == .leftRotate) {
- self.leftRotateAction()
- } else if (type == .rightRotate) {
- self.rightRotateAction()
- } else if (type == .zoomOut) {
- self.zoomOutButtonAction(sender: item?.zoomOutButton)
- } else if (type == .zoomIn) {
- self.zoomInButtonAction(sender: item?.zoomInButton)
- } else if (type == .extract) {
- self.extractAction()
- } else if (type == .replace) {
- self.replaceAction()
- } else if (type == .split) {
- self.splitAction()
- } else if (type == .reverse) {
- self.reverseAction()
- } else if (type == .delete) {
- self.deleteAction()
- } else if (type == .pageRange) {
- } else if (type == .insert) {
- self.trackEvent(type: .insert)
- } else if (type == .copy) {
- self.copyAction()
- } else if (type == .paste) {
- self.pasteAction()
- }
- }
- toolBar.pageRangeitemClick = { [weak self] type in
- self?.km_comboBoxSelectionDidChange(type)
- }
- toolBar.pageRangeValueDidChange = { [weak self] value, _ in
- if let data = self?.toolBar.pageRangeView {
- self?.km_controlTextDidEndEditing(data)
- }
- }
-
- let view = self.thumbnailView
- self.contentBox.contentView?.addSubview(view)
- view.frame = self.contentBox.contentView?.bounds ?? .zero
- view.autoresizingMask = [.width, .height]
- self.pageEditThumbnailView.delegate = self
- self.pageEditThumbnailView.selectionDidChange = { [weak self] selectedIndexs in
- guard let self = self else {
- return
- }
- self.selectionDidChange?(selectedIndexs)
- self.view.window?.makeFirstResponder(self)
-
- let enabled = (selectedIndexs.count > 0)
- for i in 0 ..< self.toolBar.toolBar.items.count {
- let item = self.toolBar.toolBar.items[i]
- if item.itemIdentifier == KMToolbarPageEditLeftRotateItemIdentifier
- || item.itemIdentifier == KMToolbarPageEditRightRotateItemIdentifier {
- item.unEnabled = !enabled
- }
- }
-
- if (self.pageIsUpdate == false) {
- self.pageIsUpdate = true
- return
- }
-
- var indexs: Array<Int> = []
- for indexPath in selectedIndexs {
- indexs.append(indexPath.item)
- }
- indexs.sort(){$0 < $1}
- self.toolBar.setPageRangeString(KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs))
-
- if self.listView != nil { // 存储阅读视图的当前页面索引
- if indexs.count != 0 {
- self._listViewCurrentIndex = indexs.last!
- }
- }
- }
- }
-
- override func interfaceThemeDidChanged(_ appearance: NSAppearance.Name) {
- super.interfaceThemeDidChanged(appearance)
-
- self.thumbnailView.collectionView.wantsLayer = true
- if KMAppearance.isDarkMode() {
- self.thumbnailView.collectionView.layer?.backgroundColor = NSColor.km_init(hex: "#5F5F60").cgColor
- } else {
- self.thumbnailView.collectionView.layer?.backgroundColor = NSColor.km_init(hex: "#DADBDE").cgColor
- }
- Task { @MainActor in
- let ips = self.thumbnailView.selectionIndexPaths
- self.thumbnailView.collectionView.reloadData()
- self.thumbnailView.selectionIndexPaths = ips
- }
- }
-
-
- override func keyDown(with event: NSEvent) {
- // super.keyDown(with: event)
- let cmd = event.modifierFlags.contains(.command)
- let shift = event.modifierFlags.contains(.shift)
-
- let code = event.keyCode
- let isLeft = code == 123
- let isUp = code == 126
- let isRight = code == 124
- let isDown = code == 125
- if cmd {
- if code == 0 { // cmd + a
- self.km_comboBoxSelectionDidChange(.all)
- return
- }
-
- // let ips = self.thumbnailView.selectionIndexPaths
- // let indexs = self.indexpathsToIndexs(indexpaths: ips)
- //// let idx = indexs.last ?? 0
- // var selectedIndexs = indexs
- // let numberItems = self.thumbnailView.collectionView.numberOfItems(inSection: 0)
- // let firstIdx = 0
- // let lastIdx = max(numberItems-1, 0)
- // if isLeft { // +
- // if self.isEmptySelection() {
- // selectedIndexs.insert(lastIdx)
- // } else {
- // if let idx = selectedIndexs.first, idx > 0 {
- // selectedIndexs.insert(idx-1)
- // }
- // }
- // } else if isRight { // -
- // if self.isEmptySelection() {
- // selectedIndexs.insert(firstIdx)
- // } else {
- // if let idx = selectedIndexs.last, idx < lastIdx {
- // selectedIndexs.insert(idx+1)
- // }
- // }
- // } else {
- // var numberPerLine = 0
- // let itemW = self.thumbnailView.itemSize.width
- // if itemW > 0 {
- // numberPerLine = Int(NSWidth(self.thumbnailView.collectionView.frame) / itemW)
- // }
- // if isUp {
- // if self.isEmptySelection() {
- // selectedIndexs.insert(lastIdx)
- // } else {
- // if let idx = selectedIndexs.first, idx > 0 {
- // selectedIndexs.insert(max(idx-numberPerLine, 0))
- // }
- // }
- // } else if isDown {
- // if self.isEmptySelection() {
- // selectedIndexs.insert(firstIdx)
- // } else {
- // if let idx = selectedIndexs.last, idx < lastIdx {
- // selectedIndexs.insert(min(idx+numberPerLine, lastIdx))
- // }
- // }
- // }
- // }
- //
- // if selectedIndexs.isEmpty == false {
- // let ips = self.indexsToIndexpaths(indexs: selectedIndexs)
- // self.thumbnailView.selectionIndexPaths = ips
- // self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
- // }
- } else if shift {
-
- } else {
- let ips = self.thumbnailView.selectionIndexPaths
- let indexs = self.indexpathsToIndexs(indexpaths: ips)
- let idx = indexs.last ?? 0
- var selectedIndexs = IndexSet()
- let numberItems = self.thumbnailView.collectionView.numberOfItems(inSection: 0)
- let firstIdx = 0
- let lastIdx = max(numberItems-1, 0)
- if isLeft {
- if self.isEmptySelection() {
- selectedIndexs.insert(lastIdx)
- } else {
- if idx > 0 {
- selectedIndexs.insert(idx-1)
- }
- }
- } else if isRight {
- if self.isEmptySelection() {
- selectedIndexs.insert(firstIdx)
- } else {
- if idx < lastIdx {
- selectedIndexs.insert(idx+1)
- }
- }
- } else {
- var numberPerLine = 0
- let itemW = self.thumbnailView.itemSize.width
- if itemW > 0 {
- numberPerLine = Int(NSWidth(self.thumbnailView.collectionView.frame) / itemW)
- }
- if isUp {
- if self.isEmptySelection() {
- selectedIndexs.insert(lastIdx)
- } else {
- selectedIndexs.insert(max(idx-numberPerLine, 0))
- }
- } else if isDown {
- if self.isEmptySelection() {
- selectedIndexs.insert(firstIdx)
- } else {
- selectedIndexs.insert(min(idx+numberPerLine, lastIdx))
- }
- }
- }
-
- if selectedIndexs.isEmpty == false {
- let ips = self.indexsToIndexpaths(indexs: selectedIndexs)
- self.thumbnailView.selectionIndexPaths = ips
- self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
- }
- }
- }
-
- // MARK: Private Methods
-
- private func getSelecteIndex() -> Int {
- let index = self.getPasteIndex()
- if (index != NSNotFound) {
- return index
- }
- return 0
- }
-
- private func getSelectedPage() -> CPDFPage? {
- return self.pdfDocument?.page(at: UInt(getSelecteIndex()))
- }
-
- private func selectPages(indexs: IndexSet) {
- var indexpaths: Set<IndexPath> = []
- for index in indexs {
- indexpaths.insert(IndexPath(item: index, section: 0))
- }
- self.selectPages(indexpaths: indexpaths)
- }
-
- private func km_becomeFirstResponder() {
- DispatchQueue.main.async {
- self.view.window?.makeFirstResponder(self)
- }
- }
-
- fileprivate func dealPdfDocumentDidEditCallback(type: KMPageEditType = .none) {
- self._isEdited = true
-
- // 提醒外面文档已编辑
- guard let callback = self.documentEditedCallback else {
- return
- }
- callback(type)
- }
-
- private func _progressHUD(message: String, style: KMCustomAlertStyle = .blue) {
- _ = CustomAlertView.alertView(message: message, fromView: self.thumbnailView, withStyle: style)
- }
-
- private func _showPDFEditDetails() {
- var insertItem: KMToolbarItemView?
- for item in self.toolBar.toolBar.items {
- if item.itemIdentifier == KMToolbarPageEditInsetItemIdentifier {
- insertItem = item
- break
- }
- }
- if insertItem?.window == nil {
- return
- }
- let showConvertDetails = KMPageEditPopViewController.showPageEditDetails()
- if (showConvertDetails) {
- let item = insertItem
- let popViewController = KMPageEditPopViewController()
- self.popOver_ = NSPopover()
- self.popOver_?.contentViewController = popViewController
- self.popOver_?.animates = false
- self.popOver_?.setBackgroundColor(KMAppearance.Interactive.a0Color())
- self.popOver_?.behavior = .transient
- // self.popOver.appearance = NSPopoverAppearanceMinimal;
- // self.popOver_?.appearance = .minimal
- self.popOver_?.contentSize = popViewController.view.frame.size
- self.popOver_?.show(relativeTo: item?.bounds ?? .zero, of: item!, preferredEdge: .maxY)
- }
- }
-
- // MARK: - 清空选择
-
- private func clearSelectPages() {
- self.selectPages(indexs: IndexSet())
- }
-
- override func refreshUI(indexpaths: Set<IndexPath> = [], keepSelected: Bool = false) {
- super.refreshUI(indexpaths: indexpaths, keepSelected: keepSelected)
-
- self.listView?.layoutDocumentView()
- }
-
- override func cutAction() {
- if KMMemberInfo.shared.isMemberAllFunction == false {
- KMMemberInfo.shared.advancedFunctionUsage()
- return
- }
- let pageCnt = self.pdfDocument?.pageCount ?? 0
- if (self.thumbnailView.selectionIndexPaths.count == pageCnt) {
- self._progressHUD(message: NSLocalizedString("Can not delete all pages.", comment: ""))
- return
- }
- super.cutAction()
- }
-
- override func copyAction() {
- self.trackEvent_copy()
-
- super.copyAction()
- }
-
- override func deleteAction() {
- if KMMemberInfo.shared.isMemberAllFunction == false {
- let winC = KMProductCompareWC.shared
- if self.kEventTag == 1 {
- winC.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC.kEventName = "Reading_Delete_BuyNow"
- }
- KMMemberInfo.shared.advancedFunctionUsage()
- return
- }
-
- if self.isEmptySelection() {
- self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
- return
- }
-
- let msg = String(format: NSLocalizedString("Are you sure to delete page %@ ?", comment: ""), KMTools.parseIndexSet(indexSet: self.indexpathsToIndexs(indexpaths: self.thumbnailView.selectionIndexPaths)))
- Task {
- let res = await KMAlertTool.runModel(message: msg, buttons: [NSLocalizedString("Delete", comment: ""), NSLocalizedString("Cancel", comment: "")])
- if res != .alertFirstButtonReturn {
- return
- }
- self.trackEvent(type: .delete)
-
- super.deleteAction()
-
- self.toolBar.unSelectItem(for: KMToolbarPageEditDeleteItemIdentifier)
- }
- }
-
- override func deleteIndexPaths(indexpaths: Set<IndexPath>) {
- guard let pageCount = self.thumbnailView.document?.pageCount else {
- KMPrint("pageCount invalid.")
- return
- }
- if (indexpaths.count == pageCount) {
- self._progressHUD(message: NSLocalizedString("Can not delete all pages.", comment: ""))
- return
- }
-
- self.dealPdfDocumentDidEditCallback(type: .delete)
-
- super.deleteIndexPaths(indexpaths: indexpaths)
- }
-
- override func leftRotateAction() {
- if KMMemberInfo.shared.isMemberAllFunction == false {
- KMMemberInfo.shared.advancedFunctionUsage()
- return
- }
-
- self.trackEvent(type: .leftRotate)
-
- super.leftRotateAction()
- }
-
- override func leftRotateIndexpaths(indexpaths: Set<IndexPath>) {
- if (!self.indexpathsIsValid(indexpaths: indexpaths) || !self.canRotate()) {
- return
- }
- super.leftRotateIndexpaths(indexpaths: indexpaths)
- self.dealPdfDocumentDidEditCallback(type: .leftRotate)
- }
-
- override func rightRotateAction() {
- if KMMemberInfo.shared.isMemberAllFunction == false {
- let winC = KMProductCompareWC.shared
- if self.kEventTag == 1 {
- winC.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC.kEventName = "Reading_Rotate_BuyNow"
- }
- KMMemberInfo.shared.advancedFunctionUsage()
- return
- }
-
- if self.isEmptySelection() {
- self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
- return
- }
-
- self.trackEvent(type: .rightRotate)
-
- super.rightRotateAction()
- }
-
- override func rightRotateIndexpaths(indexpaths: Set<IndexPath>) {
- if (!self.indexpathsIsValid(indexpaths: indexpaths) || !self.canRotate()) {
- return
- }
-
- super.rightRotateIndexpaths(indexpaths: indexpaths)
- self.dealPdfDocumentDidEditCallback(type: .rightRotate)
- }
-
- override func insertPages(pages: Array<CPDFPage>, at indexs: IndexSet) {
- super.insertPages(pages: pages, at: indexs)
-
- if (!indexs.isEmpty) {
- self.selectPages(indexs: indexs)
- self.dealPdfDocumentDidEditCallback(type: .insert)
- }
- }
-
- override func pasteAction() {
- if KMMemberInfo.shared.isMemberAllFunction == false {
- KMMemberInfo.shared.advancedFunctionUsage()
- return
- }
-
- if (self.canPaste()) {
- super.pasteAction()
-
- self.dealPdfDocumentDidEditCallback(type: .paste)
- } else {
- if KMThumbnailManager.manager.copyPages.count <= 0 {
- self._progressHUD(message: KMLocalizedString("No copied page selected. Please select and copy a page first."))
- }
- }
- }
-
- @objc func pasteActonForEmpty(_ sender: NSMenuItem) {
- guard let indexpaths = sender.representedObject as? IndexPath else {
- NSSound.beep()
- return
- }
- let idx = max(0, indexpaths.item-1)
- // self.pastePage(at: indexpaths.item)
- self.pastePage(at: idx)
-
- dealPdfDocumentDidEditCallback(type: .copy)
- }
-
- override func pastePage(at index: Int) {
- if KMMemberInfo.shared.isMemberAllFunction == false {
- KMMemberInfo.shared.advancedFunctionUsage()
- return
- }
-
- super.pastePage(at: index)
- }
-
- override func extractAction() {
- if KMMemberInfo.shared.isMemberAllFunction == false {
- let winC = KMProductCompareWC.shared
- if self.kEventTag == 1 {
- winC.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC.kEventName = "Reading_Extract_BuyNow"
- }
- KMMemberInfo.shared.advancedFunctionUsage()
- return
- }
-
- if self.isEmptySelection() {
- self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
- return
- }
-
- self.trackEvent(type: .extract)
-
- super.extractAction()
-
- DispatchQueue.main.async {
- self.toolBar.unSelectItem(for: KMToolbarPageEditExtractItemIdentifier)
- }
- }
-
- override func replaceAction() {
- if KMMemberInfo.shared.isMemberAllFunction == false {
- let winC = KMProductCompareWC.shared
- if self.kEventTag == 1 {
- winC.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC.kEventName = "Reading_Replace_BuyNow"
- }
- KMMemberInfo.shared.advancedFunctionUsage()
- return
- }
-
- if self.isEmptySelection() {
- self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
- return
- }
-
- self.trackEvent(type: .replace)
-
- super.replaceAction()
-
- DispatchQueue.main.async {
- self.toolBar.unSelectItem(for: KMToolbarPageEditReplaceItemIdentifier)
- }
- }
-
- override func replacePages(of targetIndexpaths: Set<IndexPath>, with documents: [CPDFDocument]) {
- self.model.insertedDocumentSet.formUnion(documents)
-
- super.replacePages(of: targetIndexpaths, with: documents)
- }
-
- // 插入规则:选中后面插入[多选插入第后个后面];没有选中,插入阅读页当前页;
-
- override func getInsertIndex() -> Int {
- let ips = self.thumbnailView.selectionIndexPaths.sorted()
- if ips.isEmpty {
- return self.listView?.currentPageIndex ?? 0
- }
- return ips.last?.item ?? 0
- }
-
- override func splitAction() {
- if KMMemberInfo.shared.isMemberAllFunction == false {
- let winC = KMProductCompareWC.shared
- if self.kEventTag == 1 {
- winC.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC.kEventName = "Reading_Split_BuyNow"
- }
- KMMemberInfo.shared.advancedFunctionUsage()
- return
- }
-
- if self.isEmptySelection() {
- self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
- return
- }
- guard let doc = self.pdfDocument else {
- NSSound.beep()
- return
- }
-
- let windowC = SplitWindowController(document: doc)
- windowC.fileAttribute?.pagesType = .custom
- let ips = self.indexpathsToIndexs(indexpaths: self.thumbnailView.selectionIndexPaths).sorted()
- let string = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: ips)
- windowC.fileAttribute?.pagesString = string
- self.km_beginSheet(windowC: windowC)
- }
-
- func splitMethod(windowC: KMPageEditSplitWindowController, model: KMPageEditSplitSettingModel, limit: Bool = false) {
- if KMMemberInfo.shared.isMemberAllFunction == false {
- KMMemberInfo.shared.advancedFunctionUsage()
- return
- }
-
- if self.isEmptySelection() {
- self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
- return
- }
-
- self._splitMethod(windowC: windowC, model: model, limit: limit)
- }
-
- func splitMenuAction() {
- if KMMemberInfo.shared.isMemberAllFunction == false {
- let winC = KMProductCompareWC.shared
- if self.kEventTag == 1 {
- winC.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC.kEventName = "Reading_Split_BuyNow"
- }
- KMMemberInfo.shared.advancedFunctionUsage()
- return
- }
-
- let pdf = self.thumbnailView.document
- let pages = self.thumbnailView.selectionIndexPaths
- if (pages.isEmpty == false) {
- if self.fileAttri_ == nil {
- self.fileAttri_ = KMFileAttribute()
- self.fileAttri_?.password = self.thumbnailView.document?.password ?? ""
- self.fileAttri_?.filePath = self.thumbnailView.document?.documentURL.path ?? ""
- }
- let fileAttribute = self.fileAttri_
- fileAttribute?.bAllPage = false
- fileAttribute?.pagesType = .custom
- fileAttribute?.pdfDocument = pdf
- fileAttribute?.pagesString = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: self.indexpathsToIndexs(indexpaths: pages).sorted())
- fileAttribute?.pageCnt = Int(self.thumbnailView.document?.pageCount ?? 0)
- let pages = fileAttribute?.fetchSelectPages() ?? []
- if pages.isEmpty {
- KMAlertTool.runModelForMainThread(message: KMLocalizedString("Invalid page range or the page number is out of range. Please try again.", nil))
- } else {
- let panel = NSOpenPanel()
- panel.canChooseFiles = false
- panel.canChooseDirectories = true
- panel.canCreateDirectories = true
- panel.beginSheetModal(for: self.view.window!) { result in
- if (result == .OK) {
- let outputURL = panel.urls.first!
- var tFolderPath = outputURL.path
-
- var index = 0
- var folderName = self.pdfDocument?.documentURL.deletingPathExtension().lastPathComponent
- if folderName == nil {
- folderName = KMLocalizedString("Untitled", nil)
- }
- var folderPath = "\(tFolderPath)/\(folderName ?? "")"
- //创建目录
- while (FileManager.default.fileExists(atPath: folderPath)) {
- index += 1
- folderPath = "\(tFolderPath)/\(folderName ?? "")_\(index)"
- // folderPath = [tFolderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%ld",folderName,index]];
- }
- tFolderPath = folderPath
- let result = try?FileManager.default.createDirectory(atPath: tFolderPath, withIntermediateDirectories: true)
- if (result == nil) {
- // if (![[NSFileManager defaultManager] createDirectoryAtPath:tFolderPath withIntermediateDirectories:YES attributes:nil error:nil]) {
- KMAlertTool.runModelForMainThread(message: KMLocalizedString("Failed to split!", nil))
- return
- }
- let vc = KMProgressWindowController()
- NSApp.beginSheet(vc.window!, modalFor: self.view.window!, modalDelegate: nil, didEnd: nil, contextInfo: nil)
- DispatchQueue.global().async {
- // NSArray * successArray = [self.pdfDocument splitByFileWithPages:fileAttribute folerPath:tFolderPath fileName:folderName];
- let successArray = self.pdfDocument?.splitByFileWithPages(fileAttribute!, folerPath: tFolderPath, fileName: folderName ?? "") ?? []
- DispatchQueue.main.async {
- if successArray.count > 0 {
- let filePath = successArray.first ?? ""
-
- let workSpace = NSWorkspace.shared
- workSpace.activateFileViewerSelecting([URL(fileURLWithPath: filePath)])
- } else {
- KMAlertTool.runModelForMainThread(message: KMLocalizedString("Failed to split!", nil))
- }
- NSApp.endSheet(vc.window!)
- vc.close()
- }
- }
- }
- }
- }
- } else{
- self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
- }
- }
-
- override func reverseAction() {
- if KMMemberInfo.shared.isMemberAllFunction == false {
- let winC = KMProductCompareWC.shared
- winC.kEventName = "Reading_Reverse_BuyNow"
- KMMemberInfo.shared.advancedFunctionUsage()
- return
- }
-
- let cnt = self.thumbnailView.selectionIndexPaths.count
- if cnt < 2 {
- self._progressHUD(message: KMLocalizedString("No page selected. Please select at least two pages to organize."))
- return
- }
- self.trackEvent(type: .reverse)
- self.toolBar.unSelectItem(for: KMToolbarPageEditReverseItemIdentifier)
- self.reverseMenuAction(sender: nil)
- }
-
- func showSplitWindow(callback: @escaping (KMPageEditSplitWindowController, KMPageEditSplitSettingModel)->Void) {
- let model = KMPageEditSplitSettingModel()
- model.documentURL = self.listView?.document.documentURL
- if let pagecnt = self.thumbnailView.document?.pageCount {
- model.pageCount = Int(pagecnt)
- }
-
- model.fileName = model.documentURL?.lastPathComponent ?? ""
- model.pathExtension = model.fileName?.components(separatedBy: ".").last
-
- if (self.isEmptySelection() == false) {
- model.type = 2
- model.pageRangeType = 2
- var selectedIndexs: Array<Int> = []
- for indexpath in self.thumbnailView.selectionIndexPaths {
- selectedIndexs.append(indexpath.item)
- }
-
- model.pageRangeString = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: selectedIndexs)
- } else {
- model.type = 0
- }
-
- let windowController = KMPageEditSplitWindowController(model)
- self.km_beginSheet(windowC: windowController)
-
- windowController.itemClick = { [weak self] index, value in
- if (index == 1) { /// 取消
- self?.km_endSheet()
- return
- }
- guard let _windowC = self?.kmCurrentWindowC as? KMPageEditSplitWindowController else {
- self?.km_endSheet()
- return
- }
-
- callback(_windowC, model)
- }
- }
-
- private func _splitMethod(windowC: KMPageEditSplitWindowController, model: KMPageEditSplitSettingModel, limit: Bool = false) {
- let outputModel = windowC.model as! KMPageEditSplitSettingModel
-
- DispatchQueue.main.async {
- let panel = NSOpenPanel()
- panel.canChooseFiles = false
- panel.canChooseDirectories = true
- panel.canCreateDirectories = true
- panel.beginSheetModal(for: NSWindow.currentWindow()) { response in
- if (response == .cancel) {
- return
- }
-
- let file_indexs = outputModel.getSplitIndexSets ?? []
- if (file_indexs.count <= 0) {
- return
- }
-
- DispatchQueue.main.async {
- self.showProgressWindow(message: NSLocalizedString("Spliting...", comment: ""))
- self.progressC?.maxValue = Double(file_indexs.count)
- let _document = self.listView?.document
-
- let filePath = "\(panel.url!.path)/\(_document?.documentURL.deletingPathExtension().lastPathComponent ?? "")"
- let uniqueFilePath = KMTools.getUniqueFilePath(filePath: filePath)
- // Swift.debugPrint(uniqueFilePath)
- if (!FileManager.default.fileExists(atPath: uniqueFilePath)) {
- try?FileManager.default.createDirectory(atPath: uniqueFilePath, withIntermediateDirectories: true)
- }
-
- var filepaths: [String] = []
- for i in 0 ..< file_indexs.count {
- let indexs = file_indexs[i]
- if (indexs.isEmpty) {
- continue
- }
- let filepath = String(format: "%@/%@.pdf", uniqueFilePath, model.getNewOutputFileName(index: i+1))
- filepaths.append(filepath)
-
- let newDocument = CPDFDocument()
- newDocument?.importPages(indexs, from: _document, at: 0)
- self.progressC?.increment(by: 1.0)
- newDocument?.write(to: URL(fileURLWithPath: filepath))
- }
- self.hiddenProgressWindow()
- self.km_endSheet()
- if let _urlString = filepaths.first?.deletingLastPathComponent {
- NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: _urlString)])
- }
- }
- }
- }
- }
-
- // MARK: Undo / Redo
-
- @objc private func reversePages(indexs: IndexSet) {
- if let doc = self.thumbnailView.document {
- KMThumbnailCache.shared.clearCache()
- // KMPageEditTools.reverse(doc, indexs
- // ) { result, error in
- // if (result) {
- // self.refreshUI(indexpaths: self.indexsToIndexpaths(indexs: indexs), keepSelected: true)
- //
- // self.kmUndoManager?.registerUndo(withTarget: self, selector: #selector(self.reversePages), object: indexs)
- // }
- // }
- var theIdxs = indexs
- var res = false
- for i in 0 ..< indexs.count {
- guard let first = theIdxs.first else {
- break
- }
- guard let last = theIdxs.last else {
- break
- }
- if first == last {
- break
- }
- res = self.pdfDocument?.exchangePage(at: UInt(first), withPageAt: UInt(last)) ?? false
- if res {
- theIdxs.remove(first)
- theIdxs.remove(last)
- }
- }
- if res {
- self.refreshUI(indexpaths: self.indexsToIndexpaths(indexs: indexs), keepSelected: true)
- self.kmUndoManager?.registerUndo(withTarget: self, selector: #selector(self.reversePages), object: indexs)
- }
- }
- }
-
- @objc private func dragPages(_ indexs: IndexSet, _ toIndex: Int, dp: NSCollectionView.DropOperation, reversed: Bool = false) {
- if (indexs.count <= 0) {
- return
- }
- self.listViewCurrentPageUpdateForDrag(indexs: indexs, toIndex: toIndex)
- // 插入位置偏移量
- var toIndexOffset: Int = 0
- // 需要移动的页面index数组
- var newPages: [CPDFPage] = []
- var currentPage: CPDFPage?
- var originalIndex = self.listViewCurrentIndex
- // 从后面往前删除
- for index in indexs.reversed() {
- let newPage = (self.pdfDocument?.page(at: UInt(index)))?.copy() as? CPDFPage
- if (newPage == nil) {
- continue
- }
- newPages.insert(newPage!, at: 0)
- self.pdfDocument?.removePage(at: UInt(index))
- if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
- toIndexOffset += 1
- }
- if (currentPage == nil) && (originalIndex == index) {
- currentPage = newPage
- }
- }
-
- if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
- toIndexOffset -= 1
- }
- let insertIndex = max(0, toIndex-toIndexOffset)
- var selectIndexs: IndexSet = []
- for (index, page) in newPages.enumerated() {
- self.pdfDocument?.insertPageObject(page, at: UInt(insertIndex+index))
- selectIndexs.insert(insertIndex+index)
- if (currentPage?.pageIndex() == page.pageIndex()) {
- // self._listViewCurrentIndex = insertIndex+index
- }
- }
-
- // 新增 undo
- self.kmUndoManager?.registerUndo(withTarget: self) { target in
- target.clearSelectPages()
- target.dragPages_reversed(indexs, toIndex, newPages, dp: dp)
- }
-
- KMThumbnailCache.shared.clearCache()
- // 刷新UI
- self.refreshUI()
-
- if (reversed == false) {
- self.selectPages(indexs: selectIndexs)
- }
- }
-
- @objc private func new_dragPages(_ indexs: IndexSet, _ toIndex: Int, dp: NSCollectionView.DropOperation, reversed: Bool = false) {
- if (indexs.count <= 0) {
- return
- }
- self.listViewCurrentPageUpdateForDrag(indexs: indexs, toIndex: toIndex)
- // 插入位置偏移量
- var toIndexOffset: Int = 0
- // 需要移动的页面index数组
- var newPages: [CPDFPage] = []
- var currentPage: CPDFPage?
- var originalIndex = self.listViewCurrentIndex
- // 从后面往前删除
- for index in indexs.reversed() {
- let newPage = (self.pdfDocument?.page(at: UInt(index)))?.copy() as? CPDFPage
- if (newPage == nil) {
- continue
- }
- newPages.insert(newPage!, at: 0)
- // self.pdfDocument?.removePage(at: UInt(index))
- if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
- toIndexOffset += 1
- }
- if (currentPage == nil) && (originalIndex == index) {
- currentPage = newPage
- }
- }
- var after = false
- if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
- toIndexOffset -= 1
- after = true
- }
- let insertIndex = max(0, toIndex-toIndexOffset)
- var selectIndexs: IndexSet = []
- for (index, page) in newPages.enumerated() {
- // self.pdfDocument?.insertPageObject(page, at: UInt(insertIndex+index))
- selectIndexs.insert(insertIndex+index)
- if (currentPage?.pageIndex() == page.pageIndex()) {
- // self._listViewCurrentIndex = insertIndex+index
- }
- // self.pdfDocument?.movePage(at: UInt(index), withPageAt: UInt(insertIndex+index))
- }
- var theToIndex = toIndex
- if indexs.count == 1 {
- theToIndex = insertIndex
- }
- if after {
- var offset = 0
- for index in indexs {
- self.pdfDocument?.movePage(at: UInt(index-offset), withPageAt: UInt(theToIndex))
- offset += 1
- }
- } else {
- var offset = 0
- for index in indexs.reversed() {
- self.pdfDocument?.movePage(at: UInt(index+offset), withPageAt: UInt(theToIndex))
- offset += 1
- }
- }
-
- // 新增 undo
- self.kmUndoManager?.registerUndo(withTarget: self) { target in
- target.clearSelectPages()
- target.new_dragPages_reversed(indexs, toIndex, newPages, dp: dp)
- }
-
- KMThumbnailCache.shared.clearCache()
- // 刷新UI
- self.refreshUI()
-
- if (reversed == false) {
- self.selectPages(indexs: selectIndexs)
- }
- }
-
- @objc private func dragPages_reversed(_ indexs: IndexSet, _ toIndex: Int, _ pages: [CPDFPage], dp: NSCollectionView.DropOperation) {
- if (indexs.count <= 0) {
- return
- }
-
- // 插入位置偏移量
- var toIndexOffset: Int = 0
- for index in indexs {
- if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
- toIndexOffset += 1
- }
- }
- if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
- toIndexOffset -= 1
- }
- let insertIndex = max(0, toIndex-toIndexOffset)
- // 需要移动的页面index数组
- var datas: [Int] = []
- for index in insertIndex ..< (insertIndex + indexs.count) {
- datas.append(index)
- }
-
- // 从后面开始删除
- for index in datas.reversed() {
- self.pdfDocument?.removePage(at: UInt(index))
- }
- // 再插入到对应的位置
- for (index,value) in indexs.enumerated() {
- var page: CPDFPage?
- if (index < pages.count) {
- page = pages[index]
- }
- if (page != nil) {
- self.pdfDocument?.insertPageObject(page!, at: UInt(value))
- }
-
- }
- // 新增 undo
- self.kmUndoManager?.registerUndo(withTarget: self) { target in
- target.dragPages(indexs, toIndex, dp: dp, reversed: true)
- }
- // 刷新UI
- self.refreshUI()
- }
-
- @objc private func new_dragPages_reversed(_ indexs: IndexSet, _ toIndex: Int, _ pages: [CPDFPage], dp: NSCollectionView.DropOperation) {
- if (indexs.count <= 0) {
- return
- }
-
- // 插入位置偏移量
- var toIndexOffset: Int = 0
- for index in indexs {
- if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
- toIndexOffset += 1
- }
- }
- var after = false
- if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
- toIndexOffset -= 1
- after = true
- }
- let insertIndex = max(0, toIndex-toIndexOffset)
- // 需要移动的页面index数组
- var datas: [Int] = []
- for index in insertIndex ..< (insertIndex + indexs.count) {
- datas.append(index)
- }
-
- // 从后面开始删除
- for index in datas.reversed() {
- // self.pdfDocument?.removePage(at: UInt(index))
- }
- // 再插入到对应的位置
- for (index,value) in indexs.enumerated() {
- var page: CPDFPage?
- if (index < pages.count) {
- page = pages[index]
- }
- if (page != nil) {
- // self.pdfDocument?.insertPageObject(page!, at: UInt(value))
- }
- }
-
- if after {
- // var offset = 0
- for (index,value) in indexs.enumerated() {
- let idx = datas[index]
- self.pdfDocument?.movePage(at: UInt(idx), withPageAt: UInt(value))
- // offset += 1
- }
- // for index in datas.reversed() {
- // self.pdfDocument?.movePage(at: UInt(index+offset), withPageAt: UInt(toIndex))
- // offset += 1
- // }
- } else {
- // var offset = 0
- for (index,value) in indexs.reversed().enumerated() {
- let idx = datas.reversed()[index]
- self.pdfDocument?.movePage(at: UInt(idx), withPageAt: UInt(value))
- }
- // for index in indexs {
- // self.pdfDocument?.movePage(at: UInt(index-offset), withPageAt: UInt(toIndex))
- // offset += 1
- // }
- }
-
- // 新增 undo
- self.kmUndoManager?.registerUndo(withTarget: self) { target in
- target.new_dragPages(indexs, toIndex, dp: dp, reversed: true)
- }
- KMThumbnailCache.shared.clearCache()
- // 刷新UI
- self.refreshUI()
- }
-
- // MARK: topBar 事件
-
- @objc func zoomOutButtonAction(sender: NSButton?) {
- if (self.itemSize.width > self.defaultItemSize.width) {
- return
- }
-
- if (self.itemSize.width < self.defaultItemSize.width) {
- self.itemSize = self.defaultItemSize
- } else if (self.itemSize.width == self.defaultItemSize.width) {
- self.itemSize = NSSize(width: self.defaultItemSize.width*2, height: self.defaultItemSize.height*2)
- }
- // self.toolBar.zoomInButton?.isEnabled = true
- // if (self.itemSize.width > self.defaultItemSize.width) {
- // sender?.isEnabled = false
- // }
- KMThumbnailCache.shared.clearCache()
- self.pageEditThumbnailView.zoomOut()
- if pageEditThumbnailView.canZoomIn() {
- zoomOutButton.isEnabled = true
- } else {
- zoomOutButton.isEnabled = false
- }
-
- if pageEditThumbnailView.canZoomOut() {
- zoomInButton.isEnabled = true
- } else {
- zoomInButton.isEnabled = false
- }
- }
-
- @objc func zoomInButtonAction(sender: NSButton?) {
- if (self.itemSize.width < self.defaultItemSize.width) {
- return
- }
-
- if (self.itemSize.width > self.defaultItemSize.width) {
- self.itemSize = self.defaultItemSize
- } else if (self.itemSize.width == self.defaultItemSize.width) {
- self.itemSize = NSSize(width: self.defaultItemSize.width*0.5, height: self.defaultItemSize.height*0.5)
- }
- // self.toolBar.zoomOutButton?.isEnabled = true
- // if (self.itemSize.width < self.defaultItemSize.width) {
- // sender?.isEnabled = false
- // }
- KMThumbnailCache.shared.clearCache()
- self.pageEditThumbnailView.zoomIn()
- if pageEditThumbnailView.canZoomIn() {
- zoomOutButton.isEnabled = true
- } else {
- zoomOutButton.isEnabled = false
- }
-
- if pageEditThumbnailView.canZoomOut() {
- zoomInButton.isEnabled = true
- } else {
- zoomInButton.isEnabled = false
- }
- }
-
- // MARK: menu 菜单事件
-
- override func menuNeedsUpdate(_ menu: NSMenu) {
- // let row = self.thumbnailView.collectionView.selectionIndexes
- // let point = self.thumbnailView.collectionView.convert(NSEvent.mouseLocation, to: nil)
- let point = self.view.window?.currentEvent?.locationInView(self.thumbnailView.collectionView) ?? .zero
- let indexpaths = self.thumbnailView.collectionView.indexPathForItem(at: point)
- menu.removeAllItems()
- if indexpaths == nil || indexpaths!.isEmpty { // 空白处点击
- if KMThumbnailManager.manager.copyPages.isEmpty { // 不能粘贴
- // if self.canPaste() {
- return
- }
- let item_ = menu.addItem(withTitle: NSLocalizedString("Paste", comment: ""), action: #selector(pasteActonForEmpty), target: self)
- // item_?.keyEquivalent = KMKeyEquivalent.paste
- let repObj = self.thumbnailView.collectionView.km_indexPathForItem(at: point, nearest: true)
- item_?.representedObject = repObj
- return
- }
-
- super.menuNeedsUpdate(menu)
- }
-
- @objc func item_insertCustomPage(sender: NSMenuItem?) {
- if KMMemberInfo.shared.isMemberAllFunction == false {
- let winC = KMProductCompareWC.shared
- if self.kEventTag == 1 {
- winC.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC.kEventName = "Reading_InsertBlankPage_BuyNow"
- }
- KMMemberInfo.shared.advancedFunctionUsage()
- return
- }
-
- guard let doc = self.pdfDocument else {
- NSSound.beep()
- return
- }
-
- let windowC = KMPDFEditInsertBlankPageWindow(document: doc)
- windowC.currentPage = self.getSelecteIndex() + 1
- windowC.insertLocation = 3
- windowC.callback = { [weak self] pdfDoc, _, pages, insertI in
- if pages != nil {
- // mm 单位的大小
- guard let _winC = self?.kmCurrentWindowC as? KMPDFEditInsertBlankPageWindow else {
- self?.km_endSheet()
- return
- }
- var pageSize = _winC.pageSize
- let direction = windowC.pageRotation == 0 ? 0 : 1
- if (direction == 0) { // 纵向
- if (pageSize.width > pageSize.height) { // 需要交换
- let tmp = pageSize.width
- pageSize.width = pageSize.height
- pageSize.height = tmp
- } else {
- // no things.
- }
- } else { // 横向
- if (pageSize.width > pageSize.height) {
- // no things.
- } else { // 需要交换
- let tmp = pageSize.width
- pageSize.width = pageSize.height
- pageSize.height = tmp
- }
- }
-
- /// 插入位置
- let document = CPDFDocument()
- document?.insertPage(pageSize, at: 0)
- if let page: CPDFPage = (document?.page(at: 0)) {
- self?.insertPages(pages: [page], at: IndexSet(integer: insertI))
- }
- let ips: Set<IndexPath> = [IndexPath(item: insertI, section: 0)]
- self?.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
- }
- self?.km_endSheet()
- }
- self.km_beginSheet(windowC: windowC)
- }
-
- @objc func item_insertFromImage(sender: NSMenuItem?) {
- if KMMemberInfo.shared.isMemberAllFunction == false {
- let winC = KMProductCompareWC.shared
- if self.kEventTag == 1 {
- winC.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC.kEventName = "Reading_InsertImage_BuyNow"
- }
- KMMemberInfo.shared.advancedFunctionUsage()
- return
- }
-
- let openPanel = NSOpenPanel()
- openPanel.allowedFileTypes = KMImageToPDFMethod.supportedImageTypes()
- openPanel.allowsMultipleSelection = true
- openPanel.message = KMLocalizedString("Select images to create a new document. To select multiple files press cmd ⌘ button on keyboard and click on the target files one by one.", nil)
- openPanel.canChooseDirectories = false
- openPanel.allowsMultipleSelection = false
- openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
- if result == NSApplication.ModalResponse.OK {
- if let fileURL = openPanel.urls.first {
- // self.choosePositionWindow {[weak self] index in
- // /// 插入位置
- if NSDocument.isDamage(url: fileURL, needAlertIfDamage: true) { // 损坏图片
- return
- }
- if let imag = NSImage(contentsOfFile: fileURL.path ) {
- let index = self.getInsertIndex() + 1
- let document = CPDFDocument()
- _ = document?.km_insertPage(imag.size, withImage: fileURL.path , at: 0)
- if let page: CPDFPage = (document?.page(at: 0)) {
- self.insertPages(pages: [page], at: IndexSet(integer: index))
- }
- let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
- self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
- }
- // }
- }
- }
- }
-
- }
-
- func choosePositionWindow(completion: @escaping KMIndexChooseBlock) -> Void {
- // guard let doc = self.pdfDocument else {
- // NSSound.beep()
- // return
- // }
- // let windowC = KMFileInsertPositionWindowController(document: doc)
- // windowC.currentPage = self.getSelecteIndex() + 1
- // windowC.insertLocation = 3
- // windowC.callback = { [weak self] pdfDoc, _, insertI in
- // if insertI >= 0 {
- // if (completion != nil) {
- // completion(insertI);
- // }
- // }
- // self?.km_endSheet()
- // }
- // self.km_beginSheet(windowC: windowC)
- }
-
- @objc func item_insertFromClipboard(sender: NSMenuItem?) {
- if KMMemberInfo.shared.isMemberAllFunction == false {
- let winC = KMProductCompareWC.shared
- if self.kEventTag == 1 {
- winC.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC.kEventName = "Reading_InsertClipboard_BuyNow"
- }
- KMMemberInfo.shared.advancedFunctionUsage()
- return
- }
- /// 插入位置
- var error: NSError?
- guard let document: CPDFDocument = self.openDocumentWithImageFromPasteboard(NSPasteboard.general, error: &error) else {
- return
- }
- let index = self.getInsertIndex() + 1
- if let page: CPDFPage = (document.page(at: 0)) {
- self.insertPages(pages: [page], at: IndexSet(integer: index))
- }
- let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
- self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
- }
-
- @objc func item_insertFromScanner(sender: NSMenuItem?) {
- if KMMemberInfo.shared.isMemberAllFunction == false {
- let winC = KMProductCompareWC.shared
- if self.kEventTag == 1 {
- winC.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC.kEventName = "Reading_InsertSacnner_BuyNow"
- }
- KMMemberInfo.shared.advancedFunctionUsage()
- return
- }
-
- let vc = KMDeviceBrowserWindowController.shared
- vc.type = .scanner
- vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
- /// 插入位置
- if let imag = NSImage(contentsOfFile: url.path! ) {
- let index = (self?.getInsertIndex())! + 1
- let document = CPDFDocument()
- _ = document?.km_insertPage(imag.size, withImage: url.path! , at: 0)
- if let page: CPDFPage = (document?.page(at: 0)) {
- self?.insertPages(pages: [page], at: IndexSet(integer: index))
- }
- let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
- self?.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
- }
- vc.close()
- }
- vc.showWindow(NSApp.mainWindow)
- }
-
- func openDocumentWithImageFromPasteboard(_ pboard: NSPasteboard, error outError: AutoreleasingUnsafeMutablePointer<NSError?>?) -> CPDFDocument? {
- var document: CPDFDocument? = nil
- var data: Data? = nil
-
- if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.pdf.rawValue]) {
- data = pboard.data(forType: NSPasteboard.PasteboardType.pdf)
- } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.postScript.rawValue]) {
- data = pboard.data(forType: NSPasteboard.PasteboardType.postScript)
- } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.tiff.rawValue]) {
- data = convertTIFFDataToPDF(pboard.data(forType: NSPasteboard.PasteboardType.tiff) ?? Data())
- } else {
- let images = pboard.readObjects(forClasses: [NSImage.self], options: [:])
- let strings = pboard.readObjects(forClasses: [NSAttributedString.self], options: [:])
- if images?.count ?? 0 > 0 {
- data = convertTIFFDataToPDF((images![0] as AnyObject).tiffRepresentation!)
- } else if strings?.count ?? 0 > 0 {
- data = KMOCTool.convertStringsToPDF(withString: strings ?? [""]) // convertStringsToPDF(strings!)
- }
- }
-
- if let data = data {
- document = CPDFDocument(data: data)
-
- } else if let outError = outError {
- outError.pointee = NSError(domain: "SKDocumentErrorDomain", code: 3, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("Unable to load data from clipboard", comment: "Error description")])
- }
-
- return document
- }
-
- func convertTIFFDataToPDF(_ tiffData: Data) -> Data? {
- guard let imsrc = CGImageSourceCreateWithData(tiffData as CFData, [kCGImageSourceTypeIdentifierHint: kUTTypeTIFF] as CFDictionary), CGImageSourceGetCount(imsrc) > 0, let cgImage = CGImageSourceCreateImageAtIndex(imsrc, 0, nil) else { return nil }
- let pdfData = NSMutableData(capacity: tiffData.count)
- let consumer = CGDataConsumer(data: pdfData! as CFMutableData)!
-
- var rect = CGRect(x: 0, y: 0, width: CGFloat(cgImage.width), height: CGFloat(cgImage.height))
- let ctxt = CGContext(consumer: consumer, mediaBox: &rect, nil)
- ctxt!.beginPDFPage(nil)
- ctxt!.draw(cgImage, in: rect)
- ctxt!.endPDFPage()
- ctxt!.closePDF()
-
- return pdfData as? Data
- }
-
- func extractSelectPageItemAction() {
- if KMMemberInfo.shared.isMemberAllFunction == false {
- let winC = KMProductCompareWC.shared
- if self.kEventTag == 1 {
- winC.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC.kEventName = "Reading_Extract_BuyNow"
- }
- KMMemberInfo.shared.advancedFunctionUsage()
- return
- }
-
- let indexs = self.thumbnailView.selectionIndexPaths
- if indexs.isEmpty {
- self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
- return
- }
-
- self.extractPages(indexpaths: indexs, oneDocumentPerPage: false) { result, params in }
- }
-
- // MARK: toolBar 菜单事件
-
- @objc func reverseMenuAction(sender: AnyObject?) {
- let selectedIndexs = self.thumbnailView.selectionIndexPaths
- if (selectedIndexs.count < 2 ) {
- let alertView = CustomAlertView.alertView(message: NSLocalizedString("Please select at least two pages for editing first", comment: ""), fromView: self.thumbnailView, withStyle: .blue)
- alertView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
- alertView?.layer?.cornerRadius = 4
- return
- }
-
- self.reversePages(indexs: self.indexpathsToIndexs(indexpaths: selectedIndexs))
- self.dealPdfDocumentDidEditCallback(type: .reverse)
- }
-
- override func addMenuItem(menu: NSMenu, item: KMPDFThumbViewMenu.Item) -> NSMenuItem? {
- var item_: NSMenuItem?
- if (item.sel == KMPDFThumbViewMenu.insertSelector) {
- item_ = menu.addItem(withTitle: NSLocalizedString("Blank Page", comment: ""), action: #selector(insertPageItemAction), target: self)
- } else if (item.sel == KMPDFThumbViewMenu.splitSelector) {
- if (self.thumbnailView.selectionIndexPaths.count > 1) {
- item_ = menu.addItem(withTitle: NSLocalizedString("Split", comment: ""), action: KMPDFThumbViewMenu.splitSelector, target: self)
- }
- } else if (item.sel == KMPDFThumbViewMenu.reverseSelector) {
- if (self.thumbnailView.selectionIndexPaths.count > 1) {
- item_ = menu.addItem(withTitle: NSLocalizedString("Reverse", comment: ""), action: KMPDFThumbViewMenu.reverseSelector, target: self)
- }
- } else {
- return super.addMenuItem(menu: menu, item: item)
- }
- return item_
- }
-
- // MARK: - Zoom Methods
-
- @IBAction func buttonClicked_Bigger(_ sender: AnyObject?) {
- // if (self.thumbnailView.thumbnailSize.width == 100.) {
- // self.thumbnailView.thumbnailSize = CGSizeMake(200, 200);
- // } else if (self.thumbnailView.thumbnailSize.width == 200.) {
- // self.thumbnailView.thumbnailSize = CGSizeMake(400, 400);
- // }
- self.zoomOutButtonAction(sender: sender as? NSButton)
- }
-
- @IBAction func buttonClicked_Smaller(_ sender: AnyObject?) {
- // if (self.thumbnailView.thumbnailSize.width == 400.) {
- // self.thumbnailView.thumbnailSize = CGSizeMake(200, 200);
- // } else if (self.thumbnailView.thumbnailSize.width == 200.) {
- // self.thumbnailView.thumbnailSize = CGSizeMake(100, 100);
- // }
- self.zoomInButtonAction(sender: sender as? NSButton)
- }
-
- override func mouseMoved(with event: NSEvent) {
- super.mouseMoved(with: event)
-
- self.view.window?.mouseMoved(with: event)
- }
- }
- extension KMPDFEditViewController {
- //MARK: menu Action
-
- @objc func insertPageItemAction(menu:NSMenuItem) {
- if (menu.tag == 0) {
- self.insertBlankPageAction()
- } else if (menu.tag == 1) {
- self.item_insertCustomPage(sender: nil)
- } else if (menu.tag == 2) {
- self.insertFileAction()
- }
- }
-
- @objc func sharePageItemAction(menu:NSMenuItem) {
- guard let item = menu.parent else {
- NSSound.beep()
- return
- }
- let index = (item.representedObject as? IndexSet)?.first ?? -1
- if Int(index) >= 0 {
- let doucument = self.pdfDocument
- // let page = doucument.page(at: UInt(index))
- let filename : String = doucument?.documentURL.lastPathComponent ?? ""
- let folderPath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(filename)) ?? ""
- try? FileManager.default.removeItem(atPath: folderPath)
- let pdfdocument = CPDFDocument()
- let ret = pdfdocument?.importPages((item.representedObject as? IndexSet) ?? [], from: self.thumbnailView.document, at: 0) ?? false
- let url = URL(fileURLWithPath: folderPath)
- if ret {
- let success = pdfdocument?.write(to:url) ?? false
- // if success {
- // let workspace = NSWorkspace.shared
- // workspace.activateFileViewerSelecting([url])
- // }
- }
- let represent = menu.representedObject as? NSSharingService
- represent?.perform(withItems: [url])
- }
- }
-
- @objc func showPageSizeItemAction(menu: NSMenuItem) {
- self.thumbnailView.isShowPageSize = !self.thumbnailView.isShowPageSize
-
- self.refreshUIForKeepSelecteds()
- }
-
- @objc func printItemAction(menu:NSMenuItem) {
- var datas: [Int] = []
- for indexpath in self.thumbnailView.selectionIndexPaths {
- datas.append(indexpath.item)
- }
-
- guard let callback = self.itemClick else {
- return
- }
-
- callback(2, datas.sorted())
- }
-
- override func menuItemAction_extract(_ sender: Any?) {
- self.extractSelectPageItemAction()
- }
- }
- extension KMPDFEditViewController {
- override func menuItemAction_print(_ sender: Any?) {
- if let item = sender as? NSMenuItem {
- self.printItemAction(menu: item)
- }
- }
- override func menuItemAction_showPageSize(_ sender: Any?) {
- if let item = sender as? NSMenuItem {
- self.showPageSizeItemAction(menu: item)
- }
- }
- override func menuItemAction_share(_ sender: Any?) {
- if let item = sender as? NSMenuItem {
- self.sharePageItemAction(menu: item)
- }
- }
- }
- // MARK: - KMSelectPopButtonDelegate
- extension KMPDFEditViewController {
- func km_comboBoxSelectionDidChange(_ obj: KMPageRange) {
- self.pageIsUpdate = false
-
- var indexpaths: Set<IndexPath> = []
- let type: KMPageRange? = obj
- let pageCnt = self.pdfDocument?.pageCount ?? 0
- for i in 0 ..< pageCnt {
- if (type == .all) {
- indexpaths.insert(IndexPath(item: Int(i), section: 0))
- } else if (type == .odd) {
- if (i % 2 == 1) {
- continue
- }
- indexpaths.insert(IndexPath(item: Int(i), section: 0))
- } else if (type == .even) {
- if (i % 2 == 0) {
- continue
- }
- indexpaths.insert(IndexPath(item: Int(i), section: 0))
- } else if (type == .horizontal) {
- let page = self.pdfDocument?.page(at: i)
- guard let isVertical = page?.isVertical(), !isVertical else {
- continue
- }
- indexpaths.insert(IndexPath(item: Int(i), section: 0))
- } else if (type == .vertical) {
- let page = self.pdfDocument?.page(at: i)
- guard let isHorizontal = page?.isHorizontal(), !isHorizontal else {
- continue
- }
- indexpaths.insert(IndexPath(item: Int(i), section: 0))
- }
- }
-
- if (type == .custom) {
- let windowC = KMPDFEditPageRangeWindowController()
- windowC.pdfDocument = self.pdfDocument
- windowC.pageSelectCallBack = { [weak self] pagesArray in
- var indexpaths = Set<IndexPath>()
- for page in pagesArray {
- indexpaths.insert(IndexPath(item: page-1, section: 0))
- }
- self?.km_endSheet()
-
- self?.selectPages(indexpaths: indexpaths)
- self?.thumbnailView.collectionView.scrollToItems(at: indexpaths, scrollPosition: .bottom)
- }
- self.km_beginSheet(windowC: windowC)
-
- } else {
- self.pageEditThumbnailView.selectPages(at: indexpaths)
- }
- }
-
- func km_controlTextDidEndEditing(_ obj: KMDesignSelect) {
- self.view.window?.makeFirstResponder(self)
-
- for index in 0 ..< obj.numberOfItems {
- if (obj.items[index] == obj.stringValue) {
- return
- }
- }
-
- let pages = KMPageRangeTools.findSelectPage(pageRangeString: self.toolBar.pageRangeView?.stringValue ?? "", pageCount: Int((self.listView?.document.pageCount) ?? 0))
- if (pages.isEmpty) {
- let alert = NSAlert()
- alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
- alert.runModal()
- self.toolBar.setPageRangeString("")
- DispatchQueue.main.async {
- self.view.window?.makeFirstResponder(self.toolBar.pageRangeView?.textField)
- }
- return
- }
-
- var indexpaths: Set<IndexPath> = []
- for page in pages {
- if (page >= 1) {
- indexpaths.insert(IndexPath(item: page-1, section: 0))
- }
- }
-
- self.pageIsUpdate = false
- self.pageEditThumbnailView.selectPages(at: indexpaths)
- }
- }
- // MARK: -
- // MARK: KMThumbnailViewDelegate
- extension KMPDFEditViewController: KMThumbnailViewDelegate {
- func thumbnailView(thumbanView: KMThumbnailView, canDragItemsAt indexPaths: Set<IndexPath>, with event: NSEvent) -> Bool {
- return KMMemberInfo.shared.isMemberAllFunction
- }
- func thumbnailView(thumbanView: KMThumbnailView, shouldAcceptDrop draggingInfo: NSDraggingInfo, indexPath: IndexPath, dropOperation: NSCollectionView.DropOperation) -> Bool {
- return true
- }
- func thumbnailView(thumbanView: KMThumbnailView, didDragAddFiles files: [URL], indexpath: IndexPath) {
- self.km_add_file_multi(fileUrls: files) { index, params in
- if (self.fetchProgressBlockParamsIsPasswordFile(params: params)) { // 加密文档进度回调
- return
- }
-
- let _fileUrl = self.fetchProgressBlockParamsForFileUrl(params: params)
- if let exn = _fileUrl?.pathExtension, KMTools.isPDFType(exn) {
- if (_fileUrl!.path.isPDFValid() == false) {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
- alert.runModal()
- }
- }
- } completionBlock: { [weak self] documents in
- var insertIndex: Int = indexpath.item
- var pages: Array<CPDFPage> = []
- var indexs = IndexSet()
- self?.model.insertedDocumentSet.formUnion(documents)
- for document in documents {
- for i in 0 ..< document.pageCount {
- if let page = document.page(at: i) {
- pages.append(page)
- indexs.insert(insertIndex)
- insertIndex += 1
- }
- }
- }
- self?.insertPages(pages: pages, at: indexs)
- }
- }
-
- func thumbnailView(thumbanView: KMThumbnailView, didDrag dragedIndexPaths: [IndexPath], indexpath: IndexPath, dragInfo: [KMThumbnailViewDragInfoKey.RawValue : Any]) {
- let toIndex = max(0, indexpath.item)
- var indexs = IndexSet()
- for indexpath in dragedIndexPaths {
- indexs.insert(indexpath.item)
- }
-
- var dp = NSCollectionView.DropOperation.on
- if let _dp = dragInfo[KMThumbnailViewDragInfoKey.dropOperation.rawValue] as? NSCollectionView.DropOperation {
- dp = _dp
- }
-
- self.new_dragPages(indexs, toIndex, dp: dp)
-
- if (dragedIndexPaths.count > 0) {
- self.dealPdfDocumentDidEditCallback()
- }
- }
-
- func thumbnailView(thumbanView: KMThumbnailView, shouldPasteboardWriterForItemAt indexPath: IndexPath) -> Bool {
- // if (!self.canPayFunction) {
- // return false
- // }
- return true
- }
-
- func thumbnailView(thumbanView: KMThumbnailView, insetForSectionAt section: Int) -> NSEdgeInsets {
- return NSEdgeInsets(top: 6, left: 40, bottom: 0, right: 40)
- }
-
- func thumbnailView(thumbanView: KMThumbnailView, sizeForItemAt indexpath: IndexPath) -> NSSize {
- self.thumbnailView.thumbnailSzie = CGSize(width: 120, height: 155)
- if (!self.thumbnailView.isShowPageSize) {
- return NSMakeSize(self.itemSize.width, self.itemSize.height+26)
- }
- return self.itemSize
- }
-
- func thumbnailView(thumbanView: KMThumbnailView, numberOfItemsInSection section: Int) -> Int {
- if let count = self.pdfDocument?.pageCount {
- return Int(count)
- }
- return 0
- }
-
- func thumbnailView(thumbanView: KMThumbnailView, itemForRepresentedObjectAt indexpath: IndexPath) -> NSCollectionViewItem {
- let cellView: KMPageEditThumbnailItem = thumbanView.collectionView.km.dequeueReusableCell(for: indexpath)
- cellView.isShowPageSize = self.thumbnailView.isShowPageSize
- if let data = self.pdfDocument?.page(at: UInt(indexpath.item)) {
- cellView.setPage(page: data)
- }
-
- let bks = self.listView?.document.bookmarks()
- var hasBookmark = false
- for bk in bks ?? [] {
- if indexpath.item == bk.pageIndex {
- hasBookmark = true
- break
- }
- }
- cellView.bkIcon.isHidden = !hasBookmark
-
- cellView.doubleClickAction = { [weak self] _ in
- guard let callback = self?.itemClick else {
- return
- }
- callback(1, indexpath.item)
- }
- cellView.mouseDownAction = { [unowned self] _ in
- let selectionIndexPaths = self.thumbnailView.selectionIndexPaths
- if (selectionIndexPaths.count == 1 && selectionIndexPaths.first?.item == indexpath.item) {
- return
- }
-
- self.selectPages(indexs: IndexSet.init(integer: indexpath.item))
- }
-
- cellView.rightMouseDownAction = { [weak self] _ in
- self?.selectPages(indexs: IndexSet.init(integer: indexpath.item))
- }
-
- return cellView
- }
- }
- // MARK: - 系统菜单栏
- extension KMPDFEditViewController {
- override func undo(_ sender: Any?) {
- super.undo(sender)
-
- self.km_becomeFirstResponder()
- }
-
- override func redo(_ sender: Any?) {
- super.redo(sender)
-
- self.km_becomeFirstResponder()
- }
- }
- // MARK: - KMExtensions
- extension KMPDFEditViewController {
- override func deleteAfter(indexpaths: Set<IndexPath>) {
- self.clearSelectPages()
- self.km_becomeFirstResponder()
- }
- override func copyAfter(indexpaths: Set<IndexPath>) {
- self.km_becomeFirstResponder()
- }
- override func pasteAfter(at index: Int) {
- self.km_becomeFirstResponder()
- }
- override func cutAfter(indexpaths: Set<IndexPath>) {
- self.clearSelectPages()
- self.km_becomeFirstResponder()
- }
- override func leftRotateAfter(indexpaths: Set<IndexPath>) {
- NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMPDFViewRotatePage"), object: self.thumbnailView.document)
-
- self.km_becomeFirstResponder()
- }
- override func rightRotateAfter(indexpaths: Set<IndexPath>) {
- NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMPDFViewRotatePage"), object: self.thumbnailView.document)
-
- self.km_becomeFirstResponder()
- }
-
- override func replaceAfter(of targetIndexs: IndexSet, with pages: [CPDFPage], at index: Int) {
- var indexpaths = Set<IndexPath>()
- var insertIndex = index
- for _ in pages {
- indexpaths.insert(IndexPath(item: insertIndex, section: 0))
- insertIndex += 1
- }
- self.thumbnailView.selectionIndexPaths = indexpaths
- self.dealPdfDocumentDidEditCallback(type: .replace)
- }
-
- override func insertBlankPageAfter(size: NSSize, at index: Int) {
- self.selectPages(indexs: IndexSet(integer: index))
- let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
- self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
- self.dealPdfDocumentDidEditCallback(type: .insert)
- }
-
- func listViewCurrentPageUpdateForDrag(indexs: IndexSet, toIndex: Int) {
- if (indexs.isEmpty) {
- return
- }
- // listView 当前页面 被拖拽
- if (indexs.contains(self._listViewCurrentIndex)) {
- // let idx = indexs.firstIndex(of: self._listViewCurrentIndex)
- var idx: Int = 0
- for index in indexs {
- if (index == self._listViewCurrentIndex) {
- break
- }
- idx += 1
- }
- // 插入位置偏移量
- var toIndexOffset: Int = 0
- // 从后面往前删除
- for index in indexs.reversed() {
- let newPage = (self.listView?.document.page(at: UInt(index)))?.copy() as? CPDFPage
- if (newPage == nil) {
- continue
- }
- if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
- toIndexOffset += 1
- }
- }
- if (indexs.last! < toIndex) { // 往后拖拽
- toIndexOffset -= 1
- }
- let insertIndex = max(0, toIndex-toIndexOffset)
- self._listViewCurrentIndex = insertIndex+idx
- } else {
- var forwardCnt = 0
- var nextCnt = 0
- for index in indexs {
- if (index > self._listViewCurrentIndex) {
- nextCnt += 1
- } else {
- forwardCnt += 1
- }
- }
-
- if (self._listViewCurrentIndex > toIndex) { // 插入到目标前面, 前面不管,只管后面的格式
- self._listViewCurrentIndex += nextCnt
- } else if (self._listViewCurrentIndex < toIndex) { // 插入到目标后面, 后面不管,只管前面的格式
- self._listViewCurrentIndex = max(0, self._listViewCurrentIndex - forwardCnt)
- } else { // 插入到目标位置 [跟插入到目标后面一样]
- self._listViewCurrentIndex = max(0, self._listViewCurrentIndex - forwardCnt)
- }
- }
- }
- }
- // MARK: - Analytics (埋点)
- extension KMPDFEditViewController {
- func trackEvent(type: KMPageEditType, index: Int = 0) -> Void {
- if (type == .insert) {
- if index == 0 {
- KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Insert", parameters: [
- KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
- KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
- } else if index == KMPageEditType.insert_blank_page || index == KMPageEditType.insert_custom_page {
- self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertBlankPage"], platform: .AppCenter)
- } else if index == KMPageEditType.insert_files {
- self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertPDF"], platform: .AppCenter)
- } else if index == KMPageEditType.insert_fromImage {
- self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertImage"], platform: .AppCenter)
- } else if index == KMPageEditType.insert_fromClipboard {
- self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertClipboard"], platform: .AppCenter)
- } else if index == KMPageEditType.insert_fromScanner {
- self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertScanner"], platform: .AppCenter)
- }
- } else if (type == .extract) {
- KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Extract", parameters: [
- KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
- KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
- } else if (type == .leftRotate || type == .rightRotate) {
- KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Rotate", parameters: [
- KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
- KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
- } else if (type == .replace) {
- KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Replace", parameters: [
- KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
- KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
- } else if (type == .split) {
- KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Split", parameters: [
- KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
- KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
- } else if (type == .reverse) {
- KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Reverse", parameters: [
- KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
- KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
- } else if (type == .delete) {
- KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Delete", parameters: [
- KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
- KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
- }
- }
-
- func trackEvent_copy() -> Void {
- KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Copy", parameters: [
- KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
- KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
- }
- }
|