12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226 |
- //
- // KMBatchOperateLeftViewController.swift
- // PDF Reader Pro
- //
- // Created by kdanmobile on 2023/10/26.
- //
- import Cocoa
- import KMComponentLibrary
- let KMBatchDragType = "KMBatchDragType"
- class KMBatchOperateLeftViewController: KMNBaseViewController {
- @IBOutlet var selectFileButton: KMLongerButton!
- @IBOutlet var deleteFileButton: NSButton!
- @IBOutlet var tableView: NSTableView!
- @IBOutlet var indexTableColumn: NSTableColumn!
- @IBOutlet var fileNameTableColumn: NSTableColumn!
- @IBOutlet var pageRangeTableColumn: NSTableColumn!
- @IBOutlet var sizeTableColumn: NSTableColumn!
- @IBOutlet var stateTableColumn: NSTableColumn!
- @IBOutlet var DPIColumn: NSTableColumn!
- @IBOutlet var dimensionsTableColumn: NSTableColumn!
- @IBOutlet var headerOperateView: NSView!
- @IBOutlet var showInFinderMenuItem: NSMenuItem!
- @IBOutlet var deleteMenuItem: NSMenuItem!
- @IBOutlet var blankView: KMBlankView!
-
- var files: [KMBatchOperateFile] = []
- var type: KMBatchOperationType?
- var lockFilePathArr: NSMutableArray?
- var lockFileIndex: Int = 0
- var popOver: NSPopover?
- var progressInt: Int = 0
-
- private var addFileButton_: ComponentDropdown?
- private var deleteButton_: ComponentButton?
- private var groupView_: ComponentGroup?
- private var emptyViewTopLine: NSView = {
- let view = NSView()
- view.wantsLayer = true
- return view
- }()
- private var emptyView_: ComponentEmpty = {
- let view = ComponentEmpty()
- view.properties = ComponentEmptyProperty(emptyType: .add_File, state: .normal, image: NSImage(named: "KMEmptyIcon"), text: KMLocalizedString("Select Files"), subText: KMLocalizedString("Drop files here or Click Add Files at upper left corner. You can drag files to reorder as you need."))
- return view
- }()
-
- private var dividerColor_: NSColor?
-
- private var isSizeAsc_ = false
- private var dimensionsAsc_ = false
- private var fileNameAsc_ = false
-
- deinit {
- DistributedNotificationCenter.default().removeObserver(self)
- }
- override func viewDidLoad() {
- super.viewDidLoad()
-
- for i in 0..<self.tableView.tableColumns.count {
- let column = self.tableView.tableColumns[i]
- column.headerCell = KMTableHeaderCell(textCell: column.title)
- }
-
- self.deleteFileButton.addHoverEffect = true
-
- self.indexTableColumn.resizingMask = []
- self.fileNameTableColumn.resizingMask = .autoresizingMask
- self.pageRangeTableColumn.resizingMask = []
- self.sizeTableColumn.resizingMask = []
- self.stateTableColumn.resizingMask = []
- self.DPIColumn.resizingMask = []
- self.dimensionsTableColumn.resizingMask = []
- self.tableView.moveColumn(5, toColumn: 2)
-
- self.indexTableColumn.title = " \(KMLocalizedString("Index", comment: ""))"
- self.fileNameTableColumn.title = KMLocalizedString("File Name", comment: "")
- self.pageRangeTableColumn.title = KMLocalizedString("Page Range", comment: "")
- self.sizeTableColumn.title = KMLocalizedString("Size", comment: "")
- self.stateTableColumn.title = KMLocalizedString("Status", comment: "")
- self.DPIColumn.title = KMLocalizedString("DPI", comment: "")
- self.dimensionsTableColumn.title = KMLocalizedString("Dimensions", comment: "")
-
- self.DPIColumn.isHidden = true
- self.tableView.intercellSpacing = CGSize(width: 0, height: 0)
- self.tableView.allowsColumnReordering = false
- self.tableView.allowsMultipleSelection = true
- self.tableView.enclosingScrollView?.borderType = .noBorder
-
- self.headerOperateView.wantsLayer = true
-
- self.tableView.registerForDraggedTypes([NSPasteboard.PasteboardType.string,NSPasteboard.PasteboardType.fileURL, NSPasteboard.PasteboardType(KMBatchDragType)])
- self.lockFilePathArr = NSMutableArray()
- self.lockFileIndex = 0
- self.progressInt = 0
-
- selectFileButton.title = ""
- addFileButton_ = ComponentDropdown()
- addFileButton_?.properties = ComponentDropdownProperty(type: .split_graySecondary, size: .s, split: true, text: KMLocalizedString("Add Files..."))
- // addFileButton_?.splitRightButton.properties.icon = NSImage(named: "ImageToPDFDropdownButtonIcon")
-
- selectFileButton.addSubview(addFileButton_!)
- addFileButton_?.frame = selectFileButton.bounds
- addFileButton_?.autoresizingMask = [.width, .height]
- addFileButton_?.componentDelegate = self
-
- deleteButton_ = ComponentButton()
- deleteButton_?.properties = ComponentButtonProperty(type: .text_gray_low, size: .s, state: .normal, onlyIcon: true)
- deleteButton_?.setTarget(self, action: #selector(buttonClicked_DeleteFile))
- deleteFileButton.image = nil
- deleteFileButton.addSubview(deleteButton_!)
- deleteButton_?.frame = deleteFileButton.bounds
- deleteButton_?.autoresizingMask = [.width, .height]
- deleteButton_?.properties.propertyInfo.leftIcon_nor = NSImage(named: "KMImageNameDeleteFileIcon")
- deleteButton_?.setTarget(self, action: #selector(buttonClicked_DeleteFile))
-
- tableView.headerView = nil
-
- self.showInFinderMenuItem.title = KMLocalizedString("Show in Finder", comment: "")
- self.deleteMenuItem.title = KMLocalizedString("Delete", comment: "")
- self.blankView.wantsLayer = true
- self.blankView.layer?.backgroundColor = NSColor.clear.cgColor
- self.blankView.titleLabel.stringValue = ""
- self.blankView.imageView.isHidden = true
- self.blankView.addButton.isHidden = true
- self.blankView.secondTitleLabel.stringValue = ""
- self.blankView.mouseActionCallBack = { [weak self] mouseType in
- if mouseType == .mouseDown {
- self?.chooseFile()
- }
- }
- self.blankView.addSubview(emptyView_)
-
- blankView.addSubview(emptyViewTopLine)
- emptyViewTopLine.km_add_top_constraint(constant: 4)
- emptyViewTopLine.km_add_left_constraint(constant: 24)
- emptyViewTopLine.km_add_right_constraint(constant: -24)
- emptyViewTopLine.km_add_height_constraint(constant: 1)
- emptyViewTopLine.wantsLayer = true
- let dividerColor = ComponentLibrary.shared.getComponentColorFromKey("colorBorder/divider")
- emptyViewTopLine.layer?.backgroundColor = dividerColor.cgColor
-
- emptyView_.km_add_top_constraint(constant: 96)
- emptyView_.km_add_bottom_constraint()
- emptyView_.km_add_leading_constraint()
- emptyView_.km_add_trailing_constraint()
- emptyView_.setTarget(self, action: #selector(emptyAddFileAction))
- }
-
- override func addNotifations() {
- super.addNotifations()
-
- NotificationCenter.default.addObserver(self.tableView!, selector: #selector(self.reloadData), name: NSNotification.Name(kNeedChangePageRangeNotification), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(imageToPDFSuccessNotification(aNotification:)), name: NSNotification.Name("KMBatchOperateImageToPDFSuccessNotification"), object: nil)
- }
-
- override func updateUILanguage() {
- super.updateUILanguage()
-
- KMMainThreadExecute {
- self.addFileButton_?.properties.text = KMLocalizedString("Add Files...")
- self.addFileButton_?.reloadData()
-
- self.tableView.reloadData()
- }
- }
-
- override func updateUIThemeColor() {
- super.updateUIThemeColor()
-
- self.dividerColor_ = ComponentLibrary.shared.getComponentColorFromKey("colorBorder/divider")
-
- KMMainThreadExecute {
- self.updateViewColor()
-
- self.tableView.reloadData()
- }
- }
-
- @objc func reloadData() {
- if Thread.isMainThread {
- tableView.reloadData()
- } else {
- DispatchQueue.main.async {
- self.tableView.reloadData()
- }
- }
- }
-
- @objc func imageToPDFSuccessNotification(aNotification: Notification) {
- guard let dict = aNotification.userInfo, let isSuccess = dict["isSuccess"] as? Bool else { return }
- if isSuccess {
- progressInt = 1
- } else {
- progressInt = -1
- }
-
- DispatchQueue.main.async {
- self.tableView.reloadData()
- }
- }
-
- func updateViewColor() {
- self.view.wantsLayer = true
- if KMAppearance.isDarkMode() {
- let color = ComponentLibrary.shared.getComponentColorFromKey("colorBg/layout-low")
- view.layer?.backgroundColor = color.cgColor
- } else {
- view.layer?.backgroundColor = .white
- }
- }
-
- func chooseFile() {
- #if VERSION_FREE
- if !IAPProductsManager.default().isAvailableAllFunction() {
- if files.count >= 1 {
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- if type == .CreatePDF {
- winC?.kEventName = "Onbrd_ImagetoPDF_BuyNow"
- }
- winC?.showWindow(nil)
- return
- }
- }
- #endif
- self.progressInt = 0
- let panel = NSOpenPanel()
- if type == .CreatePDF {
- panel.allowedFileTypes = KMImageToPDFMethod.supportedImageTypes()
- } else {
- panel.allowedFileTypes = ["pdf", "PDF"]
- }
- if IAPProductsManager.default().isAvailableAllFunction() {
- panel.allowsMultipleSelection = true
- panel.canChooseDirectories = true
- }
- panel.canChooseFiles = true
- #if VERSION_FREE
- #else
- panel.message = KMLocalizedString("To select multiple files press cmd ⌘ button on keyboard and click on the target files one by one.", comment: "")
- #endif
- panel.beginSheetModal(for: self.view.window!) {
- (result) in
- if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
- let addArray = NSMutableArray()
- for fileURL in panel.urls {
- let filePath = fileURL.path
- var isDirectory = ObjCBool(false)
- FileManager.default.fileExists(atPath: filePath, isDirectory: &isDirectory)
- if isDirectory.boolValue {
- let containFiles = self.fetchAvailableFiles(in: filePath)
- addArray.addObjects(from: containFiles)
- } else {
-
- let typeIdentifier =
- UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, filePath.customPathExtension as CFString, nil)
- let TypeCFString = typeIdentifier!.takeRetainedValue() as String
- if self.type == .CreatePDF {
- if UTTypeConformsTo(TypeCFString as CFString, kUTTypeImage) {
- addArray.add(filePath)
- }
- } else {
- if UTTypeConformsTo(TypeCFString as CFString, kUTTypePDF) {
- addArray.add(filePath)
- }
- }
- }
- }
- self.addFilesToList(addArray: addArray)
- }
- }
- }
- func fetchAvailableFiles(in folderPath: String) -> [String] {
- let array = NSMutableArray()
- let subFileArray = (FileManager.default.subpaths(atPath: folderPath)! as NSArray).mutableCopy() as? NSMutableArray
- for i in 0..<subFileArray!.count {
- if let path = (folderPath as NSString).appendingPathComponent(subFileArray!.object(at: i) as! String) as String? {
- if let UTTypeString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, path.customPathExtension as CFString, nil)?.takeRetainedValue() as String? {
- let TypeCFString = UTTypeString as CFString
- if self.type == .CreatePDF {
- if UTTypeConformsTo(TypeCFString, kUTTypeImage) {
- array.add(path)
- }
- } else {
- if UTTypeConformsTo(TypeCFString, kUTTypePDF) {
- array.add(path)
- }
- }
- }
- }
- }
- return array as! [String]
- }
- func addFilesToList(addArray: NSMutableArray) {
- self.lockFilePathArr!.removeAllObjects()
- self.lockFileIndex = 0
- for i in 0..<addArray.count {
- let filePath = addArray[i] as! String
- let UTTypeString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, filePath.customPathExtension as CFString, nil)!.takeRetainedValue() as String
- let TypeCFString = UTTypeString as CFString
- if UTTypeConformsTo(TypeCFString, kUTTypePDF) {
- let document = CPDFDocument(url: URL(fileURLWithPath: filePath))
- if document?.isLocked == true {
- var isContaint = false
- for file in self.files {
- if (file as AnyObject).filePath == filePath {
- isContaint = true
- break
- }
- }
- if !isContaint {
- self.lockFilePathArr!.add(filePath)
- }
- } else {
- let file = KMBatchOperateFile(filePath: addArray[i] as! String, type: self.type!)
- if !self.files.contains(file) {
- self.files.append(file)
- }
- }
- } else {
- let file = KMBatchOperateFile(filePath: addArray[i] as! String, type: self.type!)
- if !self.files.contains(file) {
- self.files.append(file)
- }
- }
- }
- self.tableView.reloadData()
- if self.lockFilePathArr!.count > 0 {
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
- self.openPasswordWindow()
- }
- }
- }
-
- func openPasswordWindow() {
- if lockFilePathArr!.count > lockFileIndex {
- let filePath = lockFilePathArr![lockFileIndex] as! String
- KMBaseWindowController.checkPassword(url: URL(fileURLWithPath: filePath), type: .owner) { [unowned self] success, resultPassword in
- self.closePwd()
- if !resultPassword.isEmpty {
- let file = KMBatchOperateFile(filePath: filePath, type: self.type!)
- file.password = resultPassword
- self.files.append(file)
- self.tableView.reloadData()
- }
- self.lockFileIndex += 1
- if self.lockFilePathArr?.count ?? 0 > self.lockFileIndex {
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
- self.openPasswordWindow()
- }
- } else {
- self.tableView.reloadData()
- }
- }
- }
- }
-
- func closePwd() {
- self.km_endSheet()
- }
-
- // MARK: - Actions
-
- func chooseFileFromCamera() {
- self.progressInt = 0
- let vc = KMDeviceBrowserWindowController.shared
- vc.type = .camera
- vc.importCameraFileCallback = { [weak self](url: NSURL) -> Void in
- self?.addFilesToList(addArray: [url.path!])
- }
- vc.showWindow(nil)
- }
- func chooseFileFromScanner() {
- self.progressInt = 0
- let vc = KMDeviceBrowserWindowController.shared
- vc.type = .scanner
- vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
- self?.addFilesToList(addArray: [url.path!])
- }
- vc.showWindow(nil)
- }
-
-
- @IBAction func blankViewAddFileAction(_ sender: Any) {
- self.chooseFile()
- }
-
- @IBAction func buttonClicked_DeleteFile(_ sender: Any) {
- let set = self.tableView.selectedRowIndexes
- let newArr: NSMutableArray = NSMutableArray.init(array: self.files)
- let arr = newArr.objects(at: set)
- if arr.count > 0 {
- newArr.removeObjects(in: arr)
- self.files = newArr as! [KMBatchOperateFile]
- self.tableView.reloadData()
- } else {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = KMLocalizedString("Clear All Recents", comment: "")+"?"
- alert.addButton(withTitle: KMLocalizedString("Delete", comment: ""))
- alert.addButton(withTitle: KMLocalizedString("Cancel", comment: ""))
- alert.beginSheetModal(for: self.view.window!) {[weak self] response in
- if response == NSApplication.ModalResponse.alertFirstButtonReturn {
- self?.files.removeAll()
- self?.tableView.reloadData()
- }
- }
- }
- }
- func fetchAvailableFilesInFolder(_ folderPath: String) -> [String] {
- var array: [String] = []
- let subFileArray = FileManager().subpaths(atPath: folderPath)
- for i in 0..<subFileArray!.count {
- let path = folderPath.stringByAppendingPathComponent(subFileArray![i])
- let TypeCFString = KMTools.UTIforFileExtension(path.customPathExtension) as CFString
- if self.type == .CreatePDF {
- if UTTypeConformsTo(TypeCFString, kUTTypeImage) {
- array.append(path)
- }
- } else {
- if UTTypeConformsTo(TypeCFString, kUTTypePDF) {
- array.append(path)
- }
- }
- }
- return array
- }
- func folderContainAvailableFile(_ folderPath: String) -> Bool {
- var containFile = false
- guard let subFileArray = FileManager.default.subpaths(atPath: folderPath) else {
- return containFile
- }
- for i in 0..<subFileArray.count {
- let path = folderPath.stringByAppendingPathComponent(subFileArray[i] )
- let TypeCFString = KMTools.UTIforFileExtension(path.customPathExtension) as CFString
- if type == .CreatePDF {
- if UTTypeConformsTo(TypeCFString, kUTTypeImage) {
- containFile = true
- }
- } else {
- if UTTypeConformsTo(TypeCFString, kUTTypePDF) {
- containFile = true
- }
- }
- if containFile {
- break
- }
- }
- return containFile
- }
-
- func switchToOperateType(_ type: KMBatchOperationType) {
- self.type = type
- self.indexTableColumn.isHidden = false
- self.fileNameTableColumn.isHidden = false
- self.pageRangeTableColumn.isHidden = false
- self.sizeTableColumn.isHidden = false
- self.stateTableColumn.isHidden = false
- self.DPIColumn.isHidden = true
- self.dimensionsTableColumn.isHidden = true
- if type == .Compress || type == .AddPassword || type == .RemovePassword || type == .RemoveWatermark || type == .RemoveBackground || type == .RemoveHeaderFooter || type == .RemoveBates || type == .CreatePDF {
- self.pageRangeTableColumn.isHidden = true
- } else {
- self.pageRangeTableColumn.isHidden = false
- }
-
- self.selectFileButton.isImageToPDF = type == .CreatePDF
- if type == .CreatePDF {
- self.pageRangeTableColumn.isHidden = false
- self.pageRangeTableColumn.title = KMLocalizedString("Dimensions", comment: "")
- }
-
- for i in 0..<self.files.count {
- let file = self.files[i]
- file.currentOperateType = type
- }
- self.tableView.sizeToFit()
- self.tableView.reloadData()
- }
-
- @IBAction func menuItem_ShowInFinder(_ sender: Any) {
- let row = self.tableView.clickedRow
- let file: KMBatchOperateFile = self.files[row]
- if file.currentOperateInfo?.status == .Success {
- NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: file.currentOperateInfo!.outPutPath!)])
- }else {
- NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: file.filePath)])
- }
- }
-
- @IBAction func menuItem_Delete(_ sender: Any) {
- let row = self.tableView.clickedRow
- self.files.remove(at: row)
- self.tableView.reloadData()
- }
-
-
- func addOpendFile() {
- let documentArray = NSDocumentController.shared.documents
- var pdfArray = NSMutableArray()
- for i in 0..<documentArray.count {
- let document = documentArray[i]
- let path: String = document.fileURL?.path ?? ""
- let UTTypeString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, path.customPathExtension as CFString, nil)?.takeRetainedValue() as String?
- let TypeCFString = UTTypeString as CFString?
- if UTTypeConformsTo(TypeCFString!, kUTTypePDF) {
- pdfArray.add(path as Any)
- }
- }
- if !IAPProductsManager.default().isAvailableAllFunction() {
- if self.files.count < 1 {
- pdfArray = NSMutableArray(array: [pdfArray.firstObject as Any])
- } else {
- KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
- return
- }
- }
- addFilesToList(addArray: pdfArray)
- }
-
- @objc func emptyAddFileAction() {
- self.chooseFile()
- }
-
- //MARK: - GroupView
-
- func showGroupView() {
- var viewHeight: CGFloat = 8
- var menuItemArr: [ComponentMenuitemProperty] = []
- for i in ["Add Files...", "Add Folder...", "Import from Clipboard...", "Import from Scanner..."] {
- let properties_Menuitem: ComponentMenuitemProperty = ComponentMenuitemProperty(multipleSelect: false,
- itemSelected: false,
- isDisabled: false,
- keyEquivalent: nil,
- text: KMLocalizedString(i))
- menuItemArr.append(properties_Menuitem)
- viewHeight += 36
- }
-
- if groupView_ == nil {
- groupView_ = ComponentGroup.createFromNib(in: ComponentLibrary.shared.componentBundle())
- }
- groupView_?.groupDelegate = self
- groupView_?.frame = CGRectMake(310, 0, 200, viewHeight)
- groupView_?.updateGroupInfo(menuItemArr)
-
- var point = addFileButton_?.convert(addFileButton_!.frame.origin, to: nil) ?? .zero
- point.y -= viewHeight
- groupView_?.showWithPoint(point, relativeTo: addFileButton_)
-
- addFileButton_?.properties.state = .pressed
- addFileButton_?.reloadData()
- }
-
- func removeGroupView() {
- if groupView_ != nil {
- groupView_?.removeFromSuperview()
- }
- addFileButton_?.properties.state = .normal
- addFileButton_?.reloadData()
- }
-
- func openDocumentWithImageFromPasteboard(_ pboard: NSPasteboard, error outError: AutoreleasingUnsafeMutablePointer<NSError?>?) -> CPDFDocument? {
- var document: CPDFDocument? = nil
- var data: Data? = nil
-
- if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.pdf.rawValue]) {
- data = pboard.data(forType: NSPasteboard.PasteboardType.pdf)
- } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.postScript.rawValue]) {
- data = pboard.data(forType: NSPasteboard.PasteboardType.postScript)
- } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.tiff.rawValue]) {
- data = convertTIFFDataToPDF(pboard.data(forType: NSPasteboard.PasteboardType.tiff) ?? Data())
- } else {
- let images = pboard.readObjects(forClasses: [NSImage.self], options: [:])
- let strings = pboard.readObjects(forClasses: [NSAttributedString.self], options: [:])
- if images?.count ?? 0 > 0 {
- data = convertTIFFDataToPDF((images![0] as AnyObject).tiffRepresentation!)
- } else if strings?.count ?? 0 > 0 {
- data = KMOCTool.convertStringsToPDF(withString: strings ?? [""]) // convertStringsToPDF(strings!)
- }
- }
-
- if let data = data {
- document = CPDFDocument(data: data)
-
- } else if let outError = outError {
- outError.pointee = NSError(domain: "SKDocumentErrorDomain", code: 3, userInfo: [NSLocalizedDescriptionKey: KMLocalizedString("Unable to load data from clipboard", comment: "Error description")])
- }
-
- return document
- }
-
- func convertTIFFDataToPDF(_ tiffData: Data) -> Data? {
- guard let imsrc = CGImageSourceCreateWithData(tiffData as CFData, [kCGImageSourceTypeIdentifierHint: kUTTypeTIFF] as CFDictionary), CGImageSourceGetCount(imsrc) > 0, let cgImage = CGImageSourceCreateImageAtIndex(imsrc, 0, nil) else { return nil }
- let pdfData = NSMutableData(capacity: tiffData.count)
- let consumer = CGDataConsumer(data: pdfData! as CFMutableData)!
-
- var rect = CGRect(x: 0, y: 0, width: CGFloat(cgImage.width), height: CGFloat(cgImage.height))
- let ctxt = CGContext(consumer: consumer, mediaBox: &rect, nil)
- ctxt!.beginPDFPage(nil)
- ctxt!.draw(cgImage, in: rect)
- ctxt!.endPDFPage()
- ctxt!.closePDF()
-
- return pdfData as? Data
- }
-
- // MARK: - Private Methods
-
- private func _saveImagePath() -> String {
- let rootPath = KMDataManager.fetchAppSupportOfBundleIdentifierDirectory()
- let path = rootPath.appendingPathComponent("ImageToPDF").path
- if FileManager.default.fileExists(atPath: path) == false {
- try?FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: false)
- }
- return path
- }
-
- private func _clearImageData() {
- let path = self._saveImagePath()
- if FileManager.default.fileExists(atPath: path) {
- try?FileManager.default.removeItem(atPath: path)
- }
- }
-
- private func _initHeaderCellView(cellView: KMNTableHeaderCellView) {
- var dividerColor = self.dividerColor_
- if dividerColor == nil {
- dividerColor = ComponentLibrary.shared.getComponentColorFromKey("colorBorder/divider")
- }
-
- cellView.leftLine.wantsLayer = true
- cellView.leftLine.layer?.backgroundColor = dividerColor?.cgColor ?? .black
- cellView.rightLine.wantsLayer = true
- cellView.rightLine.layer?.backgroundColor = dividerColor?.cgColor ?? .black
- cellView.bottomLine.wantsLayer = true
- cellView.bottomLine.layer?.backgroundColor = dividerColor?.cgColor ?? .black
- }
-
- private func _addFolderAction() {
- let openPanel = NSOpenPanel()
- // openPanel.title = NSLocalizedString("选择并合并文件。按下键盘上的命令按钮,逐次点击目标文件,即可选择多个文件", comment: "")
- openPanel.canChooseDirectories = true
- openPanel.canChooseFiles = false
- openPanel.allowsMultipleSelection = true
-
- openPanel.beginSheetModal(for: view.window!, completionHandler: { [self] result in
- if result != .OK {
-
- } else {
- var result: [URL] = []
- for folderURL in openPanel.urls {
- _findAllFiles(folder: folderURL, result: &result)
- }
-
- var paths: [String] = []
- for url in result {
- paths.append(url.path)
- }
- self.addFilesToList(addArray: NSMutableArray(array: paths))
- }
- })
- }
-
- private func _findAllFiles(folder: URL, result: inout [URL]) {
- let fileManager = FileManager.default
- var isDirectory: ObjCBool = ObjCBool(false)
- fileManager.fileExists(atPath: folder.path, isDirectory: &isDirectory)
- if (!isDirectory.boolValue) {
- return
- }
-
- let contents = try?fileManager.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)
- if contents?.count == 0 {
- return
- }
-
- let array = ["jpg","cur","bmp","jpeg","gif","png","tiff","tif","ico","icns","tga","psd","eps","hdr","jp2","jpc","pict","sgi","heic"]
- for documentURL in contents! {
- var isDirectory: ObjCBool = ObjCBool(false)
- fileManager.fileExists(atPath: documentURL.path, isDirectory: &isDirectory)
- if (isDirectory.boolValue) {
- _findAllFiles(folder: documentURL, result: &result)
- } else {
- if !array.contains(documentURL.pathExtension.lowercased()) {
- continue
- }
-
- result.append(documentURL)
- }
- }
- }
-
- func switchToOperateType(_ operateType: KMBatchOperationType, files: [KMBatchOperateFile]) {
- switchToOperateType(operateType)
- self.files = files
- self.tableView.reloadData()
- }
- func checkNeedPasswordSwitchToOperateType(_ operateType: KMBatchOperationType, files: [KMBatchOperateFile]) {
- switchToOperateType(operateType)
- var arr: [String] = []
- for i in 0..<files.count {
- let file = files[i]
- arr.append(file.filePath)
- }
-
- self.files = files
- self.files.removeAll()
- addFilesToList(addArray: NSMutableArray.init(array: arr))
- self.tableView.reloadData()
- }
- func reloadFile(_ file: KMBatchOperateFile) {
- var rowIndexSet = IndexSet()
- for i in 0..<self.files.count {
- if file.filePath == self.files[i].filePath {
- rowIndexSet.insert(i)
- break
- }
- }
- var columnIndexSet = IndexSet()
- for i in 0..<self.tableView.numberOfColumns {
- let identifier = self.tableView.tableColumns[i].identifier
- if identifier.rawValue == "status" {
- columnIndexSet.insert(i)
- break
- }
- }
-
- if Thread.isMainThread {
- self.tableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: columnIndexSet)
- } else {
- DispatchQueue.main.async {
- self.tableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: columnIndexSet)
- }
- }
- }
- func refreshConvertProgress(_ progress: CGFloat, file: KMBatchOperateFile) {
- self.tableView.reloadData()
- }
- func reloadConvertInterface(withType type: KMConvertWithPDFType) {
- if type == .WordAdvance || type == .WordStandard || type == .Excel || type == .PowerPoint || type == .RTF || type == .CSV || type == .HTML || type == .Text || type == .Json {
- self.DPIColumn.isHidden = true
- } else {
- self.DPIColumn.isHidden = false
- }
- self.tableView.reloadData()
- }
- }
- // MARK: - NSTableViewDelegate,NSTableViewDataSource
- extension KMBatchOperateLeftViewController: NSTableViewDelegate,NSTableViewDataSource {
- func numberOfRows(in tableView: NSTableView) -> Int {
- NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMBatchFilesCountNotification"), object: self.files, userInfo: [kObjectKey : self])
- self.deleteFileButton.isEnabled = self.files.count > 0
- deleteButton_?.properties.isDisabled = self.files.count <= 0
- self.blankView.isHidden = self.files.count > 0
- if self.files.count == 0 {
- return 0
- }
- return self.files.count + 1;
- }
-
- func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
- let identifier = tableColumn?.identifier
-
- let rowIdx = max(0, row-1)
- let file = self.files[rowIdx]
-
- let cellColor = ComponentLibrary.shared.getComponentColorFromKey("olorFill/4")
- let titleFont = ComponentLibrary.shared.getFontFromKey("mac/body-s-medium")
- let titleColor = ComponentLibrary.shared.getComponentColorFromKey("colorText/1")
-
- if identifier?.rawValue == "index" {
- if row == 0 {
- let cellView = KMNTableHeaderCellView()
- cellView.wantsLayer = true
- cellView.layer?.backgroundColor = cellColor.cgColor
- // cellView.layer?.backgroundColor = NSColor(hex: "#F6F6F8").cgColor
- cellView.titleLabel.stringValue = KMLocalizedString("")
-
- _initHeaderCellView(cellView: cellView)
- return cellView
- }
- let cellView = KMBatchTableCellView(type: .Size)
- _ = row + 1
- cellView.textField?.stringValue = String(format: "%d", row);
- return cellView;
- } else if identifier?.rawValue == "pageRange"{
- if (file.currentOperateType == .CreatePDF) {
- if row == 0 {
- let cellView = KMNTableHeaderCellView()
- cellView.wantsLayer = true
- cellView.layer?.backgroundColor = cellColor.cgColor
-
- cellView.titleLabel.stringValue = KMLocalizedString("Dimensions")
- cellView.titleLabel.font = titleFont
- cellView.titleLabel.textColor = titleColor
- _initHeaderCellView(cellView: cellView)
- cellView.itemClick = { [weak self] idx, _ in
- if idx == 1 { // 排序
- let asc = self?.dimensionsAsc_ ?? false
- if asc {
- self?.files.sort(){$0.dimensions > $1.dimensions}
- } else {
- self?.files.sort(){$0.dimensions <= $1.dimensions}
- }
- self?.dimensionsAsc_ = !asc
- self?.reloadData()
- }
- }
- return cellView
- }
- let cellView = KMBatchTableCellView(type: .Size)
-
- if (file.fileType == .Image) {
- let image = NSImage(contentsOfFile: file.filePath)
- cellView.textField?.stringValue = String(Int(image?.size.width ?? 0)) + "x" + String(Int(image?.size.height ?? 0))
- file.dimensions = Float((image?.size.width ?? 0) * (image?.size.height ?? 0))
- }
-
- return cellView;
- } else {
- let cellView = KMBatchTableCellView(type: .PageRange)
- cellView.updateInterface(file)
- return cellView;
- }
- } else if identifier?.rawValue == "status"{
- if row == 0 {
- let cellView = KMNTableHeaderCellView()
- cellView.wantsLayer = true
- cellView.layer?.backgroundColor = cellColor.cgColor
- cellView.titleLabel.stringValue = KMLocalizedString("State")
- cellView.titleLabel.font = titleFont
- cellView.titleLabel.textColor = titleColor
-
- _initHeaderCellView(cellView: cellView)
- return cellView
- }
- let cellView = KMBatchTableCellView(type: .Status)
- if (file.currentOperateType == .CreatePDF) {
- cellView.updateInterface(file: file, progress: file.progress ?? 0)
- } else {
- cellView.updateInterface(file: file, progress: file.progress ?? 0)
- }
- cellView.removeFileCallBack = { [weak self] file in
- self?.files.removeObject(file)
- self?.tableView.reloadData()
- }
- return cellView;
- } else if identifier?.rawValue == "size"{
- if row == 0 {
- let cellView = KMNTableHeaderCellView()
- cellView.wantsLayer = true
- cellView.layer?.backgroundColor = cellColor.cgColor
-
- cellView.titleLabel.stringValue = KMLocalizedString("Size")
- cellView.titleLabel.font = titleFont
- cellView.titleLabel.textColor = titleColor
- _initHeaderCellView(cellView: cellView)
- cellView.itemClick = { [weak self] idx, _ in
- if idx == 1 { // 排序
- let asc = self?.isSizeAsc_ ?? false
- if asc {
- self?.files.sort(){$0.fileSize > $1.fileSize}
- } else {
- self?.files.sort(){$0.fileSize <= $1.fileSize}
- }
- self?.isSizeAsc_ = !asc
- self?.reloadData()
- }
- }
- return cellView
- }
- let cellView = KMBatchTableCellView(type: .Size)
- cellView.updateInterface(file)
- return cellView;
- } else if identifier?.rawValue == "fileName"{
- if row == 0 {
- let cellView = KMNTableHeaderCellView()
- cellView.wantsLayer = true
- cellView.layer?.backgroundColor = cellColor.cgColor
-
- cellView.titleLabel.stringValue = KMLocalizedString("File Name")
- cellView.titleLabel.font = titleFont
- cellView.titleLabel.textColor = titleColor
- _initHeaderCellView(cellView: cellView)
- cellView.itemClick = { [weak self] idx, _ in
- if idx == 1 { // 排序
- let asc = self?.fileNameAsc_ ?? false
- if asc {
- self?.files.sort(){$0.filePath.lastPathComponent > $1.filePath.lastPathComponent}
- } else {
- self?.files.sort(){$0.filePath.lastPathComponent <= $1.filePath.lastPathComponent}
- }
- self?.fileNameAsc_ = !asc
- self?.reloadData()
- }
- }
- return cellView
- }
- let cellView = KMBatchTableCellView(type: .FileName)
- cellView.updateInterface(file)
-
- cellView.fileIv?.wantsLayer = true
- cellView.fileIv?.layer?.borderWidth = 1
- cellView.fileIv?.layer?.borderColor = ComponentLibrary.shared.getComponentColorFromKey("colorBorder/3-default").cgColor
-
- let rowView: KMBatchTableRowView = tableView.rowView(atRow: row, makeIfNecessary: true) as! KMBatchTableRowView
- if ((file.error) != nil) {
- rowView.backgroundColor = KMAppearance.Status.errBGColor();
- }
- return cellView;
- } else if identifier?.rawValue == "dpi"{
- let cellView = KMBatchTableCellView(type: .DPI)
- cellView.updateInterface(file)
- return cellView;
- } else if identifier?.rawValue == "dimensions"{
- if row == 0 {
- let cellView = KMNTableHeaderCellView()
- cellView.wantsLayer = true
- cellView.layer?.backgroundColor = cellColor.cgColor
-
- cellView.titleLabel.stringValue = KMLocalizedString("Dimensions")
- cellView.titleLabel.font = titleFont
- cellView.titleLabel.textColor = titleColor
- _initHeaderCellView(cellView: cellView)
- return cellView
- }
- let cellView = KMBatchTableCellView(type: .Size)
-
- if (file.fileType == .Image) {
- let image = NSImage(contentsOfFile: file.filePath)
- cellView.textField?.stringValue = String(Int(image?.size.width ?? 0)) + "x" + String(Int(image?.size.height ?? 0))
- }
-
- return cellView;
- }
- return nil;
- }
- func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
- let rowIdx = max(0, row-1)
- let file = self.files[rowIdx]
- if self.type == .CreatePDF {
- if row == 0 {
- return 32
- }
- if (file.error != nil) {
- return 104
- } else {
- return 80
- }
- } else {
- if file.fileType == .PDF {
- if (file.error != nil) {
- return 64
- } else {
- return 40
- }
- } else {
- return 0.0000001
- }
- }
- }
- func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
- if row == 0 {
- let rowView = KMBatchTableRowView()
- rowView.selectionBackgroundColorBlock = {
- return .clear
- }
- rowView.selectionHighlightStyle = .none
- rowView.isSelected = false
- return rowView
- }
- let rowView = KMBatchTableRowView()
- return rowView
- }
- func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
- if rowIndexes.first == 0 {
- return false
- }
-
- var theIndex = IndexSet()
- for idx in rowIndexes {
- theIndex.insert(idx-1)
- }
-
- let indexSetData = try? NSKeyedArchiver.archivedData(withRootObject: theIndex, requiringSecureCoding: true)
- pboard.declareTypes([NSPasteboard.PasteboardType.string], owner: self)
- pboard.setData(indexSetData, forType: NSPasteboard.PasteboardType(rawValue: KMBatchDragType) )
- return true
- }
- func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
- if row == 0 {
- return NSDragOperation(rawValue: 0)
- }
- var isCanDrag = false
- var result: NSDragOperation = []
- let pboard = info.draggingPasteboard
- 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
- }
- var isDirectory: ObjCBool = false
- let fileExists = FileManager.default.fileExists(atPath: _url.path, isDirectory: &isDirectory)
- if fileExists && isDirectory.boolValue {
- let containFile = folderContainAvailableFile(_url.path)
- if containFile {
- isCanDrag = true
- break
- }
- } else {
- if let UTType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, _url.pathExtension as CFString, nil)?.takeRetainedValue() as String? {
- if self.type == .CreatePDF {
- if UTTypeConformsTo(UTType as CFString, kUTTypeImage) {
- isCanDrag = true
- }
- } else {
- if UTTypeConformsTo(UTType as CFString, kUTTypePDF) {
- isCanDrag = true
- }
- }
- }
- if isCanDrag {
- break
- }
- }
- }
- if isCanDrag {
- result = .copy
- }
- return result
- } else {
- return .move
- }
- }
- func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
- let pboard = info.draggingPasteboard
- if pboard.availableType(from: [.init(KMBatchDragType)]) != nil {
- guard let rowData = pboard.data(forType: .init(KMBatchDragType)),
- let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: rowData) as? NSIndexSet else { return false }
- let backUpArray = self.files
- var referenceIndex = -1
- rowIndexes.enumerate(options: .reverse, using: { (idx, stop) in
- let theIdx = max(0, idx)
- let sortFile = backUpArray[theIdx]
- let theRow = row-1
- if referenceIndex < 0 {
- if idx > theRow {
- self.files.remove(at: idx)
- self.files.insert(sortFile, at: theRow)
- } else if idx < theRow {
- if theRow > self.files.count {
- self.files.remove(at: idx)
- self.files.append(sortFile)
- } else {
- self.files.remove(at: idx)
- self.files.insert(sortFile, at: theRow - 1)
- }
- }
- referenceIndex = self.files.firstIndex(of: sortFile) ?? -1
- } else {
- let currentIndex = self.files.firstIndex(of: sortFile) ?? -1
- if currentIndex > referenceIndex {
- self.files.remove(at: currentIndex)
- self.files.insert(sortFile, at: referenceIndex)
- } else {
- referenceIndex -= 1
- self.files.remove(at: currentIndex)
- self.files.insert(sortFile, at: referenceIndex)
- }
- }
- })
- self.tableView.reloadData()
- return true
- } else if pboard.availableType(from: [.fileURL]) != nil {
- if (pboard.pasteboardItems == nil) {
-
- return true
- }
-
- let allFilesArray = NSMutableArray()
- for item in pboard.pasteboardItems! {
- let fileURL = item.string(forType: .fileURL)
- if (fileURL == nil) {
- continue
- }
- let path = URL.init(string: fileURL!)
- if (path == nil) {
- continue
- }
- var isFolder = ObjCBool(false)
- FileManager.default.fileExists(atPath: path!.path, isDirectory: &isFolder)
- if isFolder.boolValue {
- let containFiles = fetchAvailableFilesInFolder(path!.path)
- allFilesArray.addObjects(from: containFiles)
- } else {
- allFilesArray.add(path!.path)
- }
- }
- var insertArray = NSMutableArray()
- lockFilePathArr?.removeAllObjects()
- lockFileIndex = 0
- for i in 0..<allFilesArray.count {
- let filePath: String = allFilesArray[i] as! String
-
- if filePath.hasSuffix(".pdf") || filePath.hasSuffix(".PDF") {
- let document = CPDFDocument(url: URL(fileURLWithPath: filePath))
- if let pdf = CPDFDocument(url: URL(fileURLWithPath: filePath)) {
- if !pdf.allowsPrinting || !pdf.allowsCopying {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = KMLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
- alert.runModal()
- continue
- } else if document?.isLocked ?? false {
- lockFilePathArr?.add(filePath)
- } else {
- let file = KMBatchOperateFile(filePath: filePath, type: self.type!)
- if !(self.files.contains(file) ) {
- insertArray.add(file)
- }
- }
- }
- } else {
- let file = KMBatchOperateFile(filePath: filePath, type: self.type!)
- if !(self.files.contains(file) ) {
- insertArray.add(file)
- }
- }
- }
- if !(IAPProductsManager.default().isAvailableAllFunction)() {
- if self.files.count < 1 && insertArray.count > 0 {
- let firstObject = insertArray.firstObject
- insertArray.removeAllObjects()
- insertArray.add(firstObject as Any)
- } else {
- KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
- return false
- }
- }
- for i in 0..<insertArray.count {
- self.files.insert(insertArray[i] as! KMBatchOperateFile, at: row + i)
- }
- self.tableView.reloadData()
- if lockFilePathArr!.count > 0 {
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
- self.openPasswordWindow()
- }
- }
- return true
- }
- return false
- }
- }
- // MARK: - NSMenuDelegate, NSMenuItemValidation
- extension KMBatchOperateLeftViewController: NSMenuDelegate, NSMenuItemValidation {
- func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
- let action = menuItem.action
- if action == #selector(menuItem_ShowInFinder(_:)) || action == #selector(menuItem_Delete(_:)) {
- if tableView.clickedRow == -1 {
- return false
- }
- return true
- }
- return true
- }
- }
- //MARK: - ComponentDropdownDelegate
- extension KMBatchOperateLeftViewController: ComponentDropdownDelegate {
- func componentDropdownDidShowMenuItem(dropdown: ComponentDropdown) {
- showGroupView()
- }
- }
- //MARK: - ComponentGroupDelegate
- extension KMBatchOperateLeftViewController: ComponentGroupDelegate {
- func componentGroupDidDismiss(group: ComponentGroup?) {
- removeGroupView()
- }
-
- func componentGroupDidSelect(group: ComponentGroup?, menuItemProperty: ComponentMenuitemProperty?) {
- if let selItem = menuItemProperty {
- let index = group?.menuItemArr.firstIndex(of: selItem)
- if index == 0 {
- chooseFile()
- } else if index == 1 {
- _addFolderAction()
- } else if index == 2 {
- let pboard = NSPasteboard.general
- if let document = self.openDocumentWithImageFromPasteboard(pboard, error: nil) {
- // Document opened successfully
- if let page = document.page(at: 0) {
- let data = page.PDFListViewTIFFData(for: page.bounds)
- var path = self._saveImagePath() + "/Untitled.png"
- path = KMTools.getUniqueFilePath(filePath: path)
- try?data?.write(to: URL(fileURLWithPath: path), options: .atomic)
-
- self.addFilesToList(addArray: [path])
- }
- }
- } else if index == 3 {
- chooseFileFromCamera()
- }
- }
- }
- }
|