KMBatchOperateLeftViewController.swift 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  1. //
  2. // KMBatchOperateLeftViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by kdanmobile on 2023/10/26.
  6. //
  7. import Cocoa
  8. import KMComponentLibrary
  9. let KMBatchDragType = "KMBatchDragType"
  10. class KMBatchOperateLeftViewController: KMNBaseViewController {
  11. @IBOutlet var selectFileButton: KMLongerButton!
  12. @IBOutlet var deleteFileButton: NSButton!
  13. @IBOutlet var tableView: NSTableView!
  14. @IBOutlet var indexTableColumn: NSTableColumn!
  15. @IBOutlet var fileNameTableColumn: NSTableColumn!
  16. @IBOutlet var pageRangeTableColumn: NSTableColumn!
  17. @IBOutlet var sizeTableColumn: NSTableColumn!
  18. @IBOutlet var stateTableColumn: NSTableColumn!
  19. @IBOutlet var DPIColumn: NSTableColumn!
  20. @IBOutlet var dimensionsTableColumn: NSTableColumn!
  21. @IBOutlet var headerOperateView: NSView!
  22. @IBOutlet var showInFinderMenuItem: NSMenuItem!
  23. @IBOutlet var deleteMenuItem: NSMenuItem!
  24. @IBOutlet var blankView: KMBlankView!
  25. var files: [KMBatchOperateFile] = []
  26. var type: KMBatchOperationType?
  27. var lockFilePathArr: NSMutableArray?
  28. var lockFileIndex: Int = 0
  29. var popOver: NSPopover?
  30. var progressInt: Int = 0
  31. private var addFileButton_: ComponentDropdown?
  32. private var deleteButton_: ComponentButton?
  33. private var groupView_: ComponentGroup?
  34. private var emptyViewTopLine: NSView = {
  35. let view = NSView()
  36. view.wantsLayer = true
  37. return view
  38. }()
  39. private var emptyView_: ComponentEmpty = {
  40. let view = ComponentEmpty()
  41. 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."))
  42. return view
  43. }()
  44. private var dividerColor_: NSColor?
  45. private var isSizeAsc_ = false
  46. private var dimensionsAsc_ = false
  47. private var fileNameAsc_ = false
  48. deinit {
  49. DistributedNotificationCenter.default().removeObserver(self)
  50. }
  51. override func viewDidLoad() {
  52. super.viewDidLoad()
  53. for i in 0..<self.tableView.tableColumns.count {
  54. let column = self.tableView.tableColumns[i]
  55. column.headerCell = KMTableHeaderCell(textCell: column.title)
  56. }
  57. self.deleteFileButton.addHoverEffect = true
  58. self.indexTableColumn.resizingMask = []
  59. self.fileNameTableColumn.resizingMask = .autoresizingMask
  60. self.pageRangeTableColumn.resizingMask = []
  61. self.sizeTableColumn.resizingMask = []
  62. self.stateTableColumn.resizingMask = []
  63. self.DPIColumn.resizingMask = []
  64. self.dimensionsTableColumn.resizingMask = []
  65. self.tableView.moveColumn(5, toColumn: 2)
  66. self.indexTableColumn.title = " \(KMLocalizedString("Index", comment: ""))"
  67. self.fileNameTableColumn.title = KMLocalizedString("File Name", comment: "")
  68. self.pageRangeTableColumn.title = KMLocalizedString("Page Range", comment: "")
  69. self.sizeTableColumn.title = KMLocalizedString("Size", comment: "")
  70. self.stateTableColumn.title = KMLocalizedString("Status", comment: "")
  71. self.DPIColumn.title = KMLocalizedString("DPI", comment: "")
  72. self.dimensionsTableColumn.title = KMLocalizedString("Dimensions", comment: "")
  73. self.DPIColumn.isHidden = true
  74. self.tableView.intercellSpacing = CGSize(width: 0, height: 0)
  75. self.tableView.allowsColumnReordering = false
  76. self.tableView.allowsMultipleSelection = true
  77. self.tableView.enclosingScrollView?.borderType = .noBorder
  78. self.headerOperateView.wantsLayer = true
  79. self.tableView.registerForDraggedTypes([NSPasteboard.PasteboardType.string,NSPasteboard.PasteboardType.fileURL, NSPasteboard.PasteboardType(KMBatchDragType)])
  80. self.lockFilePathArr = NSMutableArray()
  81. self.lockFileIndex = 0
  82. self.progressInt = 0
  83. selectFileButton.title = ""
  84. addFileButton_ = ComponentDropdown()
  85. addFileButton_?.properties = ComponentDropdownProperty(type: .split_graySecondary, size: .s, split: true, text: KMLocalizedString("Add Files..."))
  86. // addFileButton_?.splitRightButton.properties.icon = NSImage(named: "ImageToPDFDropdownButtonIcon")
  87. selectFileButton.addSubview(addFileButton_!)
  88. addFileButton_?.frame = selectFileButton.bounds
  89. addFileButton_?.autoresizingMask = [.width, .height]
  90. addFileButton_?.componentDelegate = self
  91. deleteButton_ = ComponentButton()
  92. deleteButton_?.properties = ComponentButtonProperty(type: .text_gray_low, size: .s, state: .normal, onlyIcon: true)
  93. deleteButton_?.setTarget(self, action: #selector(buttonClicked_DeleteFile))
  94. deleteFileButton.image = nil
  95. deleteFileButton.addSubview(deleteButton_!)
  96. deleteButton_?.frame = deleteFileButton.bounds
  97. deleteButton_?.autoresizingMask = [.width, .height]
  98. deleteButton_?.properties.propertyInfo.leftIcon_nor = NSImage(named: "KMImageNameDeleteFileIcon")
  99. deleteButton_?.setTarget(self, action: #selector(buttonClicked_DeleteFile))
  100. tableView.headerView = nil
  101. self.showInFinderMenuItem.title = KMLocalizedString("Show in Finder", comment: "")
  102. self.deleteMenuItem.title = KMLocalizedString("Delete", comment: "")
  103. self.blankView.wantsLayer = true
  104. self.blankView.layer?.backgroundColor = NSColor.clear.cgColor
  105. self.blankView.titleLabel.stringValue = ""
  106. self.blankView.imageView.isHidden = true
  107. self.blankView.addButton.isHidden = true
  108. self.blankView.secondTitleLabel.stringValue = ""
  109. self.blankView.mouseActionCallBack = { [weak self] mouseType in
  110. if mouseType == .mouseDown {
  111. self?.chooseFile()
  112. }
  113. }
  114. self.blankView.addSubview(emptyView_)
  115. blankView.addSubview(emptyViewTopLine)
  116. emptyViewTopLine.km_add_top_constraint(constant: 4)
  117. emptyViewTopLine.km_add_left_constraint(constant: 24)
  118. emptyViewTopLine.km_add_right_constraint(constant: -24)
  119. emptyViewTopLine.km_add_height_constraint(constant: 1)
  120. emptyViewTopLine.wantsLayer = true
  121. let dividerColor = ComponentLibrary.shared.getComponentColorFromKey("colorBorder/divider")
  122. emptyViewTopLine.layer?.backgroundColor = dividerColor.cgColor
  123. emptyView_.km_add_top_constraint(constant: 96)
  124. emptyView_.km_add_bottom_constraint()
  125. emptyView_.km_add_leading_constraint()
  126. emptyView_.km_add_trailing_constraint()
  127. emptyView_.setTarget(self, action: #selector(emptyAddFileAction))
  128. }
  129. override func addNotifations() {
  130. super.addNotifations()
  131. NotificationCenter.default.addObserver(self.tableView!, selector: #selector(self.reloadData), name: NSNotification.Name(kNeedChangePageRangeNotification), object: nil)
  132. NotificationCenter.default.addObserver(self, selector: #selector(imageToPDFSuccessNotification(aNotification:)), name: NSNotification.Name("KMBatchOperateImageToPDFSuccessNotification"), object: nil)
  133. }
  134. override func updateUILanguage() {
  135. super.updateUILanguage()
  136. KMMainThreadExecute {
  137. self.addFileButton_?.properties.text = KMLocalizedString("Add Files...")
  138. self.addFileButton_?.reloadData()
  139. self.tableView.reloadData()
  140. }
  141. }
  142. override func updateUIThemeColor() {
  143. super.updateUIThemeColor()
  144. self.dividerColor_ = ComponentLibrary.shared.getComponentColorFromKey("colorBorder/divider")
  145. KMMainThreadExecute {
  146. self.updateViewColor()
  147. self.tableView.reloadData()
  148. }
  149. }
  150. @objc func reloadData() {
  151. if Thread.isMainThread {
  152. tableView.reloadData()
  153. } else {
  154. DispatchQueue.main.async {
  155. self.tableView.reloadData()
  156. }
  157. }
  158. }
  159. @objc func imageToPDFSuccessNotification(aNotification: Notification) {
  160. guard let dict = aNotification.userInfo, let isSuccess = dict["isSuccess"] as? Bool else { return }
  161. if isSuccess {
  162. progressInt = 1
  163. } else {
  164. progressInt = -1
  165. }
  166. DispatchQueue.main.async {
  167. self.tableView.reloadData()
  168. }
  169. }
  170. func updateViewColor() {
  171. self.view.wantsLayer = true
  172. if KMAppearance.isDarkMode() {
  173. let color = ComponentLibrary.shared.getComponentColorFromKey("colorBg/layout-low")
  174. view.layer?.backgroundColor = color.cgColor
  175. } else {
  176. view.layer?.backgroundColor = .white
  177. }
  178. }
  179. func chooseFile() {
  180. #if VERSION_FREE
  181. if !IAPProductsManager.default().isAvailableAllFunction() {
  182. if files.count >= 1 {
  183. let winC = KMPurchaseCompareWindowController.sharedInstance()
  184. if type == .CreatePDF {
  185. winC?.kEventName = "Onbrd_ImagetoPDF_BuyNow"
  186. }
  187. winC?.showWindow(nil)
  188. return
  189. }
  190. }
  191. #endif
  192. self.progressInt = 0
  193. let panel = NSOpenPanel()
  194. if type == .CreatePDF {
  195. panel.allowedFileTypes = KMImageToPDFMethod.supportedImageTypes()
  196. } else {
  197. panel.allowedFileTypes = ["pdf", "PDF"]
  198. }
  199. if IAPProductsManager.default().isAvailableAllFunction() {
  200. panel.allowsMultipleSelection = true
  201. panel.canChooseDirectories = true
  202. }
  203. panel.canChooseFiles = true
  204. #if VERSION_FREE
  205. #else
  206. panel.message = KMLocalizedString("To select multiple files press cmd ⌘ button on keyboard and click on the target files one by one.", comment: "")
  207. #endif
  208. panel.beginSheetModal(for: self.view.window!) {
  209. (result) in
  210. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  211. let addArray = NSMutableArray()
  212. for fileURL in panel.urls {
  213. let filePath = fileURL.path
  214. var isDirectory = ObjCBool(false)
  215. FileManager.default.fileExists(atPath: filePath, isDirectory: &isDirectory)
  216. if isDirectory.boolValue {
  217. let containFiles = self.fetchAvailableFiles(in: filePath)
  218. addArray.addObjects(from: containFiles)
  219. } else {
  220. let typeIdentifier =
  221. UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, filePath.customPathExtension as CFString, nil)
  222. let TypeCFString = typeIdentifier!.takeRetainedValue() as String
  223. if self.type == .CreatePDF {
  224. if UTTypeConformsTo(TypeCFString as CFString, kUTTypeImage) {
  225. addArray.add(filePath)
  226. }
  227. } else {
  228. if UTTypeConformsTo(TypeCFString as CFString, kUTTypePDF) {
  229. addArray.add(filePath)
  230. }
  231. }
  232. }
  233. }
  234. self.addFilesToList(addArray: addArray)
  235. }
  236. }
  237. }
  238. func fetchAvailableFiles(in folderPath: String) -> [String] {
  239. let array = NSMutableArray()
  240. let subFileArray = (FileManager.default.subpaths(atPath: folderPath)! as NSArray).mutableCopy() as? NSMutableArray
  241. for i in 0..<subFileArray!.count {
  242. if let path = (folderPath as NSString).appendingPathComponent(subFileArray!.object(at: i) as! String) as String? {
  243. if let UTTypeString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, path.customPathExtension as CFString, nil)?.takeRetainedValue() as String? {
  244. let TypeCFString = UTTypeString as CFString
  245. if self.type == .CreatePDF {
  246. if UTTypeConformsTo(TypeCFString, kUTTypeImage) {
  247. array.add(path)
  248. }
  249. } else {
  250. if UTTypeConformsTo(TypeCFString, kUTTypePDF) {
  251. array.add(path)
  252. }
  253. }
  254. }
  255. }
  256. }
  257. return array as! [String]
  258. }
  259. func addFilesToList(addArray: NSMutableArray) {
  260. self.lockFilePathArr!.removeAllObjects()
  261. self.lockFileIndex = 0
  262. for i in 0..<addArray.count {
  263. let filePath = addArray[i] as! String
  264. let UTTypeString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, filePath.customPathExtension as CFString, nil)!.takeRetainedValue() as String
  265. let TypeCFString = UTTypeString as CFString
  266. if UTTypeConformsTo(TypeCFString, kUTTypePDF) {
  267. let document = CPDFDocument(url: URL(fileURLWithPath: filePath))
  268. if document?.isLocked == true {
  269. var isContaint = false
  270. for file in self.files {
  271. if (file as AnyObject).filePath == filePath {
  272. isContaint = true
  273. break
  274. }
  275. }
  276. if !isContaint {
  277. self.lockFilePathArr!.add(filePath)
  278. }
  279. } else {
  280. let file = KMBatchOperateFile(filePath: addArray[i] as! String, type: self.type!)
  281. if !self.files.contains(file) {
  282. self.files.append(file)
  283. }
  284. }
  285. } else {
  286. let file = KMBatchOperateFile(filePath: addArray[i] as! String, type: self.type!)
  287. if !self.files.contains(file) {
  288. self.files.append(file)
  289. }
  290. }
  291. }
  292. self.tableView.reloadData()
  293. if self.lockFilePathArr!.count > 0 {
  294. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  295. self.openPasswordWindow()
  296. }
  297. }
  298. }
  299. func openPasswordWindow() {
  300. if lockFilePathArr!.count > lockFileIndex {
  301. let filePath = lockFilePathArr![lockFileIndex] as! String
  302. KMBaseWindowController.checkPassword(url: URL(fileURLWithPath: filePath), type: .owner) { [unowned self] success, resultPassword in
  303. self.closePwd()
  304. if !resultPassword.isEmpty {
  305. let file = KMBatchOperateFile(filePath: filePath, type: self.type!)
  306. file.password = resultPassword
  307. self.files.append(file)
  308. self.tableView.reloadData()
  309. }
  310. self.lockFileIndex += 1
  311. if self.lockFilePathArr?.count ?? 0 > self.lockFileIndex {
  312. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  313. self.openPasswordWindow()
  314. }
  315. } else {
  316. self.tableView.reloadData()
  317. }
  318. }
  319. }
  320. }
  321. func closePwd() {
  322. self.km_endSheet()
  323. }
  324. // MARK: - Actions
  325. func chooseFileFromCamera() {
  326. self.progressInt = 0
  327. let vc = KMDeviceBrowserWindowController.shared
  328. vc.type = .camera
  329. vc.importCameraFileCallback = { [weak self](url: NSURL) -> Void in
  330. self?.addFilesToList(addArray: [url.path!])
  331. }
  332. vc.showWindow(nil)
  333. }
  334. func chooseFileFromScanner() {
  335. self.progressInt = 0
  336. let vc = KMDeviceBrowserWindowController.shared
  337. vc.type = .scanner
  338. vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  339. self?.addFilesToList(addArray: [url.path!])
  340. }
  341. vc.showWindow(nil)
  342. }
  343. @IBAction func blankViewAddFileAction(_ sender: Any) {
  344. self.chooseFile()
  345. }
  346. @IBAction func buttonClicked_DeleteFile(_ sender: Any) {
  347. let set = self.tableView.selectedRowIndexes
  348. let newArr: NSMutableArray = NSMutableArray.init(array: self.files)
  349. let arr = newArr.objects(at: set)
  350. if arr.count > 0 {
  351. newArr.removeObjects(in: arr)
  352. self.files = newArr as! [KMBatchOperateFile]
  353. self.tableView.reloadData()
  354. } else {
  355. let alert = NSAlert()
  356. alert.alertStyle = .critical
  357. alert.messageText = KMLocalizedString("Clear All Recents", comment: "")+"?"
  358. alert.addButton(withTitle: KMLocalizedString("Delete", comment: ""))
  359. alert.addButton(withTitle: KMLocalizedString("Cancel", comment: ""))
  360. alert.beginSheetModal(for: self.view.window!) {[weak self] response in
  361. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  362. self?.files.removeAll()
  363. self?.tableView.reloadData()
  364. }
  365. }
  366. }
  367. }
  368. func fetchAvailableFilesInFolder(_ folderPath: String) -> [String] {
  369. var array: [String] = []
  370. let subFileArray = FileManager().subpaths(atPath: folderPath)
  371. for i in 0..<subFileArray!.count {
  372. let path = folderPath.stringByAppendingPathComponent(subFileArray![i])
  373. let TypeCFString = KMTools.UTIforFileExtension(path.customPathExtension) as CFString
  374. if self.type == .CreatePDF {
  375. if UTTypeConformsTo(TypeCFString, kUTTypeImage) {
  376. array.append(path)
  377. }
  378. } else {
  379. if UTTypeConformsTo(TypeCFString, kUTTypePDF) {
  380. array.append(path)
  381. }
  382. }
  383. }
  384. return array
  385. }
  386. func folderContainAvailableFile(_ folderPath: String) -> Bool {
  387. var containFile = false
  388. guard let subFileArray = FileManager.default.subpaths(atPath: folderPath) else {
  389. return containFile
  390. }
  391. for i in 0..<subFileArray.count {
  392. let path = folderPath.stringByAppendingPathComponent(subFileArray[i] )
  393. let TypeCFString = KMTools.UTIforFileExtension(path.customPathExtension) as CFString
  394. if type == .CreatePDF {
  395. if UTTypeConformsTo(TypeCFString, kUTTypeImage) {
  396. containFile = true
  397. }
  398. } else {
  399. if UTTypeConformsTo(TypeCFString, kUTTypePDF) {
  400. containFile = true
  401. }
  402. }
  403. if containFile {
  404. break
  405. }
  406. }
  407. return containFile
  408. }
  409. func switchToOperateType(_ type: KMBatchOperationType) {
  410. self.type = type
  411. self.indexTableColumn.isHidden = false
  412. self.fileNameTableColumn.isHidden = false
  413. self.pageRangeTableColumn.isHidden = false
  414. self.sizeTableColumn.isHidden = false
  415. self.stateTableColumn.isHidden = false
  416. self.DPIColumn.isHidden = true
  417. self.dimensionsTableColumn.isHidden = true
  418. if type == .Compress || type == .AddPassword || type == .RemovePassword || type == .RemoveWatermark || type == .RemoveBackground || type == .RemoveHeaderFooter || type == .RemoveBates || type == .CreatePDF {
  419. self.pageRangeTableColumn.isHidden = true
  420. } else {
  421. self.pageRangeTableColumn.isHidden = false
  422. }
  423. self.selectFileButton.isImageToPDF = type == .CreatePDF
  424. if type == .CreatePDF {
  425. self.pageRangeTableColumn.isHidden = false
  426. self.pageRangeTableColumn.title = KMLocalizedString("Dimensions", comment: "")
  427. }
  428. for i in 0..<self.files.count {
  429. let file = self.files[i]
  430. file.currentOperateType = type
  431. }
  432. self.tableView.sizeToFit()
  433. self.tableView.reloadData()
  434. }
  435. @IBAction func menuItem_ShowInFinder(_ sender: Any) {
  436. let row = self.tableView.clickedRow
  437. let file: KMBatchOperateFile = self.files[row]
  438. if file.currentOperateInfo?.status == .Success {
  439. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: file.currentOperateInfo!.outPutPath!)])
  440. }else {
  441. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: file.filePath)])
  442. }
  443. }
  444. @IBAction func menuItem_Delete(_ sender: Any) {
  445. let row = self.tableView.clickedRow
  446. self.files.remove(at: row)
  447. self.tableView.reloadData()
  448. }
  449. func addOpendFile() {
  450. let documentArray = NSDocumentController.shared.documents
  451. var pdfArray = NSMutableArray()
  452. for i in 0..<documentArray.count {
  453. let document = documentArray[i]
  454. let path: String = document.fileURL?.path ?? ""
  455. let UTTypeString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, path.customPathExtension as CFString, nil)?.takeRetainedValue() as String?
  456. let TypeCFString = UTTypeString as CFString?
  457. if UTTypeConformsTo(TypeCFString!, kUTTypePDF) {
  458. pdfArray.add(path as Any)
  459. }
  460. }
  461. if !IAPProductsManager.default().isAvailableAllFunction() {
  462. if self.files.count < 1 {
  463. pdfArray = NSMutableArray(array: [pdfArray.firstObject as Any])
  464. } else {
  465. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  466. return
  467. }
  468. }
  469. addFilesToList(addArray: pdfArray)
  470. }
  471. @objc func emptyAddFileAction() {
  472. self.chooseFile()
  473. }
  474. //MARK: - GroupView
  475. func showGroupView() {
  476. var viewHeight: CGFloat = 8
  477. var menuItemArr: [ComponentMenuitemProperty] = []
  478. for i in ["Add Files...", "Add Folder...", "Import from Clipboard...", "Import from Scanner..."] {
  479. let properties_Menuitem: ComponentMenuitemProperty = ComponentMenuitemProperty(multipleSelect: false,
  480. itemSelected: false,
  481. isDisabled: false,
  482. keyEquivalent: nil,
  483. text: KMLocalizedString(i))
  484. menuItemArr.append(properties_Menuitem)
  485. viewHeight += 36
  486. }
  487. if groupView_ == nil {
  488. groupView_ = ComponentGroup.createFromNib(in: ComponentLibrary.shared.componentBundle())
  489. }
  490. groupView_?.groupDelegate = self
  491. groupView_?.frame = CGRectMake(310, 0, 200, viewHeight)
  492. groupView_?.updateGroupInfo(menuItemArr)
  493. var point = addFileButton_?.convert(addFileButton_!.frame.origin, to: nil) ?? .zero
  494. point.y -= viewHeight
  495. groupView_?.showWithPoint(point, relativeTo: addFileButton_)
  496. addFileButton_?.properties.state = .pressed
  497. addFileButton_?.reloadData()
  498. }
  499. func removeGroupView() {
  500. if groupView_ != nil {
  501. groupView_?.removeFromSuperview()
  502. }
  503. addFileButton_?.properties.state = .normal
  504. addFileButton_?.reloadData()
  505. }
  506. func openDocumentWithImageFromPasteboard(_ pboard: NSPasteboard, error outError: AutoreleasingUnsafeMutablePointer<NSError?>?) -> CPDFDocument? {
  507. var document: CPDFDocument? = nil
  508. var data: Data? = nil
  509. if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.pdf.rawValue]) {
  510. data = pboard.data(forType: NSPasteboard.PasteboardType.pdf)
  511. } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.postScript.rawValue]) {
  512. data = pboard.data(forType: NSPasteboard.PasteboardType.postScript)
  513. } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.tiff.rawValue]) {
  514. data = convertTIFFDataToPDF(pboard.data(forType: NSPasteboard.PasteboardType.tiff) ?? Data())
  515. } else {
  516. let images = pboard.readObjects(forClasses: [NSImage.self], options: [:])
  517. let strings = pboard.readObjects(forClasses: [NSAttributedString.self], options: [:])
  518. if images?.count ?? 0 > 0 {
  519. data = convertTIFFDataToPDF((images![0] as AnyObject).tiffRepresentation!)
  520. } else if strings?.count ?? 0 > 0 {
  521. data = KMOCTool.convertStringsToPDF(withString: strings ?? [""]) // convertStringsToPDF(strings!)
  522. }
  523. }
  524. if let data = data {
  525. document = CPDFDocument(data: data)
  526. } else if let outError = outError {
  527. outError.pointee = NSError(domain: "SKDocumentErrorDomain", code: 3, userInfo: [NSLocalizedDescriptionKey: KMLocalizedString("Unable to load data from clipboard", comment: "Error description")])
  528. }
  529. return document
  530. }
  531. func convertTIFFDataToPDF(_ tiffData: Data) -> Data? {
  532. guard let imsrc = CGImageSourceCreateWithData(tiffData as CFData, [kCGImageSourceTypeIdentifierHint: kUTTypeTIFF] as CFDictionary), CGImageSourceGetCount(imsrc) > 0, let cgImage = CGImageSourceCreateImageAtIndex(imsrc, 0, nil) else { return nil }
  533. let pdfData = NSMutableData(capacity: tiffData.count)
  534. let consumer = CGDataConsumer(data: pdfData! as CFMutableData)!
  535. var rect = CGRect(x: 0, y: 0, width: CGFloat(cgImage.width), height: CGFloat(cgImage.height))
  536. let ctxt = CGContext(consumer: consumer, mediaBox: &rect, nil)
  537. ctxt!.beginPDFPage(nil)
  538. ctxt!.draw(cgImage, in: rect)
  539. ctxt!.endPDFPage()
  540. ctxt!.closePDF()
  541. return pdfData as? Data
  542. }
  543. // MARK: - Private Methods
  544. private func _saveImagePath() -> String {
  545. let rootPath = KMDataManager.fetchAppSupportOfBundleIdentifierDirectory()
  546. let path = rootPath.appendingPathComponent("ImageToPDF").path
  547. if FileManager.default.fileExists(atPath: path) == false {
  548. try?FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: false)
  549. }
  550. return path
  551. }
  552. private func _clearImageData() {
  553. let path = self._saveImagePath()
  554. if FileManager.default.fileExists(atPath: path) {
  555. try?FileManager.default.removeItem(atPath: path)
  556. }
  557. }
  558. private func _initHeaderCellView(cellView: KMNTableHeaderCellView) {
  559. var dividerColor = self.dividerColor_
  560. if dividerColor == nil {
  561. dividerColor = ComponentLibrary.shared.getComponentColorFromKey("colorBorder/divider")
  562. }
  563. cellView.leftLine.wantsLayer = true
  564. cellView.leftLine.layer?.backgroundColor = dividerColor?.cgColor ?? .black
  565. cellView.rightLine.wantsLayer = true
  566. cellView.rightLine.layer?.backgroundColor = dividerColor?.cgColor ?? .black
  567. cellView.bottomLine.wantsLayer = true
  568. cellView.bottomLine.layer?.backgroundColor = dividerColor?.cgColor ?? .black
  569. }
  570. private func _addFolderAction() {
  571. let openPanel = NSOpenPanel()
  572. // openPanel.title = NSLocalizedString("选择并合并文件。按下键盘上的命令按钮,逐次点击目标文件,即可选择多个文件", comment: "")
  573. openPanel.canChooseDirectories = true
  574. openPanel.canChooseFiles = false
  575. openPanel.allowsMultipleSelection = true
  576. openPanel.beginSheetModal(for: view.window!, completionHandler: { [self] result in
  577. if result != .OK {
  578. } else {
  579. var result: [URL] = []
  580. for folderURL in openPanel.urls {
  581. _findAllFiles(folder: folderURL, result: &result)
  582. }
  583. var paths: [String] = []
  584. for url in result {
  585. paths.append(url.path)
  586. }
  587. self.addFilesToList(addArray: NSMutableArray(array: paths))
  588. }
  589. })
  590. }
  591. private func _findAllFiles(folder: URL, result: inout [URL]) {
  592. let fileManager = FileManager.default
  593. var isDirectory: ObjCBool = ObjCBool(false)
  594. fileManager.fileExists(atPath: folder.path, isDirectory: &isDirectory)
  595. if (!isDirectory.boolValue) {
  596. return
  597. }
  598. let contents = try?fileManager.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)
  599. if contents?.count == 0 {
  600. return
  601. }
  602. let array = ["jpg","cur","bmp","jpeg","gif","png","tiff","tif","ico","icns","tga","psd","eps","hdr","jp2","jpc","pict","sgi","heic"]
  603. for documentURL in contents! {
  604. var isDirectory: ObjCBool = ObjCBool(false)
  605. fileManager.fileExists(atPath: documentURL.path, isDirectory: &isDirectory)
  606. if (isDirectory.boolValue) {
  607. _findAllFiles(folder: documentURL, result: &result)
  608. } else {
  609. if !array.contains(documentURL.pathExtension.lowercased()) {
  610. continue
  611. }
  612. result.append(documentURL)
  613. }
  614. }
  615. }
  616. func switchToOperateType(_ operateType: KMBatchOperationType, files: [KMBatchOperateFile]) {
  617. switchToOperateType(operateType)
  618. self.files = files
  619. self.tableView.reloadData()
  620. }
  621. func checkNeedPasswordSwitchToOperateType(_ operateType: KMBatchOperationType, files: [KMBatchOperateFile]) {
  622. switchToOperateType(operateType)
  623. var arr: [String] = []
  624. for i in 0..<files.count {
  625. let file = files[i]
  626. arr.append(file.filePath)
  627. }
  628. self.files = files
  629. self.files.removeAll()
  630. addFilesToList(addArray: NSMutableArray.init(array: arr))
  631. self.tableView.reloadData()
  632. }
  633. func reloadFile(_ file: KMBatchOperateFile) {
  634. var rowIndexSet = IndexSet()
  635. for i in 0..<self.files.count {
  636. if file.filePath == self.files[i].filePath {
  637. rowIndexSet.insert(i)
  638. break
  639. }
  640. }
  641. var columnIndexSet = IndexSet()
  642. for i in 0..<self.tableView.numberOfColumns {
  643. let identifier = self.tableView.tableColumns[i].identifier
  644. if identifier.rawValue == "status" {
  645. columnIndexSet.insert(i)
  646. break
  647. }
  648. }
  649. if Thread.isMainThread {
  650. self.tableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: columnIndexSet)
  651. } else {
  652. DispatchQueue.main.async {
  653. self.tableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: columnIndexSet)
  654. }
  655. }
  656. }
  657. func refreshConvertProgress(_ progress: CGFloat, file: KMBatchOperateFile) {
  658. self.tableView.reloadData()
  659. }
  660. func reloadConvertInterface(withType type: KMConvertWithPDFType) {
  661. if type == .WordAdvance || type == .WordStandard || type == .Excel || type == .PowerPoint || type == .RTF || type == .CSV || type == .HTML || type == .Text || type == .Json {
  662. self.DPIColumn.isHidden = true
  663. } else {
  664. self.DPIColumn.isHidden = false
  665. }
  666. self.tableView.reloadData()
  667. }
  668. }
  669. // MARK: - NSTableViewDelegate,NSTableViewDataSource
  670. extension KMBatchOperateLeftViewController: NSTableViewDelegate,NSTableViewDataSource {
  671. func numberOfRows(in tableView: NSTableView) -> Int {
  672. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMBatchFilesCountNotification"), object: self.files, userInfo: [kObjectKey : self])
  673. self.deleteFileButton.isEnabled = self.files.count > 0
  674. deleteButton_?.properties.isDisabled = self.files.count <= 0
  675. self.blankView.isHidden = self.files.count > 0
  676. if self.files.count == 0 {
  677. return 0
  678. }
  679. return self.files.count + 1;
  680. }
  681. func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  682. let identifier = tableColumn?.identifier
  683. let rowIdx = max(0, row-1)
  684. let file = self.files[rowIdx]
  685. let cellColor = ComponentLibrary.shared.getComponentColorFromKey("olorFill/4")
  686. let titleFont = ComponentLibrary.shared.getFontFromKey("mac/body-s-medium")
  687. let titleColor = ComponentLibrary.shared.getComponentColorFromKey("colorText/1")
  688. if identifier?.rawValue == "index" {
  689. if row == 0 {
  690. let cellView = KMNTableHeaderCellView()
  691. cellView.wantsLayer = true
  692. cellView.layer?.backgroundColor = cellColor.cgColor
  693. // cellView.layer?.backgroundColor = NSColor(hex: "#F6F6F8").cgColor
  694. cellView.titleLabel.stringValue = KMLocalizedString("")
  695. _initHeaderCellView(cellView: cellView)
  696. return cellView
  697. }
  698. let cellView = KMBatchTableCellView(type: .Size)
  699. _ = row + 1
  700. cellView.textField?.stringValue = String(format: "%d", row);
  701. return cellView;
  702. } else if identifier?.rawValue == "pageRange"{
  703. if (file.currentOperateType == .CreatePDF) {
  704. if row == 0 {
  705. let cellView = KMNTableHeaderCellView()
  706. cellView.wantsLayer = true
  707. cellView.layer?.backgroundColor = cellColor.cgColor
  708. cellView.titleLabel.stringValue = KMLocalizedString("Dimensions")
  709. cellView.titleLabel.font = titleFont
  710. cellView.titleLabel.textColor = titleColor
  711. _initHeaderCellView(cellView: cellView)
  712. cellView.itemClick = { [weak self] idx, _ in
  713. if idx == 1 { // 排序
  714. let asc = self?.dimensionsAsc_ ?? false
  715. if asc {
  716. self?.files.sort(){$0.dimensions > $1.dimensions}
  717. } else {
  718. self?.files.sort(){$0.dimensions <= $1.dimensions}
  719. }
  720. self?.dimensionsAsc_ = !asc
  721. self?.reloadData()
  722. }
  723. }
  724. return cellView
  725. }
  726. let cellView = KMBatchTableCellView(type: .Size)
  727. if (file.fileType == .Image) {
  728. let image = NSImage(contentsOfFile: file.filePath)
  729. cellView.textField?.stringValue = String(Int(image?.size.width ?? 0)) + "x" + String(Int(image?.size.height ?? 0))
  730. file.dimensions = Float((image?.size.width ?? 0) * (image?.size.height ?? 0))
  731. }
  732. return cellView;
  733. } else {
  734. let cellView = KMBatchTableCellView(type: .PageRange)
  735. cellView.updateInterface(file)
  736. return cellView;
  737. }
  738. } else if identifier?.rawValue == "status"{
  739. if row == 0 {
  740. let cellView = KMNTableHeaderCellView()
  741. cellView.wantsLayer = true
  742. cellView.layer?.backgroundColor = cellColor.cgColor
  743. cellView.titleLabel.stringValue = KMLocalizedString("State")
  744. cellView.titleLabel.font = titleFont
  745. cellView.titleLabel.textColor = titleColor
  746. _initHeaderCellView(cellView: cellView)
  747. return cellView
  748. }
  749. let cellView = KMBatchTableCellView(type: .Status)
  750. if (file.currentOperateType == .CreatePDF) {
  751. cellView.updateInterface(file: file, progress: file.progress ?? 0)
  752. } else {
  753. cellView.updateInterface(file: file, progress: file.progress ?? 0)
  754. }
  755. cellView.removeFileCallBack = { [weak self] file in
  756. self?.files.removeObject(file)
  757. self?.tableView.reloadData()
  758. }
  759. return cellView;
  760. } else if identifier?.rawValue == "size"{
  761. if row == 0 {
  762. let cellView = KMNTableHeaderCellView()
  763. cellView.wantsLayer = true
  764. cellView.layer?.backgroundColor = cellColor.cgColor
  765. cellView.titleLabel.stringValue = KMLocalizedString("Size")
  766. cellView.titleLabel.font = titleFont
  767. cellView.titleLabel.textColor = titleColor
  768. _initHeaderCellView(cellView: cellView)
  769. cellView.itemClick = { [weak self] idx, _ in
  770. if idx == 1 { // 排序
  771. let asc = self?.isSizeAsc_ ?? false
  772. if asc {
  773. self?.files.sort(){$0.fileSize > $1.fileSize}
  774. } else {
  775. self?.files.sort(){$0.fileSize <= $1.fileSize}
  776. }
  777. self?.isSizeAsc_ = !asc
  778. self?.reloadData()
  779. }
  780. }
  781. return cellView
  782. }
  783. let cellView = KMBatchTableCellView(type: .Size)
  784. cellView.updateInterface(file)
  785. return cellView;
  786. } else if identifier?.rawValue == "fileName"{
  787. if row == 0 {
  788. let cellView = KMNTableHeaderCellView()
  789. cellView.wantsLayer = true
  790. cellView.layer?.backgroundColor = cellColor.cgColor
  791. cellView.titleLabel.stringValue = KMLocalizedString("File Name")
  792. cellView.titleLabel.font = titleFont
  793. cellView.titleLabel.textColor = titleColor
  794. _initHeaderCellView(cellView: cellView)
  795. cellView.itemClick = { [weak self] idx, _ in
  796. if idx == 1 { // 排序
  797. let asc = self?.fileNameAsc_ ?? false
  798. if asc {
  799. self?.files.sort(){$0.filePath.lastPathComponent > $1.filePath.lastPathComponent}
  800. } else {
  801. self?.files.sort(){$0.filePath.lastPathComponent <= $1.filePath.lastPathComponent}
  802. }
  803. self?.fileNameAsc_ = !asc
  804. self?.reloadData()
  805. }
  806. }
  807. return cellView
  808. }
  809. let cellView = KMBatchTableCellView(type: .FileName)
  810. cellView.updateInterface(file)
  811. cellView.fileIv?.wantsLayer = true
  812. cellView.fileIv?.layer?.borderWidth = 1
  813. cellView.fileIv?.layer?.borderColor = ComponentLibrary.shared.getComponentColorFromKey("colorBorder/3-default").cgColor
  814. let rowView: KMBatchTableRowView = tableView.rowView(atRow: row, makeIfNecessary: true) as! KMBatchTableRowView
  815. if ((file.error) != nil) {
  816. rowView.backgroundColor = KMAppearance.Status.errBGColor();
  817. }
  818. return cellView;
  819. } else if identifier?.rawValue == "dpi"{
  820. let cellView = KMBatchTableCellView(type: .DPI)
  821. cellView.updateInterface(file)
  822. return cellView;
  823. } else if identifier?.rawValue == "dimensions"{
  824. if row == 0 {
  825. let cellView = KMNTableHeaderCellView()
  826. cellView.wantsLayer = true
  827. cellView.layer?.backgroundColor = cellColor.cgColor
  828. cellView.titleLabel.stringValue = KMLocalizedString("Dimensions")
  829. cellView.titleLabel.font = titleFont
  830. cellView.titleLabel.textColor = titleColor
  831. _initHeaderCellView(cellView: cellView)
  832. return cellView
  833. }
  834. let cellView = KMBatchTableCellView(type: .Size)
  835. if (file.fileType == .Image) {
  836. let image = NSImage(contentsOfFile: file.filePath)
  837. cellView.textField?.stringValue = String(Int(image?.size.width ?? 0)) + "x" + String(Int(image?.size.height ?? 0))
  838. }
  839. return cellView;
  840. }
  841. return nil;
  842. }
  843. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  844. let rowIdx = max(0, row-1)
  845. let file = self.files[rowIdx]
  846. if self.type == .CreatePDF {
  847. if row == 0 {
  848. return 32
  849. }
  850. if (file.error != nil) {
  851. return 104
  852. } else {
  853. return 80
  854. }
  855. } else {
  856. if file.fileType == .PDF {
  857. if (file.error != nil) {
  858. return 64
  859. } else {
  860. return 40
  861. }
  862. } else {
  863. return 0.0000001
  864. }
  865. }
  866. }
  867. func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
  868. if row == 0 {
  869. let rowView = KMBatchTableRowView()
  870. rowView.selectionBackgroundColorBlock = {
  871. return .clear
  872. }
  873. rowView.selectionHighlightStyle = .none
  874. rowView.isSelected = false
  875. return rowView
  876. }
  877. let rowView = KMBatchTableRowView()
  878. return rowView
  879. }
  880. func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
  881. if rowIndexes.first == 0 {
  882. return false
  883. }
  884. var theIndex = IndexSet()
  885. for idx in rowIndexes {
  886. theIndex.insert(idx-1)
  887. }
  888. let indexSetData = try? NSKeyedArchiver.archivedData(withRootObject: theIndex, requiringSecureCoding: true)
  889. pboard.declareTypes([NSPasteboard.PasteboardType.string], owner: self)
  890. pboard.setData(indexSetData, forType: NSPasteboard.PasteboardType(rawValue: KMBatchDragType) )
  891. return true
  892. }
  893. func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
  894. if row == 0 {
  895. return NSDragOperation(rawValue: 0)
  896. }
  897. var isCanDrag = false
  898. var result: NSDragOperation = []
  899. let pboard = info.draggingPasteboard
  900. if pboard.availableType(from: [.fileURL]) != nil {
  901. guard let pbItems = pboard.pasteboardItems else {
  902. return NSDragOperation(rawValue: 0)
  903. }
  904. var hasValidFile = false
  905. for item in pbItems {
  906. guard let data = item.string(forType: .fileURL), let _url = URL(string: data) else {
  907. continue
  908. }
  909. var isDirectory: ObjCBool = false
  910. let fileExists = FileManager.default.fileExists(atPath: _url.path, isDirectory: &isDirectory)
  911. if fileExists && isDirectory.boolValue {
  912. let containFile = folderContainAvailableFile(_url.path)
  913. if containFile {
  914. isCanDrag = true
  915. break
  916. }
  917. } else {
  918. if let UTType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, _url.pathExtension as CFString, nil)?.takeRetainedValue() as String? {
  919. if self.type == .CreatePDF {
  920. if UTTypeConformsTo(UTType as CFString, kUTTypeImage) {
  921. isCanDrag = true
  922. }
  923. } else {
  924. if UTTypeConformsTo(UTType as CFString, kUTTypePDF) {
  925. isCanDrag = true
  926. }
  927. }
  928. }
  929. if isCanDrag {
  930. break
  931. }
  932. }
  933. }
  934. if isCanDrag {
  935. result = .copy
  936. }
  937. return result
  938. } else {
  939. return .move
  940. }
  941. }
  942. func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
  943. let pboard = info.draggingPasteboard
  944. if pboard.availableType(from: [.init(KMBatchDragType)]) != nil {
  945. guard let rowData = pboard.data(forType: .init(KMBatchDragType)),
  946. let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: rowData) as? NSIndexSet else { return false }
  947. let backUpArray = self.files
  948. var referenceIndex = -1
  949. rowIndexes.enumerate(options: .reverse, using: { (idx, stop) in
  950. let theIdx = max(0, idx)
  951. let sortFile = backUpArray[theIdx]
  952. let theRow = row-1
  953. if referenceIndex < 0 {
  954. if idx > theRow {
  955. self.files.remove(at: idx)
  956. self.files.insert(sortFile, at: theRow)
  957. } else if idx < theRow {
  958. if theRow > self.files.count {
  959. self.files.remove(at: idx)
  960. self.files.append(sortFile)
  961. } else {
  962. self.files.remove(at: idx)
  963. self.files.insert(sortFile, at: theRow - 1)
  964. }
  965. }
  966. referenceIndex = self.files.firstIndex(of: sortFile) ?? -1
  967. } else {
  968. let currentIndex = self.files.firstIndex(of: sortFile) ?? -1
  969. if currentIndex > referenceIndex {
  970. self.files.remove(at: currentIndex)
  971. self.files.insert(sortFile, at: referenceIndex)
  972. } else {
  973. referenceIndex -= 1
  974. self.files.remove(at: currentIndex)
  975. self.files.insert(sortFile, at: referenceIndex)
  976. }
  977. }
  978. })
  979. self.tableView.reloadData()
  980. return true
  981. } else if pboard.availableType(from: [.fileURL]) != nil {
  982. if (pboard.pasteboardItems == nil) {
  983. return true
  984. }
  985. let allFilesArray = NSMutableArray()
  986. for item in pboard.pasteboardItems! {
  987. let fileURL = item.string(forType: .fileURL)
  988. if (fileURL == nil) {
  989. continue
  990. }
  991. let path = URL.init(string: fileURL!)
  992. if (path == nil) {
  993. continue
  994. }
  995. var isFolder = ObjCBool(false)
  996. FileManager.default.fileExists(atPath: path!.path, isDirectory: &isFolder)
  997. if isFolder.boolValue {
  998. let containFiles = fetchAvailableFilesInFolder(path!.path)
  999. allFilesArray.addObjects(from: containFiles)
  1000. } else {
  1001. allFilesArray.add(path!.path)
  1002. }
  1003. }
  1004. var insertArray = NSMutableArray()
  1005. lockFilePathArr?.removeAllObjects()
  1006. lockFileIndex = 0
  1007. for i in 0..<allFilesArray.count {
  1008. let filePath: String = allFilesArray[i] as! String
  1009. if filePath.hasSuffix(".pdf") || filePath.hasSuffix(".PDF") {
  1010. let document = CPDFDocument(url: URL(fileURLWithPath: filePath))
  1011. if let pdf = CPDFDocument(url: URL(fileURLWithPath: filePath)) {
  1012. if !pdf.allowsPrinting || !pdf.allowsCopying {
  1013. let alert = NSAlert()
  1014. alert.alertStyle = .critical
  1015. alert.messageText = KMLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1016. alert.runModal()
  1017. continue
  1018. } else if document?.isLocked ?? false {
  1019. lockFilePathArr?.add(filePath)
  1020. } else {
  1021. let file = KMBatchOperateFile(filePath: filePath, type: self.type!)
  1022. if !(self.files.contains(file) ) {
  1023. insertArray.add(file)
  1024. }
  1025. }
  1026. }
  1027. } else {
  1028. let file = KMBatchOperateFile(filePath: filePath, type: self.type!)
  1029. if !(self.files.contains(file) ) {
  1030. insertArray.add(file)
  1031. }
  1032. }
  1033. }
  1034. if !(IAPProductsManager.default().isAvailableAllFunction)() {
  1035. if self.files.count < 1 && insertArray.count > 0 {
  1036. let firstObject = insertArray.firstObject
  1037. insertArray.removeAllObjects()
  1038. insertArray.add(firstObject as Any)
  1039. } else {
  1040. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1041. return false
  1042. }
  1043. }
  1044. for i in 0..<insertArray.count {
  1045. self.files.insert(insertArray[i] as! KMBatchOperateFile, at: row + i)
  1046. }
  1047. self.tableView.reloadData()
  1048. if lockFilePathArr!.count > 0 {
  1049. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  1050. self.openPasswordWindow()
  1051. }
  1052. }
  1053. return true
  1054. }
  1055. return false
  1056. }
  1057. }
  1058. // MARK: - NSMenuDelegate, NSMenuItemValidation
  1059. extension KMBatchOperateLeftViewController: NSMenuDelegate, NSMenuItemValidation {
  1060. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  1061. let action = menuItem.action
  1062. if action == #selector(menuItem_ShowInFinder(_:)) || action == #selector(menuItem_Delete(_:)) {
  1063. if tableView.clickedRow == -1 {
  1064. return false
  1065. }
  1066. return true
  1067. }
  1068. return true
  1069. }
  1070. }
  1071. //MARK: - ComponentDropdownDelegate
  1072. extension KMBatchOperateLeftViewController: ComponentDropdownDelegate {
  1073. func componentDropdownDidShowMenuItem(dropdown: ComponentDropdown) {
  1074. showGroupView()
  1075. }
  1076. }
  1077. //MARK: - ComponentGroupDelegate
  1078. extension KMBatchOperateLeftViewController: ComponentGroupDelegate {
  1079. func componentGroupDidDismiss(group: ComponentGroup?) {
  1080. removeGroupView()
  1081. }
  1082. func componentGroupDidSelect(group: ComponentGroup?, menuItemProperty: ComponentMenuitemProperty?) {
  1083. if let selItem = menuItemProperty {
  1084. let index = group?.menuItemArr.firstIndex(of: selItem)
  1085. if index == 0 {
  1086. chooseFile()
  1087. } else if index == 1 {
  1088. _addFolderAction()
  1089. } else if index == 2 {
  1090. let pboard = NSPasteboard.general
  1091. if let document = self.openDocumentWithImageFromPasteboard(pboard, error: nil) {
  1092. // Document opened successfully
  1093. if let page = document.page(at: 0) {
  1094. let data = page.PDFListViewTIFFData(for: page.bounds)
  1095. var path = self._saveImagePath() + "/Untitled.png"
  1096. path = KMTools.getUniqueFilePath(filePath: path)
  1097. try?data?.write(to: URL(fileURLWithPath: path), options: .atomic)
  1098. self.addFilesToList(addArray: [path])
  1099. }
  1100. }
  1101. } else if index == 3 {
  1102. chooseFileFromCamera()
  1103. }
  1104. }
  1105. }
  1106. }