KMHomeRightView.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. //
  2. // KMHomeRightView.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by Niehaoyu on 2024/10/10.
  6. //
  7. import Cocoa
  8. import KMComponentLibrary
  9. @objc public protocol KMHomeRightViewDelegate: AnyObject {
  10. //点击管理快捷工具按钮
  11. @objc optional func homeRightViewDidManageQuickTools(_ view: KMHomeRightView)
  12. //点击快捷工具列表中的某一项
  13. @objc optional func homeRightViewDidQuickToolsItemClicked(_ view: KMHomeRightView, _ toolType: HomeQuickToolType)
  14. //最近文件列表删除更新结束后回调
  15. @objc optional func homeRightViewDidRecentFilesUpdated(_ view: KMHomeRightView)
  16. //选择打开文件
  17. @objc optional func homeRightViewDidChooseFileToOpen(_ view: KMHomeRightView, _ fileURL: URL)
  18. }
  19. public class KMHomeRightView: BaseXibView {
  20. @IBOutlet var scrollView: NSScrollView!
  21. @IBOutlet var collectionView: NSCollectionView!
  22. var filesHeaderView: KMHomeFilesHeaderView = KMHomeFilesHeaderView()
  23. var quickToolsView: KMHomeQuickToolsView = KMHomeQuickToolsView()
  24. var filesEmptyView: KMHistoryEmptyView = KMHistoryEmptyView()
  25. var groupView: ComponentGroup!
  26. var menuActionIndexPaths: Set<IndexPath> = []
  27. var groupActionView: NSView?
  28. var groupViewPoint: CGPoint = CGPointZero
  29. var refreshItemData: Bool = true
  30. weak open var delegate: KMHomeRightViewDelegate?
  31. //MARK: - func
  32. public override func draw(_ dirtyRect: NSRect) {
  33. super.draw(dirtyRect)
  34. // Drawing code here.
  35. }
  36. public required init?(coder decoder: NSCoder) {
  37. super.init(coder: decoder)
  38. }
  39. override init(frame frameRect: NSRect) {
  40. super.init(frame: frameRect)
  41. }
  42. public override func awakeFromNib() {
  43. super.awakeFromNib()
  44. configUI()
  45. }
  46. public func resetScrollerStyle() {
  47. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
  48. self.scrollView.scrollerStyle = .overlay
  49. }
  50. }
  51. func configUI() {
  52. collectionView.backgroundColors = [NSColor.clear]
  53. collectionView.wantsLayer = true
  54. collectionView.layer?.backgroundColor = NSColor.clear.cgColor
  55. collectionView.delegate = self
  56. collectionView.dataSource = self
  57. collectionView.allowsEmptySelection = true
  58. collectionView.register(KMHistoryFileThumbItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMHistoryFileThumbItem"))
  59. collectionView.register(KMHistoryFileListItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMHistoryFileListItem"))
  60. collectionView.register(KMHomeQuickToolsView.self, forSupplementaryViewOfKind: NSCollectionView.elementKindSectionHeader, withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "kmHomeQuickToolsView"))
  61. collectionView.register(KMHomeFilesHeaderView.self, forSupplementaryViewOfKind: NSCollectionView.elementKindSectionHeader, withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "kmHomeFilesHeaderView"))
  62. collectionView.register(KMHomeFilesEmptyHeaderView.self, forSupplementaryViewOfKind: NSCollectionView.elementKindSectionHeader, withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMHomeFilesEmptyHeaderView"))
  63. collectionView.register(KMHomeFilesEmptyHeaderView.self, forSupplementaryViewOfKind: NSCollectionView.elementKindSectionFooter, withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMHomeFilesEmptyHeaderView"))
  64. }
  65. //刷新所有数据
  66. public func reloadData() {
  67. HistoryFilesManager.manager.refreshHistoryFile()
  68. collectionView.reloadData()
  69. filesHeaderView.updateDeleteButtonState()
  70. collectionViewSelectedChanged()
  71. }
  72. //刷新列表文件UI
  73. public func updateHistoryFileListItemUI() {
  74. if HistoryFilesManager.manager.showMode == .List {
  75. refreshItemData = false
  76. collectionView.reloadItems(at: collectionView.indexPathsForVisibleItems())
  77. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  78. self.refreshItemData = true
  79. }
  80. }
  81. }
  82. //刷新快捷工具列表
  83. public func reloadQuickTools() {
  84. quickToolsView.reloadData()
  85. }
  86. public func updateQuickToolsUI() {
  87. quickToolsView.refreshUI()
  88. }
  89. //窗口大小变化时调用此方法
  90. public func windowFrameUpdated() {
  91. updateHistoryFileListItemUI()
  92. updateQuickToolsUI()
  93. }
  94. //MARK: - Private
  95. private func collectionViewSelectedChanged() {
  96. let indexs = collectionView.selectionIndexPaths
  97. HistoryFilesManager.manager.selectFiles.removeAll()
  98. if indexs.count >= 0 {
  99. for index in indexs {
  100. let url = HistoryFilesManager.manager.files[index.item]
  101. HistoryFilesManager.manager.selectFiles.append(url)
  102. }
  103. }
  104. filesHeaderView.updateDeleteButtonState()
  105. }
  106. //显示右键菜单
  107. func showFileMoreActionMenu(point: CGPoint, _ actionView: NSView? = nil) {
  108. var viewHeight: CGFloat = 8
  109. var menuItemArr: [ComponentMenuitemProperty] = []
  110. var items: [(String, String)] = [("Show in Finder", "ShowInFinderKey"),
  111. ("Remove from Recents", "RemovefromRecentKey"),
  112. (" ", " "),
  113. ("Share...", "ShareKey")]
  114. if collectionView.selectionIndexPaths.count > 1 {
  115. items = [("Show in Finder", "ShowInFinderKey"),
  116. ("Remove from Recents", "RemovefromRecentKey"),
  117. (" ", " "),
  118. ("Share...", "ShareKey")]
  119. }
  120. for (i, value) in items {
  121. if i == " " {
  122. let property: ComponentMenuitemProperty = ComponentMenuitemProperty.divider()
  123. menuItemArr.append(property)
  124. viewHeight += 8
  125. } else {
  126. let properties_Menuitem: ComponentMenuitemProperty = ComponentMenuitemProperty(multipleSelect: false,
  127. itemSelected: false,
  128. isDisabled: false,
  129. keyEquivalent: nil,
  130. text: KMLocalizedString(i),
  131. identifier: value)
  132. if value == "FileInformationKey" {
  133. properties_Menuitem.keyEquivalent = "⌘ D"
  134. } else if value == "PrintKey" {
  135. properties_Menuitem.keyEquivalent = "⌘ P"
  136. }
  137. menuItemArr.append(properties_Menuitem)
  138. viewHeight += 36
  139. }
  140. }
  141. if groupView == nil {
  142. groupView = ComponentGroup.createFromNib(in: ComponentLibrary.shared.componentBundle())
  143. }
  144. groupView.groupDelegate = self
  145. groupView?.frame = CGRectMake(0, 0, 180, viewHeight)
  146. groupView.updateGroupInfo(menuItemArr)
  147. if HistoryFilesManager.manager.showMode == .Thumbnail {
  148. groupView.showWithPoint(CGPoint(x: point.x, y: point.y - viewHeight), relativeTo: actionView)
  149. } else {
  150. groupView.showWithPoint(CGPoint(x: point.x, y: point.y - viewHeight), relativeTo: actionView)
  151. }
  152. menuActionIndexPaths = collectionView.selectionIndexPaths
  153. }
  154. //MARK: -删除文件列表
  155. func historyFileDeleteAction(_ indexPaths: [URL]) -> Void {
  156. self.fileDeleteAction()
  157. }
  158. @objc func emptyViewAddFileClicked(_ sender: NSView) {
  159. let openPanel = NSOpenPanel()
  160. openPanel.allowedFileTypes = ["pdf", "PDF"]
  161. openPanel.allowsMultipleSelection = false
  162. openPanel.beginSheetModal(for: self.window!) { [weak self] result in
  163. if result == NSApplication.ModalResponse.OK {
  164. if let url = openPanel.url {
  165. guard let weakSelf = self else { return }
  166. weakSelf.delegate?.homeRightViewDidChooseFileToOpen?(weakSelf, url)
  167. }
  168. }
  169. }
  170. }
  171. func fileDeleteAction() {
  172. if HistoryFilesManager.manager.selectFiles.count > 0 {
  173. if UserDefaults.standard.object(forKey: "HomeFilesDeleteConfirmKey") != nil {
  174. var selects: [URL] = []
  175. if HistoryFilesManager.manager.selectFiles.count > 0 {
  176. for selecturl in HistoryFilesManager.manager.selectFiles {
  177. selects.append(selecturl)
  178. }
  179. }
  180. HistoryFilesManager.manager.historyFileDeleteAction(selects)
  181. self.reloadData()
  182. return
  183. }
  184. let alert = NSAlert()
  185. alert.alertStyle = .informational
  186. alert.informativeText = KMLocalizedString("Remove Selected Files from your Recent Files?")
  187. alert.messageText = KMLocalizedString("The file will disappear from the recent list.")
  188. alert.addButton(withTitle: KMLocalizedString("Delete"))
  189. alert.addButton(withTitle: KMLocalizedString("Cancel"))
  190. alert.showsSuppressionButton = true
  191. let response = alert.runModal()
  192. if response.rawValue == 1000 {
  193. var selects: [URL] = []
  194. for selecturl in HistoryFilesManager.manager.selectFiles {
  195. selects.append(selecturl)
  196. }
  197. HistoryFilesManager.manager.historyFileDeleteAction(selects)
  198. self.reloadData()
  199. if alert.suppressionButton?.state == .on {
  200. UserDefaults.standard.set("YES", forKey: "HomeFilesDeleteConfirmKey")
  201. UserDefaults.standard.synchronize()
  202. }
  203. }
  204. } else {
  205. //删除所有文件
  206. let alert = NSAlert()
  207. alert.alertStyle = .informational
  208. alert.informativeText = KMLocalizedString("Remove Files from your Recent Files?")
  209. alert.messageText = KMLocalizedString("The file will disappear from the recent list.")
  210. alert.addButton(withTitle: KMLocalizedString("Delete"))
  211. alert.addButton(withTitle: KMLocalizedString("Cancel"))
  212. let response = alert.runModal()
  213. if response.rawValue == 1000 {
  214. var selects: [URL] = []
  215. for selecturl in HistoryFilesManager.manager.files {
  216. selects.append(selecturl)
  217. }
  218. HistoryFilesManager.manager.historyFileDeleteAction(selects)
  219. self.reloadData()
  220. }
  221. }
  222. }
  223. //MARK: - MouseEvent
  224. public override func rightMouseDown(with event: NSEvent) {
  225. super.rightMouseDown(with: event)
  226. var point = convert(event.locationInWindow, from: nil)
  227. if HistoryFilesManager.manager.showMode == .List {
  228. point.x += 10
  229. }
  230. let collectionPoint = convert(point, to: collectionView)
  231. if let indexPath = collectionView.indexPathForItem(at: collectionPoint) {
  232. if collectionView.selectionIndexPaths.contains(indexPath) {
  233. } else {
  234. collectionView.deselectAll(nil)
  235. collectionView.selectItems(at: [indexPath], scrollPosition: .nearestHorizontalEdge)
  236. }
  237. groupActionView = collectionView.item(at: indexPath)?.view
  238. groupViewPoint = point
  239. showFileMoreActionMenu(point: event.locationInWindow)
  240. }
  241. collectionViewSelectedChanged()
  242. }
  243. }
  244. //MARK: - NSCollectionViewDelegate, NSCollectionViewDataSource
  245. extension KMHomeRightView: NSCollectionViewDelegate, NSCollectionViewDataSource, NSCollectionViewDelegateFlowLayout {
  246. public func numberOfSections(in collectionView: NSCollectionView) -> Int {
  247. return 2
  248. }
  249. public func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
  250. if section == 0 {
  251. return 0
  252. }
  253. return HistoryFilesManager.manager.files.count
  254. }
  255. public func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
  256. if indexPath.item >= HistoryFilesManager.manager.files.count {
  257. return NSCollectionViewItem()
  258. }
  259. if HistoryFilesManager.manager.showMode == .Thumbnail {
  260. let item: KMHistoryFileThumbItem = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMHistoryFileThumbItem"), for: indexPath) as! KMHistoryFileThumbItem
  261. item.fileURL = HistoryFilesManager.manager.files[indexPath.item]
  262. item.reloadData()
  263. item.delegate = self
  264. return item
  265. } else if HistoryFilesManager.manager.showMode == .List {
  266. let item: KMHistoryFileListItem = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMHistoryFileListItem"), for: indexPath) as! KMHistoryFileListItem
  267. item.fileURL = HistoryFilesManager.manager.files[indexPath.item]
  268. item.reloadData()
  269. item.delegate = self
  270. return item
  271. }
  272. return NSCollectionViewItem()
  273. }
  274. public func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
  275. if HistoryFilesManager.manager.showMode == .Thumbnail {
  276. return CGSize(width: 172, height: 248)
  277. } else if HistoryFilesManager.manager.showMode == .List {
  278. print(collectionView.frame.size.width, self.frame.size.width)
  279. return CGSize(width: collectionView.frame.size.width-80, height: 80)
  280. }
  281. return CGSize(width: 0.01, height: 0.01)
  282. }
  283. public func collectionView(_ collectionView: NSCollectionView, viewForSupplementaryElementOfKind kind: NSCollectionView.SupplementaryElementKind, at indexPath: IndexPath) -> NSView {
  284. if kind == NSCollectionView.elementKindSectionHeader {
  285. if indexPath.section == 0 {
  286. //quick tools
  287. quickToolsView = collectionView.makeSupplementaryView(ofKind: kind, withIdentifier: NSUserInterfaceItemIdentifier("kmHomeQuickToolsView"), for: indexPath) as! KMHomeQuickToolsView
  288. quickToolsView.delegate = self
  289. quickToolsView.reloadData()
  290. return quickToolsView
  291. } else if indexPath.section == 1 {
  292. //Recently
  293. filesHeaderView = collectionView.makeSupplementaryView(ofKind: kind, withIdentifier: NSUserInterfaceItemIdentifier("kmHomeFilesHeaderView"), for: indexPath) as! KMHomeFilesHeaderView
  294. filesHeaderView.delegate = self
  295. return filesHeaderView
  296. }
  297. } else if kind == NSCollectionView.elementKindSectionFooter {
  298. let view = collectionView.makeSupplementaryView(ofKind: kind, withIdentifier: NSUserInterfaceItemIdentifier("KMHomeFilesEmptyHeaderView"), for: indexPath) as! KMHomeFilesEmptyHeaderView
  299. if self.filesEmptyView.superview != nil {
  300. self.filesEmptyView.removeFromSuperview()
  301. }
  302. if indexPath.section == 1 &&
  303. HistoryFilesManager.manager.files.count == 0 {
  304. filesEmptyView.frame = CGRectMake((CGRectGetWidth(collectionView.frame)-520)/2, (344-184)/2, 520, 184)
  305. filesEmptyView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  306. filesEmptyView.emptyView.setTarget(self, action: #selector(emptyViewAddFileClicked(_:)))
  307. view.addSubview(filesEmptyView)
  308. }
  309. return view
  310. }
  311. return NSView()
  312. }
  313. public func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  314. return 8
  315. }
  316. public func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  317. return 0.01
  318. }
  319. public func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> NSSize {
  320. if section == 0 {
  321. if KMNHomeQuickToolManager.defaultManager.collapseTools {
  322. if KMNHomeQuickToolManager.defaultManager.quickToolsItemMutableArray.count <= 4 {
  323. return NSSize(width: collectionView.frame.size.width, height: 172+32+2-60-14) //折叠
  324. }
  325. return NSSize(width: collectionView.frame.size.width, height: 172+32+2) //折叠
  326. } else {
  327. if KMNHomeQuickToolManager.defaultManager.quickToolsItemMutableArray.count <= 4 {
  328. return NSSize(width: collectionView.frame.size.width, height: 228+32-88-14)
  329. }
  330. return NSSize(width: collectionView.frame.size.width, height: 228+32)
  331. }
  332. } else if section == 1 {
  333. return NSSize(width: collectionView.frame.size.width, height: 28)
  334. }
  335. return NSSize(width: 0, height: 0.01)
  336. }
  337. public func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, referenceSizeForFooterInSection section: Int) -> NSSize {
  338. if section == 0 {
  339. return NSSize(width: 0, height: 40-16)
  340. } else if section == 1 {
  341. if HistoryFilesManager.manager.files.count == 0 {
  342. return NSSize(width: collectionView.frame.size.width, height: 344)
  343. }
  344. }
  345. return NSSize(width: 0, height: 0.01)
  346. }
  347. public func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, insetForSectionAt section: Int) -> NSEdgeInsets {
  348. return NSEdgeInsetsMake(12, 40, 0, 40)
  349. }
  350. public func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
  351. self.collectionViewSelectedChanged()
  352. }
  353. public func collectionView(_ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set<IndexPath>) {
  354. self.collectionViewSelectedChanged()
  355. }
  356. }
  357. //MARK: - KMHomeFilesHeaderViewDelegate
  358. extension KMHomeRightView: KMHomeFilesHeaderViewDelegate {
  359. public func homeFilesShowModeDidUpdate(_ view: KMHomeFilesHeaderView) {
  360. self.reloadData()
  361. }
  362. public func homeFilesHeaderViewDeleteButtonClicked(_ view: KMHomeFilesHeaderView) {
  363. self.fileDeleteAction()
  364. }
  365. }
  366. //MARK: - KMHomeQuickToolsViewDelegate
  367. extension KMHomeRightView: KMHomeQuickToolsViewDelegate {
  368. public func homeQuickToolsViewDidCollapseStateChanged(_ view: KMHomeQuickToolsView) {
  369. DispatchQueue.main.async {
  370. self.reloadData()
  371. }
  372. }
  373. public func homeQuickToolsViewDidManageTools(_ view: KMHomeQuickToolsView) {
  374. DispatchQueue.main.async {
  375. self.delegate?.homeRightViewDidManageQuickTools?(self)
  376. }
  377. }
  378. public func homeQuickToolsViewDidItemClicked(_ view: KMHomeQuickToolsView, _ toolType: HomeQuickToolType) {
  379. DispatchQueue.main.async {
  380. self.delegate?.homeRightViewDidQuickToolsItemClicked?(self, toolType)
  381. }
  382. }
  383. }
  384. //MARK: - ComponentGroupDelegate
  385. extension KMHomeRightView: ComponentGroupDelegate {
  386. public func componentGroupDidSelect(group: ComponentGroup?, menuItemProperty: ComponentMenuitemProperty?) {
  387. var selects: [URL] = []
  388. let indexs = self.menuActionIndexPaths
  389. if indexs.count >= 0 {
  390. for index in indexs {
  391. let url = HistoryFilesManager.manager.files[index.item]
  392. selects.append(url)
  393. }
  394. }
  395. if menuItemProperty?.identifier == "ShowInFinderKey" {
  396. NSWorkspace.shared.activateFileViewerSelecting(selects)
  397. } else if menuItemProperty?.identifier == "FileInformationKey" {
  398. } else if menuItemProperty?.identifier == "RemovefromRecentKey" {
  399. self.historyFileDeleteAction(selects)
  400. } else if menuItemProperty?.identifier == "ShareKey" {
  401. let picker = NSSharingServicePicker.init(items: selects)
  402. if let actionView = self.groupActionView {
  403. picker.show(relativeTo: actionView.bounds, of: actionView, preferredEdge: NSRectEdge.minY)
  404. } else {
  405. picker.show(relativeTo: NSRect(x: self.groupViewPoint.x, y: self.groupViewPoint.y, width: 0, height: 0), of: self.collectionView, preferredEdge: NSRectEdge.minY)
  406. }
  407. } else if menuItemProperty?.identifier == "PrintKey" {
  408. }
  409. }
  410. }
  411. //MARK: - KMHistoryFileListItemDelegate
  412. extension KMHomeRightView: KMHistoryFileListItemDelegate {
  413. public func historyFileListItemDidClickedMore(_ view: KMHistoryFileListItem) {
  414. if let indexPath = collectionView.indexPath(for: view) {
  415. if collectionView.selectionIndexPaths.contains(indexPath) {
  416. } else {
  417. collectionView.deselectAll(nil)
  418. collectionView.selectItems(at: [indexPath], scrollPosition: .nearestHorizontalEdge)
  419. }
  420. }
  421. groupActionView = view.moreButton
  422. let point = view.moreButton.superview?.convert(view.moreButton.frame.origin, to: self) ?? CGPointZero
  423. showFileMoreActionMenu(point: point, groupActionView)
  424. }
  425. public func historyFileListItemDidDoubleClicked(_ view: KMHistoryFileListItem) {
  426. if let url = view.fileURL {
  427. delegate?.homeRightViewDidChooseFileToOpen?(self, url)
  428. }
  429. }
  430. }
  431. //MARK: - KMHistoryFileThumbItemDelegate
  432. extension KMHomeRightView: KMHistoryFileThumbItemDelegate {
  433. func historyFileThumbItemDidDoubleClicked(_ view: KMHistoryFileThumbItem) {
  434. if let url = view.fileURL {
  435. delegate?.homeRightViewDidChooseFileToOpen?(self, url)
  436. }
  437. }
  438. }