123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148 |
- //
- // 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 IAPProductsManager.default().isAvailableAllFunction() == false {
- KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
- 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 IAPProductsManager.default().isAvailableAllFunction() == false {
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- if self.kEventTag == 1 {
- winC?.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC?.kEventName = "Reading_Delete_BuyNow"
- }
- winC?.showWindow(nil)
- 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 IAPProductsManager.default().isAvailableAllFunction() == false {
- KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
- return
- }
-
- self.trackEvent(type: .leftRotate)
-
- super.leftRotateAction()
-
- // self.toolBar.unSelectItem(for: KMToolbarPageEditLeftRotateItemIdentifier)
- }
-
- 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 IAPProductsManager.default().isAvailableAllFunction() == false {
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- if self.kEventTag == 1 {
- winC?.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC?.kEventName = "Reading_Rotate_BuyNow"
- }
- winC?.showWindow(nil)
- return
- }
-
- if self.isEmptySelection() {
- self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
- return
- }
-
- self.trackEvent(type: .rightRotate)
-
- super.rightRotateAction()
-
- // self.toolBar.unSelectItem(for: KMToolbarPageEditRightRotateItemIdentifier)
- }
-
- 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 IAPProductsManager.default().isAvailableAllFunction() == false {
- KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
- 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 IAPProductsManager.default().isAvailableAllFunction() == false {
- KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
- return
- }
-
- super.pastePage(at: index)
- }
-
- override func extractAction() {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- if self.kEventTag == 1 {
- winC?.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC?.kEventName = "Reading_Extract_BuyNow"
- }
- winC?.showWindow(nil)
- 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 IAPProductsManager.default().isAvailableAllFunction() == false {
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- if self.kEventTag == 1 {
- winC?.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC?.kEventName = "Reading_Replace_BuyNow"
- }
- winC?.showWindow(nil)
- 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 IAPProductsManager.default().isAvailableAllFunction() == false {
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- if self.kEventTag == 1 {
- winC?.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC?.kEventName = "Reading_Split_BuyNow"
- }
- winC?.showWindow(nil)
- 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 IAPProductsManager.default().isAvailableAllFunction() == false {
- KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
- return
- }
-
- if self.isEmptySelection() {
- self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
- return
- }
-
- self._splitMethod(windowC: windowC, model: model, limit: limit)
- }
-
- func splitMenuAction() {
- // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
- // #if VERSION_DMG
- // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
- // #else
- // KMToolCompareWindowController * vc = [KMToolCompareWindowController toolCompareWithType:KMCompareWithToolType_PageEdit setSelectIndex:1];
- // [vc startModal:nil];
- // #endif
- // return;
- // }
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- if self.kEventTag == 1 {
- winC?.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC?.kEventName = "Reading_Split_BuyNow"
- }
- winC?.showWindow(nil)
- 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 IAPProductsManager.default().isAvailableAllFunction() == false {
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- winC?.kEventName = "Reading_Reverse_BuyNow"
- winC?.showWindow(nil)
- 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 IAPProductsManager.default().isAvailableAllFunction() == false {
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- if self.kEventTag == 1 {
- winC?.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC?.kEventName = "Reading_InsertBlankPage_BuyNow"
- }
- winC?.showWindow(nil)
- 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 IAPProductsManager.default().isAvailableAllFunction() == false {
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- if self.kEventTag == 1 {
- winC?.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC?.kEventName = "Reading_InsertImage_BuyNow"
- }
- winC?.showWindow(nil)
- 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 IAPProductsManager.default().isAvailableAllFunction() == false {
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- if self.kEventTag == 1 {
- winC?.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC?.kEventName = "Reading_InsertClipboard_BuyNow"
- }
- winC?.showWindow(nil)
- return
- }
- // self.choosePositionWindow {[weak self] index in
- /// 插入位置
- 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 IAPProductsManager.default().isAvailableAllFunction() == false {
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- if self.kEventTag == 1 {
- winC?.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC?.kEventName = "Reading_InsertSacnner_BuyNow"
- }
- winC?.showWindow(nil)
- return
- }
-
- let vc = KMDeviceBrowserWindowController.shared
- vc.type = .scanner
- vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
- // self?.choosePositionWindow {[weak self] index 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 IAPProductsManager.default().isAvailableAllFunction() == false {
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- if self.kEventTag == 1 {
- winC?.kEventName = "Onbrd_EditPage_BuyNow"
- } else {
- winC?.kEventName = "Reading_Extract_BuyNow"
- }
- winC?.showWindow(nil)
- 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 IAPProductsManager.default().isAvailableAllFunction()
- }
- 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)
- }
- }
|