KMHomeHistoryFileViewController.swift 36 KB

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