KMHomeHistoryFileViewController.swift 35 KB

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