KMHomeHistoryFileViewController.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  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: [Any] = []
  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. reloadData()
  299. }
  300. func initializeUI() {
  301. deleteBox.fillColor = .clear
  302. deleteBox.contentView = deleteButtonVC.view
  303. deleteButtonVC.target = self
  304. deleteButtonVC.action = #selector(deleteAction(_:))
  305. deleteButtonVC.image = NSImage(named: "icon_btn_clear_false_norm")!
  306. deleteButtonVC.button(type: .Sec, size: .m, height: deleteBoxHeight)
  307. historyFileLabel.font = NSFont(name: "SFProText-Semibold", size: 20)
  308. historyFileLabel.textColor = NSColor(red: 37/255.0, green: 38/255.0, blue: 41/255.0, alpha: 1.0)
  309. modeBox.fillColor = KMDesignToken.shared.fill(withToken: "segmented.bg")
  310. modeBox.cornerRadius = KMDesignToken.shared.borderRadius(withToken: "segmented.bg").stringToCGFloat()
  311. emptyImageView.image = NSImage(named: "icon_empty_add_norm")
  312. emptyTitleLabel.textColor = NSColor(hex: "#616469")
  313. emptyTitleLabel.font = NSFont(name: "SFProText-Regular", size: 14.0)
  314. emptySubtitleLabel.textColor = NSColor(hex: "#94989C")
  315. emptySubtitleLabel.font = NSFont(name: "SFProText-Regular", size: 12.0)
  316. }
  317. func initLocalization() {
  318. let fastToolParagraphStyle = NSMutableParagraphStyle()
  319. fastToolParagraphStyle.lineSpacing = 28.0
  320. historyFileLabel.attributedStringValue = NSAttributedString(string: NSLocalizedString("Recent", comment: ""), attributes: [NSAttributedString.Key.paragraphStyle: fastToolParagraphStyle])
  321. emptyTitleLabel.stringValue = NSLocalizedString("No recently opened files", comment: "")
  322. emptySubtitleLabel.stringValue = NSLocalizedString("Click to open the file or drag the file directly here to open the file.", comment: "")
  323. }
  324. // MARK: Get && Set
  325. // MARK: Private Methods
  326. func refreshMode() {
  327. switch showMode {
  328. case .Thumbnail:
  329. listBox.fillColor = KMDesignToken.shared.fill(withToken: "segmented.bg-item.unsel")
  330. listBox.cornerRadius = KMDesignToken.shared.borderRadius(withToken: "segmented.bg").stringToCGFloat()
  331. thumbnailBox.fillColor = KMDesignToken.shared.fill(withToken: "segmented.bg-item.sel")
  332. thumbnailBox.cornerRadius = KMDesignToken.shared.borderRadius(withToken: "segmented.bg").stringToCGFloat()
  333. listScrollView.isHidden = true
  334. thumbnailSCrollView.isHidden = false
  335. UserDefaults.standard.setValue(false, forKey: "kFileListViewListModeKey")
  336. break
  337. case .List:
  338. listBox.fillColor = KMDesignToken.shared.fill(withToken: "segmented.bg-item.sel")
  339. listBox.cornerRadius = KMDesignToken.shared.borderRadius(withToken: "segmented.bg").stringToCGFloat()
  340. thumbnailBox.fillColor = KMDesignToken.shared.fill(withToken: "segmented.bg-item.unsel")
  341. thumbnailBox.cornerRadius = KMDesignToken.shared.borderRadius(withToken: "segmented.bg").stringToCGFloat()
  342. listScrollView.isHidden = false
  343. thumbnailSCrollView.isHidden = true
  344. UserDefaults.standard.setValue(true, forKey: "kFileListViewListModeKey")
  345. break
  346. default:
  347. break
  348. }
  349. UserDefaults.standard.synchronize()
  350. reloadData()
  351. }
  352. func reloadData() -> Void {
  353. files.removeAll()
  354. for url in NSDocumentController.shared.recentDocumentURLs {
  355. if FileManager.default.fileExists(atPath: url.path) {
  356. self.files.append(url)
  357. }
  358. }
  359. let fileNumber = KMPreferenceManager.shared.getData(forKey: KMPreference.documentMaximunDisplayNumberKey) as? Int ?? 10
  360. if fileNumber <= files.count {
  361. let arr1 = files.prefix(fileNumber)
  362. self.files = Array(arr1)
  363. }
  364. thumbnailSCrollView.isHidden = true
  365. listScrollView.isHidden = true
  366. emptyMainBox.isHidden = true
  367. if files.count > 0 {
  368. deleteButtonVC.enabled = true
  369. deleteButtonVC.state = .Norm
  370. if showMode == .Thumbnail {
  371. thumbnailSCrollView.isHidden = false
  372. historyFileCollectionView.reloadData()
  373. } else {
  374. listScrollView.isHidden = false
  375. historyFileTableView.reloadData()
  376. }
  377. } else {
  378. deleteButtonVC.enabled = false
  379. deleteButtonVC.state = .Disabled
  380. emptyMainBox.isHidden = false
  381. historyFileCollectionView.reloadData()
  382. historyFileTableView.reloadData()
  383. }
  384. deleteButtonVC.updateUI()
  385. }
  386. func multipleChoicesAction(choiceBox box: KMBox, choiceRow row: Int) -> Void {
  387. if allowMultipleChoices_cmd {
  388. if multipleChoices.contains(box) {
  389. box.fillColor = .clear
  390. multipleChoices.removeObject(box)
  391. } else {
  392. multipleChoices.append(box)
  393. }
  394. for box in multipleChoices {
  395. box.fillColor = NSColor(red: 37/255.0, green: 139/255.0, blue: 251/255.0, alpha: 1.0)
  396. }
  397. } else if allowMultipleChoices_shift {
  398. for box in multipleChoices {
  399. box.fillColor = NSColor(red: 37/255.0, green: 139/255.0, blue: 251/255.0, alpha: 1.0)
  400. }
  401. } else {
  402. for iBox in multipleChoices {
  403. iBox.fillColor = .clear
  404. }
  405. multipleChoices.removeAll()
  406. multipleChoices.append(box)
  407. box.fillColor = NSColor(red: 37/255.0, green: 139/255.0, blue: 251/255.0, alpha: 1.0)
  408. }
  409. multipleChoicesIntsAction(choiceRow: row)
  410. }
  411. func multipleChoicesIntsAction(choiceRow row: Int) -> Void {
  412. if allowMultipleChoices_cmd {
  413. if multipleChoicesInts.contains(row) {
  414. multipleChoicesInts.removeObject(row)
  415. } else {
  416. multipleChoicesInts.append(row)
  417. }
  418. } else if allowMultipleChoices_shift {
  419. } else {
  420. multipleChoicesInts.removeAll()
  421. multipleChoicesInts.append(row)
  422. }
  423. }
  424. override func flagsChanged(with event: NSEvent) {
  425. super.flagsChanged(with: event)
  426. if event.type == .flagsChanged {
  427. if event.keyCode == 55 { // cmd
  428. if allowMultipleChoices_cmd {
  429. selectFiles_shift.removeAll()
  430. selectFiles.removeAll()
  431. allowMultipleChoices_cmd = false
  432. } else {
  433. allowMultipleChoices_cmd = true
  434. allowMultipleChoices_shift = false
  435. }
  436. } else if event.keyCode == 56 { // shift
  437. if allowMultipleChoices_shift {
  438. selectFiles_shift.removeAll()
  439. selectFiles.removeAll()
  440. allowMultipleChoices_shift = false
  441. } else {
  442. allowMultipleChoices_shift = true
  443. allowMultipleChoices_cmd = false
  444. }
  445. }
  446. }
  447. }
  448. @objc func willBecomeActive() {
  449. self.reloadData()
  450. }
  451. // MARK: Action
  452. @IBAction func deleteAction(_ sender: NSButton) -> Void {
  453. if selectFiles.count == 0 {
  454. for url in NSDocumentController.shared.recentDocumentURLs {
  455. if FileManager.default.fileExists(atPath: url.path) {
  456. selectFiles.append(url)
  457. }
  458. }
  459. self.delete?.historyFileViewController!(self, deleteDocuments: selectFiles)
  460. } else if selectFiles.count > 0 {
  461. // let urls: Array<URL> = NSDocumentController.shared.recentDocumentURLs
  462. // NSDocumentController.shared.clearRecentDocuments(nil)
  463. // DispatchQueue.main.asyncAfter(deadline: .now()) { [self] in
  464. // for (_, url) in urls.enumerated() {
  465. // if !selectFiles.contains(url) {
  466. // NSDocumentController.shared.noteNewRecentDocumentURL(url)
  467. // }
  468. // }
  469. // NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "KMHomeFileRectChange"), object: NSApp.mainWindow)
  470. // }
  471. self.delete?.historyFileViewController!(self, deleteDocuments: selectFiles)
  472. }
  473. }
  474. @IBAction func openFileAction(_ sender: NSButton) {
  475. let openPanel = NSOpenPanel()
  476. openPanel.allowedFileTypes = ["pdf", "PDF"]
  477. openPanel.allowsMultipleSelection = true
  478. openPanel.beginSheetModal(for: self.view.window!) { result in
  479. if result == .OK {
  480. for url in openPanel.urls {
  481. if !url.path.isPDFValid() {
  482. let alert = NSAlert()
  483. alert.alertStyle = .critical
  484. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  485. alert.runModal()
  486. return
  487. }
  488. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  489. if error != nil {
  490. NSApp.presentError(error!)
  491. } else {
  492. }
  493. }
  494. }
  495. }
  496. }
  497. }
  498. // MARK: NSCollectionViewDataSource
  499. func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
  500. return files.count
  501. }
  502. func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
  503. if collectionView.isEqual(to: historyFileCollectionView) {
  504. let item: KMHistoryFileCollectionViewItem = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMHistoryFileCollectionViewItem"), for: indexPath) as! KMHistoryFileCollectionViewItem
  505. if (indexPath.item > files.count) {
  506. return item
  507. }
  508. let i: Int = indexPath.item
  509. let url: URL = files[i] as! URL
  510. item.selectUrls = selectFiles
  511. item.refreshUI(url)
  512. item.mainBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  513. if self != nil {
  514. if downEntered {
  515. if self.allowMultipleChoices_shift {
  516. if self.selectFiles_shift.count == 0 {
  517. self.selectFiles.append(url)
  518. self.selectFiles_shift.append(i)
  519. } else if self.selectFiles_shift.count == 1 {
  520. let first = self.selectFiles_shift[0] as Int
  521. self.selectFiles.removeAll()
  522. if first > i {
  523. for path in self.files[i...first] {
  524. self.selectFiles.append(path as! URL)
  525. }
  526. } else {
  527. for path in self.files[first...i] {
  528. self.selectFiles.append(path as! URL)
  529. }
  530. }
  531. self.selectFiles_shift.append(i)
  532. } else if self.selectFiles_shift.count == 2 {
  533. let first = self.selectFiles_shift[0] as Int
  534. self.selectFiles.removeAll()
  535. if first > i {
  536. for path in self.files[i...first] {
  537. self.selectFiles.append(path as! URL)
  538. }
  539. } else {
  540. for path in self.files[first...i] {
  541. self.selectFiles.append(path as! URL)
  542. }
  543. }
  544. self.selectFiles_shift[1] = i
  545. }
  546. } else if self.allowMultipleChoices_cmd {
  547. if self.selectFiles.contains(url) {
  548. self.selectFiles.removeObject(url)
  549. } else {
  550. self.selectFiles.append(url)
  551. }
  552. if self.selectFiles_shift.contains(i) {
  553. self.selectFiles_shift.removeObject(i)
  554. } else {
  555. self.selectFiles_shift.append(i)
  556. }
  557. } else {
  558. self.selectFiles.removeAll()
  559. self.selectFiles_shift.removeAll()
  560. self.selectFiles.append(url)
  561. self.selectFiles_shift.append(i)
  562. }
  563. collectionView.reloadData()
  564. }
  565. }
  566. }
  567. item.mainBox.doubleCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox) -> Void in
  568. if self != nil {
  569. if downEntered {
  570. self.selectFiles.removeAll()
  571. var indexs: [URL] = []
  572. let index: URL = self.files[i] as! URL
  573. indexs.append(index)
  574. self.delete?.historyFileViewController!(self, didSelectItemsAt: indexs)
  575. }
  576. }
  577. }
  578. return item
  579. }
  580. return NSCollectionViewItem.init()
  581. }
  582. // MARK: NSCollectionViewDelegate
  583. func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
  584. }
  585. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
  586. if collectionView.isEqual(to: historyFileCollectionView) {
  587. return CGSize(width: 226, height: 248)
  588. }
  589. return CGSize(width: 226, height: 248)
  590. }
  591. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  592. return 16
  593. }
  594. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  595. return 16
  596. }
  597. // MARK: NSTableViewDelegate
  598. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  599. return 72.0;
  600. }
  601. func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  602. let url: URL = files[row] as! URL
  603. let identifier = tableColumn?.identifier
  604. let cellView: KMHomeHistoryFileTableviewCell = tableView.makeView(withIdentifier:identifier!, owner: self) as! KMHomeHistoryFileTableviewCell
  605. cellView.selectUrls = selectFiles
  606. cellView.initializeUI(url)
  607. cellView.highlightCell(multipleChoicesInts, row)
  608. cellView.mainBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  609. if self != nil {
  610. if downEntered {
  611. if self.allowMultipleChoices_shift {
  612. if self.selectFiles_shift.count == 0 {
  613. self.selectFiles.append(url)
  614. self.selectFiles_shift.append(row)
  615. } else if self.selectFiles_shift.count == 1 {
  616. let first = self.selectFiles_shift[0] as Int
  617. self.selectFiles.removeAll()
  618. if first > row {
  619. for path in self.files[row...first] {
  620. self.selectFiles.append(path as! URL)
  621. }
  622. } else {
  623. for path in self.files[first...row] {
  624. self.selectFiles.append(path as! URL)
  625. }
  626. }
  627. self.selectFiles_shift.append(row)
  628. } else if self.selectFiles_shift.count == 2 {
  629. let first = self.selectFiles_shift[0] as Int
  630. self.selectFiles.removeAll()
  631. if first > row {
  632. for path in self.files[row...first] {
  633. self.selectFiles.append(path as! URL)
  634. }
  635. } else {
  636. for path in self.files[first...row] {
  637. self.selectFiles.append(path as! URL)
  638. }
  639. }
  640. self.selectFiles_shift[1] = row
  641. }
  642. } else if self.allowMultipleChoices_cmd {
  643. if self.selectFiles.contains(url) {
  644. self.selectFiles.removeObject(url)
  645. } else {
  646. self.selectFiles.append(url)
  647. }
  648. if self.selectFiles_shift.contains(row) {
  649. self.selectFiles_shift.removeObject(row)
  650. } else {
  651. self.selectFiles_shift.append(row)
  652. }
  653. } else {
  654. self.selectFiles.removeAll()
  655. self.selectFiles_shift.removeAll()
  656. self.selectFiles.append(url)
  657. self.selectFiles_shift.append(row)
  658. }
  659. tableView.reloadData()
  660. }
  661. }
  662. }
  663. cellView.mainBox.doubleCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox) -> Void in
  664. if self != nil {
  665. if downEntered {
  666. self.selectFiles.removeAll()
  667. var indexs: [URL] = []
  668. let index: URL = self.files[row] as! URL
  669. indexs.append(index)
  670. self.delete?.historyFileViewController!(self, didSelectItemsAt: indexs)
  671. }
  672. }
  673. }
  674. return cellView
  675. }
  676. // MARK: NSTableViewDataSource
  677. func numberOfRows(in tableView: NSTableView) -> Int {
  678. return files.count
  679. }
  680. }