KMBatchOperateLeftViewController.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  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. let winC = KMPurchaseCompareWindowController.sharedInstance()
  138. if type == .CreatePDF {
  139. winC?.kEventName = "Onbrd_ImagetoPDF_BuyNow"
  140. }
  141. winC?.showWindow(nil)
  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 IAPProductsManager.default().isAvailableAllFunction() {
  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)
  418. let UTTypeString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, path.customPathExtension as CFString, nil)?.takeRetainedValue() as String?
  419. let TypeCFString = UTTypeString as CFString?
  420. if UTTypeConformsTo(TypeCFString!, kUTTypePDF) {
  421. pdfArray.add(path as Any)
  422. // UTTypeString?.release()
  423. } else {
  424. // UTTypeString?.release()
  425. }
  426. }
  427. if !IAPProductsManager.default().isAvailableAllFunction() {
  428. if self.files.count < 1 {
  429. pdfArray = NSMutableArray(array: [pdfArray.firstObject as Any])
  430. } else {
  431. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  432. return
  433. }
  434. }
  435. addFilesToList(addArray: pdfArray)
  436. }
  437. func numberOfRows(in tableView: NSTableView) -> Int {
  438. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMBatchFilesCountNotification"), object: self.files, userInfo: [kObjectKey : self])
  439. self.deleteFileButton.isEnabled = self.files.count > 0
  440. self.blankView.isHidden = self.files.count > 0
  441. return self.files.count;
  442. }
  443. func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  444. let identifier = tableColumn?.identifier
  445. let file = self.files[row]
  446. if identifier?.rawValue == "index" {
  447. let cellView = KMBatchTableCellView(type: .Size)
  448. _ = row + 1
  449. cellView.textField?.stringValue = String(format: "%d", row + 1);
  450. return cellView;
  451. } else if identifier?.rawValue == "pageRange"{
  452. if (file.currentOperateType == .CreatePDF) {
  453. let cellView = KMBatchTableCellView(type: .Size)
  454. if (file.fileType == .Image) {
  455. let image = NSImage(contentsOfFile: file.filePath)
  456. cellView.textField?.stringValue = String(Int(image?.size.width ?? 0)) + "x" + String(Int(image?.size.height ?? 0))
  457. }
  458. return cellView;
  459. } else {
  460. let cellView = KMBatchTableCellView(type: .PageRange)
  461. cellView.updateInterface(file)
  462. return cellView;
  463. }
  464. } else if identifier?.rawValue == "status"{
  465. let cellView = KMBatchTableCellView(type: .Status)
  466. if (file.currentOperateType == .CreatePDF) {
  467. cellView.updateInterface(file: file, progress: file.progress ?? 0)
  468. } else {
  469. cellView.updateInterface(file: file, progress: file.progress ?? 0)
  470. }
  471. cellView.removeFileCallBack = { [weak self] file in
  472. self?.files.removeObject(file)
  473. self?.tableView.reloadData()
  474. }
  475. return cellView;
  476. } else if identifier?.rawValue == "size"{
  477. let cellView = KMBatchTableCellView(type: .Size)
  478. cellView.updateInterface(file)
  479. return cellView;
  480. } else if identifier?.rawValue == "fileName"{
  481. let cellView = KMBatchTableCellView(type: .FileName)
  482. cellView.updateInterface(file)
  483. let rowView: KMBatchTableRowView = tableView.rowView(atRow: row, makeIfNecessary: true) as! KMBatchTableRowView
  484. if ((file.error) != nil) {
  485. rowView.backgroundColor = KMAppearance.Status.errBGColor();
  486. }
  487. return cellView;
  488. } else if identifier?.rawValue == "dpi"{
  489. let cellView = KMBatchTableCellView(type: .DPI)
  490. cellView.updateInterface(file)
  491. return cellView;
  492. } else if identifier?.rawValue == "dimensions"{
  493. let cellView = KMBatchTableCellView(type: .Size)
  494. if (file.fileType == .Image) {
  495. let image = NSImage(contentsOfFile: file.filePath)
  496. cellView.textField?.stringValue = String(Int(image?.size.width ?? 0)) + "x" + String(Int(image?.size.height ?? 0))
  497. }
  498. return cellView;
  499. }
  500. return nil;
  501. }
  502. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  503. let file = self.files[row]
  504. if self.type == .CreatePDF {
  505. if (file.error != nil) {
  506. return 64
  507. } else {
  508. return 40
  509. }
  510. } else {
  511. if file.fileType == .PDF {
  512. if (file.error != nil) {
  513. return 64
  514. } else {
  515. return 40
  516. }
  517. } else {
  518. return 0.0000001
  519. }
  520. }
  521. }
  522. func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
  523. let rowView = KMBatchTableRowView()
  524. return rowView
  525. }
  526. func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
  527. let indexSetData = try? NSKeyedArchiver.archivedData(withRootObject: rowIndexes, requiringSecureCoding: true)
  528. pboard.declareTypes([NSPasteboard.PasteboardType.string], owner: self)
  529. pboard.setData(indexSetData, forType: NSPasteboard.PasteboardType(rawValue: KMBatchDragType) )
  530. return true
  531. }
  532. func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
  533. var isCanDrag = false
  534. var result: NSDragOperation = []
  535. let pboard = info.draggingPasteboard
  536. if pboard.availableType(from: [.fileURL]) != nil {
  537. guard let pbItems = pboard.pasteboardItems else {
  538. return NSDragOperation(rawValue: 0)
  539. }
  540. var hasValidFile = false
  541. for item in pbItems {
  542. guard let data = item.string(forType: .fileURL), let _url = URL(string: data) else {
  543. continue
  544. }
  545. var isDirectory: ObjCBool = false
  546. let fileExists = FileManager.default.fileExists(atPath: _url.path, isDirectory: &isDirectory)
  547. if fileExists && isDirectory.boolValue {
  548. let containFile = folderContainAvailableFile(_url.path)
  549. if containFile {
  550. isCanDrag = true
  551. break
  552. }
  553. } else {
  554. if let UTType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, _url.pathExtension as CFString, nil)?.takeRetainedValue() as String? {
  555. if self.type == .CreatePDF {
  556. if UTTypeConformsTo(UTType as CFString, kUTTypeImage) {
  557. isCanDrag = true
  558. }
  559. } else {
  560. if UTTypeConformsTo(UTType as CFString, kUTTypePDF) {
  561. isCanDrag = true
  562. }
  563. }
  564. }
  565. if isCanDrag {
  566. break
  567. }
  568. }
  569. }
  570. if isCanDrag {
  571. result = .copy
  572. }
  573. return result
  574. } else {
  575. return .move
  576. }
  577. }
  578. func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
  579. let pboard = info.draggingPasteboard
  580. if pboard.availableType(from: [.init(KMBatchDragType)]) != nil {
  581. guard let rowData = pboard.data(forType: .init(KMBatchDragType)),
  582. let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: rowData) as? NSIndexSet else { return false }
  583. let backUpArray = self.files
  584. var referenceIndex = -1
  585. rowIndexes.enumerate(options: .reverse, using: { (idx, stop) in
  586. let sortFile = backUpArray[idx]
  587. if referenceIndex < 0 {
  588. if idx > row {
  589. self.files.remove(at: idx)
  590. self.files.insert(sortFile, at: row)
  591. } else if idx < row {
  592. if row > self.files.count {
  593. self.files.remove(at: idx)
  594. self.files.append(sortFile)
  595. } else {
  596. self.files.remove(at: idx)
  597. self.files.insert(sortFile, at: row - 1)
  598. }
  599. }
  600. referenceIndex = self.files.firstIndex(of: sortFile) ?? -1
  601. } else {
  602. let currentIndex = self.files.firstIndex(of: sortFile) ?? -1
  603. if currentIndex > referenceIndex {
  604. self.files.remove(at: currentIndex)
  605. self.files.insert(sortFile, at: referenceIndex)
  606. } else {
  607. referenceIndex -= 1
  608. self.files.remove(at: currentIndex)
  609. self.files.insert(sortFile, at: referenceIndex)
  610. }
  611. }
  612. })
  613. self.tableView.reloadData()
  614. return true
  615. } else if pboard.availableType(from: [.fileURL]) != nil {
  616. if (pboard.pasteboardItems == nil) {
  617. return true
  618. }
  619. let allFilesArray = NSMutableArray()
  620. for item in pboard.pasteboardItems! {
  621. let fileURL = item.string(forType: .fileURL)
  622. if (fileURL == nil) {
  623. continue
  624. }
  625. let path = URL.init(string: fileURL!)
  626. if (path == nil) {
  627. continue
  628. }
  629. var isFolder = ObjCBool(false)
  630. FileManager.default.fileExists(atPath: path!.path, isDirectory: &isFolder)
  631. if isFolder.boolValue {
  632. let containFiles = fetchAvailableFilesInFolder(path!.path)
  633. allFilesArray.addObjects(from: containFiles)
  634. } else {
  635. allFilesArray.add(path!.path)
  636. }
  637. }
  638. var insertArray = NSMutableArray()
  639. lockFilePathArr?.removeAllObjects()
  640. lockFileIndex = 0
  641. for i in 0..<allFilesArray.count {
  642. let filePath: String = allFilesArray[i] as! String
  643. if filePath.hasSuffix(".pdf") || filePath.hasSuffix(".PDF") {
  644. let document = CPDFDocument(url: URL(fileURLWithPath: filePath))
  645. if let pdf = CPDFDocument(url: URL(fileURLWithPath: filePath)) {
  646. if !pdf.allowsPrinting || !pdf.allowsCopying {
  647. let alert = NSAlert()
  648. alert.alertStyle = .critical
  649. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  650. alert.runModal()
  651. continue
  652. } else if document?.isLocked ?? false {
  653. lockFilePathArr?.add(filePath)
  654. } else {
  655. let file = KMBatchOperateFile(filePath: filePath, type: self.type!)
  656. if !(self.files.contains(file) ) {
  657. insertArray.add(file)
  658. }
  659. }
  660. }
  661. } else {
  662. let file = KMBatchOperateFile(filePath: filePath, type: self.type!)
  663. if !(self.files.contains(file) ) {
  664. insertArray.add(file)
  665. }
  666. }
  667. }
  668. if !(IAPProductsManager.default().isAvailableAllFunction)() {
  669. if self.files.count < 1 && insertArray.count > 0 {
  670. let firstObject = insertArray.firstObject
  671. insertArray.removeAllObjects()
  672. insertArray.add(firstObject as Any)
  673. } else {
  674. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  675. return false
  676. }
  677. }
  678. for i in 0..<insertArray.count {
  679. self.files.insert(insertArray[i] as! KMBatchOperateFile, at: row + i)
  680. }
  681. self.tableView.reloadData()
  682. if lockFilePathArr!.count > 0 {
  683. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  684. self.openPasswordWindow()
  685. }
  686. }
  687. return true
  688. }
  689. return false
  690. }
  691. func switchToOperateType(_ operateType: KMBatchOperationType, files: [KMBatchOperateFile]) {
  692. switchToOperateType(operateType)
  693. self.files = files
  694. self.tableView.reloadData()
  695. }
  696. func checkNeedPasswordSwitchToOperateType(_ operateType: KMBatchOperationType, files: [KMBatchOperateFile]) {
  697. switchToOperateType(operateType)
  698. var arr: [String] = []
  699. for i in 0..<files.count {
  700. let file = files[i]
  701. arr.append(file.filePath)
  702. }
  703. self.files = files
  704. self.files.removeAll()
  705. addFilesToList(addArray: NSMutableArray.init(array: arr))
  706. self.tableView.reloadData()
  707. }
  708. func reloadFile(_ file: KMBatchOperateFile) {
  709. var rowIndexSet = IndexSet()
  710. for i in 0..<self.files.count {
  711. if file.filePath == self.files[i].filePath {
  712. rowIndexSet.insert(i)
  713. break
  714. }
  715. }
  716. var columnIndexSet = IndexSet()
  717. for i in 0..<self.tableView.numberOfColumns {
  718. let identifier = self.tableView.tableColumns[i].identifier
  719. if identifier.rawValue == "status" {
  720. columnIndexSet.insert(i)
  721. break
  722. }
  723. }
  724. if Thread.isMainThread {
  725. self.tableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: columnIndexSet)
  726. } else {
  727. DispatchQueue.main.async {
  728. self.tableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: columnIndexSet)
  729. }
  730. }
  731. }
  732. func refreshConvertProgress(_ progress: CGFloat, file: KMBatchOperateFile) {
  733. self.tableView.reloadData()
  734. }
  735. func reloadConvertInterface(withType type: KMConvertWithPDFType) {
  736. if type == .WordAdvance || type == .WordStandard || type == .Excel || type == .PowerPoint || type == .RTF || type == .CSV || type == .HTML || type == .Text || type == .Json {
  737. self.DPIColumn.isHidden = true
  738. } else {
  739. self.DPIColumn.isHidden = false
  740. }
  741. self.tableView.reloadData()
  742. }
  743. }
  744. extension KMBatchOperateLeftViewController: NSMenuDelegate, NSMenuItemValidation{
  745. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  746. let action = menuItem.action
  747. if action == #selector(menuItem_ShowInFinder(_:)) || action == #selector(menuItem_Delete(_:)) {
  748. if tableView.clickedRow == -1 {
  749. return false
  750. }
  751. return true
  752. }
  753. return true
  754. }
  755. }