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