Files
Terminal.Gui/Terminal.Gui/FileServices/FileSystemTreeBuilder.cs
Thomas Nind a8d1a79615 Fixes #2726 - Refactor filedialog classes to be more easily reused (#2727)
* Refactor FileDialogTreeBuilder to be more generally useful outside of dialog context

* Fix comparer

* Change TreeViewFileSystem scenario to use the core builder

* Refactor icon provision for reusability

* Add IsOpenGetter implementations

* Xmldoc and tests

* xmldoc and trim icon when blank (files and no nerd)

* unit test fixes

* FixFix unit tests when running on linux

* Add option to pick which icon set to use for TreeViewFileSystem

* Add spaces when using nerd to avoid icon overaps

* Refactor the addition of space for nerd icons to reduce code duplication
2023-07-05 16:51:18 -06:00

80 lines
1.9 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
namespace Terminal.Gui {
/// <summary>
/// TreeView builder for creating file system based trees.
/// </summary>
public class FileSystemTreeBuilder : ITreeBuilder<IFileSystemInfo>, IComparer<IFileSystemInfo> {
/// <summary>
/// Creates a new instance of the <see cref="FileSystemTreeBuilder"/> class.
/// </summary>
public FileSystemTreeBuilder ()
{
Sorter = this;
}
/// <inheritdoc/>
public bool SupportsCanExpand => true;
/// <summary>
/// Gets or sets a flag indicating whether to show files as leaf elements
/// in the tree. Defaults to true.
/// </summary>
public bool IncludeFiles { get; } = true;
/// <summary>
/// Gets or sets the order of directory children. Defaults to <see langword="this"/>.
/// </summary>
public IComparer<IFileSystemInfo> Sorter { get; set; }
/// <inheritdoc/>
public bool CanExpand (IFileSystemInfo toExpand)
{
return this.TryGetChildren (toExpand).Any ();
}
/// <inheritdoc/>
public IEnumerable<IFileSystemInfo> GetChildren (IFileSystemInfo forObject)
{
return this.TryGetChildren (forObject).OrderBy(k=>k,Sorter);
}
private IEnumerable<IFileSystemInfo> TryGetChildren (IFileSystemInfo entry)
{
if (entry is IFileInfo) {
return Enumerable.Empty<IFileSystemInfo> ();
}
var dir = (IDirectoryInfo)entry;
try {
return dir.GetFileSystemInfos ().Where (e => IncludeFiles || e is IDirectoryInfo);
} catch (Exception) {
return Enumerable.Empty<IFileSystemInfo> ();
}
}
/// <inheritdoc/>
public int Compare (IFileSystemInfo x, IFileSystemInfo y)
{
if (x is IDirectoryInfo && y is not IDirectoryInfo) {
return -1;
}
if (x is not IDirectoryInfo && y is IDirectoryInfo) {
return 1;
}
return x.Name.CompareTo (y.Name);
}
}
}