KMHomeHistoryFileViewController.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. //
  2. // KMHomeHistoryFileViewController.swift
  3. // PDF Master
  4. //
  5. // Created by wanjun on 2022/10/28.
  6. //
  7. import Cocoa
  8. public enum HistoryFileShowMode : Int {
  9. case Thumbnail = 0
  10. case List
  11. }
  12. @objc protocol KMHomeHistoryFileViewControllerDelegate {
  13. @objc optional func historyFileViewController(_ viewController: KMHomeHistoryFileViewController, deleteDocuments indexPaths: [URL])
  14. @objc optional func historyFileViewController(_ viewController: KMHomeHistoryFileViewController, didSelectItemsAt indexPaths: [URL])
  15. }
  16. class KMHomeHistoryFileTableviewCell: NSTableCellView {
  17. @IBOutlet weak var fileImageView: NSImageView!
  18. @IBOutlet weak var documentName: NSTextField!
  19. @IBOutlet weak var documentType: NSTextField!
  20. @IBOutlet weak var documentSize: NSTextField!
  21. @IBOutlet weak var moreButton: NSButton!
  22. @IBOutlet weak var lastModificationTime: NSTextField!
  23. @IBOutlet weak var mainBox: KMBox!
  24. var file: URL?
  25. var selectUrls: [URL] = []
  26. var isSelect: Bool = false
  27. var currentWindowController: NSWindowController?
  28. // MARK: Init
  29. override func awakeFromNib() {
  30. super.awakeFromNib()
  31. mainBox.menu = tableCellMenu
  32. documentName.maximumNumberOfLines = 1
  33. mainBox.moveCallback = { [weak self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  34. if self != nil {
  35. if !self!.isSelect {
  36. if mouseEntered {
  37. self!.documentName.textColor = NSColor(hex: "#252629")
  38. self!.documentType.textColor = NSColor(hex: "#94989C")
  39. self!.documentSize.textColor = NSColor(hex: "#94989C")
  40. self!.lastModificationTime.textColor = NSColor(hex: "#94989C")
  41. self!.mainBox.fillColor = NSColor(hex: "#CED0D4", alpha: 0.6)
  42. self!.mainBox.cornerRadius = 4.0
  43. } else {
  44. self!.documentName.textColor = NSColor(hex: "#252629")
  45. self!.documentType.textColor = NSColor(hex: "#94989C")
  46. self!.documentSize.textColor = NSColor(hex: "#94989C")
  47. self!.lastModificationTime.textColor = NSColor(hex: "#94989C")
  48. self!.mainBox.fillColor = .clear
  49. self!.mainBox.cornerRadius = 0.0
  50. }
  51. }
  52. }
  53. }
  54. }
  55. // MARK: Private Methods
  56. func initializeUI(_ url: URL) -> Void {
  57. file = url
  58. let attrib = try? FileManager.default.attributesOfItem(atPath: url.path) as? Dictionary<FileAttributeKey , Any>
  59. if attrib != nil {
  60. let dateFormatter: DateFormatter = DateFormatter.init()
  61. let fileDate: Date = attrib![FileAttributeKey(rawValue: "NSFileModificationDate")] as! Date
  62. var fileTime: String = ""
  63. if fileDate.isToday() {
  64. dateFormatter.dateFormat = "HH:mm"
  65. } else if isSameWeek(withDate: fileDate) {
  66. dateFormatter.dateFormat = "EEE, HH:mm"
  67. } else {
  68. dateFormatter.dateFormat = "MMM d, yyyy"
  69. }
  70. let fileName = url.lastPathComponent
  71. let fileType = url.pathExtension.isEmpty ? "" : url.pathExtension
  72. let sizeFloat: Float = attrib![FileAttributeKey(rawValue: "NSFileSize")] as? Float ?? 0.0
  73. let fileSize = fileSizeString(sizeFloat).isEmpty ? "" : fileSizeString(sizeFloat)
  74. let lastTime = dateFormatter.string(from: fileDate)
  75. if fileDate.isToday() {
  76. fileTime = String(format: "%@, %@", NSLocalizedString("Today", comment: ""), lastTime)
  77. } else if isSameWeek(withDate: fileDate) {
  78. fileTime = lastTime
  79. } else {
  80. fileTime = lastTime
  81. }
  82. let paragraphStyle = NSMutableParagraphStyle()
  83. paragraphStyle.lineSpacing = 22.0
  84. documentName.stringValue = fileName
  85. // documentName.attributedStringValue = NSAttributedString(string: fileName, attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
  86. documentType.attributedStringValue = NSAttributedString(string: fileType, attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
  87. documentSize.attributedStringValue = NSAttributedString(string: fileSize, attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
  88. lastModificationTime.attributedStringValue = NSAttributedString(string: fileTime, attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
  89. mainBox.toolTip = fileName
  90. if selectUrls.contains(url) {
  91. isSelect = true
  92. mainBox.fillColor = NSColor(hex: "#CED0D4")
  93. mainBox.cornerRadius = 4.0
  94. } else {
  95. isSelect = false
  96. mainBox.fillColor = .clear
  97. mainBox.cornerRadius = 0.0
  98. }
  99. documentName.backgroundColor = .clear
  100. documentName.textColor = NSColor(hex: "#252629")
  101. documentName.font = NSFont(name: "SFProText-Regular", size: 14)
  102. documentType.textColor = NSColor(hex: "#94989C")
  103. documentSize.textColor = NSColor(hex: "#94989C")
  104. documentName.backgroundColor = .clear
  105. lastModificationTime.textColor = NSColor(hex: "#94989C")
  106. lastModificationTime.backgroundColor = .clear
  107. moreButton.image = NSImage(named: "KMHomeMoreTools")
  108. let image: NSImage = NSImage.previewForFile(path: url, ofSize: fileImageView.frame.size, asIcon: true) ?? NSImage()
  109. fileImageView.image = image
  110. }
  111. }
  112. func highlightCell(_ rows: Array<Int>, _ row: Int) -> Void {
  113. for i in rows {
  114. if i == row {
  115. mainBox.fillColor = NSColor(hex: "#CED0D4", alpha: 0.6)
  116. }
  117. }
  118. }
  119. func fileSizeString(_ fSize: Float) -> String {
  120. let fileSize = fSize / 1024
  121. let size = fileSize >= 1024 ? (fileSize < 1048576 ? fileSize/1024 : fileSize/1048576.0) : fileSize
  122. let unit = fileSize >= 1024 ? (fileSize < 1048576 ? "M" : "G") : "K"
  123. return String(format: "%0.1f %@", size, unit)
  124. }
  125. func isSameWeek (withDate date: Date) -> Bool {
  126. let currentWeekOfYear = getWeekOfYear(date: Date.init())
  127. let targetWeekOfYear = getWeekOfYear(date: date)
  128. if targetWeekOfYear == currentWeekOfYear {
  129. return false
  130. } else {
  131. return true
  132. }
  133. }
  134. func getWeekOfYear(date: Date) -> Int {
  135. let components = Calendar.current.dateComponents([Calendar.Component.weekOfYear], from: date)
  136. return components.weekOfYear ?? 0
  137. }
  138. // MARK: Menu
  139. lazy var tableCellMenu: NSMenu = {
  140. let tableCellMenu = NSMenu()
  141. var item = NSMenuItem()
  142. item.title = NSLocalizedString("Show in Finder", comment: "")
  143. item.action = #selector(buttonItemClick_ShowPath)
  144. tableCellMenu.addItem(item)
  145. item = NSMenuItem()
  146. item.title = NSLocalizedString("Remove from Recents", comment: "")
  147. item.action = #selector(buttonItemClick_ClosePath)
  148. tableCellMenu.addItem(item)
  149. return tableCellMenu
  150. }()
  151. // MARK: Action
  152. @IBAction func moreButtonAction(_ sender: NSButton) {
  153. let popViewDataArr = [NSLocalizedString("Show in Finder", comment: ""),
  154. NSLocalizedString("Remove from Recents", comment: "")]
  155. let vc: KMHomePopViewController = KMHomePopViewController().initWithPopViewDataArr(popViewDataArr)
  156. let createFilePopover: NSPopover = NSPopover.init()
  157. createFilePopover.contentViewController = vc
  158. createFilePopover.animates = true
  159. createFilePopover.behavior = .semitransient
  160. createFilePopover.setValue(true, forKey: "shouldHideAnchor")
  161. createFilePopover.show(relativeTo: CGRect(x: moreButton.bounds.origin.x, y: 10, width: moreButton.bounds.size.width, height: moreButton.bounds.size.height), of: moreButton, preferredEdge: .minY)
  162. vc.customBox.fillColor = NSColor(hex: "#F6F6F6", alpha: 0.6)
  163. vc.downCallback = { [weak self](downEntered: Bool, count: String) -> Void in
  164. if self != nil {
  165. if downEntered {
  166. if count == NSLocalizedString("Show in Finder", comment: "") {
  167. self!.buttonItemClick_ShowPath(self!.moreButton as Any)
  168. } else if count == NSLocalizedString("Remove from Recents", comment: "") {
  169. self!.buttonItemClick_ClosePath(self!.moreButton as Any)
  170. }
  171. }
  172. }
  173. }
  174. }
  175. @IBAction func buttonItemClick_ShowPath(_ sender: Any) {
  176. if FileManager.default.fileExists(atPath: file!.path) {
  177. NSWorkspace.shared.activateFileViewerSelecting([file!])
  178. }
  179. }
  180. @IBAction func buttonItemClick_ClosePath(_ sender: Any) {
  181. var selects: [URL] = []
  182. if selectUrls.count > 0 {
  183. for selecturl in self.selectUrls {
  184. selects.append(selecturl)
  185. }
  186. } else {
  187. selects.append(file!)
  188. }
  189. if UserDefaults.standard.bool(forKey: "kHistoryDeleteNOReminderKey") {
  190. historyFileDeleteAction(selects)
  191. } else {
  192. let historyFileDeleteVC: KMHistoryFileDeleteWindowController = KMHistoryFileDeleteWindowController.init(windowNibName: NSNib.Name("KMHistoryFileDeleteWindowController"))
  193. historyFileDeleteVC.indexPaths = selects
  194. self.currentWindowController = historyFileDeleteVC
  195. historyFileDeleteVC.deleteCallback = { [weak self](indexPaths: [URL], windowController: KMHistoryFileDeleteWindowController) -> Void in
  196. if self != nil {
  197. self?.currentWindowController = nil
  198. self!.historyFileDeleteAction(indexPaths)
  199. }
  200. }
  201. self.window?.beginSheet(historyFileDeleteVC.window!)
  202. }
  203. }
  204. func historyFileDeleteAction(_ indexPaths: [URL]) -> Void {
  205. let urls: Array<URL> = NSDocumentController.shared.recentDocumentURLs
  206. NSDocumentController.shared.clearRecentDocuments(nil)
  207. DispatchQueue.main.asyncAfter(deadline: .now()) { [self] in
  208. for (_, url) in urls.enumerated() {
  209. if !indexPaths.contains(url) {
  210. NSDocumentController.shared.noteNewRecentDocumentURL(url)
  211. }
  212. }
  213. NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "KMHomeFileRectChange"), object: self.window)
  214. }
  215. }
  216. }
  217. class KMHomeHistoryFileViewController: NSViewController, NSCollectionViewDelegate, NSCollectionViewDataSource, NSCollectionViewDelegateFlowLayout, NSTableViewDelegate, NSTableViewDataSource {
  218. @IBOutlet weak var historyFileLabel: NSTextField!
  219. @IBOutlet weak var modeBox: NSBox!
  220. @IBOutlet weak var modeBoxHeight: NSLayoutConstraint!
  221. @IBOutlet weak var thumbnailBox: KMBox!
  222. @IBOutlet weak var thumbnailImageView: NSImageView!
  223. @IBOutlet weak var listBox: KMBox!
  224. @IBOutlet weak var listImageView: NSImageView!
  225. @IBOutlet weak var deleteBox: KMBox!
  226. @IBOutlet weak var deleteBoxHeight: NSLayoutConstraint!
  227. @IBOutlet weak var deleteImageView: NSImageView!
  228. @IBOutlet weak var thumbnailSCrollView: NSScrollView!
  229. @IBOutlet weak var historyFileCollectionView: KMHistoryFileCollectionView!
  230. @IBOutlet weak var listScrollView: NSScrollView!
  231. @IBOutlet weak var historyFileTableView: KMHistoryFileTableView!
  232. @IBOutlet weak var emptyMainBox: NSBox!
  233. @IBOutlet weak var emptyBox: NSBox!
  234. @IBOutlet weak var emptyImageView: NSImageView!
  235. @IBOutlet weak var emptyTitleLabel: NSTextField!
  236. @IBOutlet weak var emptySubtitleLabel: NSTextField!
  237. @IBOutlet weak var emptyHovBox: KMMoveBox!
  238. var files: [Any] = []
  239. var selectFiles: [URL] = []
  240. var selectFiles_shift: [Int] = []
  241. var showMode: HistoryFileShowMode!
  242. open weak var delete: KMHomeHistoryFileViewControllerDelegate?
  243. var allowMultipleChoices_cmd: Bool!
  244. var allowMultipleChoices_shift: Bool!
  245. var multipleChoices: [KMBox] = []
  246. var multipleChoicesInts: [Int] = []
  247. var deleteButtonVC: KMDesignButton!
  248. // MARK: Init
  249. override func viewDidLoad() {
  250. super.viewDidLoad()
  251. // Do view setup here.
  252. deleteButtonVC = KMDesignButton.init(withType: .Image)
  253. historyFileCollectionView.register(KMHistoryFileCollectionViewItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMHistoryFileCollectionViewItem"))
  254. initializeUI()
  255. initLocalization()
  256. allowMultipleChoices_cmd = false
  257. allowMultipleChoices_shift = false
  258. if UserDefaults.standard.bool(forKey: "kFileListViewListModeKey") {
  259. showMode = .List
  260. } else {
  261. showMode = .Thumbnail
  262. }
  263. refreshMode()
  264. self.listBox.downCallback = { [weak self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  265. if self != nil {
  266. if downEntered {
  267. if (self!.showMode == .Thumbnail) {
  268. self!.showMode = .List
  269. self!.refreshMode()
  270. }
  271. }
  272. }
  273. }
  274. self.thumbnailBox.downCallback = { [weak self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  275. if self != nil {
  276. if downEntered {
  277. if (self!.showMode == .List) {
  278. self!.showMode = .Thumbnail
  279. self!.refreshMode()
  280. }
  281. }
  282. }
  283. }
  284. self.deleteBox.downCallback = { [weak self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  285. if self != nil {
  286. if self!.deleteButtonVC.enabled {
  287. if downEntered {
  288. self!.deleteButtonVC.state = .Sel
  289. } else {
  290. self!.deleteButtonVC.state = .Norm
  291. }
  292. self!.deleteButtonVC.updateUI()
  293. }
  294. }
  295. }
  296. self.emptyHovBox.move = { [unowned self](mouseEntered: Bool) -> Void in
  297. if mouseEntered {
  298. emptyImageView.image = NSImage(named: "icon_empty_add_hov")
  299. } else {
  300. emptyImageView.image = NSImage(named: "icon_empty_add_norm")
  301. }
  302. }
  303. }
  304. override func viewDidAppear() {
  305. super.viewDidAppear()
  306. reloadData()
  307. }
  308. func initializeUI() {
  309. deleteBox.fillColor = .clear
  310. deleteBox.contentView = deleteButtonVC.view
  311. deleteButtonVC.target = self
  312. deleteButtonVC.action = #selector(deleteAction(_:))
  313. deleteButtonVC.image = NSImage(named: "icon_btn_clear_false_norm")!
  314. deleteButtonVC.button(type: .Sec, size: .m, height: deleteBoxHeight)
  315. historyFileLabel.font = NSFont(name: "SFProText-Semibold", size: 20)
  316. historyFileLabel.textColor = NSColor(red: 37/255.0, green: 38/255.0, blue: 41/255.0, alpha: 1.0)
  317. modeBox.fillColor = KMDesignToken.shared.fill(withToken: "segmented.bg")
  318. modeBox.cornerRadius = KMDesignToken.shared.borderRadius(withToken: "segmented.bg").stringToCGFloat()
  319. emptyImageView.image = NSImage(named: "icon_empty_add_norm")
  320. emptyTitleLabel.textColor = NSColor(hex: "#616469")
  321. emptyTitleLabel.font = NSFont(name: "SFProText-Regular", size: 14.0)
  322. emptySubtitleLabel.textColor = NSColor(hex: "#94989C")
  323. emptySubtitleLabel.font = NSFont(name: "SFProText-Regular", size: 12.0)
  324. }
  325. func initLocalization() {
  326. let fastToolParagraphStyle = NSMutableParagraphStyle()
  327. fastToolParagraphStyle.lineSpacing = 28.0
  328. historyFileLabel.attributedStringValue = NSAttributedString(string: NSLocalizedString("Recent", comment: ""), attributes: [NSAttributedString.Key.paragraphStyle: fastToolParagraphStyle])
  329. emptyTitleLabel.stringValue = NSLocalizedString("No recently opened files", comment: "")
  330. emptySubtitleLabel.stringValue = NSLocalizedString("Click to open the file or drag the file directly here to open the file.", comment: "")
  331. }
  332. // MARK: Get && Set
  333. // MARK: Private Methods
  334. func refreshMode() {
  335. switch showMode {
  336. case .Thumbnail:
  337. listBox.fillColor = KMDesignToken.shared.fill(withToken: "segmented.bg-item.unsel")
  338. listBox.cornerRadius = KMDesignToken.shared.borderRadius(withToken: "segmented.bg").stringToCGFloat()
  339. thumbnailBox.fillColor = KMDesignToken.shared.fill(withToken: "segmented.bg-item.sel")
  340. thumbnailBox.cornerRadius = KMDesignToken.shared.borderRadius(withToken: "segmented.bg").stringToCGFloat()
  341. listScrollView.isHidden = true
  342. thumbnailSCrollView.isHidden = false
  343. UserDefaults.standard.setValue(false, forKey: "kFileListViewListModeKey")
  344. break
  345. case .List:
  346. listBox.fillColor = KMDesignToken.shared.fill(withToken: "segmented.bg-item.sel")
  347. listBox.cornerRadius = KMDesignToken.shared.borderRadius(withToken: "segmented.bg").stringToCGFloat()
  348. thumbnailBox.fillColor = KMDesignToken.shared.fill(withToken: "segmented.bg-item.unsel")
  349. thumbnailBox.cornerRadius = KMDesignToken.shared.borderRadius(withToken: "segmented.bg").stringToCGFloat()
  350. listScrollView.isHidden = false
  351. thumbnailSCrollView.isHidden = true
  352. UserDefaults.standard.setValue(true, forKey: "kFileListViewListModeKey")
  353. break
  354. default:
  355. break
  356. }
  357. UserDefaults.standard.synchronize()
  358. reloadData()
  359. }
  360. func reloadData() -> Void {
  361. files.removeAll()
  362. for url in NSDocumentController.shared.recentDocumentURLs {
  363. if FileManager.default.fileExists(atPath: url.path) {
  364. self.files.append(url)
  365. }
  366. }
  367. let fileNumber = KMPreferenceManager.shared.getData(forKey: KMPreference.documentMaximunDisplayNumberKey) as? Int ?? 10
  368. if fileNumber <= files.count {
  369. let arr1 = files.prefix(fileNumber)
  370. self.files = Array(arr1)
  371. }
  372. thumbnailSCrollView.isHidden = true
  373. listScrollView.isHidden = true
  374. emptyMainBox.isHidden = true
  375. if files.count > 0 {
  376. deleteButtonVC.enabled = true
  377. deleteButtonVC.state = .Norm
  378. if showMode == .Thumbnail {
  379. thumbnailSCrollView.isHidden = false
  380. historyFileCollectionView.reloadData()
  381. } else {
  382. listScrollView.isHidden = false
  383. historyFileTableView.reloadData()
  384. }
  385. } else {
  386. deleteButtonVC.enabled = false
  387. deleteButtonVC.state = .Disabled
  388. emptyMainBox.isHidden = false
  389. historyFileCollectionView.reloadData()
  390. historyFileTableView.reloadData()
  391. }
  392. deleteButtonVC.updateUI()
  393. }
  394. func multipleChoicesAction(choiceBox box: KMBox, choiceRow row: Int) -> Void {
  395. if allowMultipleChoices_cmd {
  396. if multipleChoices.contains(box) {
  397. box.fillColor = .clear
  398. multipleChoices.removeObject(box)
  399. } else {
  400. multipleChoices.append(box)
  401. }
  402. for box in multipleChoices {
  403. box.fillColor = NSColor(red: 37/255.0, green: 139/255.0, blue: 251/255.0, alpha: 1.0)
  404. }
  405. } else if allowMultipleChoices_shift {
  406. for box in multipleChoices {
  407. box.fillColor = NSColor(red: 37/255.0, green: 139/255.0, blue: 251/255.0, alpha: 1.0)
  408. }
  409. } else {
  410. for iBox in multipleChoices {
  411. iBox.fillColor = .clear
  412. }
  413. multipleChoices.removeAll()
  414. multipleChoices.append(box)
  415. box.fillColor = NSColor(red: 37/255.0, green: 139/255.0, blue: 251/255.0, alpha: 1.0)
  416. }
  417. multipleChoicesIntsAction(choiceRow: row)
  418. }
  419. func multipleChoicesIntsAction(choiceRow row: Int) -> Void {
  420. if allowMultipleChoices_cmd {
  421. if multipleChoicesInts.contains(row) {
  422. multipleChoicesInts.removeObject(row)
  423. } else {
  424. multipleChoicesInts.append(row)
  425. }
  426. } else if allowMultipleChoices_shift {
  427. } else {
  428. multipleChoicesInts.removeAll()
  429. multipleChoicesInts.append(row)
  430. }
  431. }
  432. override func flagsChanged(with event: NSEvent) {
  433. super.flagsChanged(with: event)
  434. if event.type == .flagsChanged {
  435. if event.keyCode == 55 { // cmd
  436. if allowMultipleChoices_cmd {
  437. selectFiles_shift.removeAll()
  438. allowMultipleChoices_cmd = false
  439. } else {
  440. allowMultipleChoices_cmd = true
  441. allowMultipleChoices_shift = false
  442. }
  443. } else if event.keyCode == 56 { // shift
  444. if allowMultipleChoices_shift {
  445. selectFiles_shift.removeAll()
  446. allowMultipleChoices_shift = false
  447. } else {
  448. allowMultipleChoices_shift = true
  449. allowMultipleChoices_cmd = false
  450. }
  451. }
  452. }
  453. }
  454. // MARK: Action
  455. @IBAction func deleteAction(_ sender: NSButton) -> Void {
  456. if selectFiles.count == 0 {
  457. for url in NSDocumentController.shared.recentDocumentURLs {
  458. if FileManager.default.fileExists(atPath: url.path) {
  459. selectFiles.append(url)
  460. }
  461. }
  462. self.delete?.historyFileViewController!(self, deleteDocuments: selectFiles)
  463. } else if selectFiles.count > 0 {
  464. let urls: Array<URL> = NSDocumentController.shared.recentDocumentURLs
  465. NSDocumentController.shared.clearRecentDocuments(nil)
  466. DispatchQueue.main.asyncAfter(deadline: .now()) { [self] in
  467. for (_, url) in urls.enumerated() {
  468. if !selectFiles.contains(url) {
  469. NSDocumentController.shared.noteNewRecentDocumentURL(url)
  470. }
  471. }
  472. NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "KMHomeFileRectChange"), object: NSApp.mainWindow)
  473. }
  474. }
  475. }
  476. @IBAction func openFileAction(_ sender: NSButton) {
  477. let openPanel = NSOpenPanel()
  478. openPanel.allowedFileTypes = ["pdf", "PDF"]
  479. openPanel.allowsMultipleSelection = false
  480. openPanel.beginSheetModal(for: self.view.window!) { result in
  481. if result == .OK {
  482. if !openPanel.url!.path.isPDFValid() {
  483. let alert = NSAlert()
  484. alert.alertStyle = .critical
  485. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  486. alert.runModal()
  487. return
  488. }
  489. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, documentWasAlreadyOpen, error in
  490. if error != nil {
  491. NSApp.presentError(error!)
  492. } else {
  493. }
  494. }
  495. }
  496. }
  497. }
  498. // MARK: NSCollectionViewDataSource
  499. func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
  500. return files.count
  501. }
  502. func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
  503. if collectionView.isEqual(to: historyFileCollectionView) {
  504. let item: KMHistoryFileCollectionViewItem = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMHistoryFileCollectionViewItem"), for: indexPath) as! KMHistoryFileCollectionViewItem
  505. if (indexPath.count > files.count) {
  506. return item
  507. }
  508. let i: Int = indexPath.item
  509. let url: URL = files[i] as! URL
  510. item.selectUrls = selectFiles
  511. item.refreshUI(url)
  512. item.mainBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  513. if self != nil {
  514. if downEntered {
  515. if self.allowMultipleChoices_shift {
  516. if self.selectFiles_shift.count == 0 {
  517. self.selectFiles.append(url)
  518. self.selectFiles_shift.append(i)
  519. } else if self.selectFiles_shift.count == 1 {
  520. let first = self.selectFiles_shift[0] as Int
  521. self.selectFiles.removeAll()
  522. if first > i {
  523. for path in self.files[i...first] {
  524. self.selectFiles.append(path as! URL)
  525. }
  526. } else {
  527. for path in self.files[first...i] {
  528. self.selectFiles.append(path as! URL)
  529. }
  530. }
  531. self.selectFiles_shift.append(i)
  532. } else if self.selectFiles_shift.count == 2 {
  533. let first = self.selectFiles_shift[0] as Int
  534. self.selectFiles.removeAll()
  535. if first > i {
  536. for path in self.files[i...first] {
  537. self.selectFiles.append(path as! URL)
  538. }
  539. } else {
  540. for path in self.files[first...i] {
  541. self.selectFiles.append(path as! URL)
  542. }
  543. }
  544. self.selectFiles_shift[1] = i
  545. }
  546. } else if self.allowMultipleChoices_cmd {
  547. if self.selectFiles.contains(url) {
  548. self.selectFiles.removeObject(url)
  549. } else {
  550. self.selectFiles.append(url)
  551. }
  552. if self.selectFiles_shift.contains(i) {
  553. self.selectFiles_shift.removeObject(i)
  554. } else {
  555. self.selectFiles_shift.append(i)
  556. }
  557. } else {
  558. self.selectFiles.removeAll()
  559. self.selectFiles_shift.removeAll()
  560. self.selectFiles.append(url)
  561. self.selectFiles_shift.append(i)
  562. }
  563. collectionView.reloadData()
  564. }
  565. }
  566. }
  567. item.mainBox.doubleCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox) -> Void in
  568. if self != nil {
  569. if downEntered {
  570. self.selectFiles.removeAll()
  571. var indexs: [URL] = []
  572. let index: URL = self.files[i] as! URL
  573. indexs.append(index)
  574. self.delete?.historyFileViewController!(self, didSelectItemsAt: indexs)
  575. }
  576. }
  577. }
  578. return item
  579. }
  580. return NSCollectionViewItem.init()
  581. }
  582. // MARK: NSCollectionViewDelegate
  583. func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
  584. }
  585. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
  586. if collectionView.isEqual(to: historyFileCollectionView) {
  587. return CGSize(width: 226, height: 248)
  588. }
  589. return CGSize(width: 226, height: 248)
  590. }
  591. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  592. return 16
  593. }
  594. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  595. return 16
  596. }
  597. // MARK: NSTableViewDelegate
  598. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  599. return 72.0;
  600. }
  601. func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  602. let url: URL = files[row] as! URL
  603. let identifier = tableColumn?.identifier
  604. let cellView: KMHomeHistoryFileTableviewCell = tableView.makeView(withIdentifier:identifier!, owner: self) as! KMHomeHistoryFileTableviewCell
  605. cellView.selectUrls = selectFiles
  606. cellView.initializeUI(url)
  607. cellView.highlightCell(multipleChoicesInts, row)
  608. cellView.mainBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  609. if self != nil {
  610. if downEntered {
  611. if self.allowMultipleChoices_shift {
  612. if self.selectFiles_shift.count == 0 {
  613. self.selectFiles.append(url)
  614. self.selectFiles_shift.append(row)
  615. } else if self.selectFiles_shift.count == 1 {
  616. let first = self.selectFiles_shift[0] as Int
  617. self.selectFiles.removeAll()
  618. if first > row {
  619. for path in self.files[row...first] {
  620. self.selectFiles.append(path as! URL)
  621. }
  622. } else {
  623. for path in self.files[first...row] {
  624. self.selectFiles.append(path as! URL)
  625. }
  626. }
  627. self.selectFiles_shift.append(row)
  628. } else if self.selectFiles_shift.count == 2 {
  629. let first = self.selectFiles_shift[0] as Int
  630. self.selectFiles.removeAll()
  631. if first > row {
  632. for path in self.files[row...first] {
  633. self.selectFiles.append(path as! URL)
  634. }
  635. } else {
  636. for path in self.files[first...row] {
  637. self.selectFiles.append(path as! URL)
  638. }
  639. }
  640. self.selectFiles_shift[1] = row
  641. }
  642. } else if self.allowMultipleChoices_cmd {
  643. if self.selectFiles.contains(url) {
  644. self.selectFiles.removeObject(url)
  645. } else {
  646. self.selectFiles.append(url)
  647. }
  648. if self.selectFiles_shift.contains(row) {
  649. self.selectFiles_shift.removeObject(row)
  650. } else {
  651. self.selectFiles_shift.append(row)
  652. }
  653. } else {
  654. self.selectFiles.removeAll()
  655. self.selectFiles_shift.removeAll()
  656. self.selectFiles.append(url)
  657. self.selectFiles_shift.append(row)
  658. }
  659. tableView.reloadData()
  660. }
  661. }
  662. }
  663. cellView.mainBox.doubleCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox) -> Void in
  664. if self != nil {
  665. if downEntered {
  666. self.selectFiles.removeAll()
  667. var indexs: [URL] = []
  668. let index: URL = self.files[row] as! URL
  669. indexs.append(index)
  670. self.delete?.historyFileViewController!(self, didSelectItemsAt: indexs)
  671. }
  672. }
  673. }
  674. return cellView
  675. }
  676. // MARK: NSTableViewDataSource
  677. func numberOfRows(in tableView: NSTableView) -> Int {
  678. return files.count
  679. }
  680. }