1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699 |
- //
- // KMPDFEditViewController.swift
- // Cisdem PDFMaster
- //
- // Created by tangchao on 2023/1/6.
- //
- typealias KMPDFEditViewControllerSelectionDidChange = (_ selectedIndexs: Set<IndexPath>) -> ()
- 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 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?
-
- 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 {
- 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()
- } else if (index == KMPageEditType.insert_blank_page) {
- self.insertBlankPageAction()
- } else if (index == KMPageEditType.insert_custom_page) {
- self.item_insertCustomPage(sender: nil)
- } 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 = { [unowned self] type in
- self.km_comboBoxSelectionDidChange(type)
- }
- toolBar.pageRangeValueDidChange = { [unowned 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 {
- KMPurchaseCompareWindowController.sharedInstance().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 {
- KMPurchaseCompareWindowController.sharedInstance().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)
- }
-
- 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 {
- KMPurchaseCompareWindowController.sharedInstance().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 {
- KMPurchaseCompareWindowController.sharedInstance().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 {
- KMPurchaseCompareWindowController.sharedInstance().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 {
- KMPurchaseCompareWindowController.sharedInstance().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 {
- KMPurchaseCompareWindowController.sharedInstance().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 {
- 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)
- }
- }
- }
- }
-
- @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)
- }
-
- // 刷新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()
- }
-
- // MARK: topBar 事件
-
- @objc func zoomOutButtonAction(sender: NSButton?) {
- if (self.itemSize.width > self.defaultItemSize.width) {
- return
- }
-
- if let _document = self.thumbnailView.document {
- for i in 0 ..< _document.pageCount {
- let page = _document.page(at: i)
- page?.pageEditImage = nil
- }
- }
-
- 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
- // }
- self.pageEditThumbnailView.zoomOut()
- }
-
- @objc func zoomInButtonAction(sender: NSButton?) {
- if (self.itemSize.width < self.defaultItemSize.width) {
- return
- }
-
- if let _document = self.thumbnailView.document {
- for i in 0 ..< _document.pageCount {
- let page = _document.page(at: i)
- page?.pageEditImage = nil
- }
- }
-
- 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
- // }
- self.pageEditThumbnailView.zoomIn()
- }
-
- // 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 {
- KMPurchaseCompareWindowController.sharedInstance().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)
- }
-
- func extractSelectPageItemAction() {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- KMPurchaseCompareWindowController.sharedInstance().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: { [unowned 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.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)
- }
-
- cellView.doubleClickAction = { [unowned 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 = { [unowned 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) -> Void {
- if (type == .insert) {
- 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 (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)
- }
- }
|