1
1
mirror of https://github.com/qvacua/vimr.git synced 2024-12-01 10:02:36 +03:00
vimr/VimR/FileOutlineView.swift

517 lines
15 KiB
Swift
Raw Normal View History

2016-10-03 16:03:18 +03:00
/**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Cocoa
2016-11-25 17:25:55 +03:00
import PureLayout
2016-10-03 16:03:18 +03:00
import RxSwift
class FileOutlineView: NSOutlineView,
UiComponent,
NSOutlineViewDataSource,
NSOutlineViewDelegate {
typealias StateType = MainWindow.State
required init(source: Observable<StateType>, emitter: ActionEmitter, state: StateType) {
2017-04-22 16:56:13 +03:00
self.emit = emitter.typedEmitFunction()
self.uuid = state.uuid
2017-04-22 16:56:13 +03:00
self.root = FileBrowserItem(fileItem: state.root)
self.fileSystemRoot = state.root
self.isShowHidden = state.fileBrowserShowHidden
super.init(frame: .zero)
NSOutlineView.configure(toStandard: self)
self.dataSource = self
self.delegate = self
2016-11-12 18:42:10 +03:00
guard Bundle.main.loadNibNamed("FileBrowserMenu", owner: self, topLevelObjects: nil) else {
NSLog("WARN: FileBrowserMenu.xib could not be loaded")
return
}
2017-02-26 12:12:41 +03:00
// If the target of the menu items is set to the first responder, the actions are not invoked at all when the file
// monitor fires in the background... Dunno why it worked before the redesign... -_-
self.menu?.items.forEach { $0.target = self }
2016-11-12 18:42:10 +03:00
self.doubleAction = #selector(FileOutlineView.doubleClickAction)
source
.observeOn(MainScheduler.instance)
2017-02-24 01:58:53 +03:00
.subscribe(onNext: { [unowned self] state in
2017-03-31 20:32:01 +03:00
if state.viewToBeFocused != nil, case .fileBrowser = state.viewToBeFocused! {
2017-02-25 00:47:32 +03:00
self.beFirstResponder()
}
var reloadData = false
if self.isShowHidden != state.fileBrowserShowHidden {
self.isShowHidden = state.fileBrowserShowHidden
reloadData = true
}
2017-02-24 01:58:53 +03:00
if state.cwd != self.cwd {
self.lastFileSystemUpdateMark = state.lastFileSystemUpdate.mark
self.cwd = state.cwd
reloadData = true
}
2017-02-24 01:58:53 +03:00
if reloadData {
self.lastFileSystemUpdateMark = state.lastFileSystemUpdate.mark
self.reloadData()
2017-02-24 01:58:53 +03:00
return
}
if state.lastFileSystemUpdate.mark == self.lastFileSystemUpdateMark {
return
}
2017-02-24 01:58:53 +03:00
self.lastFileSystemUpdateMark = state.lastFileSystemUpdate.mark
self.update(state.lastFileSystemUpdate.payload)
})
.disposed(by: self.disposeBag)
}
2016-11-25 17:25:55 +03:00
func select(_ url: URL) {
2016-12-11 21:47:17 +03:00
var itemsToExpand: [FileBrowserItem] = []
var stack = [self.root]
2016-12-11 21:47:17 +03:00
while let item = stack.popLast() {
if item.isChildrenScanned == false {
item.children = FileItemUtils.sortedChildren(for: item.fileItem.url, root: self.fileSystemRoot)
.map(FileBrowserItem.init)
2016-12-11 21:47:17 +03:00
item.isChildrenScanned = true
}
itemsToExpand.append(item)
if item.fileItem.url.isDirectParent(of: url) {
if let targetItem = item.children.first(where: { $0.fileItem.url == url }) {
itemsToExpand.append(targetItem)
}
break
}
stack.append(contentsOf: item.children.filter { $0.fileItem.url.isParent(of: url) })
}
itemsToExpand.forEach { self.expandItem($0) }
let targetRow = self.row(forItem: itemsToExpand.last)
self.selectRowIndexes(IndexSet(integer: targetRow), byExtendingSelection: false)
self.scrollRowToVisible(targetRow)
}
2017-04-22 16:56:13 +03:00
fileprivate let emit: (UuidAction<FileBrowser.Action>) -> Void
fileprivate let disposeBag = DisposeBag()
fileprivate let uuid: String
fileprivate var lastFileSystemUpdateMark = Token()
2017-02-26 13:00:52 +03:00
fileprivate var cwd: URL = FileUtils.userHomeUrl
fileprivate var isShowHidden: Bool
fileprivate var root: FileBrowserItem
fileprivate let fileSystemRoot: FileItem
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func update(_ fileItem: FileItem) {
let url = fileItem.url
guard let fileBrowserItem = self.fileBrowserItem(with: url) else {
return
}
self.beginUpdates()
self.update(fileBrowserItem)
self.endUpdates()
}
2016-11-26 19:59:55 +03:00
fileprivate func handleRemovals(for fileBrowserItem: FileBrowserItem, new newChildren: [FileBrowserItem]) {
let curChildren = fileBrowserItem.children
2016-11-26 17:13:21 +03:00
let curPreparedChildren = self.prepare(curChildren)
let newPreparedChildren = self.prepare(newChildren)
let childrenToRemoveIndices = curPreparedChildren
.enumerated()
.filter { newPreparedChildren.contains($0.1) == false }
.map { $0.0 }
2016-11-26 19:59:55 +03:00
2016-11-26 17:13:21 +03:00
fileBrowserItem.children = curChildren.filter { newChildren.contains($0) }
2016-11-26 19:59:55 +03:00
let parent = fileBrowserItem == self.root ? nil : fileBrowserItem
self.removeItems(at: IndexSet(childrenToRemoveIndices), inParent: parent)
}
fileprivate func handleAdditions(for fileBrowserItem: FileBrowserItem, new newChildren: [FileBrowserItem]) {
let curChildren = fileBrowserItem.children
2016-11-26 19:59:55 +03:00
2016-11-26 20:05:35 +03:00
// We don't just take newChildren because NSOutlineView look at the pointer equality for preserving the expanded
// states...
fileBrowserItem.children = newChildren.substituting(elements: curChildren)
2016-11-26 19:59:55 +03:00
let curPreparedChildren = self.prepare(curChildren)
let newPreparedChildren = self.prepare(newChildren)
2016-11-26 20:05:35 +03:00
let indicesToInsert = newPreparedChildren
.enumerated()
.filter { curPreparedChildren.contains($0.1) == false }
.map { $0.0 }
2016-11-26 19:59:55 +03:00
2016-11-26 20:05:35 +03:00
let parent = fileBrowserItem == self.root ? nil : fileBrowserItem
self.insertItems(at: IndexSet(indicesToInsert), inParent: parent)
2016-11-26 19:59:55 +03:00
}
fileprivate func handleChildren(for fileBrowserItem: FileBrowserItem, new newChildren: [FileBrowserItem]) {
let curChildren = fileBrowserItem.children
2016-11-26 19:59:55 +03:00
let curPreparedChildren = self.prepare(curChildren)
let newPreparedChildren = self.prepare(newChildren)
let keptChildren = curPreparedChildren.filter { newPreparedChildren.contains($0) }
2016-11-26 20:05:35 +03:00
let childrenToRecurse = keptChildren.filter { self.isItemExpanded($0) }
2016-11-26 17:13:21 +03:00
2016-11-26 20:05:35 +03:00
childrenToRecurse.forEach(self.update)
2016-11-26 19:59:55 +03:00
}
fileprivate func update(_ fileBrowserItem: FileBrowserItem) {
let url = fileBrowserItem.fileItem.url
// Sort the array to keep the order.
let newChildren = FileItemUtils.sortedChildren(for: url, root: self.fileSystemRoot).map(FileBrowserItem.init)
2016-11-26 19:59:55 +03:00
self.handleRemovals(for: fileBrowserItem, new: newChildren)
self.handleAdditions(for: fileBrowserItem, new: newChildren)
self.handleChildren(for: fileBrowserItem, new: newChildren)
}
2016-11-25 17:25:55 +03:00
fileprivate func fileBrowserItem(with url: URL) -> FileBrowserItem? {
2016-11-26 12:34:52 +03:00
if self.cwd == url {
return self.root
}
guard self.cwd.isParent(of: url) else {
return nil
}
let rootPathComps = self.cwd.pathComponents
let pathComps = url.pathComponents
let childPart = pathComps[rootPathComps.count..<pathComps.count]
return childPart.reduce(self.root) { (resultItem, childName) -> FileBrowserItem? in
guard let parent = resultItem else {
return nil
}
return parent.child(with: parent.fileItem.url.appendingPathComponent(childName))
}
}
}
// MARK: - NSOutlineViewDataSource
extension FileOutlineView {
2016-11-26 12:34:52 +03:00
fileprivate func prepare(_ children: [FileBrowserItem]) -> [FileBrowserItem] {
2016-12-05 20:19:46 +03:00
return self.isShowHidden ? children : children.filter { !$0.fileItem.isHidden }
2016-11-26 12:34:52 +03:00
}
func outlineView(_: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
if item == nil {
let rootFileItem = FileItemUtils.item(for: self.cwd, root: self.fileSystemRoot)
?? FileItemUtils.item(for: FileUtils.userHomeUrl, root: self.fileSystemRoot)!
self.root = FileBrowserItem(fileItem: rootFileItem)
2016-12-11 21:47:17 +03:00
if self.root.isChildrenScanned == false {
self.root.children = FileItemUtils.sortedChildren(for: self.cwd, root: self.fileSystemRoot)
.map(FileBrowserItem.init)
2016-12-11 21:47:17 +03:00
self.root.isChildrenScanned = true
}
2016-11-26 12:34:52 +03:00
return self.prepare(self.root.children).count
}
guard let fileBrowserItem = item as? FileBrowserItem else {
return 0
}
let fileItem = fileBrowserItem.fileItem
2016-11-12 18:42:10 +03:00
if fileItem.isDir {
2016-12-11 21:47:17 +03:00
if fileBrowserItem.isChildrenScanned == false {
let fileItemChildren = FileItemUtils.sortedChildren(for: fileItem.url, root: self.fileSystemRoot)
2016-12-11 21:47:17 +03:00
fileBrowserItem.fileItem.children = fileItemChildren
fileBrowserItem.children = fileItemChildren.map(FileBrowserItem.init)
fileBrowserItem.isChildrenScanned = true
}
2016-11-26 12:34:52 +03:00
return self.prepare(fileBrowserItem.children).count
}
return 0
}
func outlineView(_: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
let level = self.level(forItem: item)
if item == nil {
self.adjustColumnWidth(for: self.root.children, outlineViewLevel: level)
2016-11-26 12:34:52 +03:00
return self.prepare(self.root.children)[index]
}
guard let fileBrowserItem = item as? FileBrowserItem else {
preconditionFailure("Should not happen")
}
self.adjustColumnWidth(for: fileBrowserItem.children, outlineViewLevel: level)
2016-11-26 12:34:52 +03:00
return self.prepare(fileBrowserItem.children)[index]
}
2016-11-26 12:34:52 +03:00
func outlineView(_: NSOutlineView, isItemExpandable item: Any) -> Bool {
guard let fileBrowserItem = item as? FileBrowserItem else {
return false
}
return fileBrowserItem.fileItem.isDir
}
2016-11-26 12:34:52 +03:00
@objc(outlineView: objectValueForTableColumn:byItem:)
func outlineView(_: NSOutlineView, objectValueFor: NSTableColumn?, byItem item: Any?) -> Any? {
guard let fileBrowserItem = item as? FileBrowserItem else {
return nil
}
return fileBrowserItem
2016-10-03 16:03:18 +03:00
}
fileprivate func adjustColumnWidth() {
let column = self.outlineTableColumn!
let rows = (0..<self.numberOfRows).map {
(item: self.item(atRow: $0) as! FileBrowserItem?, level: self.level(forRow: $0))
}
let cellWidth = rows.concurrentChunkMap(20) {
guard let fileBrowserItem = $0.item else {
return 0
}
return ImageAndTextTableCell.width(with: fileBrowserItem.fileItem.url.lastPathComponent)
+ (CGFloat($0.level + 2) * (self.indentationPerLevel + 2)) // + 2 just to have a buffer... -_-
}
.max() ?? column.width
guard column.minWidth != cellWidth else {
return
}
column.minWidth = cellWidth
column.maxWidth = cellWidth
}
fileprivate func adjustColumnWidth(for items: [FileBrowserItem], outlineViewLevel level: Int) {
let column = self.outlineTableColumn!
// It seems like that caching the widths is slower due to thread-safeness of NSCache...
let cellWidth = items.concurrentChunkMap(20) {
let result = ImageAndTextTableCell.width(with: $0.fileItem.url.lastPathComponent)
return result
}
.max() ?? column.width
2016-11-25 17:25:55 +03:00
let width = cellWidth + (CGFloat(level + 2) * (self.indentationPerLevel + 2)) // + 2 just to have a buffer... -_-
guard column.minWidth < width else {
2016-11-25 17:25:55 +03:00
return
}
column.minWidth = width
column.maxWidth = width
2016-11-25 17:25:55 +03:00
}
}
2016-11-25 17:25:55 +03:00
// MARK: - NSOutlineViewDelegate
extension FileOutlineView {
2016-11-25 17:25:55 +03:00
2016-11-26 12:34:52 +03:00
@objc(outlineView: viewForTableColumn:item:)
func outlineView(_: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
guard let fileBrowserItem = item as? FileBrowserItem else {
return nil
}
let cachedCell = (self.make(withIdentifier: "file-view-row", owner: self) as? ImageAndTextTableCell)?.reset()
let cell = cachedCell ?? ImageAndTextTableCell(withIdentifier: "file-view-row")
cell.text = fileBrowserItem.fileItem.url.lastPathComponent
let icon = FileUtils.icon(forUrl: fileBrowserItem.fileItem.url)
2016-12-04 23:33:45 +03:00
cell.image = fileBrowserItem.fileItem.isHidden ? icon?.tinting(with: NSColor.white.withAlphaComponent(0.4)) : icon
return cell
}
func outlineView(_: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
return 20
}
2016-11-25 15:19:41 +03:00
func outlineViewItemDidCollapse(_ notification: Notification) {
self.adjustColumnWidth()
}
}
2016-11-12 18:42:10 +03:00
// MARK: - Actions
extension FileOutlineView {
@IBAction func doubleClickAction(_: Any?) {
guard let item = self.clickedItem as? FileBrowserItem else {
2016-11-12 18:42:10 +03:00
return
}
if item.fileItem.isDir {
2016-11-12 18:42:10 +03:00
self.toggle(item: item)
} else {
2017-04-22 16:56:13 +03:00
self.emit(
UuidAction(uuid: self.uuid, action: .open(url: item.fileItem.url, mode: .default))
2017-02-24 12:51:24 +03:00
)
2016-11-12 18:42:10 +03:00
}
}
@IBAction func openInNewTab(_: Any?) {
guard let item = self.clickedItem as? FileBrowserItem else {
2016-11-12 18:42:10 +03:00
return
}
2017-04-22 16:56:13 +03:00
self.emit(
UuidAction(uuid: self.uuid, action: .open(url: item.fileItem.url, mode: .newTab))
2017-02-24 12:51:24 +03:00
)
2016-11-12 18:42:10 +03:00
}
@IBAction func openInCurrentTab(_: Any?) {
guard let item = self.clickedItem as? FileBrowserItem else {
2016-11-12 18:42:10 +03:00
return
}
2017-04-22 16:56:13 +03:00
self.emit(
UuidAction(uuid: self.uuid, action: .open(url: item.fileItem.url, mode: .currentTab))
2017-02-24 12:51:24 +03:00
)
2016-11-12 18:42:10 +03:00
}
@IBAction func openInHorizontalSplit(_: Any?) {
guard let item = self.clickedItem as? FileBrowserItem else {
2016-11-12 18:42:10 +03:00
return
}
2017-04-22 16:56:13 +03:00
self.emit(
UuidAction(uuid: self.uuid, action: .open(url: item.fileItem.url, mode: .horizontalSplit))
2017-02-24 12:51:24 +03:00
)
2016-11-12 18:42:10 +03:00
}
@IBAction func openInVerticalSplit(_: Any?) {
guard let item = self.clickedItem as? FileBrowserItem else {
2016-11-12 18:42:10 +03:00
return
}
2017-04-22 16:56:13 +03:00
self.emit(
UuidAction(uuid: self.uuid, action: .open(url: item.fileItem.url, mode: .verticalSplit))
2017-02-24 12:51:24 +03:00
)
2016-11-12 18:42:10 +03:00
}
@IBAction func setAsWorkingDirectory(_: Any?) {
guard let item = self.clickedItem as? FileBrowserItem else {
2016-11-12 18:42:10 +03:00
return
}
guard item.fileItem.isDir else {
2016-11-12 18:42:10 +03:00
return
}
2017-04-22 16:56:13 +03:00
self.emit(
UuidAction(uuid: self.uuid, action: .setAsWorkingDirectory(item.fileItem.url))
2017-02-24 12:51:24 +03:00
)
2016-11-12 18:42:10 +03:00
}
}
// MARK: - NSUserInterfaceValidations
extension FileOutlineView {
override func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
guard let clickedItem = self.clickedItem as? FileBrowserItem else {
2016-11-12 18:42:10 +03:00
return true
}
if item.action == #selector(setAsWorkingDirectory(_:)) {
return clickedItem.fileItem.isDir
2016-11-12 18:42:10 +03:00
}
return true
}
}
// MARK: - NSView
extension FileOutlineView {
2016-10-03 16:03:18 +03:00
override func keyDown(with event: NSEvent) {
guard let char = event.charactersIgnoringModifiers?.characters.first else {
super.keyDown(with: event)
return
}
guard let item = self.selectedItem as? FileBrowserItem else {
2016-10-03 16:03:18 +03:00
super.keyDown(with: event)
return
}
switch char {
case " ", "\r": // Why "\r" and not "\n"?
if item.fileItem.isDir || item.fileItem.isPackage {
2016-10-03 16:03:18 +03:00
self.toggle(item: item)
} else {
2017-04-22 16:56:13 +03:00
self.emit(
UuidAction(uuid: self.uuid, action: .open(url: item.fileItem.url, mode: .newTab))
2017-02-24 12:51:24 +03:00
)
2016-10-03 16:03:18 +03:00
}
default:
super.keyDown(with: event)
}
}
}
fileprivate class FileBrowserItem: Hashable, Comparable, CustomStringConvertible {
static func ==(left: FileBrowserItem, right: FileBrowserItem) -> Bool {
return left.fileItem == right.fileItem
}
static func <(left: FileBrowserItem, right: FileBrowserItem) -> Bool {
return left.fileItem.url.lastPathComponent < right.fileItem.url.lastPathComponent
}
var hashValue: Int {
return self.fileItem.hashValue
}
var description: String {
return self.fileItem.url.path
}
let fileItem: FileItem
var children: [FileBrowserItem] = []
var isChildrenScanned = false
/**
`fileItem` is copied. Children are _not_ populated.
*/
init(fileItem: FileItem) {
self.fileItem = fileItem.copy()
}
func child(with url: URL) -> FileBrowserItem? {
return self.children.first { $0.fileItem.url == url }
}
}