KMHomeHistoryFileViewController.swift 35 KB

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