KMBatchOperateLeftViewController.swift 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  1. //
  2. // KMBatchOperateLeftViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by kdanmobile on 2023/10/26.
  6. //
  7. import Cocoa
  8. import KMComponentLibrary
  9. let KMBatchDragType = "KMBatchDragType"
  10. class KMBatchOperateLeftViewController: KMNBaseViewController {
  11. @IBOutlet var deleteFileButton: NSButton!
  12. @IBOutlet var tableView: KMTableView!
  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. @IBOutlet weak var addFileBox: NSBox!
  25. var files: [KMBatchOperateFile] = []
  26. var type: KMBatchOperationType?
  27. var lockFilePathArr: NSMutableArray?
  28. var lockFileIndex: Int = 0
  29. var popOver: NSPopover?
  30. var progressInt: Int = 0
  31. private lazy var topLine: NSView = {
  32. let view = NSView()
  33. view.wantsLayer = true
  34. return view
  35. }()
  36. private lazy var addFileButton_: ComponentButton = {
  37. let view = ComponentButton()
  38. let properties = ComponentButtonProperty()
  39. properties.type = .gray
  40. properties.size = .s
  41. properties.buttonText = KMLocalizedString("Add Files...")
  42. view.properties = properties
  43. properties.propertyInfo.cornerRadius_topRight = 0
  44. properties.propertyInfo.cornerRadius_bottomRight = 0
  45. view.reloadData()
  46. view.setTarget(self, action: #selector(addFileAction))
  47. return view
  48. }()
  49. private lazy var addFileDropdown_: ComponentButton = {
  50. let view = ComponentButton()
  51. let properties = ComponentButtonProperty()
  52. properties.type = .gray
  53. properties.size = .s
  54. properties.onlyIcon = true
  55. properties.icon = NSImage(named: "KMImageNameImageToPDFDropdown")
  56. view.properties = properties
  57. properties.propertyInfo.cornerRadius_topLeft = 0
  58. properties.propertyInfo.cornerRadius_bottomLeft = 0
  59. view.reloadData()
  60. view.setTarget(self, action: #selector(addFileDropdownAction))
  61. return view
  62. }()
  63. private lazy var addFileLine_: NSView = {
  64. let view = NSView()
  65. view.wantsLayer = true
  66. return view
  67. }()
  68. private var deleteButton_: ComponentButton?
  69. private var groupView_: ComponentGroup?
  70. private var rightMenuGroupView_: ComponentGroup?
  71. private var rightMenuClickRow_: Int = -1
  72. private var emptyViewTopLine: NSView = {
  73. let view = NSView()
  74. view.wantsLayer = true
  75. return view
  76. }()
  77. private var emptyView_: ComponentEmpty = {
  78. let view = ComponentEmpty()
  79. view.properties = ComponentEmptyProperty(emptyType: .add_File, state: .normal, text: KMLocalizedString("Select Files"), subText: KMLocalizedString("Drop files here or Click Add Files at upper left corner. You can drag files to reorder as you need."))
  80. return view
  81. }()
  82. private var dividerColor_: NSColor?
  83. private var isSizeAsc_ = false
  84. private var dimensionsAsc_ = false
  85. private var fileNameAsc_ = false
  86. deinit {
  87. DistributedNotificationCenter.default().removeObserver(self)
  88. }
  89. override func viewDidLoad() {
  90. super.viewDidLoad()
  91. for i in 0..<self.tableView.tableColumns.count {
  92. let column = self.tableView.tableColumns[i]
  93. column.headerCell = KMTableHeaderCell(textCell: column.title)
  94. }
  95. self.deleteFileButton.addHoverEffect = true
  96. self.indexTableColumn.resizingMask = []
  97. self.fileNameTableColumn.resizingMask = .autoresizingMask
  98. self.pageRangeTableColumn.resizingMask = []
  99. self.sizeTableColumn.resizingMask = []
  100. self.stateTableColumn.resizingMask = []
  101. self.DPIColumn.resizingMask = []
  102. self.dimensionsTableColumn.resizingMask = []
  103. self.tableView.moveColumn(5, toColumn: 2)
  104. self.indexTableColumn.title = " \(KMLocalizedString("Index", comment: ""))"
  105. self.fileNameTableColumn.title = KMLocalizedString("File Name", comment: "")
  106. self.pageRangeTableColumn.title = KMLocalizedString("Page Range", comment: "")
  107. self.sizeTableColumn.title = KMLocalizedString("Size", comment: "")
  108. self.stateTableColumn.title = KMLocalizedString("Status", comment: "")
  109. self.DPIColumn.title = KMLocalizedString("DPI", comment: "")
  110. self.dimensionsTableColumn.title = KMLocalizedString("Dimensions", comment: "")
  111. self.DPIColumn.isHidden = true
  112. self.tableView.intercellSpacing = CGSize(width: 0, height: 0)
  113. self.tableView.allowsColumnReordering = false
  114. self.tableView.allowsMultipleSelection = true
  115. self.tableView.enclosingScrollView?.borderType = .noBorder
  116. tableView.menu = NSMenu()
  117. self.headerOperateView.wantsLayer = true
  118. self.tableView.registerForDraggedTypes([NSPasteboard.PasteboardType.string,NSPasteboard.PasteboardType.fileURL, NSPasteboard.PasteboardType(KMBatchDragType)])
  119. self.lockFilePathArr = NSMutableArray()
  120. self.lockFileIndex = 0
  121. self.progressInt = 0
  122. addFileBox.borderWidth = 0
  123. addFileBox.contentView?.addSubview(addFileDropdown_)
  124. addFileBox.contentView?.addSubview(addFileButton_)
  125. let dropdownWH: CGFloat = 32
  126. let dropdownX: CGFloat = NSWidth(addFileBox.frame)-dropdownWH
  127. addFileDropdown_.frame = NSMakeRect(dropdownX-2, 0, dropdownWH, dropdownWH)
  128. addFileButton_.frame = NSMakeRect(0, 0, dropdownX, dropdownWH)
  129. addFileBox.contentView?.addSubview(addFileLine_)
  130. addFileLine_.frame = NSMakeRect(dropdownX, 1, 1, dropdownWH-2)
  131. deleteButton_ = ComponentButton()
  132. deleteButton_?.properties = ComponentButtonProperty(type: .text_gray_low, size: .s, state: .normal, onlyIcon: true)
  133. deleteButton_?.setTarget(self, action: #selector(buttonClicked_DeleteFile))
  134. deleteFileButton.image = nil
  135. deleteFileButton.addSubview(deleteButton_!)
  136. deleteButton_?.frame = deleteFileButton.bounds
  137. deleteButton_?.autoresizingMask = [.width, .height]
  138. deleteButton_?.properties.icon = NSImage(named: "KMImageNameDeleteFileIcon")
  139. tableView.headerView = nil
  140. self.showInFinderMenuItem.title = KMLocalizedString("Show in Finder", comment: "")
  141. self.deleteMenuItem.title = KMLocalizedString("Delete", comment: "")
  142. self.blankView.wantsLayer = true
  143. self.blankView.layer?.backgroundColor = NSColor.clear.cgColor
  144. self.blankView.titleLabel.stringValue = ""
  145. self.blankView.imageView.isHidden = true
  146. self.blankView.addButton.isHidden = true
  147. self.blankView.secondTitleLabel.stringValue = ""
  148. self.blankView.mouseActionCallBack = { [weak self] mouseType in
  149. if mouseType == .mouseDown {
  150. self?.chooseFile()
  151. }
  152. }
  153. self.blankView.addSubview(emptyView_)
  154. blankView.addSubview(emptyViewTopLine)
  155. emptyViewTopLine.km_add_top_constraint(constant: 4)
  156. emptyViewTopLine.km_add_left_constraint(constant: 24)
  157. emptyViewTopLine.km_add_right_constraint(constant: -24)
  158. emptyViewTopLine.km_add_height_constraint(constant: 1)
  159. emptyViewTopLine.wantsLayer = true
  160. let dividerColor = ComponentLibrary.shared.getComponentColorFromKey("colorBorder/divider")
  161. emptyViewTopLine.layer?.backgroundColor = dividerColor.cgColor
  162. emptyView_.km_add_top_constraint(constant: 96)
  163. emptyView_.km_add_bottom_constraint()
  164. emptyView_.km_add_leading_constraint(constant: 96)
  165. emptyView_.km_add_trailing_constraint(constant: -96)
  166. emptyView_.setTarget(self, action: #selector(emptyAddFileAction))
  167. view.addSubview(topLine)
  168. topLine.km_add_top_constraint()
  169. topLine.km_add_height_constraint(constant: 1)
  170. topLine.km_add_left_constraint()
  171. topLine.km_add_right_constraint()
  172. tableView.menuClickedAction = { [weak self] point in
  173. let idxs = self?.tableView.selectedRowIndexes.count ?? 0
  174. let convertP = self?.tableView.convert(point, from: nil) ?? point
  175. guard let row = self?.tableView.row(at: convertP), row != -1 else {
  176. return NSMenu()
  177. }
  178. var viewHeight: CGFloat = 0
  179. let items: [String] = ["Show in Finder", "Delete"]
  180. var menuItemArr: [ComponentMenuitemProperty] = []
  181. for value in items {
  182. let properties_Menuitem: ComponentMenuitemProperty = ComponentMenuitemProperty(multipleSelect: false,
  183. itemSelected: false,
  184. isDisabled: false,
  185. keyEquivalent: nil,
  186. text: KMLocalizedString(value),
  187. identifier: value)
  188. menuItemArr.append(properties_Menuitem)
  189. viewHeight += 36
  190. }
  191. self?.rightMenuGroupView_ = ComponentGroup.createFromNib(in: ComponentLibrary.shared.componentBundle())
  192. self?.rightMenuGroupView_?.clickedAutoHide = false
  193. self?.rightMenuGroupView_?.groupDelegate = self
  194. self?.rightMenuGroupView_?.frame = CGRectMake(0, 0, 180, viewHeight)
  195. self?.rightMenuGroupView_?.updateGroupInfo(menuItemArr)
  196. self?.rightMenuClickRow_ = row
  197. self?.rightMenuGroupView_?.showWithPoint(CGPoint(x: point.x, y: point.y - viewHeight), relativeTo: self!.tableView)
  198. return NSMenu()
  199. }
  200. }
  201. override func addNotifations() {
  202. super.addNotifations()
  203. NotificationCenter.default.addObserver(self.tableView!, selector: #selector(self.reloadData), name: NSNotification.Name(kNeedChangePageRangeNotification), object: nil)
  204. NotificationCenter.default.addObserver(self, selector: #selector(imageToPDFSuccessNotification(aNotification:)), name: NSNotification.Name("KMBatchOperateImageToPDFSuccessNotification"), object: nil)
  205. }
  206. override func updateUILanguage() {
  207. super.updateUILanguage()
  208. KMMainThreadExecute {
  209. self.addFileButton_.properties.buttonText = KMLocalizedString("Add Files...")
  210. self.addFileButton_.reloadData()
  211. self.tableView.reloadData()
  212. }
  213. }
  214. override func updateUIThemeColor() {
  215. super.updateUIThemeColor()
  216. self.dividerColor_ = ComponentLibrary.shared.getComponentColorFromKey("colorBorder/divider")
  217. KMMainThreadExecute {
  218. self.updateViewColor()
  219. self.topLine.layer?.backgroundColor = KMNColorTools.colorBorder_divider().cgColor
  220. self.addFileLine_.layer?.backgroundColor = KMNColorTools.colorBorder_divider().cgColor
  221. self.tableView.reloadData()
  222. }
  223. }
  224. @objc func reloadData() {
  225. if Thread.isMainThread {
  226. tableView.reloadData()
  227. } else {
  228. DispatchQueue.main.async {
  229. self.tableView.reloadData()
  230. }
  231. }
  232. }
  233. @objc func imageToPDFSuccessNotification(aNotification: Notification) {
  234. guard let dict = aNotification.userInfo, let isSuccess = dict["isSuccess"] as? Bool else { return }
  235. if isSuccess {
  236. progressInt = 1
  237. } else {
  238. progressInt = -1
  239. }
  240. DispatchQueue.main.async {
  241. self.tableView.reloadData()
  242. }
  243. }
  244. func updateViewColor() {
  245. self.view.wantsLayer = true
  246. KMMainThreadExecute {
  247. let color = KMNColorTools.colorBg_layoutLow()
  248. self.view.layer?.backgroundColor = color.cgColor
  249. }
  250. }
  251. func chooseFile() {
  252. #if VERSION_FREE
  253. if !IAPProductsManager.default().isAvailableAllFunction() {
  254. if files.count >= 1 {
  255. let winC = KMPurchaseCompareWindowController.sharedInstance()
  256. if type == .CreatePDF {
  257. winC?.kEventName = "Onbrd_ImagetoPDF_BuyNow"
  258. }
  259. winC?.showWindow(nil)
  260. return
  261. }
  262. }
  263. #endif
  264. self.progressInt = 0
  265. let panel = NSOpenPanel()
  266. if type == .CreatePDF {
  267. panel.allowedFileTypes = KMImageToPDFMethod.supportedImageTypes()
  268. } else {
  269. panel.allowedFileTypes = ["pdf", "PDF"]
  270. }
  271. if IAPProductsManager.default().isAvailableAllFunction() {
  272. panel.allowsMultipleSelection = true
  273. panel.canChooseDirectories = true
  274. }
  275. panel.canChooseFiles = true
  276. #if VERSION_FREE
  277. #else
  278. panel.message = KMLocalizedString("To select multiple files press cmd ⌘ button on keyboard and click on the target files one by one.", comment: "")
  279. #endif
  280. panel.beginSheetModal(for: self.view.window!) {
  281. (result) in
  282. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  283. let addArray = NSMutableArray()
  284. for fileURL in panel.urls {
  285. let filePath = fileURL.path
  286. var isDirectory = ObjCBool(false)
  287. FileManager.default.fileExists(atPath: filePath, isDirectory: &isDirectory)
  288. if isDirectory.boolValue {
  289. let containFiles = self.fetchAvailableFiles(in: filePath)
  290. addArray.addObjects(from: containFiles)
  291. } else {
  292. let typeIdentifier =
  293. UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, filePath.customPathExtension as CFString, nil)
  294. let TypeCFString = typeIdentifier!.takeRetainedValue() as String
  295. if self.type == .CreatePDF {
  296. if UTTypeConformsTo(TypeCFString as CFString, kUTTypeImage) {
  297. addArray.add(filePath)
  298. }
  299. } else {
  300. if UTTypeConformsTo(TypeCFString as CFString, kUTTypePDF) {
  301. addArray.add(filePath)
  302. }
  303. }
  304. }
  305. }
  306. self.addFilesToList(addArray: addArray)
  307. }
  308. }
  309. }
  310. func fetchAvailableFiles(in folderPath: String) -> [String] {
  311. let array = NSMutableArray()
  312. let subFileArray = (FileManager.default.subpaths(atPath: folderPath)! as NSArray).mutableCopy() as? NSMutableArray
  313. for i in 0..<subFileArray!.count {
  314. if let path = (folderPath as NSString).appendingPathComponent(subFileArray!.object(at: i) as! String) as String? {
  315. if let UTTypeString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, path.customPathExtension as CFString, nil)?.takeRetainedValue() as String? {
  316. let TypeCFString = UTTypeString as CFString
  317. if self.type == .CreatePDF {
  318. if UTTypeConformsTo(TypeCFString, kUTTypeImage) {
  319. array.add(path)
  320. }
  321. } else {
  322. if UTTypeConformsTo(TypeCFString, kUTTypePDF) {
  323. array.add(path)
  324. }
  325. }
  326. }
  327. }
  328. }
  329. return array as! [String]
  330. }
  331. func addFilesToList(addArray: NSMutableArray) {
  332. self.lockFilePathArr!.removeAllObjects()
  333. self.lockFileIndex = 0
  334. for i in 0..<addArray.count {
  335. let filePath = addArray[i] as! String
  336. let UTTypeString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, filePath.customPathExtension as CFString, nil)!.takeRetainedValue() as String
  337. let TypeCFString = UTTypeString as CFString
  338. if UTTypeConformsTo(TypeCFString, kUTTypePDF) {
  339. let document = CPDFDocument(url: URL(fileURLWithPath: filePath))
  340. if document?.isLocked == true {
  341. var isContaint = false
  342. for file in self.files {
  343. if (file as AnyObject).filePath == filePath {
  344. isContaint = true
  345. break
  346. }
  347. }
  348. if !isContaint {
  349. self.lockFilePathArr!.add(filePath)
  350. }
  351. } else {
  352. let file = KMBatchOperateFile(filePath: addArray[i] as! String, type: self.type!)
  353. if !self.files.contains(file) {
  354. self.files.append(file)
  355. }
  356. }
  357. } else {
  358. let file = KMBatchOperateFile(filePath: addArray[i] as! String, type: self.type!)
  359. if !self.files.contains(file) {
  360. self.files.append(file)
  361. }
  362. }
  363. }
  364. self.tableView.reloadData()
  365. if self.lockFilePathArr!.count > 0 {
  366. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  367. self.openPasswordWindow()
  368. }
  369. }
  370. }
  371. func openPasswordWindow() {
  372. if lockFilePathArr!.count > lockFileIndex {
  373. let filePath = lockFilePathArr![lockFileIndex] as! String
  374. NSWindowController.checkPassword(url: URL(fileURLWithPath: filePath), type: .owner) { [unowned self] success, resultPassword in
  375. self.closePwd()
  376. if !resultPassword.isEmpty {
  377. let file = KMBatchOperateFile(filePath: filePath, type: self.type!)
  378. file.password = resultPassword
  379. self.files.append(file)
  380. self.tableView.reloadData()
  381. }
  382. self.lockFileIndex += 1
  383. if self.lockFilePathArr?.count ?? 0 > self.lockFileIndex {
  384. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  385. self.openPasswordWindow()
  386. }
  387. } else {
  388. self.tableView.reloadData()
  389. }
  390. }
  391. }
  392. }
  393. func closePwd() {
  394. self.km_endSheet()
  395. }
  396. // MARK: - Actions
  397. @objc func addFileDropdownAction() {
  398. showGroupView()
  399. }
  400. @objc func addFileAction() {
  401. addFileButton_.properties.state = .normal
  402. addFileButton_.reloadData()
  403. chooseFile()
  404. }
  405. func chooseFileFromCamera() {
  406. self.progressInt = 0
  407. let vc = KMDeviceBrowserWindowController.shared
  408. vc.type = .camera
  409. vc.importCameraFileCallback = { [weak self](url: NSURL) -> Void in
  410. self?.addFilesToList(addArray: [url.path!])
  411. }
  412. vc.showWindow(nil)
  413. }
  414. func chooseFileFromScanner() {
  415. self.progressInt = 0
  416. let vc = KMDeviceBrowserWindowController.shared
  417. vc.type = .scanner
  418. vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  419. self?.addFilesToList(addArray: [url.path!])
  420. }
  421. vc.showWindow(nil)
  422. }
  423. @IBAction func blankViewAddFileAction(_ sender: Any) {
  424. self.chooseFile()
  425. }
  426. @IBAction func buttonClicked_DeleteFile(_ sender: Any) {
  427. let set = self.tableView.selectedRowIndexes
  428. var theSet = IndexSet()
  429. for i in set {
  430. theSet.insert(i-1)
  431. }
  432. let newArr: NSMutableArray = NSMutableArray.init(array: self.files)
  433. let arr = newArr.objects(at: theSet)
  434. if arr.count > 0 {
  435. newArr.removeObjects(in: arr)
  436. self.files = newArr as! [KMBatchOperateFile]
  437. self.tableView.reloadData()
  438. } else {
  439. let alert = NSAlert()
  440. alert.alertStyle = .critical
  441. alert.messageText = KMLocalizedString("Clear All Recents", comment: "")+"?"
  442. alert.addButton(withTitle: KMLocalizedString("Delete", comment: ""))
  443. alert.addButton(withTitle: KMLocalizedString("Cancel", comment: ""))
  444. alert.beginSheetModal(for: self.view.window!) {[weak self] response in
  445. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  446. self?.files.removeAll()
  447. self?.tableView.reloadData()
  448. }
  449. }
  450. }
  451. }
  452. func fetchAvailableFilesInFolder(_ folderPath: String) -> [String] {
  453. var array: [String] = []
  454. let subFileArray = FileManager().subpaths(atPath: folderPath)
  455. for i in 0..<subFileArray!.count {
  456. let path = folderPath.stringByAppendingPathComponent(subFileArray![i])
  457. let TypeCFString = KMTools.UTIforFileExtension(path.customPathExtension) as CFString
  458. if self.type == .CreatePDF {
  459. if UTTypeConformsTo(TypeCFString, kUTTypeImage) {
  460. array.append(path)
  461. }
  462. } else {
  463. if UTTypeConformsTo(TypeCFString, kUTTypePDF) {
  464. array.append(path)
  465. }
  466. }
  467. }
  468. return array
  469. }
  470. func folderContainAvailableFile(_ folderPath: String) -> Bool {
  471. var containFile = false
  472. guard let subFileArray = FileManager.default.subpaths(atPath: folderPath) else {
  473. return containFile
  474. }
  475. for i in 0..<subFileArray.count {
  476. let path = folderPath.stringByAppendingPathComponent(subFileArray[i] )
  477. let TypeCFString = KMTools.UTIforFileExtension(path.customPathExtension) as CFString
  478. if type == .CreatePDF {
  479. if UTTypeConformsTo(TypeCFString, kUTTypeImage) {
  480. containFile = true
  481. }
  482. } else {
  483. if UTTypeConformsTo(TypeCFString, kUTTypePDF) {
  484. containFile = true
  485. }
  486. }
  487. if containFile {
  488. break
  489. }
  490. }
  491. return containFile
  492. }
  493. func switchToOperateType(_ type: KMBatchOperationType) {
  494. self.type = type
  495. self.indexTableColumn.isHidden = false
  496. self.fileNameTableColumn.isHidden = false
  497. self.pageRangeTableColumn.isHidden = false
  498. self.sizeTableColumn.isHidden = false
  499. self.stateTableColumn.isHidden = false
  500. self.DPIColumn.isHidden = true
  501. self.dimensionsTableColumn.isHidden = true
  502. if type == .Compress || type == .AddPassword || type == .RemovePassword || type == .RemoveWatermark || type == .RemoveBackground || type == .RemoveHeaderFooter || type == .RemoveBates || type == .CreatePDF {
  503. self.pageRangeTableColumn.isHidden = true
  504. } else {
  505. self.pageRangeTableColumn.isHidden = false
  506. }
  507. if type == .CreatePDF {
  508. self.pageRangeTableColumn.isHidden = false
  509. self.pageRangeTableColumn.title = KMLocalizedString("Dimensions", comment: "")
  510. }
  511. for i in 0..<self.files.count {
  512. let file = self.files[i]
  513. file.currentOperateType = type
  514. }
  515. self.tableView.sizeToFit()
  516. self.tableView.reloadData()
  517. }
  518. @IBAction func menuItem_ShowInFinder(_ sender: Any) {
  519. let row = rightMenuClickRow_
  520. guard let file = self.files.safe_element(for: row-1) as? KMBatchOperateFile else {
  521. return
  522. }
  523. if file.currentOperateInfo?.status == .Success {
  524. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: file.currentOperateInfo!.outPutPath!)])
  525. }else {
  526. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: file.filePath)])
  527. }
  528. }
  529. @IBAction func menuItem_Delete(_ sender: Any) {
  530. let row = rightMenuClickRow_
  531. guard let file = self.files.safe_element(for: row-1) as? KMBatchOperateFile else {
  532. return
  533. }
  534. self.files.removeObject(file)
  535. self.tableView.reloadData()
  536. }
  537. func addOpendFile() {
  538. let documentArray = NSDocumentController.shared.documents
  539. var pdfArray = NSMutableArray()
  540. for i in 0..<documentArray.count {
  541. let document = documentArray[i]
  542. let path: String = document.fileURL?.path ?? ""
  543. let UTTypeString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, path.customPathExtension as CFString, nil)?.takeRetainedValue() as String?
  544. let TypeCFString = UTTypeString as CFString?
  545. if UTTypeConformsTo(TypeCFString!, kUTTypePDF) {
  546. pdfArray.add(path as Any)
  547. }
  548. }
  549. if !IAPProductsManager.default().isAvailableAllFunction() {
  550. if self.files.count < 1 {
  551. pdfArray = NSMutableArray(array: [pdfArray.firstObject as Any])
  552. } else {
  553. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  554. return
  555. }
  556. }
  557. addFilesToList(addArray: pdfArray)
  558. }
  559. @objc func emptyAddFileAction() {
  560. self.chooseFile()
  561. }
  562. //MARK: - GroupView
  563. func showGroupView() {
  564. var viewHeight: CGFloat = 8
  565. var menuItemArr: [ComponentMenuitemProperty] = []
  566. for i in ["Add Files...", "Add Folder...", "Import from Clipboard...", "Import from Scanner..."] {
  567. let properties_Menuitem: ComponentMenuitemProperty = ComponentMenuitemProperty(multipleSelect: false,
  568. itemSelected: false,
  569. isDisabled: false,
  570. keyEquivalent: nil,
  571. text: KMLocalizedString(i))
  572. menuItemArr.append(properties_Menuitem)
  573. viewHeight += 36
  574. }
  575. if groupView_ == nil {
  576. groupView_ = ComponentGroup.createFromNib(in: ComponentLibrary.shared.componentBundle())
  577. }
  578. groupView_?.groupDelegate = self
  579. groupView_?.frame = CGRectMake(310, 0, 200, viewHeight)
  580. groupView_?.updateGroupInfo(menuItemArr)
  581. var point = addFileButton_.convert(addFileButton_.frame.origin, to: nil)
  582. point.y -= viewHeight
  583. groupView_?.showWithPoint(point, relativeTo: addFileButton_)
  584. // addFileButton_?.properties.state = .pressed
  585. // addFileButton_?.reloadData()
  586. }
  587. func removeGroupView() {
  588. if groupView_ != nil {
  589. groupView_?.removeFromSuperview()
  590. }
  591. addFileButton_.properties.state = .normal
  592. addFileButton_.reloadData()
  593. }
  594. func openDocumentWithImageFromPasteboard(_ pboard: NSPasteboard, error outError: AutoreleasingUnsafeMutablePointer<NSError?>?) -> CPDFDocument? {
  595. var document: CPDFDocument? = nil
  596. var data: Data? = nil
  597. if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.pdf.rawValue]) {
  598. data = pboard.data(forType: NSPasteboard.PasteboardType.pdf)
  599. } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.postScript.rawValue]) {
  600. data = pboard.data(forType: NSPasteboard.PasteboardType.postScript)
  601. } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.tiff.rawValue]) {
  602. data = convertTIFFDataToPDF(pboard.data(forType: NSPasteboard.PasteboardType.tiff) ?? Data())
  603. } else {
  604. let images = pboard.readObjects(forClasses: [NSImage.self], options: [:])
  605. let strings = pboard.readObjects(forClasses: [NSAttributedString.self], options: [:])
  606. if images?.count ?? 0 > 0 {
  607. data = convertTIFFDataToPDF((images![0] as AnyObject).tiffRepresentation!)
  608. } else if strings?.count ?? 0 > 0 {
  609. data = KMOCTool.convertStringsToPDF(withString: strings ?? [""]) // convertStringsToPDF(strings!)
  610. }
  611. }
  612. if let data = data {
  613. document = CPDFDocument(data: data)
  614. } else if let outError = outError {
  615. outError.pointee = NSError(domain: "SKDocumentErrorDomain", code: 3, userInfo: [NSLocalizedDescriptionKey: KMLocalizedString("Unable to load data from clipboard", comment: "Error description")])
  616. }
  617. return document
  618. }
  619. func convertTIFFDataToPDF(_ tiffData: Data) -> Data? {
  620. guard let imsrc = CGImageSourceCreateWithData(tiffData as CFData, [kCGImageSourceTypeIdentifierHint: kUTTypeTIFF] as CFDictionary), CGImageSourceGetCount(imsrc) > 0, let cgImage = CGImageSourceCreateImageAtIndex(imsrc, 0, nil) else { return nil }
  621. let pdfData = NSMutableData(capacity: tiffData.count)
  622. let consumer = CGDataConsumer(data: pdfData! as CFMutableData)!
  623. var rect = CGRect(x: 0, y: 0, width: CGFloat(cgImage.width), height: CGFloat(cgImage.height))
  624. let ctxt = CGContext(consumer: consumer, mediaBox: &rect, nil)
  625. ctxt!.beginPDFPage(nil)
  626. ctxt!.draw(cgImage, in: rect)
  627. ctxt!.endPDFPage()
  628. ctxt!.closePDF()
  629. return pdfData as? Data
  630. }
  631. // MARK: - Private Methods
  632. private func _saveImagePath() -> String {
  633. let rootPath = KMDataManager.fetchAppSupportOfBundleIdentifierDirectory()
  634. let path = rootPath.appendingPathComponent("ImageToPDF").path
  635. if FileManager.default.fileExists(atPath: path) == false {
  636. try?FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: false)
  637. }
  638. return path
  639. }
  640. private func _clearImageData() {
  641. let path = self._saveImagePath()
  642. if FileManager.default.fileExists(atPath: path) {
  643. try?FileManager.default.removeItem(atPath: path)
  644. }
  645. }
  646. private func _initHeaderCellView(cellView: KMNTableHeaderCellView) {
  647. var dividerColor = self.dividerColor_
  648. if dividerColor == nil {
  649. dividerColor = ComponentLibrary.shared.getComponentColorFromKey("colorBorder/divider")
  650. }
  651. cellView.leftLine.wantsLayer = true
  652. cellView.leftLine.layer?.backgroundColor = dividerColor?.cgColor ?? .black
  653. cellView.rightLine.wantsLayer = true
  654. cellView.rightLine.layer?.backgroundColor = dividerColor?.cgColor ?? .black
  655. cellView.bottomLine.wantsLayer = true
  656. cellView.bottomLine.layer?.backgroundColor = dividerColor?.cgColor ?? .black
  657. }
  658. private func _addFolderAction() {
  659. let openPanel = NSOpenPanel()
  660. // openPanel.title = NSLocalizedString("选择并合并文件。按下键盘上的命令按钮,逐次点击目标文件,即可选择多个文件", comment: "")
  661. openPanel.canChooseDirectories = true
  662. openPanel.canChooseFiles = false
  663. openPanel.allowsMultipleSelection = true
  664. openPanel.beginSheetModal(for: view.window!, completionHandler: { [self] result in
  665. if result != .OK {
  666. } else {
  667. var result: [URL] = []
  668. for folderURL in openPanel.urls {
  669. _findAllFiles(folder: folderURL, result: &result)
  670. }
  671. var paths: [String] = []
  672. for url in result {
  673. paths.append(url.path)
  674. }
  675. self.addFilesToList(addArray: NSMutableArray(array: paths))
  676. }
  677. })
  678. }
  679. private func _findAllFiles(folder: URL, result: inout [URL]) {
  680. let fileManager = FileManager.default
  681. var isDirectory: ObjCBool = ObjCBool(false)
  682. fileManager.fileExists(atPath: folder.path, isDirectory: &isDirectory)
  683. if (!isDirectory.boolValue) {
  684. return
  685. }
  686. let contents = try?fileManager.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)
  687. if contents?.count == 0 {
  688. return
  689. }
  690. let array = ["jpg","cur","bmp","jpeg","gif","png","tiff","tif","ico","icns","tga","psd","eps","hdr","jp2","jpc","pict","sgi","heic"]
  691. for documentURL in contents! {
  692. var isDirectory: ObjCBool = ObjCBool(false)
  693. fileManager.fileExists(atPath: documentURL.path, isDirectory: &isDirectory)
  694. if (isDirectory.boolValue) {
  695. _findAllFiles(folder: documentURL, result: &result)
  696. } else {
  697. if !array.contains(documentURL.pathExtension.lowercased()) {
  698. continue
  699. }
  700. result.append(documentURL)
  701. }
  702. }
  703. }
  704. func switchToOperateType(_ operateType: KMBatchOperationType, files: [KMBatchOperateFile]) {
  705. switchToOperateType(operateType)
  706. self.files = files
  707. self.tableView.reloadData()
  708. }
  709. func checkNeedPasswordSwitchToOperateType(_ operateType: KMBatchOperationType, files: [KMBatchOperateFile]) {
  710. switchToOperateType(operateType)
  711. var arr: [String] = []
  712. for i in 0..<files.count {
  713. let file = files[i]
  714. arr.append(file.filePath)
  715. }
  716. self.files = files
  717. self.files.removeAll()
  718. addFilesToList(addArray: NSMutableArray.init(array: arr))
  719. self.tableView.reloadData()
  720. }
  721. func reloadFile(_ file: KMBatchOperateFile) {
  722. var rowIndexSet = IndexSet()
  723. for i in 0..<self.files.count {
  724. if file.filePath == self.files[i].filePath {
  725. rowIndexSet.insert(i)
  726. break
  727. }
  728. }
  729. var columnIndexSet = IndexSet()
  730. for i in 0..<self.tableView.numberOfColumns {
  731. let identifier = self.tableView.tableColumns[i].identifier
  732. if identifier.rawValue == "status" {
  733. columnIndexSet.insert(i)
  734. break
  735. }
  736. }
  737. if Thread.isMainThread {
  738. self.tableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: columnIndexSet)
  739. } else {
  740. DispatchQueue.main.async {
  741. self.tableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: columnIndexSet)
  742. }
  743. }
  744. }
  745. func refreshConvertProgress(_ progress: CGFloat, file: KMBatchOperateFile) {
  746. self.tableView.reloadData()
  747. }
  748. func reloadConvertInterface(withType type: KMConvertWithPDFType) {
  749. if type == .WordAdvance || type == .WordStandard || type == .Excel || type == .PowerPoint || type == .RTF || type == .CSV || type == .HTML || type == .Text || type == .Json {
  750. self.DPIColumn.isHidden = true
  751. } else {
  752. self.DPIColumn.isHidden = false
  753. }
  754. self.tableView.reloadData()
  755. }
  756. }
  757. // MARK: - NSTableViewDelegate,NSTableViewDataSource
  758. extension KMBatchOperateLeftViewController: NSTableViewDelegate,NSTableViewDataSource {
  759. func numberOfRows(in tableView: NSTableView) -> Int {
  760. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMBatchFilesCountNotification"), object: self.files, userInfo: [kObjectKey : self])
  761. self.deleteFileButton.isEnabled = self.files.count > 0
  762. deleteButton_?.properties.isDisabled = self.files.count <= 0
  763. deleteButton_?.reloadData()
  764. self.blankView.isHidden = self.files.count > 0
  765. if self.files.count == 0 {
  766. return 0
  767. }
  768. return self.files.count + 1;
  769. }
  770. func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  771. let identifier = tableColumn?.identifier
  772. let rowIdx = max(0, row-1)
  773. let file = self.files[rowIdx]
  774. let cellColor = KMNColorTools.colorFill_4()
  775. let titleFont = ComponentLibrary.shared.getFontFromKey("mac/body-s-medium")
  776. let titleColor = KMNColorTools.colorText_1()
  777. if identifier?.rawValue == "index" {
  778. if row == 0 {
  779. let cellView = KMNTableHeaderCellView()
  780. cellView.wantsLayer = true
  781. cellView.layer?.backgroundColor = cellColor.cgColor
  782. cellView.titleLabel.stringValue = KMLocalizedString("")
  783. _initHeaderCellView(cellView: cellView)
  784. return cellView
  785. }
  786. let cellView = KMBatchTableCellView(type: .Size)
  787. _ = row + 1
  788. cellView.textField?.stringValue = String(format: "%d", row);
  789. return cellView;
  790. } else if identifier?.rawValue == "pageRange"{
  791. if (file.currentOperateType == .CreatePDF) {
  792. if row == 0 {
  793. let cellView = KMNTableHeaderCellView()
  794. cellView.wantsLayer = true
  795. cellView.layer?.backgroundColor = cellColor.cgColor
  796. cellView.titleLabel.stringValue = KMLocalizedString("Dimensions")
  797. cellView.titleLabel.font = titleFont
  798. cellView.titleLabel.textColor = titleColor
  799. _initHeaderCellView(cellView: cellView)
  800. cellView.itemClick = { [weak self] idx, _ in
  801. if idx == 1 { // 排序
  802. let asc = self?.dimensionsAsc_ ?? false
  803. if asc {
  804. self?.files.sort(){$0.dimensions > $1.dimensions}
  805. } else {
  806. self?.files.sort(){$0.dimensions <= $1.dimensions}
  807. }
  808. self?.dimensionsAsc_ = !asc
  809. self?.reloadData()
  810. }
  811. }
  812. return cellView
  813. }
  814. let cellView = KMBatchTableCellView(type: .Size)
  815. if (file.fileType == .Image) {
  816. let image = NSImage(contentsOfFile: file.filePath)
  817. cellView.textField?.stringValue = String(Int(image?.size.width ?? 0)) + "x" + String(Int(image?.size.height ?? 0))
  818. file.dimensions = Float((image?.size.width ?? 0) * (image?.size.height ?? 0))
  819. }
  820. return cellView;
  821. } else {
  822. let cellView = KMBatchTableCellView(type: .PageRange)
  823. cellView.updateInterface(file)
  824. return cellView;
  825. }
  826. } else if identifier?.rawValue == "status"{
  827. if row == 0 {
  828. let cellView = KMNTableHeaderCellView()
  829. cellView.wantsLayer = true
  830. cellView.layer?.backgroundColor = cellColor.cgColor
  831. cellView.titleLabel.stringValue = KMLocalizedString("State")
  832. cellView.titleLabel.font = titleFont
  833. cellView.titleLabel.textColor = titleColor
  834. _initHeaderCellView(cellView: cellView)
  835. return cellView
  836. }
  837. let cellView = KMBatchTableCellView(type: .Status)
  838. if (file.currentOperateType == .CreatePDF) {
  839. cellView.updateInterface(file: file, progress: file.progress ?? 0)
  840. } else {
  841. cellView.updateInterface(file: file, progress: file.progress ?? 0)
  842. }
  843. cellView.removeFileCallBack = { [weak self] file in
  844. self?.files.removeObject(file)
  845. self?.tableView.reloadData()
  846. }
  847. return cellView;
  848. } else if identifier?.rawValue == "size"{
  849. if row == 0 {
  850. let cellView = KMNTableHeaderCellView()
  851. cellView.wantsLayer = true
  852. cellView.layer?.backgroundColor = cellColor.cgColor
  853. cellView.titleLabel.stringValue = KMLocalizedString("Size")
  854. cellView.titleLabel.font = titleFont
  855. cellView.titleLabel.textColor = titleColor
  856. _initHeaderCellView(cellView: cellView)
  857. cellView.itemClick = { [weak self] idx, _ in
  858. if idx == 1 { // 排序
  859. let asc = self?.isSizeAsc_ ?? false
  860. if asc {
  861. self?.files.sort(){$0.fileSize > $1.fileSize}
  862. } else {
  863. self?.files.sort(){$0.fileSize <= $1.fileSize}
  864. }
  865. self?.isSizeAsc_ = !asc
  866. self?.reloadData()
  867. }
  868. }
  869. return cellView
  870. }
  871. let cellView = KMBatchTableCellView(type: .Size)
  872. cellView.updateInterface(file)
  873. return cellView;
  874. } else if identifier?.rawValue == "fileName"{
  875. if row == 0 {
  876. let cellView = KMNTableHeaderCellView()
  877. cellView.wantsLayer = true
  878. cellView.layer?.backgroundColor = cellColor.cgColor
  879. cellView.titleLabel.stringValue = KMLocalizedString("File Name")
  880. cellView.titleLabel.font = titleFont
  881. cellView.titleLabel.textColor = titleColor
  882. _initHeaderCellView(cellView: cellView)
  883. cellView.itemClick = { [weak self] idx, _ in
  884. if idx == 1 { // 排序
  885. let asc = self?.fileNameAsc_ ?? false
  886. if asc {
  887. self?.files.sort(){$0.filePath.lastPathComponent > $1.filePath.lastPathComponent}
  888. } else {
  889. self?.files.sort(){$0.filePath.lastPathComponent <= $1.filePath.lastPathComponent}
  890. }
  891. self?.fileNameAsc_ = !asc
  892. self?.reloadData()
  893. }
  894. }
  895. return cellView
  896. }
  897. let cellView = KMBatchTableCellView(type: .FileName)
  898. cellView.updateInterface(file)
  899. cellView.fileIv?.wantsLayer = true
  900. cellView.fileIv?.layer?.borderWidth = 0
  901. cellView.fileIv?.layer?.borderColor = ComponentLibrary.shared.getComponentColorFromKey("colorBorder/3-default").cgColor
  902. let rowView: KMBatchTableRowView = tableView.rowView(atRow: row, makeIfNecessary: true) as! KMBatchTableRowView
  903. if ((file.error) != nil) {
  904. rowView.backgroundColor = KMAppearance.Status.errBGColor();
  905. }
  906. return cellView;
  907. } else if identifier?.rawValue == "dpi"{
  908. let cellView = KMBatchTableCellView(type: .DPI)
  909. cellView.updateInterface(file)
  910. return cellView;
  911. } else if identifier?.rawValue == "dimensions"{
  912. if row == 0 {
  913. let cellView = KMNTableHeaderCellView()
  914. cellView.wantsLayer = true
  915. cellView.layer?.backgroundColor = cellColor.cgColor
  916. cellView.titleLabel.stringValue = KMLocalizedString("Dimensions")
  917. cellView.titleLabel.font = titleFont
  918. cellView.titleLabel.textColor = titleColor
  919. _initHeaderCellView(cellView: cellView)
  920. return cellView
  921. }
  922. let cellView = KMBatchTableCellView(type: .Size)
  923. if (file.fileType == .Image) {
  924. let image = NSImage(contentsOfFile: file.filePath)
  925. cellView.textField?.stringValue = String(Int(image?.size.width ?? 0)) + "x" + String(Int(image?.size.height ?? 0))
  926. }
  927. return cellView;
  928. }
  929. return nil;
  930. }
  931. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  932. let rowIdx = max(0, row-1)
  933. let file = self.files[rowIdx]
  934. if self.type == .CreatePDF {
  935. if row == 0 {
  936. return 32
  937. }
  938. if (file.error != nil) {
  939. return 104
  940. } else {
  941. return 80
  942. }
  943. } else {
  944. if file.fileType == .PDF {
  945. if (file.error != nil) {
  946. return 64
  947. } else {
  948. return 40
  949. }
  950. } else {
  951. return 0.0000001
  952. }
  953. }
  954. }
  955. func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
  956. if row == 0 {
  957. let rowView = KMBatchTableRowView()
  958. rowView.selectionBackgroundColorBlock = {
  959. return .clear
  960. }
  961. rowView.selectionHighlightStyle = .none
  962. rowView.isSelected = false
  963. return rowView
  964. }
  965. let rowView = KMBatchTableRowView()
  966. rowView.selectionBackgroundColorBlock = {
  967. return KMNColorTools.colorPrimary_bgActive()
  968. }
  969. return rowView
  970. }
  971. func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
  972. if rowIndexes.first == 0 {
  973. return false
  974. }
  975. var theIndex = IndexSet()
  976. for idx in rowIndexes {
  977. theIndex.insert(idx-1)
  978. }
  979. let indexSetData = try? NSKeyedArchiver.archivedData(withRootObject: theIndex, requiringSecureCoding: true)
  980. pboard.declareTypes([NSPasteboard.PasteboardType.string], owner: self)
  981. pboard.setData(indexSetData, forType: NSPasteboard.PasteboardType(rawValue: KMBatchDragType) )
  982. return true
  983. }
  984. func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
  985. if row == 0 {
  986. return NSDragOperation(rawValue: 0)
  987. }
  988. var isCanDrag = false
  989. var result: NSDragOperation = []
  990. let pboard = info.draggingPasteboard
  991. if pboard.availableType(from: [.fileURL]) != nil {
  992. guard let pbItems = pboard.pasteboardItems else {
  993. return NSDragOperation(rawValue: 0)
  994. }
  995. var hasValidFile = false
  996. for item in pbItems {
  997. guard let data = item.string(forType: .fileURL), let _url = URL(string: data) else {
  998. continue
  999. }
  1000. var isDirectory: ObjCBool = false
  1001. let fileExists = FileManager.default.fileExists(atPath: _url.path, isDirectory: &isDirectory)
  1002. if fileExists && isDirectory.boolValue {
  1003. let containFile = folderContainAvailableFile(_url.path)
  1004. if containFile {
  1005. isCanDrag = true
  1006. break
  1007. }
  1008. } else {
  1009. if let UTType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, _url.pathExtension as CFString, nil)?.takeRetainedValue() as String? {
  1010. if self.type == .CreatePDF {
  1011. if UTTypeConformsTo(UTType as CFString, kUTTypeImage) {
  1012. isCanDrag = true
  1013. }
  1014. } else {
  1015. if UTTypeConformsTo(UTType as CFString, kUTTypePDF) {
  1016. isCanDrag = true
  1017. }
  1018. }
  1019. }
  1020. if isCanDrag {
  1021. break
  1022. }
  1023. }
  1024. }
  1025. if isCanDrag {
  1026. result = .copy
  1027. }
  1028. return result
  1029. } else {
  1030. return .move
  1031. }
  1032. }
  1033. func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
  1034. let pboard = info.draggingPasteboard
  1035. if pboard.availableType(from: [.init(KMBatchDragType)]) != nil {
  1036. guard let rowData = pboard.data(forType: .init(KMBatchDragType)),
  1037. let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: rowData) as? NSIndexSet else { return false }
  1038. let backUpArray = self.files
  1039. var referenceIndex = -1
  1040. rowIndexes.enumerate(options: .reverse, using: { (idx, stop) in
  1041. let theIdx = max(0, idx)
  1042. let sortFile = backUpArray[theIdx]
  1043. let theRow = row-1
  1044. if referenceIndex < 0 {
  1045. if idx > theRow {
  1046. self.files.remove(at: idx)
  1047. self.files.insert(sortFile, at: theRow)
  1048. } else if idx < theRow {
  1049. if theRow > self.files.count {
  1050. self.files.remove(at: idx)
  1051. self.files.append(sortFile)
  1052. } else {
  1053. self.files.remove(at: idx)
  1054. self.files.insert(sortFile, at: theRow - 1)
  1055. }
  1056. }
  1057. referenceIndex = self.files.firstIndex(of: sortFile) ?? -1
  1058. } else {
  1059. let currentIndex = self.files.firstIndex(of: sortFile) ?? -1
  1060. if currentIndex > referenceIndex {
  1061. self.files.remove(at: currentIndex)
  1062. self.files.insert(sortFile, at: referenceIndex)
  1063. } else {
  1064. referenceIndex -= 1
  1065. self.files.remove(at: currentIndex)
  1066. self.files.insert(sortFile, at: referenceIndex)
  1067. }
  1068. }
  1069. })
  1070. self.tableView.reloadData()
  1071. return true
  1072. } else if pboard.availableType(from: [.fileURL]) != nil {
  1073. if (pboard.pasteboardItems == nil) {
  1074. return true
  1075. }
  1076. let allFilesArray = NSMutableArray()
  1077. for item in pboard.pasteboardItems! {
  1078. let fileURL = item.string(forType: .fileURL)
  1079. if (fileURL == nil) {
  1080. continue
  1081. }
  1082. let path = URL.init(string: fileURL!)
  1083. if (path == nil) {
  1084. continue
  1085. }
  1086. var isFolder = ObjCBool(false)
  1087. FileManager.default.fileExists(atPath: path!.path, isDirectory: &isFolder)
  1088. if isFolder.boolValue {
  1089. let containFiles = fetchAvailableFilesInFolder(path!.path)
  1090. allFilesArray.addObjects(from: containFiles)
  1091. } else {
  1092. allFilesArray.add(path!.path)
  1093. }
  1094. }
  1095. var insertArray = NSMutableArray()
  1096. lockFilePathArr?.removeAllObjects()
  1097. lockFileIndex = 0
  1098. for i in 0..<allFilesArray.count {
  1099. let filePath: String = allFilesArray[i] as! String
  1100. if filePath.hasSuffix(".pdf") || filePath.hasSuffix(".PDF") {
  1101. let document = CPDFDocument(url: URL(fileURLWithPath: filePath))
  1102. if let pdf = CPDFDocument(url: URL(fileURLWithPath: filePath)) {
  1103. if !pdf.allowsPrinting || !pdf.allowsCopying {
  1104. let alert = NSAlert()
  1105. alert.alertStyle = .critical
  1106. alert.messageText = KMLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1107. alert.runModal()
  1108. continue
  1109. } else if document?.isLocked ?? false {
  1110. lockFilePathArr?.add(filePath)
  1111. } else {
  1112. let file = KMBatchOperateFile(filePath: filePath, type: self.type!)
  1113. if !(self.files.contains(file) ) {
  1114. insertArray.add(file)
  1115. }
  1116. }
  1117. }
  1118. } else {
  1119. let file = KMBatchOperateFile(filePath: filePath, type: self.type!)
  1120. if !(self.files.contains(file) ) {
  1121. insertArray.add(file)
  1122. }
  1123. }
  1124. }
  1125. if !(IAPProductsManager.default().isAvailableAllFunction)() {
  1126. if self.files.count < 1 && insertArray.count > 0 {
  1127. let firstObject = insertArray.firstObject
  1128. insertArray.removeAllObjects()
  1129. insertArray.add(firstObject as Any)
  1130. } else {
  1131. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1132. return false
  1133. }
  1134. }
  1135. for i in 0..<insertArray.count {
  1136. self.files.insert(insertArray[i] as! KMBatchOperateFile, at: row + i)
  1137. }
  1138. self.tableView.reloadData()
  1139. if lockFilePathArr!.count > 0 {
  1140. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  1141. self.openPasswordWindow()
  1142. }
  1143. }
  1144. return true
  1145. }
  1146. return false
  1147. }
  1148. }
  1149. // MARK: - NSMenuDelegate, NSMenuItemValidation
  1150. extension KMBatchOperateLeftViewController: NSMenuDelegate, NSMenuItemValidation {
  1151. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  1152. let action = menuItem.action
  1153. if action == #selector(menuItem_ShowInFinder(_:)) || action == #selector(menuItem_Delete(_:)) {
  1154. if tableView.clickedRow == -1 {
  1155. return false
  1156. }
  1157. return true
  1158. }
  1159. return true
  1160. }
  1161. }
  1162. //MARK: - ComponentDropdownDelegate
  1163. extension KMBatchOperateLeftViewController: ComponentDropdownDelegate {
  1164. func componentDropdownDidShowMenuItem(dropdown: ComponentDropdown) {
  1165. showGroupView()
  1166. }
  1167. }
  1168. //MARK: - ComponentGroupDelegate
  1169. extension KMBatchOperateLeftViewController: ComponentGroupDelegate {
  1170. func componentGroupDidDismiss(group: ComponentGroup?) {
  1171. removeGroupView()
  1172. addFileDropdown_.properties.state = .normal
  1173. addFileDropdown_.reloadData()
  1174. }
  1175. func componentGroupDidSelect(group: ComponentGroup?, menuItemProperty: ComponentMenuitemProperty?) {
  1176. if group == groupView_ {
  1177. if let selItem = menuItemProperty {
  1178. let index = group?.menuItemArr.firstIndex(of: selItem)
  1179. if index == 0 {
  1180. chooseFile()
  1181. } else if index == 1 {
  1182. _addFolderAction()
  1183. } else if index == 2 {
  1184. let pboard = NSPasteboard.general
  1185. if let document = self.openDocumentWithImageFromPasteboard(pboard, error: nil) {
  1186. // Document opened successfully
  1187. if let page = document.page(at: 0) {
  1188. let data = page.PDFListViewTIFFData(for: page.bounds)
  1189. var path = self._saveImagePath() + "/Untitled.png"
  1190. path = KMTools.getUniqueFilePath(filePath: path)
  1191. try?data?.write(to: URL(fileURLWithPath: path), options: .atomic)
  1192. self.addFilesToList(addArray: [path])
  1193. }
  1194. }
  1195. } else if index == 3 {
  1196. chooseFileFromCamera()
  1197. }
  1198. }
  1199. } else if group == rightMenuGroupView_ {
  1200. rightMenuGroupView_?.removeFromSuperview()
  1201. if let selItem = menuItemProperty {
  1202. let index = group?.menuItemArr.firstIndex(of: selItem)
  1203. if index == 0 {
  1204. menuItem_ShowInFinder(NSMenuItem())
  1205. } else if index == 1 {
  1206. menuItem_Delete(NSMenuItem())
  1207. }
  1208. }
  1209. }
  1210. }
  1211. }