123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562 |
- //
- // KMNThumbnailBaseViewController.swift
- // PDF Reader Pro
- //
- // Created by 丁林圭 on 2024/10/21.
- //
- import Cocoa
- @objc protocol KMNThumbnailBaseViewDelegate: AnyObject {
- @objc optional func clickThumbnailViewControlle(pageEditVC:KMNThumbnailBaseViewController?,currentIndex:Int)
-
- @objc optional func insertPDFThumbnailViewControlle(pageEditVC:KMNThumbnailBaseViewController?,pdfDocment:CPDFDocument?)
-
- @objc optional func changeIndexPathsThumbnailViewControlle(pageEditVC:KMNThumbnailBaseViewController?,selectionIndexPaths: Set<IndexPath>,selectionStrings:String )
- }
- enum KMNThumbnailChoosePageStyle: Int {
- case odd
- case even
- case horizontal
- case vertical
- case allPage
- case custom
- }
- internal let kmnThumLocalForDraggedTypes = NSPasteboard.PasteboardType(rawValue: "kmnThumLocalForDraggedTypes")
- let topThumOffset: CGFloat = 12.0 // 缩图顶部高度
- let infoThumTitleHeight: CGFloat = 16.0 //文字高度
- let infoThumTitleBottom: CGFloat = 16.0 // 底部高度
- class KMNThumbnailBaseViewController: KMNBaseViewController,NSCollectionViewDelegate, NSCollectionViewDataSource,NSCollectionViewDelegateFlowLayout {
- let maxCellHeight: CGFloat = 320.0 - infoThumTitleBottom - infoThumTitleHeight - topThumOffset * 2
- let minCellHeight: CGFloat = 80.0 - infoThumTitleBottom - infoThumTitleHeight - topThumOffset - topThumOffset * 2
- weak open var thumbnailBaseViewDelegate: KMNThumbnailBaseViewDelegate?
-
- @IBOutlet var backViewBox: NSBox!
- @IBOutlet var scrollView: NSScrollView!
- @IBOutlet var collectionView: KMNThumbnailCollectionView!
-
- private var currentDocument:CPDFDocument?
- private var isChangeIndexPaths = false
- var lockedFiles: [URL] = []
- internal var dragedIndexPaths: [IndexPath] = []
-
- public var thumbnails:[KMNThumbnail] = []
- public var dragLocalityPages: [CPDFPage] = []
- public var currentUndoManager:UndoManager?
-
- public var showDocument: CPDFDocument? {
- return currentDocument
- }
-
- public var changeDocument:CPDFDocument? {
- didSet {
- if(changeDocument != nil && changeDocument != currentDocument) {
- currentDocument = changeDocument
- refreshDatas()
- collectionView.reloadData()
- }
- }
- }
-
- public var thumbnailChoosePageStyle:KMNThumbnailChoosePageStyle = .custom {
- didSet {
- var tSelectionIndexPaths: Set<IndexPath> = []
- let pageCount = currentDocument?.pageCount ?? 0
- switch thumbnailChoosePageStyle {
- case .even:
- for i in 0 ..< pageCount {
- if(i % 2 == 0) {
- tSelectionIndexPaths.insert(IndexPath(item: Int(i), section: 0))
- }
- }
-
- case .odd:
- for i in 0 ..< pageCount {
- if(i % 2 != 0) {
- tSelectionIndexPaths.insert(IndexPath(item: Int(i), section: 0))
- }
- }
- case .allPage:
- for i in 0 ..< pageCount {
- tSelectionIndexPaths.insert(IndexPath(item: Int(i), section: 0))
-
- }
- case .vertical:
- for i in 0 ..< pageCount {
- let page = showDocument?.page(at: i)
- if(page != nil) {
- if(page!.rotation % 180 != 0) {
- tSelectionIndexPaths.insert(IndexPath(item: Int(i), section: 0))
- }
- }
- }
- case .horizontal:
- for i in 0 ..< pageCount {
- let page = showDocument?.page(at: i)
- if(page != nil) {
- if(page!.rotation % 180 == 0) {
- tSelectionIndexPaths.insert(IndexPath(item: Int(i), section: 0))
- }
- }
- }
- default: break
- }
-
- isChangeIndexPaths = true
- collectionView.selectionIndexPaths = tSelectionIndexPaths
- isChangeIndexPaths = false
- }
- }
-
- var selectionIndexPaths: Set<IndexPath> = [] {
- didSet {
- var indexpaths: Set<IndexPath> = []
- for indexpath in selectionIndexPaths {
- if (indexpath.section >= collectionView.numberOfSections) {
- continue
- }
- if indexpath.section < 0 {
- continue
- }
- if (indexpath.item >= collectionView.numberOfItems(inSection: indexpath.section)) {
- continue
- }
- if indexpath.item < 0 {
- continue
- }
-
- indexpaths.insert(indexpath)
- }
-
- collectionView.selectionIndexPaths = indexpaths
-
- if(indexpaths.count > 0) {
- let firstIndexPath = indexpaths.first
-
- let itemFrame = collectionView.frameForItem(at: firstIndexPath!.item)
- let itemFrameInCollectionView = collectionView.convert(itemFrame, to: self.view)
-
- if collectionView.bounds.contains(itemFrameInCollectionView) {
- } else {
- collectionView.scrollToItems(at: indexpaths, scrollPosition: .bottom)
- }
- }
- }
- }
-
- public var isShowPageSize:Bool = false {
- didSet {
- if oldValue != isShowPageSize {
- var pageSize = pageThumbnailSize
- if(isShowPageSize) {
- pageSize.height += infoThumTitleHeight
- } else {
- pageSize.height -= infoThumTitleHeight
-
- }
- pageThumbnailSize = pageSize
- collectionView.reloadData()
- }
- }
- }
-
- public var pageThumbnailSize:CGSize = CGSizeMake(185.0, 260) {
- didSet {
- collectionView.reloadData()
- }
- }
- public let defaultItemSize = NSMakeSize(185.0, 260)
-
- deinit {
- thumbnailBaseViewDelegate = nil
- KMPrint("KMNThumbnailBaseViewController deinit.")
- }
-
- init(_ document: CPDFDocument?) {
- super.init(nibName: "KMNThumbnailBaseViewController", bundle: nil)
- currentDocument = document
- }
-
- init(_ filePath: String,password:String?) {
- super.init(nibName: "KMNThumbnailBaseViewController", bundle: nil)
- let document = CPDFDocument.init(url: URL(fileURLWithPath: filePath))
- if password != nil {
- document?.unlock(withPassword: password as String?)
- }
-
- if document?.allowsCopying == false || document?.allowsPrinting == false {
- exitCurrentView()
- } else {
- currentDocument = document
- }
- }
-
- required init?(coder: NSCoder) {
- fatalError("init(coder:) has not been implemented")
- }
-
- override func viewDidLoad() {
- super.viewDidLoad()
-
- collectionView.delegate = self
- collectionView.dataSource = self
- collectionView.isSelectable = true //支持拖拽需设置未True
- collectionView.allowsMultipleSelection = true
- collectionView.enclosingScrollView?.hasVerticalScroller = false
- collectionView.enclosingScrollView?.hasHorizontalScroller = false
- scrollView.scrollerStyle = .overlay
-
- collectionView.register(KMNThumbnailCollectionViewItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier(rawValue: "thumbnailCollectionViewItem"))
-
- collectionView.registerForDraggedTypes([.fileURL,.string,.pdf])
- collectionView.setDraggingSourceOperationMask(.every, forLocal: false)
- collectionView.setDraggingSourceOperationMask(.every, forLocal: true)
- refreshDatas()
- }
-
- public func exitCurrentView() {
- let minIndexPath = selectionIndexPaths.max(by: { $0.item < $1.item })
- thumbnailBaseViewDelegate?.clickThumbnailViewControlle?(pageEditVC: self, currentIndex: minIndexPath?.item ?? 0)
- }
-
- public func supportDragFileTypes()->[String] {
- let supportFiles = KMNConvertTool.pdfExtensions + KMConvertPDFManager.supportFileType()
- return supportFiles
- }
-
- public func refreshDatas() {
- thumbnails = []
- if currentDocument != nil {
- for i in 0 ... currentDocument!.pageCount - 1 {
- let thumbnail = KMNThumbnail.init(document: currentDocument!, currentPageIndex: Int(i))
- thumbnails.append(thumbnail)
- }
- }
- }
-
- public func reloadDataDatas() {
- refreshDatas()
- collectionView.reloadData()
- }
-
- // MARK: - private
- public func clickMenu(point:NSPoint)->NSMenu {
- let copyPages: [CPDFPage] = KMNThumbnailManager.manager.copyPages
- let menu = NSMenu()
- // 根据 clickPoint 创建菜单项
- let copyMenuItem = NSMenuItem(title: KMLocalizedString("Copy"), action: #selector(copyMenuItemAciton), target: self)
- copyMenuItem.keyEquivalent = "c"
-
- let pastMenuItem = NSMenuItem(title: KMLocalizedString("Paste"), action: #selector(pastMenuItemAciton), target: self)
- pastMenuItem.representedObject = point
- pastMenuItem.keyEquivalent = "v"
-
- let pastNullMenuItem = NSMenuItem(title: KMLocalizedString("Paste"), action: nil, target: self)
- pastNullMenuItem.keyEquivalent = "v"
-
- let cutMenuItem = NSMenuItem(title: KMLocalizedString("Cut"), action: #selector(cutMenuItemAciton), target: self)
- cutMenuItem.keyEquivalent = "x"
-
- let deleteMenuItem = NSMenuItem(title: KMLocalizedString("Delete"), action: #selector(deleteMenuItemAciton), target: self)
- deleteMenuItem.keyEquivalent = String(Unicode.Scalar(NSBackspaceCharacter)!)
- let rotateLeftMenuItem = NSMenuItem(title: KMLocalizedString("90° CCW"), action: #selector(rotatePageLeftAction), target: self)
- rotateLeftMenuItem.keyEquivalent = "l" // 设置为字母 l
- rotateLeftMenuItem.keyEquivalentModifierMask = [.option, .command] // 设置为 Option + Command
- let rotateRightMenuItem = NSMenuItem(title: KMLocalizedString("90° CW"), action: #selector(rotatePageRightAction), target: self)
- rotateRightMenuItem.keyEquivalent = "r" // 设置为字母 r
- rotateRightMenuItem.keyEquivalentModifierMask = [.option, .command] // 设置为 Option + Command
- let insertFileMenuItem = NSMenuItem(title: KMLocalizedString("Insert File"), action: #selector(insertFromPDFAction), target: self)
- let insertBlankMenuItem = NSMenuItem(title: KMLocalizedString("Insert a Blank Page"), action: #selector(insertFromBlankAction), target: self)
-
- let replaceMenuItem = NSMenuItem(title: KMLocalizedString("Replace"), action: #selector(replacePDFAction), target: self)
-
- let extractMenuItem = NSMenuItem(title: KMLocalizedString("Export"), action: #selector(extractPDFAction), target: self)
-
- let shareMenuItem = NSMenuItem(title: KMLocalizedString("Share"), action: nil, target: self)
-
- shareMenuItem.submenu = NSSharingServicePicker.menu(forSharingItems: [showDocument?.documentURL ?? ""], subjectContext: "", withTarget: self, selector: #selector(sharePageItemAction), serviceDelegate: nil)
-
- let showFileSizeMenuItem = NSMenuItem(title: KMLocalizedString("Display Page Size"), action: #selector(displayPageSizeAction), target: self)
- showFileSizeMenuItem.state = isShowPageSize ? .on : .off
-
- let selectedIndexPaths = collectionView.selectionIndexPaths
- if(selectedIndexPaths.count > 0) {
- menu.addItem(copyMenuItem)
- menu.addItem(cutMenuItem)
- if(copyPages.count > 0) {
- menu.addItem(pastMenuItem)
- }
- menu.addItem(deleteMenuItem)
- menu.addItem(NSMenuItem.separator())
- menu.addItem(rotateRightMenuItem)
- menu.addItem(rotateLeftMenuItem)
- menu.addItem(NSMenuItem.separator())
- if(selectedIndexPaths.count == 1) {
- menu.addItem(insertFileMenuItem)
- menu.addItem(insertBlankMenuItem)
- menu.addItem(replaceMenuItem)
- }
- menu.addItem(extractMenuItem)
- menu.addItem(shareMenuItem)
- menu.addItem(NSMenuItem.separator())
- menu.addItem(showFileSizeMenuItem)
- } else {
- if(copyPages.count > 0) {
- menu.addItem(pastMenuItem)
- menu.addItem(NSMenuItem.separator())
- } else {
- menu.addItem(pastNullMenuItem)
- menu.addItem(NSMenuItem.separator())
- }
- menu.addItem(showFileSizeMenuItem)
- }
- return menu
- }
-
- // MARK: - NSCollectionViewDataSource
- func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
- return thumbnails.count
- }
-
- func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
- let item: KMNThumbnailCollectionViewItem = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "thumbnailCollectionViewItem"), for: indexPath) as! KMNThumbnailCollectionViewItem
- item.isShowFileSize = isShowPageSize
- item.doubleClickBack = { [weak self] in
- self?.thumbnailBaseViewDelegate?.clickThumbnailViewControlle?(pageEditVC: self, currentIndex: indexPath.item)
- }
-
- item.thumbnailMode = thumbnails[indexPath.item]
- return item
- }
-
- func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
- if isChangeIndexPaths == false {
- let indexpathsz = collectionView.selectionIndexPaths
- let dex:IndexSet = KMNTools.indexpathsToIndexs(indexpaths: indexpathsz)
- let selectedIndexPathsString = KMNTools.parseIndexSet(indexSet: dex)
-
- thumbnailBaseViewDelegate?.changeIndexPathsThumbnailViewControlle?(pageEditVC: self, selectionIndexPaths: indexpathsz, selectionStrings: selectedIndexPathsString)
- }
- }
-
- func collectionView(_ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set<IndexPath>) {
- if isChangeIndexPaths == false {
- let indexpathsz = self.collectionView.selectionIndexPaths
- let dex:IndexSet = KMNTools.indexpathsToIndexs(indexpaths: indexpathsz)
- let selectedIndexPathsString = KMNTools.parseIndexSet(indexSet: dex)
-
- thumbnailBaseViewDelegate?.changeIndexPathsThumbnailViewControlle?(pageEditVC: self, selectionIndexPaths: indexpathsz, selectionStrings: selectedIndexPathsString)
- }
- }
-
- // MARK: - NSCollectionViewDelegateFlowLayout
-
- func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
- return pageThumbnailSize
- }
-
- func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
- return 16.0
- }
-
- func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
- return 24.0
- }
-
- public func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, insetForSectionAt section: Int) -> NSEdgeInsets {
- return NSEdgeInsetsMake(24.0, 24.0, 24.0, 24.0)
- }
-
- //MARK: - NSCollectionViewDelegate
- func collectionView(_ collectionView: NSCollectionView,
- writeItemsAt indexPaths: Set<IndexPath>,
- to pasteboard: NSPasteboard) -> Bool {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- return false
- }
-
- var docmentName = currentDocument?.documentURL.lastPathComponent.deletingPathExtension ?? ""
- let pagesName = indexPaths.count > 1 ? " pages" : " page"
- var tFileName = pagesName + KMNTools.parseIndexPathsSet(indexSets: collectionView.selectionIndexPaths)
- if tFileName.count > 50 {
- tFileName = String(tFileName.prefix(50))
- }
-
- pasteboard.declareTypes([.fileURL], owner: self)
- let writePDFDocument = CPDFDocument()
-
- for indexPath in indexPaths {
- let row = indexPath.item
- if let copyPage = currentDocument?.page(at: UInt(row)) as? CPDFPage {
- writePDFDocument?.insertPageObject(copyPage, at: writePDFDocument?.pageCount ?? 0)
- }
- }
-
- var cachesDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
- cachesDir = cachesDir.appendingPathComponent("PageEdit_Pasteboard")
- let fileManager = FileManager.default
- if !fileManager.fileExists(atPath: cachesDir.path) {
- try? FileManager.default.createDirectory(atPath: cachesDir.path, withIntermediateDirectories: true, attributes: nil)
- }
- docmentName = "\(docmentName)\(tFileName)"
- if docmentName.count > 50 {
- docmentName = String(docmentName.prefix(50))
- }
-
- dragedIndexPaths.removeAll()
- for indexPath in indexPaths {
- dragedIndexPaths.append(indexPath)
- }
-
- let filePathURL = cachesDir.appendingPathComponent(docmentName).appendingPathExtension("pdf")
- let success = writePDFDocument?.write(to: filePathURL, isSaveFontSubset:false)
- if success == true {
- pasteboard.setPropertyList([filePathURL.path], forType: .fileURL)
- return true
- } else {
- return false
- }
- }
-
- func collectionView(_ collectionView: NSCollectionView,
- draggingSession session: NSDraggingSession,
- willBeginAt screenPoint: NSPoint,
- forItemsAt indexPaths: Set<IndexPath>) {
- let sortedIndexPaths = indexPaths.sorted { (ip1, ip2) -> Bool in
- if ip1.section == ip2.section {
- return ip1.item < ip2.item
- }
- return ip1.section < ip2.section
- }
- dragLocalityPages = []
- for fromIndexPath in sortedIndexPaths {
- let page = thumbnails[fromIndexPath.item].thumbnaiPage
- if(page != nil) {
- dragLocalityPages.append(page!)
- }
- }
- }
-
- func collectionView(_ collectionView: NSCollectionView, validateDrop draggingInfo: NSDraggingInfo, proposedIndexPath proposedDropIndexPath: AutoreleasingUnsafeMutablePointer<NSIndexPath>, dropOperation proposedDropOperation: UnsafeMutablePointer<NSCollectionView.DropOperation>) -> NSDragOperation {
- let pboard = draggingInfo.draggingPasteboard
-
- if dragLocalityPages.count != 0 {
- if proposedDropOperation.pointee == .on {
- proposedDropOperation.pointee = .before
- }
- return .move
- } else if ((pboard.availableType(from: [.fileURL])) != nil) {
- guard let pbItems = pboard.pasteboardItems else {
- return NSDragOperation(rawValue: 0)
- }
-
- var hasValidFile = false
- for item in pbItems {
- guard let data = item.string(forType: .fileURL), let url = URL(string: data) else {
- continue
- }
- let type = url.pathExtension.lowercased()
- if (supportDragFileTypes().contains(type)) {
- hasValidFile = true
- break
- }
- }
-
- if (!hasValidFile) {
- return NSDragOperation(rawValue: 0)
- }
- }
- return .copy
- }
-
- func collectionView(_ collectionView: NSCollectionView,
- acceptDrop draggingInfo: NSDraggingInfo,
- indexPath: IndexPath,
- dropOperation: NSCollectionView.DropOperation) -> Bool {
- let pboard = draggingInfo.draggingPasteboard
- if dragLocalityPages.count != 0 {
- movePages(pages: dragLocalityPages, destinationDex: indexPath.item)
- return true
- } else if ((pboard.availableType(from: [.fileURL])) != nil) {
- let index = indexPath.item
-
- guard let pbItems = pboard.pasteboardItems else {
- return false
- }
-
- //获取url
- var fileNames: [String] = []
- for item in pbItems {
- guard let data = item.string(forType: .fileURL), let url = URL(string: data) else {
- continue
- }
- let type = url.pathExtension.lowercased()
- if (supportDragFileTypes().contains(type)) {
- if(FileManager.default.fileExists(atPath: url.path)) {
- fileNames.append(url.path)
- }
- }
- }
- if(fileNames.count > 0) {
- insertFromFilePath(fileNames: fileNames, formDex: 0, indexDex: UInt(index), selectIndexs: []) { newSelectIndexs in
- }
-
- return true
- }
- }
- return false
- }
-
- func collectionView(_ collectionView: NSCollectionView,
- draggingSession session: NSDraggingSession,
- endedAt screenPoint: NSPoint,
- dragOperation operation: NSDragOperation) {
- dragLocalityPages = []
- }
- }
- // MARK: - NSFilePromiseProviderDelegate
- //extension KMNThumbnailBaseViewController: NSFilePromiseProviderDelegate {
- // func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, writePromiseTo url: URL, completionHandler: @escaping (Error?) -> Void) {
- //
- // }
- //
- // func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, writePromiseTo url: URL) async throws {
- //
- // }
- //
- // func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, fileNameForType fileType: String) -> String {
- // var fileName: String = "Untitle"
- // if let _string = showDocument?.documentURL.deletingPathExtension().lastPathComponent {
- // fileName = _string
- // }
- // fileName.append(" pages")
- // var indexs = IndexSet()
- // for indexpath in self.dragedIndexPaths {
- // indexs.insert(indexpath.item)
- // }
- // fileName.append(" ")
- // fileName.append(KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs.sorted()))
- // fileName.append(".pdf")
- //
- // return fileName
- // }
- //
- //}
|