123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665 |
- //
- // KMPDFEditViewController.swift
- // PDF Master
- //
- // Created by tangchao on 2023/1/6.
- //
- import Cocoa
- enum KMPageEditType: Int {
- case pageRange = 1
- case leftRotate = 2
- case rightRotate = 3
- case insert = 4
- case extract = 5
- case replace = 6
- case split = 7
- case reverse = 8
- case delete = 9
- }
- class KMPDFEditViewController: NSViewController {
- @IBOutlet weak var topBarBox: NSBox!
- @IBOutlet weak var contentBox: NSBox!
-
- var pageRangeView: KMDesignSelect?
- var pageRangeViewItems = [NSLocalizedString("All Pages", comment: ""),
- NSLocalizedString("Odd Pages", comment: ""),
- NSLocalizedString("Even Pages", comment: ""),
- NSLocalizedString("Horizontal Pages", comment: ""),
- NSLocalizedString("Vertical Pages", comment: ""),
- NSLocalizedString("Customized", comment: "")]
-
- var toolBar = KMToolbar()
- private var zoomOutButton: NSButton?
- private var zoomInButton: NSButton?
- lazy var rightItemView: NSView = {
- let view = NSView()
-
- let size: CGFloat = 28
- let y: CGFloat = 6
- let zoomOutButton = NSButton()
- view.addSubview(zoomOutButton)
- zoomOutButton.frame = NSMakeRect(0, y, size, size)
- zoomOutButton.isBordered = false
- zoomOutButton.image = NSImage(named: "KMImageNamePageEditZoomOut")
- zoomOutButton.target = self
- zoomOutButton.action = #selector(zoomOutButtonAction)
- self.zoomOutButton = zoomOutButton
-
- let zoomInButton = NSButton()
- view.addSubview(zoomInButton)
- zoomInButton.frame = NSMakeRect(size+7, y, size, size)
- zoomInButton.isBordered = false
- zoomInButton.image = NSImage(named: "KMImageNamePageEditZoomIn")
- zoomInButton.target = self
- zoomInButton.action = #selector(zoomInButtonAction)
- self.zoomInButton = zoomInButton
-
- return view
- }()
-
- var thumbnailView = KMPageEditThumbnailView()
-
- private var pdfDocument: CPDFDocument?
- var listView: CPDFView?
-
- var windowController: NSWindowController?
-
- var pageIsUpdate: Bool = true
- /// 临时存储 document
- private var documentCaches: [CPDFDocument] = []
- var selectedPages: [Int] = []
- var copysPages: Array<CPDFPage> = []
-
- private let defaultItemSize = NSMakeSize(218 + 12 * 2, 292 + 24)
- var itemSize: NSSize = NSMakeSize(218 + 12 * 2, 292 + 24)
-
- private var lockedFiles: Array<URL> = []
- private var undoRedoManager: UndoManager = UndoManager()
-
- // index=1 双击退出;index=2 打印
- var itemClick: KMCommonClickBlock?
- var documentEditedCallback: KMCommonBlock?
-
- internal var viewFirstAppear = true
-
- required init?(coder: NSCoder) {
- super.init(coder: coder)
- }
-
- init(_ document: CPDFDocument) {
- super.init(nibName: "KMPDFEditViewController", bundle: nil)
-
- self.pdfDocument = document
- }
-
- override func viewDidAppear() {
- super.viewDidAppear()
-
- if (self.pdfDocument?.isLocked == false && self.viewFirstAppear) {
- self.viewFirstAppear = false
- self.thumbnailView.document = self.pdfDocument!
- self.thumbnailView.reloadData()
- }
-
- if (self.selectedPages.isEmpty) {
- var index: Int = 0
- if (self.listView != nil) {
- index = self.listView!.currentPageIndex
- }
-
- self.selectPages(indexs: IndexSet(integer: index))
- self.pageRangeView?.stringValue = "\(index+1)"
- self.pageRangeView?.editable = true
- } else {
- var indexs: IndexSet = []
- for pageIndex in self.selectedPages {
- if (pageIndex < 0 || pageIndex >= (self.listView?.document.pageCount)!) {
- continue
- }
-
- indexs.insert(pageIndex)
- }
-
- self.selectPages(indexs: indexs)
-
- self.pageRangeView?.editable = true
- self.pageRangeView?.stringValue = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs.sorted())
- }
-
- self.view.window?.makeFirstResponder(self)
- }
-
- override func viewDidLoad() {
- super.viewDidLoad()
-
- self.thumbnailView.collectionView.backgroundColor(NSColor(hex: "#CED0D4"))
-
- let toolBar = self.toolBar
- self.topBarBox.contentView?.addSubview(toolBar)
- toolBar.frame = self.topBarBox.contentView!.bounds
- toolBar.autoresizingMask = [.width, .height]
- toolBar.delegate = self
- self.topBarBox.fillColor = NSColor(hex: "#F7F8FA")
-
- let rightItemView = self.rightItemView
- self.topBarBox.contentView?.addSubview(rightItemView)
- rightItemView.frame = NSMakeRect(NSWidth(self.topBarBox.contentView!.frame)-80, 0, 80, NSHeight(self.topBarBox.contentView!.frame))
- rightItemView.autoresizingMask = [.minXMargin]
-
- let view = self.thumbnailView
- self.contentBox.contentView?.addSubview(view)
- view.frame = self.contentBox.contentView!.bounds
- view.autoresizingMask = [.width, .height]
- self.thumbnailView.delegate = self
- self.thumbnailView.selectionDidChange = { [weak self] selectedIndexs in
- self?.view.window?.makeFirstResponder(self)
-
- var replaceEnable: Bool = false
- if (selectedIndexs.count == 1) { /// 替换item 置灰
- replaceEnable = true
- }
-
- var enabled: Bool = false
- if (selectedIndexs.count > 0) {
- enabled = true
- }
-
- if (self?.toolBar.items == nil) {
- return
- }
-
- var replaceItem: KMToolBoxItem?
- for i in 0 ..< (self?.toolBar.items.count)! {
- let item: KMToolBoxItem = (self?.toolBar.items[i])!
- if (item.itemIdentifier == KMToolbarPageEditReplaceItemIdentifier) {
- replaceItem = item
- }
-
- if (item.itemIdentifier == KMToolbarPageEditExtractItemIdentifier ||
- item.itemIdentifier == KMToolbarPageEditReverseItemIdentifier ||
- item.itemIdentifier == KMToolbarPageEditDeleteItemIdentifier ||
- item.itemIdentifier == KMToolbarPageEditLeftRotateItemIdentifier ||
- item.itemIdentifier == KMToolbarPageEditRightRotateItemIdentifier) {
- item.unEnabled = !enabled
- }
- }
-
- if (replaceItem != nil) {
- replaceItem?.unEnabled = !replaceEnable
- }
-
- 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?.pageRangeView?.editable = true;
- self?.pageRangeView?.stringValue = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs)
- }
-
- let menu = NSMenu()
- menu.delegate = self
- self.view.menu = menu
- }
-
- // MARK: Private Methods
-
- private func copyPages(with indexs: IndexSet) {
- Task { @MainActor in
- if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
- let _ = KMComparativeTableViewController.show(window: self.view.window!)
- return
- }
-
- if indexs.count > 0 {
- self.copysPages = []
- for i in indexs {
- let page = self.thumbnailView.document.page(at: UInt(i)).copy() as? CPDFPage
- if (page == nil) {
- continue
- }
-
- self.copysPages.append(page!)
- }
- }
- }
- }
-
- private func cutPages(with indexs: IndexSet) {
- Task { @MainActor in
- if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
- let _ = KMComparativeTableViewController.show(window: self.view.window!)
- return
- }
-
- if indexs.count > 0 {
- if (indexs.count == (self.listView?.document.pageCount)!) {
- let _ = CustomAlertView(message: NSLocalizedString("Unable to delete all pages", comment: ""), from: self.thumbnailView, with: .blue)
- return
- }
- self.copysPages = []
- for i in indexs {
- let page = self.thumbnailView.document.page(at: UInt(i)).copy() as? CPDFPage
- if (page == nil) {
- continue
- }
-
- self.copysPages.append(page!)
- }
-
- self.clearSelectPages()
- self.deletePages(indexs: indexs)
-
- // 提醒外面文档已编辑
- if (self.documentEditedCallback != nil) {
- self.documentEditedCallback!()
- }
- }
- }
- }
-
- private func pastePages(at index: Int) {
- Task { @MainActor in
- if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
- let _ = KMComparativeTableViewController.show(window: self.view.window!)
- return
- }
-
- if (index >= 0 && self.copysPages.count > 0) {
- var indexs: IndexSet = IndexSet()
- for (i, _) in self.copysPages.enumerated() {
- indexs.insert(index+i+1)
- }
-
- self.insertPagesForDescSort(pages: self.copysPages, indexs: indexs)
-
- // 提醒外面文档已编辑
- if (self.documentEditedCallback != nil) {
- self.documentEditedCallback!()
- }
-
- var indexpaths: Set<IndexPath> = []
- indexpaths.insert(IndexPath(item: index, section: 0))
- self.thumbnailView.collectionView.animator().scrollToItems(at: indexpaths, scrollPosition: .top)
- }
- }
- }
-
- private func getSelecteIndex() -> Int {
- var index: Int = 0
- for indexpath in self.thumbnailView.selectionIndexPaths {
- index = indexpath.item
- }
- return index
- }
-
- private func getSelectedPage() -> CPDFPage {
- return (self.pdfDocument!.page(at: UInt(getSelecteIndex())))!
- }
-
- private func showPasswordWindow(_ insertIndex: Int) {
- if (self.lockedFiles.count > 0) {
- let fileURL = self.lockedFiles.first
- KMPasswordInputWindow.openWindow(window: self.view.window!, type: .open, url: fileURL!) { result, password in
- if (result == .cancel) { /// 取消
- self.lockedFiles.removeFirst()
- if (self.lockedFiles.count > 0) {
- self.showPasswordWindow(insertIndex)
- }
- return
- }
-
- /// 解密成功
- let document = CPDFDocument(url: fileURL)
- document?.unlock(withPassword: password)
- var newInsertIndex: Int = insertIndex
- var pages: [CPDFPage] = []
- var indexs: IndexSet = IndexSet()
- for i in 0 ..< document!.pageCount {
- let page = document?.page(at: i)
- pages.append(page!)
- indexs.insert(newInsertIndex)
- newInsertIndex += 1
- }
-
- self.insertPagesForDescSort(pages: pages, indexs: indexs)
-
- self.lockedFiles.removeFirst()
- if (self.lockedFiles.count > 0) {
- self.showPasswordWindow(newInsertIndex)
- }
- }
- }
- }
-
- @objc private func insertPagesForDescSort(pages: Array<CPDFPage>, indexs: IndexSet) {
- self.insertPages(pages: pages, indexs: indexs)
-
- /// 选中插入的页面
- self.selectPages(indexs: indexs)
- }
-
- private func selectPages(indexs: IndexSet) {
- var indexpaths: Set<IndexPath> = []
- for index in indexs {
- indexpaths.insert(IndexPath(item: index, section: 0))
- }
- self.thumbnailView.selectPages(at: indexpaths)
- }
-
- // MARK: -
- // MARK: - 清空选择
-
- private func clearSelectPages() {
- self.selectPages(indexs: IndexSet())
- }
-
- private func refreshUI(indexs: IndexSet = []) {
- if (Thread.isMainThread) {
- self.listView?.layoutDocumentView()
-
- var indexpaths: Set<IndexPath> = []
- for index in indexs {
- indexpaths.insert(IndexPath(item: index, section: 0))
- }
- self.thumbnailView.refreshUI(indexs: indexpaths)
- } else {
- DispatchQueue.main.async {
- self.listView?.layoutDocumentView()
-
- var indexpaths: Set<IndexPath> = []
- for index in indexs {
- indexpaths.insert(IndexPath(item: index, section: 0))
- }
- self.thumbnailView.refreshUI(indexs: indexpaths)
- }
- }
- }
-
- private func refreshUIForKeepSelecteds(indexs: IndexSet = []) {
- let indexpaths = self.thumbnailView.selectionIndexPaths
- self.refreshUI(indexs: indexs)
- self.thumbnailView.selectPages(at: indexpaths)
- }
-
- // MARK: Undo / Redo
-
- @objc private func leftRotate(indexs: IndexSet) {
- Task { @MainActor in
- if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
- let _ = KMComparativeTableViewController.show(window: self.view.window!)
- return
- }
-
- if (indexs.count <= 0) {
- return
- }
-
- // 提醒外面文档已编辑
- if (self.documentEditedCallback != nil) {
- self.documentEditedCallback!()
- }
-
- for i in 0 ..< (self.listView?.document.pageCount)! {
- if (indexs.contains(IndexSet.Element(i))) {
- let page = self.listView?.document.page(at: i)
- if (page == nil) {
- continue
- }
- page!.rotation = (page!.rotation-90)%360
- }
- }
-
- self.undoRedoManager.registerUndo(withTarget: self, selector: #selector(rightRotate), object: indexs)
-
- self.refreshUIForKeepSelecteds(indexs: indexs)
-
- NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMPDFViewRotatePage"), object: self.listView?.document)
- }
- }
-
- @objc private func rightRotate(indexs: IndexSet) {
- Task { @MainActor in
- if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
- let _ = KMComparativeTableViewController.show(window: self.view.window!)
- return
- }
-
- if (indexs.count <= 0) {
- return
- }
-
- // 提醒外面文档已编辑
- if (self.documentEditedCallback != nil) {
- self.documentEditedCallback!()
- }
-
- for i in 0 ..< (self.listView?.document.pageCount)! {
- if (indexs.contains(IndexSet.Element(i))) {
- let page = self.listView?.document.page(at: i)
- if (page == nil) {
- continue
- }
- page!.rotation = (page!.rotation+90)%360
- }
- }
-
- self.undoRedoManager.registerUndo(withTarget: self, selector: #selector(leftRotate), object: indexs)
-
- self.refreshUIForKeepSelecteds(indexs: indexs)
- NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMPDFViewRotatePage"), object: self.listView?.document)
- }
- }
-
- @objc private func insertPages(pages: Array<CPDFPage>, indexs: IndexSet) {
- var count: Int = 0
- for index in indexs {
- if (count >= pages.count) {
- break
- }
- if (index > (self.listView?.document.pageCount)!) {
- break
- }
- let newPage = pages[count]
-
- self.listView?.document.insertPageObject(newPage, at: UInt(index))
- count += 1
- }
-
- self.undoRedoManager.registerUndo(withTarget: self, selector: #selector(deletePages), object: indexs)
-
- self.refreshUI()
- }
-
- @objc private func deletePages(indexs: IndexSet) {
- if (indexs.count <= 0) {
- return
- }
- if (indexs.count == (self.listView?.document.pageCount)!) {
- let _ = CustomAlertView(message: NSLocalizedString("Unable to delete all pages", comment: ""), from: self.thumbnailView, with: .blue)
- return
- }
- // 提醒外面文档已编辑
- if (self.documentEditedCallback != nil) {
- self.documentEditedCallback!()
- }
-
- var array: Array<CPDFPage> = []
- for i in indexs {
- let page = self.listView?.document.page(at: UInt(i)).copy() as? CPDFPage
- if (page != nil) {
- array.append(page!)
- }
- }
- self.listView?.document.removePage(at: indexs)
-
- self.undoRedoManager.registerUndo(withTarget: self) { target in
- target.insertPages(pages: array, indexs: indexs)
- }
- self.refreshUI()
- }
-
- @objc private func reversePages(indexs: IndexSet) {
- KMPageEditTools.reverse((self.listView?.document)!, indexs
- ) { result, error in
- if (result) {
- self.refreshUI()
-
- self.undoRedoManager.registerUndo(withTarget: self, selector: #selector(self.reversePages), object: indexs)
- }
- }
- }
-
- @objc private func dragPages(_ indexs: IndexSet, _ toIndex: Int, reversed: Bool = false) {
- if (indexs.count <= 0) {
- return
- }
-
- // 插入位置偏移量
- var toIndexOffset: Int = 0
- // 需要移动的页面index数组
- var newPages: [CPDFPage] = []
- // 从后面往前删除
- for index in indexs.reversed() {
- let newPage = (self.listView?.document.page(at: UInt(index)))?.copy() as? CPDFPage
- if (newPage == nil) {
- continue
- }
- newPages.insert(newPage!, at: 0)
- self.listView?.document.removePage(at: UInt(index))
- if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
- toIndexOffset += 1
- }
- }
- if (indexs.last! < toIndex) { // 往后拖拽
- toIndexOffset -= 1
- }
- let insertIndex = max(0, toIndex-toIndexOffset)
- var selectIndexs: IndexSet = []
- for (index, page) in newPages.enumerated() {
- self.listView?.document.insertPageObject(page, at: UInt(insertIndex+index))
- selectIndexs.insert(insertIndex+index)
- }
-
- // 新增 undo
- self.undoRedoManager.registerUndo(withTarget: self) { target in
- target.clearSelectPages()
- target.dragPages_reversed(indexs, toIndex, newPages)
- }
-
- // 刷新UI
- self.refreshUI()
-
- if (reversed == false) {
- self.selectPages(indexs: selectIndexs)
- }
- }
-
- @objc private func dragPages_reversed(_ indexs: IndexSet, _ toIndex: Int, _ pages: [CPDFPage]) {
- if (indexs.count <= 0) {
- return
- }
-
- // 插入位置偏移量
- var toIndexOffset: Int = 0
- for index in indexs {
- if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
- toIndexOffset += 1
- }
- }
- if (indexs.last! < toIndex) { // 往后拖拽
- 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.listView?.document.removePage(at: UInt(index))
- }
- // 再插入到对应的位置
- for (index,value) in indexs.enumerated() {
- var page: CPDFPage?
- if (index < pages.count) {
- page = pages[index]
- }
- if (page != nil) {
- self.listView?.document.insertPageObject(page!, at: UInt(value))
- }
-
- }
- // 新增 undo
- self.undoRedoManager.registerUndo(withTarget: self) { target in
- target.dragPages(indexs, toIndex, reversed: true)
- }
- // 刷新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*1.5, height: self.defaultItemSize.height*1.5)
- }
-
- self.zoomInButton?.isEnabled = true
- if (self.itemSize.width > self.defaultItemSize.width) {
- sender.isEnabled = false
- }
- self.thumbnailView.zoomOut()
- }
-
- @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.zoomOutButton?.isEnabled = true
- if (self.itemSize.width < self.defaultItemSize.width) {
- sender.isEnabled = false
- }
- self.thumbnailView.zoomIn()
- }
-
- // MARK: menu 菜单事件
-
- @objc func item_insertFile(sender: NSMenuItem?) {
- let panel = NSOpenPanel()
- panel.allowedFileTypes = ["pdf"]
- panel.allowsMultipleSelection = true
- panel.beginSheetModal(for: self.view.window!) { [weak self] response in
- if (response == .cancel) {
- return
- }
-
- /// 处理page
- var insertIndex: Int = (self?.getSelecteIndex())!
- self!.lockedFiles.removeAll()
- var pages: Array<CPDFPage> = []
- self?.documentCaches.removeAll()
- var indexs = IndexSet()
- for fileURL in panel.urls {
- let document = CPDFDocument(url: fileURL)
- if ((document?.isLocked)!) {
- self?.lockedFiles.append(fileURL)
- continue
- }
-
- self?.documentCaches.append(document!)
- for i in 0 ..< document!.pageCount {
- let page = document?.page(at: i)
- pages.append(page!)
- insertIndex += 1
- indexs.insert(insertIndex)
- }
- }
- self?.insertPagesForDescSort(pages: pages, indexs: indexs)
-
- if ((self?.lockedFiles.count)! <= 0) {
- self?.refreshUI()
- return
- }
-
- self?.refreshUI()
- self!.showPasswordWindow(insertIndex)
- }
- }
-
- @objc func item_insertBlankPage(sender: NSMenuItem?) {
- let index = self.getSelecteIndex()
- let page = self.listView?.document.page(at: UInt(index))
-
- self.documentCaches.removeAll()
- let document = CPDFDocument()
- document?.insertPage((page?.bounds.size)!, at: 0)
- self.documentCaches.append(document!)
- let newPage: CPDFPage = (document?.page(at: 0))!
- self.insertPagesForDescSort(pages: [newPage], indexs: IndexSet(integer: index+1))
- }
-
- @objc func item_insertCustomPage(sender: NSMenuItem?) {
- let windowController = KMPageEditInsertCustomPageWindowController(windowNibName: "KMPageEditInsertCustomPageWindowController")
- if (self.thumbnailView.selectionIndexPaths.count > 0) {
- windowController.selectedPageSize = self.getSelectedPage().bounds.size
- }
-
- self.windowController = windowController
- self.view.window?.beginSheet(windowController.window!, completionHandler: { response in})
-
- windowController.itemClick = {
- [weak self] (index: Int) in
-
- if (index == 1) { /// 取消
- self?.view.window?.endSheet((self!.windowController?.window)!)
- self?.windowController = nil
- return
- }
-
- /// 插入
- /// 样式
- let windowController_Insert: KMPageEditInsertCustomPageWindowController = self?.windowController as! KMPageEditInsertCustomPageWindowController
- let type = windowController_Insert.typeIndex
-
- /// 页面大小
- let pageSize = windowController_Insert.pageSize
-
- /// 方向
- let direction = windowController_Insert.direction
-
- /// 插入位置
- let insertIndex: Int = (self?.getSelecteIndex())!
- if (type == 1) { /// 空白页
- let document = CPDFDocument()
- document?.insertPage(pageSize, at: 0)
- let page: CPDFPage = (document?.page(at: 0))!
-
- if (direction == 0) { /// 纵向
- page.rotation = 90
- }
- self?.insertPagesForDescSort(pages: [page], indexs: IndexSet(integer: insertIndex+1))
- } else {
- let document = CPDFDocument()
- var imageName = "plaid"
- if (type == 2) {
- imageName = "horizontal_line"
- } else if (type == 3) {
- imageName = "five_line_score"
- }
- let imagePath = Bundle.main.pathForImageResource(imageName)
- document?.insertPage(pageSize, withImage: imagePath, at: 0)
- let page: CPDFPage = (document?.page(at: 0))!
- if (direction == 0) { /// 纵向
- page.rotation = 90
- }
- self?.insertPagesForDescSort(pages: [page], indexs: IndexSet(integer: insertIndex+1))
- }
-
- self?.view.window?.endSheet((self?.windowController?.window)!)
- self?.windowController = nil
- }
- }
-
- // MARK: toolBar 菜单事件
-
- @objc func pageRangeMenuAction(sender: KMToolbarClickButton) {
-
- }
-
- @objc func leftRotateMenuAction(sender: KMToolbarClickButton?) {
- let selectedIndexs = self.thumbnailView.selectionIndexPaths
- var indexs: IndexSet = []
- for indexpath in selectedIndexs {
- indexs.insert(indexpath.item)
- }
-
- self.leftRotate(indexs: indexs)
- }
-
- @objc func rightRotateMenuAction(sender: KMToolbarClickButton?) {
- let selectedIndexs = self.thumbnailView.selectionIndexPaths
- var indexs: IndexSet = []
- for indexpath in selectedIndexs {
- indexs.insert(indexpath.item)
- }
-
- self.rightRotate(indexs: indexs)
- }
-
- @objc func insertMenuAction(sender: KMToolbarClickButton) {
- let menu = NSMenu()
- let insertFileItem = NSMenuItem(title: "Insert File", action: #selector(item_insertFile), target: self)
- menu.addItem(insertFileItem!)
- let insertBlankPageItem = NSMenuItem(title: "Insert a blank page", action: #selector(item_insertBlankPage), target: self)
- menu.addItem(insertBlankPageItem!)
- let insertCustomPageItem = NSMenuItem(title: "Insert custom page", action: #selector(item_insertCustomPage), target: self)
- menu.addItem(insertCustomPageItem!)
- menu.popUp(positioning: nil, at: NSPoint(x: 0, y: 40), in: sender)
- }
-
- @objc func extractMenuAction(sender: KMToolbarClickButton?) {
- if (self.thumbnailView.selectionIndexPaths.count == 0) {
- let alert = NSAlert()
- alert.messageText = "请选择需要提取的页面"
- alert.runModal()
- return
- }
-
- let windowController = KMPageEditExtractWindowController(windowNibName: "KMPageEditSettingBaseWindowController")
- self.view.window?.beginSheet(windowController.window!)
- self.windowController = windowController
-
- windowController.itemClick = { [weak self] index, value in
- if (index == 1) { /// 取消
- self?.view.window?.endSheet((self?.windowController?.window)!)
- self?.windowController = nil
- return
- }
-
- let windowController_extract: KMPageEditExtractWindowController = self?.windowController as! KMPageEditExtractWindowController
- /// 提取设置项
- let settingView: KMPageEditExtractSettingView = windowController_extract.settingView! as! KMPageEditExtractSettingView
- let oneDocumentPerPage: Bool = settingView.independentPerPageCheck.state != .on
- let extractAfterDelete: Bool = settingView.extractAfterDeletePageCheck.state == .on
-
- self?.view.window?.endSheet((self?.windowController!.window)!)
- self?.windowController = nil
-
- // /// 提取的页面
- let indexpaths = self?.thumbnailView.selectionIndexPaths
- var indexs: IndexSet = []
- var extractPages: Array<CPDFPage> = []
- for indexpath in indexpaths! {
- let page = self?.listView?.document.page(at: UInt(indexpath.item))
- if (page != nil) {
- extractPages.append(page!)
- }
- indexs.insert(indexpath.item)
- }
- KMPageEditTools.extract((self?.listView?.document)!, indexs, oneDocumentPerPage, (self?.view.window)!) { result, urls, error in
- if (result == false) {
- return
- }
-
- if (extractAfterDelete) {
- var indexs: IndexSet = IndexSet()
- for page in extractPages {
- let indexPage: Int = Int((self?.listView?.document.index(for: page))!)
- indexs.insert(indexPage)
- }
- self?.deletePages(indexs: indexs)
- }
- }
- }
- }
-
- @objc func replaceMenuAction(sender: KMToolbarClickButton?) {
- let panel = NSOpenPanel()
- panel.allowedFileTypes = ["pdf"]
- panel.allowsMultipleSelection = true
- panel.beginSheetModal(for: self.view.window!) { [weak self] response in
- if (response == .cancel) {
- return
- }
-
- /// 处理page
- var pages: Array<CPDFPage> = []
- let selectedIndex: Int = (self?.getSelecteIndex())!
- self?.listView?.document.removePage(at: UInt(selectedIndex))
-
- var insertIndex: Int = selectedIndex
- self?.lockedFiles.removeAll()
- for fileURL in panel.urls {
- let document = CPDFDocument(url: fileURL)
- if ((document?.isLocked)!) {
- self?.lockedFiles.append(fileURL)
- continue
- }
-
- for i in 0 ..< document!.pageCount {
- let page = document?.page(at: i)
- pages.append(page!)
- self!.listView?.document.insertPageObject(page, at:UInt(insertIndex))
- insertIndex += 1
- }
- }
-
- if ((self?.lockedFiles.count)! <= 0) {
- self?.refreshUI()
- return
- }
-
- self?.refreshUI()
- self!.showPasswordWindow(insertIndex)
- }
- }
-
- @objc func splitMenuAction(sender: KMToolbarClickButton) {
- let model = KMPageEditSplitSettingModel()
- model.documentURL = self.listView?.document.documentURL
- model.fileName = model.documentURL.lastPathComponent
- model.pathExtension = model.fileName.components(separatedBy: ".").last
-
- if (self.thumbnailView.selectionIndexPaths.count > 0) {
- 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.view.window?.beginSheet(windowController.window!)
- self.windowController = windowController
-
- windowController.itemClick = { [weak self] index, value in
- if (index == 1) { /// 取消
- self?.view.window?.endSheet((self?.windowController!.window)!)
- self?.windowController = nil
- return
- }
-
- /// 拆分
- let windowController_split: KMPageEditSplitWindowController = self?.windowController as! KMPageEditSplitWindowController
- let outputModel: KMPageEditSplitSettingModel = windowController_split.model! as! KMPageEditSplitSettingModel
-
- self?.view.window?.endSheet((self?.windowController!.window)!)
- self?.windowController = nil
-
- let panel = NSOpenPanel()
- panel.canChooseFiles = false
- panel.canChooseDirectories = true
- panel.canCreateDirectories = true
- let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
- button.state = .off
- panel.accessoryView = button
- panel.beginSheetModal(for: (self?.view.window)!) { response in
- if (response == .cancel) {
- return
- }
- KMPageEditTools.split((self?.listView?.document)!, outputModel, panel.url!.path, outputModel.outputFileNameDeletePathExtension) { result, outputFilepaths, error in
- if (result) {
- if (button.state == .on) {
- for filepath in outputFilepaths! {
- if !filepath.isPDFValid() {
- 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()
- } else {
- NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filepath), display: true) { document, alreadyOpen, error in
-
- }
- }
- }
- } else {
- var urls: [URL] = []
- for filepath in outputFilepaths! {
- urls.append(URL(fileURLWithPath: filepath))
- }
- NSWorkspace.shared.activateFileViewerSelecting(urls)
- }
- }
- }
- }
- }
- }
-
- @objc func reverseMenuAction(sender: KMToolbarClickButton) {
- let selectedIndexs = self.thumbnailView.selectionIndexPaths
- if (selectedIndexs.count < 2 ) {
- let _ = CustomAlertView(message: "请先选择至少两个页面进行编辑操作", from: self.thumbnailView, with: .blue)
- return
- }
-
- var indexs: IndexSet = []
- for indexpath in selectedIndexs {
- indexs.insert(indexpath.item)
- }
-
- self.reversePages(indexs: indexs)
- }
-
- @objc func deleteMenuAction(sender: KMToolbarClickButton) {
- Task { @MainActor in
- if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
- let _ = KMComparativeTableViewController.show(window: self.view.window!)
- return
- }
-
- var indexs: IndexSet = IndexSet()
- for indexPath in self.thumbnailView.selectionIndexPaths {
- indexs.insert(indexPath.item)
- }
-
- self.clearSelectPages()
- self.deletePages(indexs: indexs)
- }
- }
- }
- // MARK: -
- // MARK: KMNewToolbarDelegate
- extension KMPDFEditViewController: KMNewToolbarDelegate {
- func toolbarDefaultItemIdentifiers(_ toolbar: KMToolbar!) -> [String]! {
- return [KMToolbarPageEditPageRangeItemIdentifier,
- KMToolbarPageEditLeftRotateItemIdentifier,
- KMToolbarPageEditRightRotateItemIdentifier,
- // KMToolbarDividerItemIdentifier,
- // KMToolbarPageEditInsetItemIdentifier,
- // KMToolbarPageEditExtractItemIdentifier,
- // KMToolbarPageEditReplaceItemIdentifier,
- // KMToolbarPageEditSplitItemIdentifier,
- // KMToolbarPageEditReverseItemIdentifier,
- KMToolbarDividerItemIdentifier,
- KMToolbarPageEditDeleteItemIdentifier]
- }
-
- func toolbar(_ toolbar: KMToolbar!, itemForItemIdentifier identifier: String!) -> KMToolBoxItem! {
- let item = KMToolBoxItem(itemIdentifier: identifier)
- if (identifier == KMToolbarPageEditPageRangeItemIdentifier) {
- // item?.image = NSImage(named: "KMImageNameMainToolbarrRight")
- item?.alternateImage = NSImage(named: "KMImageNameMainToolbarrRight")
- item?.target = self
- item?.btnTag = KMPageEditType.pageRange.rawValue
- // item?.toolTip = NSLocalizedString("pageRange", comment: "")
- item?.titleName = NSLocalizedString("pageRange ", comment: "")
- item?.boxImagePosition = KMToolBoxImagePosition.left
- item?.btnAction = #selector(pageRangeMenuAction)
-
- let view = NSView()
- item?.addSubview(view)
- view.frame = item!.bounds
- view.autoresizingMask = [.width,.height]
- view.wantsLayer = true
- view.layer?.backgroundColor = NSColor(hex: "#F7F8FA").cgColor
-
- let comBoxView = KMDesignSelect(withType: .Combox)
- view.addSubview(comBoxView.view)
- comBoxView.view.frame = NSMakeRect(0, 8, NSWidth(view.frame), 24)
- comBoxView.view.autoresizingMask = [.width]
- comBoxView.removeAllItems()
- comBoxView.addItems(withObjectValues: self.pageRangeViewItems)
- comBoxView.selectItem(at: 0)
- comBoxView.placeholderString = NSLocalizedString("eg .1,3-5,10", comment: "")
- comBoxView.editable = false
- comBoxView.delete = self
- pageRangeView = comBoxView
-
- let menuItem = NSMenuItem.init(title: "pageRange", action: #selector(pageRangeMenuAction), target: self)
- item?.menuFormRepresentation = menuItem
- } else if (identifier == KMToolbarPageEditLeftRotateItemIdentifier) {
- item?.image = NSImage(named: "KMImageNameMainToolPageLeftRotate")
- item?.alternateImage = NSImage(named: "KMImageNameMainToolPageLeftRotate")
- item?.target = self
- item?.btnTag = KMPageEditType.leftRotate.rawValue
- item?.toolTip = NSLocalizedString("Rotate Left", comment: "")
- item?.titleName = NSLocalizedString("", comment: "")
- item?.boxImagePosition = KMToolBoxImagePosition.left
- item?.btnAction = #selector(leftRotateMenuAction)
-
- let menuItem = NSMenuItem.init(title: "", action: #selector(leftRotateMenuAction), target: self)
- item?.menuFormRepresentation = menuItem
- } else if (identifier == KMToolbarPageEditRightRotateItemIdentifier) {
- item?.image = NSImage(named: "KMImageNameMainToolPageRightRotate")
- item?.alternateImage = NSImage(named: "KMImageNameMainToolPageRightRotate")
- item?.target = self
- item?.btnTag = KMPageEditType.rightRotate.rawValue
- item?.toolTip = NSLocalizedString("Rotate Right", comment: "")
- item?.titleName = NSLocalizedString("", comment: "")
- item?.boxImagePosition = KMToolBoxImagePosition.left
- item?.btnAction = #selector(rightRotateMenuAction)
-
- let menuItem = NSMenuItem.init(title: "", action: #selector(rightRotateMenuAction), target: self)
- item?.menuFormRepresentation = menuItem
- } else if (identifier == KMToolbarPageEditInsetItemIdentifier) {
- item?.image = NSImage(named: "KMImageNameMainToolPageInsert")
- item?.alternateImage = NSImage(named: "KMImageNameMainToolPageInsert")
- item?.target = self
- item?.btnTag = KMPageEditType.insert.rawValue
- item?.toolTip = NSLocalizedString("Insert", comment: "")
- item?.titleName = NSLocalizedString("Insert", comment: "")
- item?.boxImagePosition = KMToolBoxImagePosition.left
- item?.btnAction = #selector(insertMenuAction)
-
- let menuItem = NSMenuItem.init(title: "Insert", action: #selector(insertMenuAction), target: self)
- item?.menuFormRepresentation = menuItem
- } else if (identifier == KMToolbarPageEditExtractItemIdentifier) {
- item?.image = NSImage(named: "KMImageNameMainToolPageExtract")
- item?.alternateImage = NSImage(named: "KMImageNameMainToolPageExtract")
- item?.target = self
- item?.btnTag = KMPageEditType.extract.rawValue
- item?.toolTip = NSLocalizedString("Extract", comment: "")
- item?.titleName = NSLocalizedString("Extract", comment: "")
- item?.boxImagePosition = KMToolBoxImagePosition.left
- item?.btnAction = #selector(extractMenuAction)
-
- let menuItem = NSMenuItem.init(title: "Extract", action: #selector(extractMenuAction), target: self)
- item?.menuFormRepresentation = menuItem
- } else if (identifier == KMToolbarPageEditReplaceItemIdentifier) {
- item?.image = NSImage(named: "KMImageNameMainToolPageReplace")
- item?.alternateImage = NSImage(named: "KMImageNameMainToolPageReplace")
- item?.target = self
- item?.btnTag = KMPageEditType.replace.rawValue
- item?.toolTip = NSLocalizedString("Replace", comment: "")
- item?.titleName = NSLocalizedString("Replace", comment: "")
- item?.boxImagePosition = KMToolBoxImagePosition.left
- item?.btnAction = #selector(replaceMenuAction)
-
- let menuItem = NSMenuItem.init(title: "Replace", action: #selector(replaceMenuAction), target: self)
- item?.menuFormRepresentation = menuItem
- } else if (identifier == KMToolbarPageEditSplitItemIdentifier) {
- item?.image = NSImage(named: "KMImageNameMainToolPageSplit")
- item?.alternateImage = NSImage(named: "KMImageNameMainToolPageSplit")
- item?.target = self
- item?.btnTag = KMPageEditType.split.rawValue
- item?.toolTip = NSLocalizedString("Split the PDF into multiple files", comment: "")
- item?.titleName = NSLocalizedString("Split", comment: "")
- item?.boxImagePosition = KMToolBoxImagePosition.left
- item?.btnAction = #selector(splitMenuAction)
-
- let menuItem = NSMenuItem.init(title: "Split", action: #selector(splitMenuAction), target: self)
- item?.menuFormRepresentation = menuItem
- } else if (identifier == KMToolbarPageEditReverseItemIdentifier) {
- item?.image = NSImage(named: "KMImageNameMainToolPageReverse")
- item?.alternateImage = NSImage(named: "KMImageNameMainToolPageReverse")
- item?.target = self
- item?.btnTag = KMPageEditType.reverse.rawValue
- item?.toolTip = NSLocalizedString("Reverse", comment: "")
- item?.titleName = NSLocalizedString("Reverse", comment: "")
- item?.boxImagePosition = KMToolBoxImagePosition.left
- item?.btnAction = #selector(reverseMenuAction)
-
- let menuItem = NSMenuItem.init(title: "Reverse", action: #selector(reverseMenuAction), target: self)
- item?.menuFormRepresentation = menuItem
- } else if (identifier == KMToolbarPageEditDeleteItemIdentifier) {
- item?.image = NSImage(named: "KMImageNameMainToolPageDelete")
- item?.alternateImage = NSImage(named: "KMImageNameMainToolPageDelete")
- item?.target = self
- item?.btnTag = KMPageEditType.delete.rawValue
- item?.toolTip = NSLocalizedString("Delete", comment: "")
- item?.titleName = NSLocalizedString("", comment: "")
- item?.boxImagePosition = KMToolBoxImagePosition.left
- item?.btnAction = #selector(deleteMenuAction)
-
- let menuItem = NSMenuItem.init(title: "Delete", action: #selector(deleteMenuAction), target: self)
- item?.menuFormRepresentation = menuItem
- }
-
- return item
- }
-
- //MARK: menu Action
-
- @objc func insertPageItemAction(menu:NSMenuItem) {
- if (menu.tag == 0) {
- self.item_insertFile(sender: nil)
- } else if (menu.tag == 1) {
- self.item_insertBlankPage(sender: nil)
- } else if (menu.tag == 2) {
- self.item_insertCustomPage(sender: nil)
- }
- }
-
- @objc func rotatePageItemAction(menu:NSMenuItem) {
- rightRotateMenuAction(sender: nil)
- }
-
- @objc func leftRotatePageItemAction(menu:NSMenuItem) {
- leftRotateMenuAction(sender: nil)
- }
-
- @objc func extractPageItemAction(menu:NSMenuItem) {
- extractMenuAction(sender: nil)
- }
-
- @objc func replacePageItemAction(menu:NSMenuItem) {
- replaceMenuAction(sender: nil)
- }
-
- @objc func deletePageItemAction(menu:NSMenuItem) {
- Task { @MainActor in
- if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
- let _ = KMComparativeTableViewController.show(window: self.view.window!)
- return
- }
-
- let indexs = menu.representedObject as! IndexSet
- if indexs.count > 0 {
- self.clearSelectPages()
- self.deletePages(indexs: indexs)
- }
- }
- }
-
- @objc func sharePageItemAction(menu:NSMenuItem) {
- let item = menu.parent!
- let index = (item.representedObject as! IndexSet).first ?? -1
- if Int(index) >= 0 {
- let doucument = self.thumbnailView.document
- 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)
- let url = URL(fileURLWithPath: folderPath)
- if ret {
- let success = pdfdocument!.write(to:url)
- if success {
- let workspace = NSWorkspace.shared
- workspace.activateFileViewerSelecting([url])
- }
- }
- let represent : NSSharingService = menu.representedObject as! NSSharingService
- represent.perform(withItems: [url])
-
- }
- }
-
- @objc func copyItemAction(menu:NSMenuItem) {
- let indexs = menu.representedObject as! IndexSet
- self.copyPages(with: indexs)
- }
-
- @objc func cutItemAction(menu:NSMenuItem) {
- let indexs = menu.representedObject as! IndexSet
- self.cutPages(with: indexs)
- }
-
- @objc func pastePageItemAction(menu:NSMenuItem) {
- var index = (menu.representedObject as! IndexSet).last ?? -1
- self.pastePages(at: index)
- }
-
- @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())
- }
- }
- // MARK: -
- // MARK: NSMenuDelegate,NSMenuItemValidation
- extension KMPDFEditViewController : NSMenuDelegate,NSMenuItemValidation {
- func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
- let action = menuItem.action
- if action == #selector(insertPageItemAction) ||
- action == #selector(insertPageItemAction) ||
- action == #selector(deletePageItemAction) ||
- action == #selector(replacePageItemAction) ||
- action == #selector(rotatePageItemAction) ||
- action == #selector(leftRotatePageItemAction) ||
- action == #selector(copyItemAction) ||
- action == #selector(cutItemAction) ||
- action == #selector(pastePageItemAction) ||
- action == #selector(printItemAction) ||
- action == #selector(sharePageItemAction) ||
- action == #selector(extractPageItemAction) ||
- action == #selector(showPageSizeItemAction) {
- let row = self.thumbnailView.collectionView.selectionIndexes
- if row.count > 0 {
- if (row.count > 1 && action == #selector(replacePageItemAction)) {
- return false
- }
- return true
- }
- return false
- }
-
- if (action == #selector(cut)) {
- return self.thumbnailView.collectionView.selectionIndexes.count > 0
- }
- if (action == NSSelectorFromString("copy:")) {
- return self.thumbnailView.collectionView.selectionIndexes.count > 0
- }
- if (action == #selector(paste)) {
- return self.copysPages.count > 0
- }
- if (action == #selector(undo)) {
- return self.undoRedoManager.canUndo
- }
- if (action == #selector(redo)) {
- return self.undoRedoManager.canRedo
- }
- if (action == #selector(delete)) {
- return self.thumbnailView.collectionView.selectionIndexes.count > 0
- }
-
- return true
- }
-
- func menuNeedsUpdate(_ menu: NSMenu) {
- menu.removeAllItems()
-
- let row = self.thumbnailView.collectionView.selectionIndexes
- // let point = self.thumbnailView.collectionView.convert(NSEvent.mouseLocation, to: nil)
- // let indexpaths = self.thumbnailView.collectionView.indexPathForItem(at: point)
- if (row.isEmpty) {
- return
- }
-
- var item = NSMenuItem()
-
- // if (row.count == 1) {
- // item = menu.addItem(withTitle: NSLocalizedString("Insert", comment: ""), action: nil, target: self)
- // item.representedObject = row
- //
- // var subMenu = NSMenu()
- // var subitem = NSMenuItem()
- // subitem = subMenu.addItem(withTitle: NSLocalizedString("Insert File", comment: ""), action: #selector(insertPageItemAction), target: self, tag:0)
- // subitem.representedObject = row
- // subitem = subMenu.addItem(withTitle: NSLocalizedString("Insert blank page", comment: ""), action: #selector(insertPageItemAction), target: self, tag:1)
- // subitem.representedObject = row
- // subitem = subMenu.addItem(withTitle: NSLocalizedString("Insert page", comment: ""), action: #selector(insertPageItemAction), target: self, tag:2)
- // subitem.representedObject = row
- // item.submenu = subMenu
- // }
-
-
- // item = menu.addItem(withTitle: NSLocalizedString("Extract", comment: ""), action: #selector(extractPageItemAction), target: self)
- // item.representedObject = row
-
- // if (row.count == 1) {
- // item = menu.addItem(withTitle: NSLocalizedString("Replace Page", comment: ""), action: #selector(replacePageItemAction), target: self)
- // item.representedObject = row
- // }
- item = menu.addItem(withTitle: NSLocalizedString("Delete Page", comment: ""), action: #selector(deletePageItemAction), target: self)
- item.keyEquivalent = String(Unicode.Scalar(NSBackspaceCharacter)!)
- item.keyEquivalentModifierMask = []
- item.representedObject = row
- menu.addItem(NSMenuItem.separator())
-
- item = menu.addItem(withTitle: NSLocalizedString("Rotate Clockwise", comment: ""), action: #selector(rotatePageItemAction), target: self)
- item.representedObject = row
- item = menu.addItem(withTitle: NSLocalizedString("Rotate Counterclockwise", comment: ""), action: #selector(leftRotatePageItemAction), target: self)
- item.representedObject = row
-
- menu.addItem(NSMenuItem.separator())
-
- item = menu.addItem(withTitle: NSLocalizedString("Copy", comment: ""), action: #selector(copyItemAction), target: self)
- item.representedObject = row
- item.keyEquivalent = "c"
- item.keyEquivalentModifierMask = [.command]
- item = menu.addItem(withTitle: NSLocalizedString("Cut", comment: ""), action: #selector(cutItemAction), target: self)
- item.representedObject = row
- item.keyEquivalent = "x"
- item = menu.addItem(withTitle: NSLocalizedString("Paste", comment: ""), action: #selector(pastePageItemAction), target: self)
- item.representedObject = row
- item.keyEquivalent = "v"
-
- menu.addItem(NSMenuItem.separator())
-
- if (!self.thumbnailView.isShowPageSize) {
- item = menu.addItem(withTitle: NSLocalizedString("Hide Page Size", comment: ""), action: #selector(showPageSizeItemAction), target: self)
- item.representedObject = row
- } else {
- item = menu.addItem(withTitle: NSLocalizedString("Display Page Size", comment: ""), action: #selector(showPageSizeItemAction), target: self)
- item.representedObject = row
- }
-
- menu.addItem(NSMenuItem.separator())
-
- item = menu.addItem(withTitle: NSLocalizedString("Print", comment: ""), action: #selector(printItemAction), target: self)
- item.representedObject = row
-
- // if (row.count <= 1) {
- // item = menu.addItem(withTitle: NSLocalizedString("Share", comment: ""), action: nil, target: self)
- // item.representedObject = row
-
- // item.submenu = NSSharingServicePicker.menu(forSharingItems: [self.listView!.document.documentURL ?? ""], subjectContext: "", withTarget: self, selector: #selector(sharePageItemAction), serviceDelegate: nil)
- // }
- }
- }
- // MARK: -
- // MARK: KMSelectPopButtonDelegate
- extension KMPDFEditViewController: KMSelectPopButtonDelegate {
- func km_comboBoxSelectionDidChange(_ obj: KMDesignSelect) {
- let index: Int = self.pageRangeView!.indexOfSelectedItem
- var indexpaths: Set<IndexPath> = []
- if (index <= 0) { /// 全部页面
- self.pageRangeView?.editable = false
- for i in 0 ..< (self.listView?.document.pageCount)! {
- indexpaths.insert(IndexPath(item: Int(i), section: 0))
- }
-
- self.pageIsUpdate = false
- self.thumbnailView.selectPages(at: indexpaths)
- } else if (index == 1) { /// 奇数页
- self.pageRangeView?.editable = false
- for i in 0 ..< (self.listView?.document.pageCount)! {
- if (i % 2 == 1) {
- continue
- }
- indexpaths.insert(IndexPath(item: Int(i), section: 0))
- }
- self.pageIsUpdate = false
- self.thumbnailView.selectPages(at: indexpaths)
- } else if (index == 2) { /// 偶数页
- self.pageRangeView?.editable = false
- for i in 0 ..< (self.listView?.document.pageCount)! {
- if (i % 2 == 0) {
- continue
- }
- indexpaths.insert(IndexPath(item: Int(i), section: 0))
- }
- self.pageIsUpdate = false
- self.thumbnailView.selectPages(at: indexpaths)
- } else if (index == 3) { /// 横向页
- self.pageRangeView?.editable = false
- for i in 0 ..< (self.listView?.document.pageCount)! {
- let page = self.listView?.document.page(at: i)
- if (page?.rotation == 0 || page?.rotation == 180 || page?.rotation == -180) {
- continue
- }
- indexpaths.insert(IndexPath(item: Int(i), section: 0))
- }
- self.pageIsUpdate = false
- self.thumbnailView.selectPages(at: indexpaths)
- } else if (index == 4) { /// 纵向页
- self.pageRangeView?.editable = false
- for i in 0 ..< (self.listView?.document.pageCount)! {
- let page = self.listView?.document.page(at: i)
- if (page?.rotation == 90 || page?.rotation == 270 || page?.rotation == -90 || page?.rotation == -270) {
- continue
- }
- indexpaths.insert(IndexPath(item: Int(i), section: 0))
- }
- self.pageIsUpdate = false
- self.thumbnailView.selectPages(at: indexpaths)
- } else { /// 自定义
- self.pageIsUpdate = false
- self.pageRangeView?.editable = true
- self.clearSelectPages()
- DispatchQueue.main.async {
- self.pageRangeView?.stringValue = ""
- }
- }
- }
-
- func km_controlTextDidChange(_ obj: KMDesignSelect) {
-
- }
-
- func km_controlTextDidEndEditing(_ obj: KMDesignSelect) {
- self.view.window?.makeFirstResponder(self)
-
- for index in 0 ..< self.pageRangeView!.numberOfItems {
- if (self.pageRangeViewItems[index] == self.pageRangeView!.stringValue) {
- return
- }
- }
-
- let pages = KMPageRangeTools.findSelectPage(pageRangeString: self.pageRangeView!.stringValue, pageCount: Int((self.listView?.document.pageCount)!))
- 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()
- return
- }
-
- var indexpaths: Set<IndexPath> = []
- for page in pages {
- if (page >= 1) {
- indexpaths.insert(IndexPath(item: page-1, section: 0))
- }
- }
-
- self.pageIsUpdate = false
- self.thumbnailView.selectPages(at: indexpaths)
- }
- }
- // MARK: -
- // MARK: KMPDFThumbnailViewDelegate
- extension KMPDFEditViewController: KMPDFThumbnailViewDelegate {
- func thumbnailView(thumbanView: KMPDFThumbnailView, didDragAddFiles files: [URL], indexpath: IndexPath) {
- /// 处理page
- // var insertIndex: Int = indexpath.item
- // self.lockedFiles.removeAll()
- // var pages: Array<CPDFPage> = []
- // self.documentCaches.removeAll()
- // var indexs = IndexSet()
- // for fileURL in files {
- // let document = CPDFDocument(url: fileURL)
- // if ((document?.isLocked)!) {
- // self.lockedFiles.append(fileURL)
- // continue
- // }
- //
- // self.documentCaches.append(document!)
- // for i in 0 ..< document!.pageCount {
- // let page = document?.page(at: i)
- // pages.append(page!)
- // indexs.insert(insertIndex)
- // insertIndex += 1
- // }
- // }
- // self.insertPagesForDescSort(pages: pages, indexs: indexs)
- //
- // if (self.lockedFiles.count <= 0) {
- // self.refreshUI()
- // return
- // }
- //
- // self.refreshUI()
- // self.showPasswordWindow(insertIndex)
- }
-
- func thumbnailView(thumbanView: KMPDFThumbnailView, didDragPages pages: [Int], indexpath: IndexPath) {
- let toIndex = max(0, indexpath.item)
- var indexs = IndexSet()
- for page in pages {
- indexs.insert(page)
- }
- self.dragPages(indexs, toIndex)
-
- if (pages.count > 0) {
- // 提醒外面文档已编辑
- if (self.documentEditedCallback != nil) {
- self.documentEditedCallback!()
- }
- }
- }
-
- // MARK: thumbanView layout
-
- func thumbnailView(thumbanView: KMPDFThumbnailView, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
- return 0.01
- }
-
- func thumbnailView(thumbanView: KMPDFThumbnailView, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
- return 0.01
- }
-
- func thumbnailView(thumbanView: KMPDFThumbnailView, insetForSectionAt section: Int) -> NSEdgeInsets {
- return NSEdgeInsets(top: 16, left: 16, bottom: 0, right: 32)
- }
-
- func thumbnailView(thumbanView: KMPDFThumbnailView, 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: KMPDFThumbnailView, itemForRepresentedObjectAt indexpath: IndexPath) -> NSCollectionViewItem {
- let cellView: KMPageEditThumbnailItem = thumbanView.collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMPageEditThumbnailItem"), for: indexpath) as! KMPageEditThumbnailItem
- cellView.isShowPageSize = self.thumbnailView.isShowPageSize
- cellView.page = self.thumbnailView.document.page(at: UInt(indexpath.item))
- cellView.setPage(page: self.thumbnailView.document.page(at: UInt(indexpath.item)))
-
- 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: -
- // MARK: 系统菜单栏
- extension KMPDFEditViewController: KMEditMenuProtocol {
- @IBAction func cut(_ sender: Any) {
- self.cutPages(with: self.thumbnailView.collectionView.selectionIndexes)
- }
-
- @IBAction func copy(_ sender: Any) {
- self.copyPages(with: self.thumbnailView.collectionView.selectionIndexes)
- }
-
- @IBAction func paste(_ sender: Any) {
- var index: Int = Int(self.thumbnailView.document.pageCount-1)
- let indexSet = self.thumbnailView.collectionView.selectionIndexes
- if (indexSet.isEmpty == false) {
- index = indexSet.last!
- }
-
- self.pastePages(at: index)
- }
-
- @IBAction func delete(_ sender: Any) {
- Task { @MainActor in
- if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
- let _ = KMComparativeTableViewController.show(window: self.view.window!)
- return
- }
-
- let selectedIndexs = self.thumbnailView.collectionView.selectionIndexPaths
- var indexs: IndexSet = IndexSet()
- for indexPath in selectedIndexs {
- indexs.insert(indexPath.item)
- }
- self.clearSelectPages()
- self.deletePages(indexs: indexs)
- }
- }
-
- @IBAction func undo(_ sender: Any) {
- if (self.undoRedoManager.canUndo) {
- self.undoRedoManager.undo()
- }
- }
-
- @IBAction func redo(_ sender: Any) {
- if (self.undoRedoManager.canRedo) {
- self.undoRedoManager.redo()
- }
- }
-
- }
|