KMBatchOperateLeftViewController.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. //
  2. // KMBatchOperateLeftViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by kdanmobile on 2023/10/26.
  6. //
  7. import Cocoa
  8. let KMBatchDragType = "KMBatchDragType"
  9. class KMBatchOperateLeftViewController: NSViewController,NSTableViewDelegate,NSTableViewDataSource{
  10. @IBOutlet var selectFileButton: KMLongerButton!
  11. @IBOutlet var deleteFileButton: NSButton!
  12. @IBOutlet var tableView: NSTableView!
  13. @IBOutlet var indexTableColumn: NSTableColumn!
  14. @IBOutlet var fileNameTableColumn: NSTableColumn!
  15. @IBOutlet var pageRangeTableColumn: NSTableColumn!
  16. @IBOutlet var sizeTableColumn: NSTableColumn!
  17. @IBOutlet var stateTableColumn: NSTableColumn!
  18. @IBOutlet var DPIColumn: NSTableColumn!
  19. @IBOutlet var dimensionsTableColumn: NSTableColumn!
  20. @IBOutlet var headerOperateView: NSView!
  21. @IBOutlet var showInFinderMenuItem: NSMenuItem!
  22. @IBOutlet var deleteMenuItem: NSMenuItem!
  23. @IBOutlet var blankView: KMBlankView!
  24. var files: [KMBatchOperateFile] = []
  25. var type: KMBatchOperationType?
  26. var lockFilePathArr: NSMutableArray?
  27. var lockFileIndex: Int = 0
  28. var popOver: NSPopover?
  29. var progressInt: Int = 0
  30. deinit {
  31. NotificationCenter.default.removeObserver(self)
  32. DistributedNotificationCenter.default().removeObserver(self)
  33. }
  34. override func viewDidLoad() {
  35. super.viewDidLoad()
  36. NotificationCenter.default.addObserver(self.tableView!, selector: #selector(self.reloadData), name: NSNotification.Name(kNeedChangePageRangeNotification), object: nil)
  37. NotificationCenter.default.addObserver(self, selector: #selector(imageToPDFSuccessNotification(aNotification:)), name: NSNotification.Name("KMBatchOperateImageToPDFSuccessNotification"), object: nil)
  38. DistributedNotificationCenter.default.addObserver(self, selector: #selector(themeChanged(notification:)), name: NSNotification.Name("AppleInterfaceThemeChangedNotification"), object: nil)
  39. for i in 0..<self.tableView.tableColumns.count {
  40. let column = self.tableView.tableColumns[i]
  41. column.headerCell = KMTableHeaderCell(textCell: column.title)
  42. }
  43. self.deleteFileButton.addHoverEffect = true
  44. self.indexTableColumn.resizingMask = []
  45. self.fileNameTableColumn.resizingMask = .autoresizingMask
  46. self.pageRangeTableColumn.resizingMask = []
  47. self.sizeTableColumn.resizingMask = []
  48. self.stateTableColumn.resizingMask = []
  49. self.DPIColumn.resizingMask = []
  50. self.dimensionsTableColumn.resizingMask = []
  51. self.tableView.moveColumn(5, toColumn: 2)
  52. self.indexTableColumn.title = " \(NSLocalizedString("Index", comment: ""))"
  53. self.fileNameTableColumn.title = NSLocalizedString("File Name", comment: "")
  54. self.pageRangeTableColumn.title = NSLocalizedString("Page Range", comment: "")
  55. self.sizeTableColumn.title = NSLocalizedString("Size", comment: "")
  56. self.stateTableColumn.title = NSLocalizedString("Status", comment: "")
  57. self.DPIColumn.title = NSLocalizedString("DPI", comment: "")
  58. self.dimensionsTableColumn.title = NSLocalizedString("Dimensions", comment: "")
  59. self.DPIColumn.isHidden = true
  60. self.tableView.intercellSpacing = CGSize(width: 0, height: 0)
  61. self.tableView.backgroundColor = KMAppearance.Layout.bgColor()
  62. self.tableView.allowsColumnReordering = false
  63. self.tableView.allowsMultipleSelection = true
  64. self.tableView.enclosingScrollView?.borderType = .noBorder
  65. self.headerOperateView.wantsLayer = true
  66. self.tableView.registerForDraggedTypes([NSPasteboard.PasteboardType.string,NSPasteboard.PasteboardType.fileURL]) //[KMBatchDragType,NSFilenamesPboardType]
  67. self.lockFilePathArr = NSMutableArray()
  68. self.lockFileIndex = 0
  69. self.progressInt = 0
  70. self.selectFileButton.title = " " + NSLocalizedString("Add Files", comment: "")
  71. self.selectFileButton.wantsLayer = true
  72. self.selectFileButton.layer?.borderWidth = 1.0
  73. self.selectFileButton.layer?.borderColor = KMAppearance.Interactive.m0Color().cgColor
  74. self.selectFileButton.layer?.cornerRadius = 1.0
  75. self.selectFileButton.setTitleColor(KMAppearance.Layout.mColor())
  76. self.selectFileButton.containerViewController = self
  77. self.showInFinderMenuItem.title = NSLocalizedString("Show in Finder", comment: "")
  78. self.deleteMenuItem.title = NSLocalizedString("Delete", comment: "")
  79. self.blankView.wantsLayer = true
  80. self.blankView.layer?.backgroundColor = NSColor.clear.cgColor
  81. self.blankView.titleLabel.stringValue = NSLocalizedString("Select Files", comment: "")
  82. self.blankView.imageView.isHidden = true
  83. self.blankView.addButton.isHidden = false
  84. self.blankView.secondTitleLabel.stringValue = NSLocalizedString("Drop files here or Click Add Files at upper left corner. You can drag files to reorder as you need.", comment: "")
  85. self.blankView.mouseActionCallBack = { [weak self] mouseType in
  86. guard let self = self else { return }
  87. if mouseType == .mouseEnter {
  88. self.blankView.imageView.image = NSImage(named: "KMImageNameEmptyListHov")
  89. } else if mouseType == .mouseExit {
  90. self.blankView.imageView.image = NSImage(named: "KMImageNameEmptyListNor")
  91. } else if mouseType == .mouseDown {
  92. self.blankView.imageView.image = NSImage(named: "KMImageNameEmptyListPre")
  93. self.chooseFile()
  94. } else if mouseType == .mouseUp {
  95. self.blankView.imageView.image = NSImage(named: "KMImageNameEmptyListHov")
  96. }
  97. }
  98. updateViewColor()
  99. }
  100. @objc func reloadData() {
  101. if Thread.isMainThread {
  102. tableView.reloadData()
  103. } else {
  104. DispatchQueue.main.async {
  105. self.tableView.reloadData()
  106. }
  107. }
  108. }
  109. @objc func imageToPDFSuccessNotification(aNotification: Notification) {
  110. guard let dict = aNotification.userInfo, let isSuccess = dict["isSuccess"] as? Bool else { return }
  111. if isSuccess {
  112. progressInt = 1
  113. } else {
  114. progressInt = -1
  115. }
  116. DispatchQueue.main.async {
  117. self.tableView.reloadData()
  118. }
  119. }
  120. @objc func themeChanged(notification: Notification) {
  121. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: {
  122. self.updateViewColor()
  123. })
  124. }
  125. func updateViewColor() {
  126. self.view.wantsLayer = true
  127. if KMAppearance.isDarkMode() {
  128. self.headerOperateView.layer?.backgroundColor = NSColor(red: 0.055, green: 0.067, blue: 0.078, alpha: 1).cgColor
  129. } else {
  130. self.headerOperateView.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  131. }
  132. }
  133. func chooseFile() {
  134. #if VERSION_FREE
  135. if KMMemberInfo.shared.isMemberAllFunction == false {
  136. if files.count >= 1 {
  137. let winC = KMProductCompareWC.shared
  138. if type == .CreatePDF {
  139. winC.kEventName = "Onbrd_ImagetoPDF_BuyNow"
  140. }
  141. KMMemberInfo.shared.advancedFunctionUsage()
  142. return
  143. }
  144. }
  145. #endif
  146. self.progressInt = 0
  147. let panel = NSOpenPanel()
  148. if type == .CreatePDF {
  149. panel.allowedFileTypes = KMImageToPDFMethod.supportedImageTypes()
  150. } else {
  151. panel.allowedFileTypes = ["pdf", "PDF"]
  152. }
  153. if KMMemberInfo.shared.isMemberAllFunction {
  154. panel.allowsMultipleSelection = true
  155. panel.canChooseDirectories = true
  156. }
  157. panel.canChooseFiles = true
  158. #if VERSION_FREE
  159. #else
  160. panel.message = NSLocalizedString("To select multiple files press cmd ⌘ button on keyboard and click on the target files one by one.", comment: "")
  161. #endif
  162. panel.beginSheetModal(for: self.view.window!) {
  163. (result) in
  164. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  165. let addArray = NSMutableArray()
  166. for fileURL in panel.urls {
  167. let filePath = fileURL.path
  168. var isDirectory = ObjCBool(false)
  169. FileManager.default.fileExists(atPath: filePath, isDirectory: &isDirectory)
  170. if isDirectory.boolValue {
  171. let containFiles = self.fetchAvailableFiles(in: filePath)
  172. addArray.addObjects(from: containFiles)
  173. } else {
  174. let typeIdentifier =
  175. UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, filePath.customPathExtension as CFString, nil)
  176. let TypeCFString = typeIdentifier!.takeRetainedValue() as String
  177. if self.type == .CreatePDF {
  178. if UTTypeConformsTo(TypeCFString as CFString, kUTTypeImage) {
  179. addArray.add(filePath)
  180. }
  181. } else {
  182. if UTTypeConformsTo(TypeCFString as CFString, kUTTypePDF) {
  183. addArray.add(filePath)
  184. }
  185. }
  186. }
  187. }
  188. self.addFilesToList(addArray: addArray)
  189. }
  190. }
  191. }
  192. func fetchAvailableFiles(in folderPath: String) -> [String] {
  193. let array = NSMutableArray()
  194. let subFileArray = (FileManager.default.subpaths(atPath: folderPath)! as NSArray).mutableCopy() as? NSMutableArray
  195. for i in 0..<subFileArray!.count {
  196. if let path = (folderPath as NSString).appendingPathComponent(subFileArray!.object(at: i) as! String) as String? {
  197. if let UTTypeString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, path.customPathExtension as CFString, nil)?.takeRetainedValue() as String? {
  198. let TypeCFString = UTTypeString as CFString
  199. if self.type == .CreatePDF {
  200. if UTTypeConformsTo(TypeCFString, kUTTypeImage) {
  201. array.add(path)
  202. }
  203. } else {
  204. if UTTypeConformsTo(TypeCFString, kUTTypePDF) {
  205. array.add(path)
  206. }
  207. }
  208. }
  209. }
  210. }
  211. return array as! [String]
  212. }
  213. func addFilesToList(addArray: NSMutableArray) {
  214. self.lockFilePathArr!.removeAllObjects()
  215. self.lockFileIndex = 0
  216. for i in 0..<addArray.count {
  217. let filePath = addArray[i] as! String
  218. let UTTypeString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, filePath.customPathExtension as CFString, nil)!.takeRetainedValue() as String
  219. let TypeCFString = UTTypeString as CFString
  220. if UTTypeConformsTo(TypeCFString, kUTTypePDF) {
  221. let document = CPDFDocument(url: URL(fileURLWithPath: filePath))
  222. if document?.isLocked == true {
  223. var isContaint = false
  224. for file in self.files {
  225. if (file as AnyObject).filePath == filePath {
  226. isContaint = true
  227. break
  228. }
  229. }
  230. if !isContaint {
  231. self.lockFilePathArr!.add(filePath)
  232. }
  233. } else {
  234. let file = KMBatchOperateFile(filePath: addArray[i] as! String, type: self.type!)
  235. if !self.files.contains(file) {
  236. self.files.append(file)
  237. }
  238. }
  239. } else {
  240. let file = KMBatchOperateFile(filePath: addArray[i] as! String, type: self.type!)
  241. if !self.files.contains(file) {
  242. self.files.append(file)
  243. }
  244. }
  245. }
  246. self.tableView.reloadData()
  247. if self.lockFilePathArr!.count > 0 {
  248. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  249. self.openPasswordWindow()
  250. }
  251. }
  252. }
  253. func openPasswordWindow() {
  254. if lockFilePathArr!.count > lockFileIndex {
  255. let filePath = lockFilePathArr![lockFileIndex] as! String
  256. KMBaseWindowController.checkPassword(url: URL(fileURLWithPath: filePath), type: .owner) { [unowned self] success, resultPassword in
  257. self.closePwd()
  258. if !resultPassword.isEmpty {
  259. let file = KMBatchOperateFile(filePath: filePath, type: self.type!)
  260. file.password = resultPassword
  261. self.files.append(file)
  262. self.tableView.reloadData()
  263. }
  264. self.lockFileIndex += 1
  265. if self.lockFilePathArr?.count ?? 0 > self.lockFileIndex {
  266. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  267. self.openPasswordWindow()
  268. }
  269. } else {
  270. self.tableView.reloadData()
  271. }
  272. }
  273. }
  274. }
  275. func closePwd() {
  276. self.km_endSheet()
  277. }
  278. func chooseFileFromCamera() {
  279. self.progressInt = 0
  280. let vc = KMDeviceBrowserWindowController.shared
  281. vc.type = .camera
  282. vc.importCameraFileCallback = { [weak self](url: NSURL) -> Void in
  283. self?.addFilesToList(addArray: [url.path!])
  284. }
  285. vc.showWindow(nil)
  286. }
  287. func chooseFileFromScanner() {
  288. self.progressInt = 0
  289. let vc = KMDeviceBrowserWindowController.shared
  290. vc.type = .scanner
  291. vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  292. self?.addFilesToList(addArray: [url.path!])
  293. }
  294. vc.showWindow(nil)
  295. }
  296. @IBAction func buttonClicked_SelectFile(_ sender: Any) {
  297. }
  298. @IBAction func blankViewAddFileAction(_ sender: Any) {
  299. self.chooseFile()
  300. }
  301. @IBAction func buttonClicked_DeleteFile(_ sender: Any) {
  302. let set = self.tableView.selectedRowIndexes
  303. let newArr: NSMutableArray = NSMutableArray.init(array: self.files)
  304. let arr = newArr.objects(at: set)
  305. if arr.count > 0 {
  306. newArr.removeObjects(in: arr)
  307. self.files = newArr as! [KMBatchOperateFile]
  308. self.tableView.reloadData()
  309. } else {
  310. // if KMAlertWindowController.needShowRemoveAllFilesHint() {
  311. let alert = NSAlert()
  312. alert.alertStyle = .critical
  313. alert.messageText = NSLocalizedString("Clear All Recents", comment: "")+"?"
  314. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  315. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  316. alert.beginSheetModal(for: self.view.window!) {[weak self] response in
  317. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  318. self?.files.removeAll()
  319. self?.tableView.reloadData()
  320. }
  321. }
  322. // } else {
  323. // self.files.removeAll()
  324. // self.tableView.reloadData()
  325. // }
  326. }
  327. }
  328. func fetchAvailableFilesInFolder(_ folderPath: String) -> [String] {
  329. var array: [String] = []
  330. let subFileArray = FileManager().subpaths(atPath: folderPath)
  331. for i in 0..<subFileArray!.count {
  332. let path = folderPath.stringByAppendingPathComponent(subFileArray![i])
  333. let TypeCFString = KMTools.UTIforFileExtension(path.customPathExtension) as CFString
  334. if self.type == .CreatePDF {
  335. if UTTypeConformsTo(TypeCFString, kUTTypeImage) {
  336. array.append(path)
  337. }
  338. } else {
  339. if UTTypeConformsTo(TypeCFString, kUTTypePDF) {
  340. array.append(path)
  341. }
  342. }
  343. // UTTypeString?.release()
  344. }
  345. return array
  346. }
  347. func folderContainAvailableFile(_ folderPath: String) -> Bool {
  348. var containFile = false
  349. guard let subFileArray = FileManager.default.subpaths(atPath: folderPath) else {
  350. return containFile
  351. }
  352. for i in 0..<subFileArray.count {
  353. let path = folderPath.stringByAppendingPathComponent(subFileArray[i] )
  354. let TypeCFString = KMTools.UTIforFileExtension(path.customPathExtension) as CFString
  355. if type == .CreatePDF {
  356. if UTTypeConformsTo(TypeCFString, kUTTypeImage) {
  357. containFile = true
  358. }
  359. } else {
  360. if UTTypeConformsTo(TypeCFString, kUTTypePDF) {
  361. containFile = true
  362. }
  363. }
  364. // UTTypeString?.release()
  365. if containFile {
  366. break
  367. }
  368. }
  369. return containFile
  370. }
  371. func switchToOperateType(_ type: KMBatchOperationType) {
  372. self.type = type
  373. self.indexTableColumn.isHidden = false
  374. self.fileNameTableColumn.isHidden = false
  375. self.pageRangeTableColumn.isHidden = false
  376. self.sizeTableColumn.isHidden = false
  377. self.stateTableColumn.isHidden = false
  378. self.DPIColumn.isHidden = true
  379. self.dimensionsTableColumn.isHidden = true
  380. if type == .Compress || type == .AddPassword || type == .RemovePassword || type == .RemoveWatermark || type == .RemoveBackground || type == .RemoveHeaderFooter || type == .RemoveBates || type == .CreatePDF {
  381. self.pageRangeTableColumn.isHidden = true
  382. } else {
  383. self.pageRangeTableColumn.isHidden = false
  384. }
  385. self.selectFileButton.isImageToPDF = type == .CreatePDF
  386. if type == .CreatePDF {
  387. self.pageRangeTableColumn.isHidden = false
  388. self.pageRangeTableColumn.title = NSLocalizedString("Dimensions", comment: "")
  389. }
  390. for i in 0..<self.files.count {
  391. let file = self.files[i]
  392. file.currentOperateType = type
  393. }
  394. self.tableView.sizeToFit()
  395. self.tableView.reloadData()
  396. }
  397. @IBAction func menuItem_ShowInFinder(_ sender: Any) {
  398. let row = self.tableView.clickedRow
  399. let file: KMBatchOperateFile = self.files[row]
  400. if file.currentOperateInfo?.status == .Success {
  401. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: file.currentOperateInfo!.outPutPath!)])
  402. }else {
  403. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: file.filePath)])
  404. }
  405. }
  406. @IBAction func menuItem_Delete(_ sender: Any) {
  407. let row = self.tableView.clickedRow
  408. self.files.remove(at: row)
  409. self.tableView.reloadData()
  410. }
  411. func addOpendFile() {
  412. let documentArray = NSDocumentController.shared.documents
  413. var pdfArray = NSMutableArray()
  414. for i in 0..<documentArray.count {
  415. let document = documentArray[i]
  416. let path: String = document.fileURL?.path ?? ""
  417. let UTTypeString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, path.customPathExtension as CFString, nil)?.takeRetainedValue() as String?
  418. let TypeCFString = UTTypeString as CFString?
  419. if UTTypeConformsTo(TypeCFString!, kUTTypePDF) {
  420. pdfArray.add(path as Any)
  421. } else {
  422. }
  423. }
  424. if KMMemberInfo.shared.isMemberAllFunction == false {
  425. if self.files.count < 1 {
  426. pdfArray = NSMutableArray(array: [pdfArray.firstObject as Any])
  427. } else {
  428. KMMemberInfo.shared.advancedFunctionUsage()
  429. return
  430. }
  431. }
  432. addFilesToList(addArray: pdfArray)
  433. }
  434. func numberOfRows(in tableView: NSTableView) -> Int {
  435. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMBatchFilesCountNotification"), object: self.files, userInfo: [kObjectKey : self])
  436. self.deleteFileButton.isEnabled = self.files.count > 0
  437. self.blankView.isHidden = self.files.count > 0
  438. return self.files.count;
  439. }
  440. func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  441. let identifier = tableColumn?.identifier
  442. let file = self.files[row]
  443. if identifier?.rawValue == "index" {
  444. let cellView = KMBatchTableCellView(type: .Size)
  445. _ = row + 1
  446. cellView.textField?.stringValue = String(format: "%d", row + 1);
  447. return cellView;
  448. } else if identifier?.rawValue == "pageRange"{
  449. if (file.currentOperateType == .CreatePDF) {
  450. let cellView = KMBatchTableCellView(type: .Size)
  451. if (file.fileType == .Image) {
  452. let image = NSImage(contentsOfFile: file.filePath)
  453. cellView.textField?.stringValue = String(Int(image?.size.width ?? 0)) + "x" + String(Int(image?.size.height ?? 0))
  454. }
  455. return cellView;
  456. } else {
  457. let cellView = KMBatchTableCellView(type: .PageRange)
  458. cellView.updateInterface(file)
  459. return cellView;
  460. }
  461. } else if identifier?.rawValue == "status"{
  462. let cellView = KMBatchTableCellView(type: .Status)
  463. if (file.currentOperateType == .CreatePDF) {
  464. cellView.updateInterface(file: file, progress: file.progress ?? 0)
  465. } else {
  466. cellView.updateInterface(file: file, progress: file.progress ?? 0)
  467. }
  468. cellView.removeFileCallBack = { [weak self] file in
  469. self?.files.removeObject(file)
  470. self?.tableView.reloadData()
  471. }
  472. return cellView;
  473. } else if identifier?.rawValue == "size"{
  474. let cellView = KMBatchTableCellView(type: .Size)
  475. cellView.updateInterface(file)
  476. return cellView;
  477. } else if identifier?.rawValue == "fileName"{
  478. let cellView = KMBatchTableCellView(type: .FileName)
  479. cellView.updateInterface(file)
  480. let rowView: KMBatchTableRowView = tableView.rowView(atRow: row, makeIfNecessary: true) as! KMBatchTableRowView
  481. if ((file.error) != nil) {
  482. rowView.backgroundColor = KMAppearance.Status.errBGColor();
  483. }
  484. return cellView;
  485. } else if identifier?.rawValue == "dpi"{
  486. let cellView = KMBatchTableCellView(type: .DPI)
  487. cellView.updateInterface(file)
  488. return cellView;
  489. } else if identifier?.rawValue == "dimensions"{
  490. let cellView = KMBatchTableCellView(type: .Size)
  491. if (file.fileType == .Image) {
  492. let image = NSImage(contentsOfFile: file.filePath)
  493. cellView.textField?.stringValue = String(Int(image?.size.width ?? 0)) + "x" + String(Int(image?.size.height ?? 0))
  494. }
  495. return cellView;
  496. }
  497. return nil;
  498. }
  499. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  500. let file = self.files[row]
  501. if self.type == .CreatePDF {
  502. if (file.error != nil) {
  503. return 64
  504. } else {
  505. return 40
  506. }
  507. } else {
  508. if file.fileType == .PDF {
  509. if (file.error != nil) {
  510. return 64
  511. } else {
  512. return 40
  513. }
  514. } else {
  515. return 0.0000001
  516. }
  517. }
  518. }
  519. func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
  520. let rowView = KMBatchTableRowView()
  521. return rowView
  522. }
  523. func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
  524. let indexSetData = try? NSKeyedArchiver.archivedData(withRootObject: rowIndexes, requiringSecureCoding: true)
  525. pboard.declareTypes([NSPasteboard.PasteboardType.string], owner: self)
  526. pboard.setData(indexSetData, forType: NSPasteboard.PasteboardType(rawValue: KMBatchDragType) )
  527. return true
  528. }
  529. func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
  530. var isCanDrag = false
  531. var result: NSDragOperation = []
  532. let pboard = info.draggingPasteboard
  533. if pboard.availableType(from: [.fileURL]) != nil {
  534. guard let pbItems = pboard.pasteboardItems else {
  535. return NSDragOperation(rawValue: 0)
  536. }
  537. var hasValidFile = false
  538. for item in pbItems {
  539. guard let data = item.string(forType: .fileURL), let _url = URL(string: data) else {
  540. continue
  541. }
  542. var isDirectory: ObjCBool = false
  543. let fileExists = FileManager.default.fileExists(atPath: _url.path, isDirectory: &isDirectory)
  544. if fileExists && isDirectory.boolValue {
  545. let containFile = folderContainAvailableFile(_url.path)
  546. if containFile {
  547. isCanDrag = true
  548. break
  549. }
  550. } else {
  551. if let UTType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, _url.pathExtension as CFString, nil)?.takeRetainedValue() as String? {
  552. if self.type == .CreatePDF {
  553. if UTTypeConformsTo(UTType as CFString, kUTTypeImage) {
  554. isCanDrag = true
  555. }
  556. } else {
  557. if UTTypeConformsTo(UTType as CFString, kUTTypePDF) {
  558. isCanDrag = true
  559. }
  560. }
  561. }
  562. if isCanDrag {
  563. break
  564. }
  565. }
  566. }
  567. if isCanDrag {
  568. result = .copy
  569. }
  570. return result
  571. } else {
  572. return .move
  573. }
  574. }
  575. func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
  576. let pboard = info.draggingPasteboard
  577. if pboard.availableType(from: [.init(KMBatchDragType)]) != nil {
  578. guard let rowData = pboard.data(forType: .init(KMBatchDragType)),
  579. let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: rowData) as? NSIndexSet else { return false }
  580. let backUpArray = self.files
  581. var referenceIndex = -1
  582. rowIndexes.enumerate(options: .reverse, using: { (idx, stop) in
  583. let sortFile = backUpArray[idx]
  584. if referenceIndex < 0 {
  585. if idx > row {
  586. self.files.remove(at: idx)
  587. self.files.insert(sortFile, at: row)
  588. } else if idx < row {
  589. if row > self.files.count {
  590. self.files.remove(at: idx)
  591. self.files.append(sortFile)
  592. } else {
  593. self.files.remove(at: idx)
  594. self.files.insert(sortFile, at: row - 1)
  595. }
  596. }
  597. referenceIndex = self.files.firstIndex(of: sortFile) ?? -1
  598. } else {
  599. let currentIndex = self.files.firstIndex(of: sortFile) ?? -1
  600. if currentIndex > referenceIndex {
  601. self.files.remove(at: currentIndex)
  602. self.files.insert(sortFile, at: referenceIndex)
  603. } else {
  604. referenceIndex -= 1
  605. self.files.remove(at: currentIndex)
  606. self.files.insert(sortFile, at: referenceIndex)
  607. }
  608. }
  609. })
  610. self.tableView.reloadData()
  611. return true
  612. } else if pboard.availableType(from: [.fileURL]) != nil {
  613. if (pboard.pasteboardItems == nil) {
  614. return true
  615. }
  616. let allFilesArray = NSMutableArray()
  617. for item in pboard.pasteboardItems! {
  618. let fileURL = item.string(forType: .fileURL)
  619. if (fileURL == nil) {
  620. continue
  621. }
  622. let path = URL.init(string: fileURL!)
  623. if (path == nil) {
  624. continue
  625. }
  626. var isFolder = ObjCBool(false)
  627. FileManager.default.fileExists(atPath: path!.path, isDirectory: &isFolder)
  628. if isFolder.boolValue {
  629. let containFiles = fetchAvailableFilesInFolder(path!.path)
  630. allFilesArray.addObjects(from: containFiles)
  631. } else {
  632. allFilesArray.add(path!.path)
  633. }
  634. }
  635. var insertArray = NSMutableArray()
  636. lockFilePathArr?.removeAllObjects()
  637. lockFileIndex = 0
  638. for i in 0..<allFilesArray.count {
  639. let filePath: String = allFilesArray[i] as! String
  640. if filePath.hasSuffix(".pdf") || filePath.hasSuffix(".PDF") {
  641. let document = CPDFDocument(url: URL(fileURLWithPath: filePath))
  642. if let pdf = CPDFDocument(url: URL(fileURLWithPath: filePath)) {
  643. if !pdf.allowsPrinting || !pdf.allowsCopying {
  644. let alert = NSAlert()
  645. alert.alertStyle = .critical
  646. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  647. alert.runModal()
  648. continue
  649. } else if document?.isLocked ?? false {
  650. lockFilePathArr?.add(filePath)
  651. } else {
  652. let file = KMBatchOperateFile(filePath: filePath, type: self.type!)
  653. if !(self.files.contains(file) ) {
  654. insertArray.add(file)
  655. }
  656. }
  657. }
  658. } else {
  659. let file = KMBatchOperateFile(filePath: filePath, type: self.type!)
  660. if !(self.files.contains(file) ) {
  661. insertArray.add(file)
  662. }
  663. }
  664. }
  665. if KMMemberInfo.shared.isMemberAllFunction == false {
  666. if self.files.count < 1 && insertArray.count > 0 {
  667. let firstObject = insertArray.firstObject
  668. insertArray.removeAllObjects()
  669. insertArray.add(firstObject as Any)
  670. } else {
  671. KMMemberInfo.shared.advancedFunctionUsage()
  672. return false
  673. }
  674. }
  675. for i in 0..<insertArray.count {
  676. self.files.insert(insertArray[i] as! KMBatchOperateFile, at: row + i)
  677. }
  678. self.tableView.reloadData()
  679. if lockFilePathArr!.count > 0 {
  680. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  681. self.openPasswordWindow()
  682. }
  683. }
  684. return true
  685. }
  686. return false
  687. }
  688. func switchToOperateType(_ operateType: KMBatchOperationType, files: [KMBatchOperateFile]) {
  689. switchToOperateType(operateType)
  690. self.files = files
  691. self.tableView.reloadData()
  692. }
  693. func checkNeedPasswordSwitchToOperateType(_ operateType: KMBatchOperationType, files: [KMBatchOperateFile]) {
  694. switchToOperateType(operateType)
  695. var arr: [String] = []
  696. for i in 0..<files.count {
  697. let file = files[i]
  698. arr.append(file.filePath)
  699. }
  700. self.files = files
  701. self.files.removeAll()
  702. addFilesToList(addArray: NSMutableArray.init(array: arr))
  703. self.tableView.reloadData()
  704. }
  705. func reloadFile(_ file: KMBatchOperateFile) {
  706. var rowIndexSet = IndexSet()
  707. for i in 0..<self.files.count {
  708. if file.filePath == self.files[i].filePath {
  709. rowIndexSet.insert(i)
  710. break
  711. }
  712. }
  713. var columnIndexSet = IndexSet()
  714. for i in 0..<self.tableView.numberOfColumns {
  715. let identifier = self.tableView.tableColumns[i].identifier
  716. if identifier.rawValue == "status" {
  717. columnIndexSet.insert(i)
  718. break
  719. }
  720. }
  721. if Thread.isMainThread {
  722. self.tableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: columnIndexSet)
  723. } else {
  724. DispatchQueue.main.async {
  725. self.tableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: columnIndexSet)
  726. }
  727. }
  728. }
  729. func refreshConvertProgress(_ progress: CGFloat, file: KMBatchOperateFile) {
  730. self.tableView.reloadData()
  731. }
  732. func reloadConvertInterface(withType type: KMConvertWithPDFType) {
  733. if type == .WordAdvance || type == .WordStandard || type == .Excel || type == .PowerPoint || type == .RTF || type == .CSV || type == .HTML || type == .Text || type == .Json {
  734. self.DPIColumn.isHidden = true
  735. } else {
  736. self.DPIColumn.isHidden = false
  737. }
  738. self.tableView.reloadData()
  739. }
  740. }
  741. extension KMBatchOperateLeftViewController: NSMenuDelegate, NSMenuItemValidation{
  742. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  743. let action = menuItem.action
  744. if action == #selector(menuItem_ShowInFinder(_:)) || action == #selector(menuItem_Delete(_:)) {
  745. if tableView.clickedRow == -1 {
  746. return false
  747. }
  748. return true
  749. }
  750. return true
  751. }
  752. }