KMHomeHistoryFileViewController.swift 34 KB

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