KMBatchOperateLeftViewController.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  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 !IAPProductsManager.default().isAvailableAllFunction() {
  136. if files.count >= 1 {
  137. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  138. return
  139. }
  140. }
  141. #endif
  142. self.progressInt = 0
  143. let panel = NSOpenPanel()
  144. if type == .CreatePDF {
  145. panel.allowedFileTypes = KMImageToPDFMethod.supportedImageTypes()
  146. } else {
  147. panel.allowedFileTypes = ["pdf", "PDF"]
  148. }
  149. if IAPProductsManager.default().isAvailableAllFunction() {
  150. panel.allowsMultipleSelection = true
  151. panel.canChooseDirectories = true
  152. }
  153. panel.canChooseFiles = true
  154. #if VERSION_FREE
  155. #else
  156. panel.message = NSLocalizedString("To select multiple files press cmd ⌘ button on keyboard and click on the target files one by one.", comment: "")
  157. #endif
  158. panel.beginSheetModal(for: self.view.window!) {
  159. (result) in
  160. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  161. let addArray = NSMutableArray()
  162. for fileURL in panel.urls {
  163. let filePath = fileURL.path
  164. var isDirectory = ObjCBool(false)
  165. FileManager.default.fileExists(atPath: filePath, isDirectory: &isDirectory)
  166. if isDirectory.boolValue {
  167. let containFiles = self.fetchAvailableFiles(in: filePath)
  168. addArray.addObjects(from: containFiles)
  169. } else {
  170. let typeIdentifier =
  171. UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, filePath.customPathExtension as CFString, nil)
  172. let TypeCFString = typeIdentifier!.takeRetainedValue() as String
  173. if self.type == .CreatePDF {
  174. if UTTypeConformsTo(TypeCFString as CFString, kUTTypeImage) {
  175. addArray.add(filePath)
  176. }
  177. } else {
  178. if UTTypeConformsTo(TypeCFString as CFString, kUTTypePDF) {
  179. addArray.add(filePath)
  180. }
  181. }
  182. }
  183. }
  184. self.addFilesToList(addArray: addArray)
  185. }
  186. }
  187. }
  188. func fetchAvailableFiles(in folderPath: String) -> [String] {
  189. let array = NSMutableArray()
  190. let subFileArray = (FileManager.default.subpaths(atPath: folderPath)! as NSArray).mutableCopy() as? NSMutableArray
  191. for i in 0..<subFileArray!.count {
  192. if let path = (folderPath as NSString).appendingPathComponent(subFileArray!.object(at: i) as! String) as String? {
  193. if let UTTypeString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, path.customPathExtension as CFString, nil)?.takeRetainedValue() as String? {
  194. let TypeCFString = UTTypeString as CFString
  195. if self.type == .CreatePDF {
  196. if UTTypeConformsTo(TypeCFString, kUTTypeImage) {
  197. array.add(path)
  198. }
  199. } else {
  200. if UTTypeConformsTo(TypeCFString, kUTTypePDF) {
  201. array.add(path)
  202. }
  203. }
  204. }
  205. }
  206. }
  207. return array as! [String]
  208. }
  209. func addFilesToList(addArray: NSMutableArray) {
  210. self.lockFilePathArr!.removeAllObjects()
  211. self.lockFileIndex = 0
  212. for i in 0..<addArray.count {
  213. let filePath = addArray[i] as! String
  214. let UTTypeString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, filePath.customPathExtension as CFString, nil)!.takeRetainedValue() as String
  215. let TypeCFString = UTTypeString as CFString
  216. if UTTypeConformsTo(TypeCFString, kUTTypePDF) {
  217. let document = CPDFDocument(url: URL(fileURLWithPath: filePath))
  218. if document?.isLocked == true {
  219. var isContaint = false
  220. for file in self.files {
  221. if (file as AnyObject).filePath == filePath {
  222. isContaint = true
  223. break
  224. }
  225. }
  226. if !isContaint {
  227. self.lockFilePathArr!.add(filePath)
  228. }
  229. } else {
  230. let file = KMBatchOperateFile(filePath: addArray[i] as! String, type: self.type!)
  231. if !self.files.contains(file) {
  232. self.files.append(file)
  233. }
  234. }
  235. } else {
  236. let file = KMBatchOperateFile(filePath: addArray[i] as! String, type: self.type!)
  237. if !self.files.contains(file) {
  238. self.files.append(file)
  239. }
  240. }
  241. }
  242. self.tableView.reloadData()
  243. if self.lockFilePathArr!.count > 0 {
  244. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  245. self.openPasswordWindow()
  246. }
  247. }
  248. }
  249. func openPasswordWindow() {
  250. if lockFilePathArr!.count > lockFileIndex {
  251. let filePath = lockFilePathArr![lockFileIndex] as! String
  252. KMBaseWindowController.checkPassword(url: URL(fileURLWithPath: filePath), type: .owner) { [unowned self] success, resultPassword in
  253. self.closePwd()
  254. if !resultPassword.isEmpty {
  255. let file = KMBatchOperateFile(filePath: filePath, type: self.type!)
  256. file.password = resultPassword
  257. self.files.append(file)
  258. self.tableView.reloadData()
  259. }
  260. self.lockFileIndex += 1
  261. if self.lockFilePathArr?.count ?? 0 > self.lockFileIndex {
  262. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  263. self.openPasswordWindow()
  264. }
  265. } else {
  266. self.tableView.reloadData()
  267. }
  268. }
  269. }
  270. }
  271. func closePwd() {
  272. self.km_endSheet()
  273. }
  274. func chooseFileFromCamera() {
  275. self.progressInt = 0
  276. let vc = KMDeviceBrowserWindowController.shared
  277. vc.type = .camera
  278. vc.importCameraFileCallback = { [weak self](url: NSURL) -> Void in
  279. self?.addFilesToList(addArray: [url.path!])
  280. }
  281. vc.showWindow(nil)
  282. }
  283. func chooseFileFromScanner() {
  284. self.progressInt = 0
  285. let vc = KMDeviceBrowserWindowController.shared
  286. vc.type = .scanner
  287. vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  288. self?.addFilesToList(addArray: [url.path!])
  289. }
  290. vc.showWindow(nil)
  291. }
  292. @IBAction func buttonClicked_SelectFile(_ sender: Any) {
  293. }
  294. @IBAction func blankViewAddFileAction(_ sender: Any) {
  295. self.chooseFile()
  296. }
  297. @IBAction func buttonClicked_DeleteFile(_ sender: Any) {
  298. let set = self.tableView.selectedRowIndexes
  299. let newArr: NSMutableArray = NSMutableArray.init(array: self.files)
  300. let arr = newArr.objects(at: set)
  301. if arr.count > 0 {
  302. newArr.removeObjects(in: arr)
  303. self.files = newArr as! [KMBatchOperateFile]
  304. self.tableView.reloadData()
  305. } else {
  306. // if KMAlertWindowController.needShowRemoveAllFilesHint() {
  307. let alert = NSAlert()
  308. alert.alertStyle = .critical
  309. alert.messageText = NSLocalizedString("Clear All Recents", comment: "")+"?"
  310. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  311. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  312. alert.beginSheetModal(for: self.view.window!) {[weak self] response in
  313. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  314. self?.files.removeAll()
  315. self?.tableView.reloadData()
  316. }
  317. }
  318. // } else {
  319. // self.files.removeAll()
  320. // self.tableView.reloadData()
  321. // }
  322. }
  323. }
  324. func fetchAvailableFilesInFolder(_ folderPath: String) -> [String] {
  325. var array: [String] = []
  326. let subFileArray = FileManager().subpaths(atPath: folderPath)
  327. for i in 0..<subFileArray!.count {
  328. let path = folderPath.stringByAppendingPathComponent(subFileArray![i])
  329. let UTTypeString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, path.customPathExtension as CFString, nil)
  330. let TypeCFString = UTTypeString as! CFString?
  331. if self.type == .CreatePDF {
  332. if UTTypeConformsTo(TypeCFString!, kUTTypeImage) {
  333. array.append(path)
  334. }
  335. } else {
  336. if UTTypeConformsTo(TypeCFString!, kUTTypePDF) {
  337. array.append(path)
  338. }
  339. }
  340. // UTTypeString?.release()
  341. }
  342. return array
  343. }
  344. func folderContainAvailableFile(_ folderPath: String) -> Bool {
  345. var containFile = false
  346. let subFileArray = FileManager.default.subpaths(atPath: folderPath) as? NSMutableArray
  347. for i in 0..<subFileArray!.count {
  348. let path = folderPath.stringByAppendingPathComponent(subFileArray![i] as! String)
  349. let UTTypeString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, path.customPathExtension as CFString, nil)
  350. let TypeCFString = UTTypeString as! CFString?
  351. if type == .CreatePDF {
  352. if UTTypeConformsTo(TypeCFString!, kUTTypeImage) {
  353. containFile = true
  354. }
  355. } else {
  356. if UTTypeConformsTo(TypeCFString!, kUTTypePDF) {
  357. containFile = true
  358. }
  359. }
  360. // UTTypeString?.release()
  361. if containFile {
  362. break
  363. }
  364. }
  365. return containFile
  366. }
  367. func switchToOperateType(_ type: KMBatchOperationType) {
  368. self.type = type
  369. self.indexTableColumn.isHidden = false
  370. self.fileNameTableColumn.isHidden = false
  371. self.pageRangeTableColumn.isHidden = false
  372. self.sizeTableColumn.isHidden = false
  373. self.stateTableColumn.isHidden = false
  374. self.DPIColumn.isHidden = true
  375. self.dimensionsTableColumn.isHidden = true
  376. if type == .Compress || type == .AddPassword || type == .RemovePassword || type == .RemoveWatermark || type == .RemoveBackground || type == .RemoveHeaderFooter || type == .RemoveBates || type == .CreatePDF {
  377. self.pageRangeTableColumn.isHidden = true
  378. } else {
  379. self.pageRangeTableColumn.isHidden = false
  380. }
  381. self.selectFileButton.isImageToPDF = type == .CreatePDF
  382. if type == .CreatePDF {
  383. self.pageRangeTableColumn.isHidden = false
  384. self.pageRangeTableColumn.title = NSLocalizedString("Dimensions", comment: "")
  385. }
  386. for i in 0..<self.files.count {
  387. let file = self.files[i]
  388. file.currentOperateType = type
  389. }
  390. self.tableView.sizeToFit()
  391. self.tableView.reloadData()
  392. }
  393. @IBAction func menuItem_ShowInFinder(_ sender: Any) {
  394. let row = self.tableView.clickedRow
  395. let file: KMBatchOperateFile = self.files[row]
  396. if file.currentOperateInfo?.status == .Success {
  397. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: file.currentOperateInfo!.outPutPath!)])
  398. }else {
  399. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: file.filePath)])
  400. }
  401. }
  402. @IBAction func menuItem_Delete(_ sender: Any) {
  403. let row = self.tableView.clickedRow
  404. self.files.remove(at: row)
  405. self.tableView.reloadData()
  406. }
  407. func addOpendFile() {
  408. let documentArray = NSDocumentController.shared.documents
  409. var pdfArray = NSMutableArray()
  410. for i in 0..<documentArray.count {
  411. let document = documentArray[i]
  412. let path: String = document.fileURL?.path ?? ""
  413. // let UTTypeString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, path!.customPathExtension as CFString, nil)
  414. let UTTypeString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, path.customPathExtension as CFString, nil)?.takeRetainedValue() as String?
  415. let TypeCFString = UTTypeString as CFString?
  416. if UTTypeConformsTo(TypeCFString!, kUTTypePDF) {
  417. pdfArray.add(path as Any)
  418. // UTTypeString?.release()
  419. } else {
  420. // UTTypeString?.release()
  421. }
  422. }
  423. if !IAPProductsManager.default().isAvailableAllFunction() {
  424. if self.files.count < 1 {
  425. pdfArray = NSMutableArray(array: [pdfArray.firstObject as Any])
  426. } else {
  427. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  428. return
  429. }
  430. }
  431. addFilesToList(addArray: pdfArray)
  432. }
  433. func numberOfRows(in tableView: NSTableView) -> Int {
  434. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMBatchFilesCountNotification"), object: self.files)
  435. self.deleteFileButton.isEnabled = self.files.count > 0
  436. self.blankView.isHidden = self.files.count > 0
  437. return self.files.count;
  438. }
  439. func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  440. let identifier = tableColumn?.identifier
  441. let file = self.files[row]
  442. if identifier?.rawValue == "index" {
  443. let cellView = KMBatchTableCellView(type: .Size)
  444. _ = row + 1
  445. cellView.textField?.stringValue = String(format: "%d", row + 1);
  446. return cellView;
  447. } else if identifier?.rawValue == "pageRange"{
  448. if (file.currentOperateType == .CreatePDF) {
  449. let cellView = KMBatchTableCellView(type: .Size)
  450. if (file.fileType == .Image) {
  451. let image = NSImage(contentsOfFile: file.filePath)
  452. cellView.textField?.stringValue = String(Int(image?.size.width ?? 0)) + "x" + String(Int(image?.size.height ?? 0))
  453. }
  454. return cellView;
  455. } else {
  456. let cellView = KMBatchTableCellView(type: .PageRange)
  457. cellView.updateInterface(file)
  458. return cellView;
  459. }
  460. } else if identifier?.rawValue == "status"{
  461. let cellView = KMBatchTableCellView(type: .Status)
  462. if (file.currentOperateType == .CreatePDF) {
  463. cellView.updateInterface(file: file, progress: file.progress ?? 0)
  464. } else {
  465. cellView.updateInterface(file: file, progress: file.progress ?? 0)
  466. }
  467. cellView.removeFileCallBack = { [weak self] file in
  468. self?.files.removeObject(file)
  469. self?.tableView.reloadData()
  470. }
  471. return cellView;
  472. } else if identifier?.rawValue == "size"{
  473. let cellView = KMBatchTableCellView(type: .Size)
  474. cellView.updateInterface(file)
  475. return cellView;
  476. } else if identifier?.rawValue == "fileName"{
  477. let cellView = KMBatchTableCellView(type: .FileName)
  478. cellView.updateInterface(file)
  479. let rowView: KMBatchTableRowView = tableView.rowView(atRow: row, makeIfNecessary: true) as! KMBatchTableRowView
  480. if ((file.error) != nil) {
  481. rowView.backgroundColor = KMAppearance.Status.errBGColor();
  482. }
  483. return cellView;
  484. } else if identifier?.rawValue == "dpi"{
  485. let cellView = KMBatchTableCellView(type: .DPI)
  486. cellView.updateInterface(file)
  487. return cellView;
  488. } else if identifier?.rawValue == "dimensions"{
  489. let cellView = KMBatchTableCellView(type: .Size)
  490. if (file.fileType == .Image) {
  491. let image = NSImage(contentsOfFile: file.filePath)
  492. cellView.textField?.stringValue = String(Int(image?.size.width ?? 0)) + "x" + String(Int(image?.size.height ?? 0))
  493. }
  494. return cellView;
  495. }
  496. return nil;
  497. }
  498. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  499. let file = self.files[row]
  500. if self.type == .CreatePDF {
  501. if (file.error != nil) {
  502. return 64
  503. } else {
  504. return 40
  505. }
  506. } else {
  507. if file.fileType == .PDF {
  508. if (file.error != nil) {
  509. return 64
  510. } else {
  511. return 40
  512. }
  513. } else {
  514. return 0.0000001
  515. }
  516. }
  517. }
  518. func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
  519. let rowView = KMBatchTableRowView()
  520. return rowView
  521. }
  522. func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
  523. let indexSetData = try? NSKeyedArchiver.archivedData(withRootObject: rowIndexes, requiringSecureCoding: true)
  524. pboard.declareTypes([NSPasteboard.PasteboardType.string], owner: self)
  525. pboard.setData(indexSetData, forType: NSPasteboard.PasteboardType(rawValue: KMBatchDragType) )
  526. return true
  527. }
  528. func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
  529. var isCanDrag = false
  530. var result: NSDragOperation = []
  531. let pboard = info.draggingPasteboard
  532. if pboard.availableType(from: [.fileURL]) != nil {
  533. guard let pbItems = pboard.pasteboardItems else {
  534. return NSDragOperation(rawValue: 0)
  535. }
  536. var hasValidFile = false
  537. for item in pbItems {
  538. guard let data = item.string(forType: .fileURL), let _url = URL(string: data) else {
  539. continue
  540. }
  541. var isDirectory: ObjCBool = false
  542. let fileExists = FileManager.default.fileExists(atPath: _url.path, isDirectory: &isDirectory)
  543. if fileExists && isDirectory.boolValue {
  544. let containFile = folderContainAvailableFile(_url.path)
  545. if containFile {
  546. isCanDrag = true
  547. break
  548. }
  549. } else {
  550. if let UTType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, _url.pathExtension as CFString, nil)?.takeRetainedValue() as String? {
  551. if self.type == .CreatePDF {
  552. if UTTypeConformsTo(UTType as CFString, kUTTypeImage) {
  553. isCanDrag = true
  554. }
  555. } else {
  556. if UTTypeConformsTo(UTType as CFString, kUTTypePDF) {
  557. isCanDrag = true
  558. }
  559. }
  560. }
  561. if isCanDrag {
  562. break
  563. }
  564. }
  565. }
  566. if isCanDrag {
  567. result = .copy
  568. }
  569. return result
  570. } else {
  571. return .move
  572. }
  573. }
  574. func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
  575. let pboard = info.draggingPasteboard
  576. if pboard.availableType(from: [.init(KMBatchDragType)]) != nil {
  577. guard let rowData = pboard.data(forType: .init(KMBatchDragType)),
  578. let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: rowData) as? NSIndexSet else { return false }
  579. let backUpArray = self.files
  580. var referenceIndex = -1
  581. rowIndexes.enumerate(options: .reverse, using: { (idx, stop) in
  582. let sortFile = backUpArray[idx]
  583. if referenceIndex < 0 {
  584. if idx > row {
  585. self.files.remove(at: idx)
  586. self.files.insert(sortFile, at: row)
  587. } else if idx < row {
  588. if row > self.files.count {
  589. self.files.remove(at: idx)
  590. self.files.append(sortFile)
  591. } else {
  592. self.files.remove(at: idx)
  593. self.files.insert(sortFile, at: row - 1)
  594. }
  595. }
  596. referenceIndex = self.files.firstIndex(of: sortFile) ?? -1
  597. } else {
  598. let currentIndex = self.files.firstIndex(of: sortFile) ?? -1
  599. if currentIndex > referenceIndex {
  600. self.files.remove(at: currentIndex)
  601. self.files.insert(sortFile, at: referenceIndex)
  602. } else {
  603. referenceIndex -= 1
  604. self.files.remove(at: currentIndex)
  605. self.files.insert(sortFile, at: referenceIndex)
  606. }
  607. }
  608. })
  609. self.tableView.reloadData()
  610. return true
  611. } else if pboard.availableType(from: [.fileURL]) != nil {
  612. if (pboard.pasteboardItems == nil) {
  613. return true
  614. }
  615. let allFilesArray = NSMutableArray()
  616. for item in pboard.pasteboardItems! {
  617. let fileURL = item.string(forType: .fileURL)
  618. if (fileURL == nil) {
  619. continue
  620. }
  621. let path = URL.init(string: fileURL!)
  622. if (path == nil) {
  623. continue
  624. }
  625. var isFolder = ObjCBool(false)
  626. FileManager.default.fileExists(atPath: path!.path, isDirectory: &isFolder)
  627. if isFolder.boolValue {
  628. let containFiles = fetchAvailableFilesInFolder(path!.path)
  629. allFilesArray.addObjects(from: containFiles)
  630. } else {
  631. allFilesArray.add(path!.path)
  632. }
  633. }
  634. var insertArray = NSMutableArray()
  635. lockFilePathArr?.removeAllObjects()
  636. lockFileIndex = 0
  637. for i in 0..<allFilesArray.count {
  638. let filePath: String = allFilesArray[i] as! String
  639. if filePath.hasSuffix(".pdf") || filePath.hasSuffix(".PDF") {
  640. let document = CPDFDocument(url: URL(fileURLWithPath: filePath))
  641. if let pdf = CPDFDocument(url: URL(fileURLWithPath: filePath)) {
  642. if !pdf.allowsPrinting || !pdf.allowsCopying {
  643. let alert = NSAlert()
  644. alert.alertStyle = .critical
  645. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  646. alert.runModal()
  647. continue
  648. } else if document?.isLocked ?? false {
  649. lockFilePathArr?.add(filePath)
  650. } else {
  651. let file = KMBatchOperateFile(filePath: filePath, type: self.type!)
  652. if !(self.files.contains(file) ) {
  653. insertArray.add(file)
  654. }
  655. }
  656. }
  657. } else {
  658. let file = KMBatchOperateFile(filePath: filePath, type: self.type!)
  659. if !(self.files.contains(file) ) {
  660. insertArray.add(file)
  661. }
  662. }
  663. }
  664. if !(IAPProductsManager.default().isAvailableAllFunction)() {
  665. if self.files.count < 1 {
  666. insertArray = [insertArray.first].compactMap { $0 } as! NSMutableArray
  667. } else {
  668. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  669. return false
  670. }
  671. }
  672. for i in 0..<insertArray.count {
  673. self.files.insert(insertArray[i] as! KMBatchOperateFile, at: row + i)
  674. }
  675. self.tableView.reloadData()
  676. if lockFilePathArr!.count > 0 {
  677. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  678. self.openPasswordWindow()
  679. }
  680. }
  681. return true
  682. }
  683. return false
  684. }
  685. func switchToOperateType(_ operateType: KMBatchOperationType, files: [KMBatchOperateFile]) {
  686. switchToOperateType(operateType)
  687. self.files = files
  688. self.tableView.reloadData()
  689. }
  690. func checkNeedPasswordSwitchToOperateType(_ operateType: KMBatchOperationType, files: [KMBatchOperateFile]) {
  691. switchToOperateType(operateType)
  692. var arr: [String] = []
  693. for i in 0..<files.count {
  694. let file = files[i]
  695. arr.append(file.filePath)
  696. }
  697. self.files = files
  698. self.files.removeAll()
  699. addFilesToList(addArray: NSMutableArray.init(array: arr))
  700. self.tableView.reloadData()
  701. }
  702. func reloadFile(_ file: KMBatchOperateFile) {
  703. var rowIndexSet = IndexSet()
  704. for i in 0..<self.files.count {
  705. if file.filePath == self.files[i].filePath {
  706. rowIndexSet.insert(i)
  707. break
  708. }
  709. }
  710. var columnIndexSet = IndexSet()
  711. for i in 0..<self.tableView.numberOfColumns {
  712. let identifier = self.tableView.tableColumns[i].identifier
  713. if identifier.rawValue == "status" {
  714. columnIndexSet.insert(i)
  715. break
  716. }
  717. }
  718. if Thread.isMainThread {
  719. self.tableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: columnIndexSet)
  720. } else {
  721. DispatchQueue.main.async {
  722. self.tableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: columnIndexSet)
  723. }
  724. }
  725. }
  726. func refreshConvertProgress(_ progress: CGFloat, file: KMBatchOperateFile) {
  727. self.tableView.reloadData()
  728. }
  729. func reloadConvertInterface(withType type: KMConvertWithPDFType) {
  730. if type == .WordAdvance || type == .WordStandard || type == .Excel || type == .PowerPoint || type == .RTF || type == .CSV || type == .HTML || type == .Text {
  731. self.DPIColumn.isHidden = true
  732. } else {
  733. self.DPIColumn.isHidden = false
  734. }
  735. self.tableView.reloadData()
  736. }
  737. }
  738. extension KMBatchOperateLeftViewController: NSMenuDelegate, NSMenuItemValidation{
  739. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  740. let action = menuItem.action
  741. if action == #selector(menuItem_ShowInFinder(_:)) || action == #selector(menuItem_Delete(_:)) {
  742. if tableView.clickedRow == -1 {
  743. return false
  744. }
  745. return true
  746. }
  747. return true
  748. }
  749. }