KMHomeHistoryFileViewController.swift 33 KB

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