KMHomeHistoryFileViewController.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  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. var dateArray: [Int: URL] = [:]
  389. for index in 0...self.files.count - 1 {
  390. let url = self.files[index]
  391. let attrib = try? FileManager.default.attributesOfItem(atPath: url.path) as? Dictionary<FileAttributeKey , Any>
  392. let fileDate: Date = attrib![FileAttributeKey(rawValue: "NSFileModificationDate")] as! Date
  393. let timeInterval = fileDate.timeIntervalSince1970
  394. dateArray.updateValue(url, forKey: Int(timeInterval))
  395. }
  396. let sortedKeys = dateArray.keys.sorted(by: >)
  397. files.removeAll()
  398. for key in sortedKeys {
  399. files.append(dateArray[key]!)
  400. print("\(key): \(dateArray[key]!)")
  401. }
  402. let fileNumber = KMPreferenceManager.shared.getData(forKey: KMPreference.documentMaximunDisplayNumberKey) as? Int ?? 10
  403. if fileNumber <= files.count {
  404. let arr1 = files.prefix(fileNumber)
  405. self.files = Array(arr1)
  406. }
  407. thumbnailSCrollView.isHidden = true
  408. listScrollView.isHidden = true
  409. emptyMainBox.isHidden = true
  410. if files.count > 0 {
  411. deleteButtonVC.enabled = true
  412. deleteButtonVC.state = .Norm
  413. if showMode == .Thumbnail {
  414. thumbnailSCrollView.isHidden = false
  415. historyFileCollectionView.reloadData()
  416. } else {
  417. listScrollView.isHidden = false
  418. historyFileTableView.reloadData()
  419. }
  420. } else {
  421. deleteButtonVC.enabled = false
  422. deleteButtonVC.state = .Disabled
  423. emptyMainBox.isHidden = false
  424. historyFileCollectionView.reloadData()
  425. historyFileTableView.reloadData()
  426. }
  427. deleteButtonVC.updateUI()
  428. }
  429. func multipleChoicesAction(choiceBox box: KMBox, choiceRow row: Int) -> Void {
  430. if allowMultipleChoices_cmd {
  431. if multipleChoices.contains(box) {
  432. box.fillColor = .clear
  433. multipleChoices.removeObject(box)
  434. } else {
  435. multipleChoices.append(box)
  436. }
  437. for box in multipleChoices {
  438. box.fillColor = NSColor(red: 37/255.0, green: 139/255.0, blue: 251/255.0, alpha: 1.0)
  439. }
  440. } else if allowMultipleChoices_shift {
  441. for box in multipleChoices {
  442. box.fillColor = NSColor(red: 37/255.0, green: 139/255.0, blue: 251/255.0, alpha: 1.0)
  443. }
  444. } else {
  445. for iBox in multipleChoices {
  446. iBox.fillColor = .clear
  447. }
  448. multipleChoices.removeAll()
  449. multipleChoices.append(box)
  450. box.fillColor = NSColor(red: 37/255.0, green: 139/255.0, blue: 251/255.0, alpha: 1.0)
  451. }
  452. multipleChoicesIntsAction(choiceRow: row)
  453. }
  454. func multipleChoicesIntsAction(choiceRow row: Int) -> Void {
  455. if allowMultipleChoices_cmd {
  456. if multipleChoicesInts.contains(row) {
  457. multipleChoicesInts.removeObject(row)
  458. } else {
  459. multipleChoicesInts.append(row)
  460. }
  461. } else if allowMultipleChoices_shift {
  462. } else {
  463. multipleChoicesInts.removeAll()
  464. multipleChoicesInts.append(row)
  465. }
  466. }
  467. override func flagsChanged(with event: NSEvent) {
  468. super.flagsChanged(with: event)
  469. if event.type == .flagsChanged {
  470. if event.keyCode == 55 { // cmd
  471. if allowMultipleChoices_cmd {
  472. selectFiles_shift.removeAll()
  473. selectFiles.removeAll()
  474. allowMultipleChoices_cmd = false
  475. } else {
  476. allowMultipleChoices_cmd = true
  477. allowMultipleChoices_shift = false
  478. }
  479. } else if event.keyCode == 56 { // shift
  480. if allowMultipleChoices_shift {
  481. selectFiles_shift.removeAll()
  482. selectFiles.removeAll()
  483. allowMultipleChoices_shift = false
  484. } else {
  485. allowMultipleChoices_shift = true
  486. allowMultipleChoices_cmd = false
  487. }
  488. }
  489. }
  490. }
  491. // @objc func willBecomeActive() {
  492. // self.reloadData()
  493. // }
  494. // MARK: Action
  495. @IBAction func deleteAction(_ sender: NSButton) -> Void {
  496. if selectFiles.count == 0 {
  497. for url in NSDocumentController.shared.recentDocumentURLs {
  498. if FileManager.default.fileExists(atPath: url.path) {
  499. selectFiles.append(url)
  500. }
  501. }
  502. self.delete?.historyFileViewController!(self, deleteDocuments: selectFiles)
  503. } else if selectFiles.count > 0 {
  504. // let urls: Array<URL> = NSDocumentController.shared.recentDocumentURLs
  505. // NSDocumentController.shared.clearRecentDocuments(nil)
  506. // DispatchQueue.main.asyncAfter(deadline: .now()) { [self] in
  507. // for (_, url) in urls.enumerated() {
  508. // if !selectFiles.contains(url) {
  509. // NSDocumentController.shared.noteNewRecentDocumentURL(url)
  510. // }
  511. // }
  512. // NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "KMHomeFileRectChange"), object: NSApp.mainWindow)
  513. // }
  514. self.delete?.historyFileViewController!(self, deleteDocuments: selectFiles)
  515. }
  516. }
  517. @IBAction func openFileAction(_ sender: NSButton) {
  518. let openPanel = NSOpenPanel()
  519. openPanel.allowedFileTypes = ["pdf", "PDF"]
  520. openPanel.allowsMultipleSelection = true
  521. openPanel.beginSheetModal(for: self.view.window!) { result in
  522. if result == .OK {
  523. for url in openPanel.urls {
  524. if !url.path.isPDFValid() {
  525. let alert = NSAlert()
  526. alert.alertStyle = .critical
  527. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  528. alert.runModal()
  529. return
  530. }
  531. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  532. if error != nil {
  533. NSApp.presentError(error!)
  534. } else {
  535. }
  536. }
  537. }
  538. }
  539. }
  540. }
  541. // MARK: NSCollectionViewDataSource
  542. func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
  543. return files.count
  544. }
  545. func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
  546. if collectionView.isEqual(to: historyFileCollectionView) {
  547. let item: KMHistoryFileCollectionViewItem = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMHistoryFileCollectionViewItem"), for: indexPath) as! KMHistoryFileCollectionViewItem
  548. if (indexPath.item > files.count) {
  549. return item
  550. }
  551. let i: Int = indexPath.item
  552. let url: URL = files[i] as! URL
  553. item.selectUrls = selectFiles
  554. item.refreshUI(url)
  555. item.mainBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  556. if self != nil {
  557. if downEntered {
  558. if self.allowMultipleChoices_shift {
  559. if self.selectFiles_shift.count == 0 {
  560. self.selectFiles.append(url)
  561. self.selectFiles_shift.append(i)
  562. } else if self.selectFiles_shift.count == 1 {
  563. let first = self.selectFiles_shift[0] as Int
  564. self.selectFiles.removeAll()
  565. if first > i {
  566. for path in self.files[i...first] {
  567. self.selectFiles.append(path as! URL)
  568. }
  569. } else {
  570. for path in self.files[first...i] {
  571. self.selectFiles.append(path as! URL)
  572. }
  573. }
  574. self.selectFiles_shift.append(i)
  575. } else if self.selectFiles_shift.count == 2 {
  576. let first = self.selectFiles_shift[0] as Int
  577. self.selectFiles.removeAll()
  578. if first > i {
  579. for path in self.files[i...first] {
  580. self.selectFiles.append(path as! URL)
  581. }
  582. } else {
  583. for path in self.files[first...i] {
  584. self.selectFiles.append(path as! URL)
  585. }
  586. }
  587. self.selectFiles_shift[1] = i
  588. }
  589. } else if self.allowMultipleChoices_cmd {
  590. if self.selectFiles.contains(url) {
  591. self.selectFiles.removeObject(url)
  592. } else {
  593. self.selectFiles.append(url)
  594. }
  595. if self.selectFiles_shift.contains(i) {
  596. self.selectFiles_shift.removeObject(i)
  597. } else {
  598. self.selectFiles_shift.append(i)
  599. }
  600. } else {
  601. self.selectFiles.removeAll()
  602. self.selectFiles_shift.removeAll()
  603. self.selectFiles.append(url)
  604. self.selectFiles_shift.append(i)
  605. }
  606. collectionView.reloadData()
  607. }
  608. }
  609. }
  610. item.mainBox.doubleCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox) -> Void in
  611. if self != nil {
  612. if downEntered {
  613. self.selectFiles.removeAll()
  614. var indexs: [URL] = []
  615. let index: URL = self.files[i] as! URL
  616. indexs.append(index)
  617. self.delete?.historyFileViewController!(self, didSelectItemsAt: indexs)
  618. }
  619. }
  620. }
  621. return item
  622. }
  623. return NSCollectionViewItem.init()
  624. }
  625. // MARK: NSCollectionViewDelegate
  626. func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
  627. }
  628. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
  629. if collectionView.isEqual(to: historyFileCollectionView) {
  630. return CGSize(width: 226, height: 248)
  631. }
  632. return CGSize(width: 226, height: 248)
  633. }
  634. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  635. return 16
  636. }
  637. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  638. return 16
  639. }
  640. // MARK: NSTableViewDelegate
  641. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  642. return 72.0;
  643. }
  644. func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  645. let url: URL = files[row] as! URL
  646. let identifier = tableColumn?.identifier
  647. let cellView: KMHomeHistoryFileTableviewCell = tableView.makeView(withIdentifier:identifier!, owner: self) as! KMHomeHistoryFileTableviewCell
  648. cellView.selectUrls = selectFiles
  649. cellView.initializeUI(url)
  650. cellView.highlightCell(multipleChoicesInts, row)
  651. cellView.mainBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  652. if self != nil {
  653. if downEntered {
  654. if self.allowMultipleChoices_shift {
  655. if self.selectFiles_shift.count == 0 {
  656. self.selectFiles.append(url)
  657. self.selectFiles_shift.append(row)
  658. } else if self.selectFiles_shift.count == 1 {
  659. let first = self.selectFiles_shift[0] as Int
  660. self.selectFiles.removeAll()
  661. if first > row {
  662. for path in self.files[row...first] {
  663. self.selectFiles.append(path as! URL)
  664. }
  665. } else {
  666. for path in self.files[first...row] {
  667. self.selectFiles.append(path as! URL)
  668. }
  669. }
  670. self.selectFiles_shift.append(row)
  671. } else if self.selectFiles_shift.count == 2 {
  672. let first = self.selectFiles_shift[0] as Int
  673. self.selectFiles.removeAll()
  674. if first > row {
  675. for path in self.files[row...first] {
  676. self.selectFiles.append(path as! URL)
  677. }
  678. } else {
  679. for path in self.files[first...row] {
  680. self.selectFiles.append(path as! URL)
  681. }
  682. }
  683. self.selectFiles_shift[1] = row
  684. }
  685. } else if self.allowMultipleChoices_cmd {
  686. if self.selectFiles.contains(url) {
  687. self.selectFiles.removeObject(url)
  688. } else {
  689. self.selectFiles.append(url)
  690. }
  691. if self.selectFiles_shift.contains(row) {
  692. self.selectFiles_shift.removeObject(row)
  693. } else {
  694. self.selectFiles_shift.append(row)
  695. }
  696. } else {
  697. self.selectFiles.removeAll()
  698. self.selectFiles_shift.removeAll()
  699. self.selectFiles.append(url)
  700. self.selectFiles_shift.append(row)
  701. }
  702. tableView.reloadData()
  703. }
  704. }
  705. }
  706. cellView.mainBox.doubleCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox) -> Void in
  707. if self != nil {
  708. if downEntered {
  709. self.selectFiles.removeAll()
  710. var indexs: [URL] = []
  711. let index: URL = self.files[row] as! URL
  712. indexs.append(index)
  713. self.delete?.historyFileViewController!(self, didSelectItemsAt: indexs)
  714. }
  715. }
  716. }
  717. return cellView
  718. }
  719. @objc func tableViewDidScroll(_ notification: Notification) {
  720. self.historyFileTableView.reloadData()
  721. }
  722. // MARK: NSTableViewDataSource
  723. func numberOfRows(in tableView: NSTableView) -> Int {
  724. return files.count
  725. }
  726. }