KMBatchOperateLeftViewController.swift 34 KB

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