KMBatchOperateLeftViewController.swift 35 KB

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