Files
Explorer-Workbench/src/Explorer.Application/FolderStatusText.cs

74 lines
2.1 KiB
C#

using Explorer.Domain;
namespace Explorer.Application;
public static class FolderStatusText
{
public static string Format(IEnumerable<FileSystemItem> folderItems, IEnumerable<FileSystemItem> selectedItems)
{
var selected = selectedItems as IReadOnlyCollection<FileSystemItem> ?? selectedItems.ToList();
var isSelection = selected.Count > 0;
var totals = Measure(isSelection ? selected : folderItems);
var noun = totals.Count == 1 ? "item" : "items";
var prefix = isSelection
? $"{totals.Count:N0} {noun} selected"
: $"{totals.Count:N0} {noun}";
if (!ShouldShowSize(totals))
{
return prefix;
}
return $"{prefix} · {FormatSize(totals.KnownBytes)}";
}
public static FolderStatusTotals Measure(IEnumerable<FileSystemItem> items)
{
var count = 0;
var files = 0;
var knownBytes = 0L;
var hasKnownSize = false;
foreach (var item in items)
{
count++;
if (!item.IsDirectory)
{
files++;
}
if (item.SizeKnowledge == SizeKnowledge.Unknown)
{
continue;
}
knownBytes += Math.Max(0, item.SizeBytes);
hasKnownSize = true;
}
return new FolderStatusTotals(count, files, knownBytes, hasKnownSize);
}
private static bool ShouldShowSize(FolderStatusTotals totals)
=> totals.HasKnownSize && (totals.KnownBytes > 0 || totals.Files > 0);
private static string FormatSize(long bytes)
{
if (bytes < 0)
{
return string.Empty;
}
string[] units = ["B", "KB", "MB", "GB", "TB", "PB"];
double value = bytes;
var unit = 0;
while (value >= 1024 && unit < units.Length - 1)
{
value /= 1024;
unit++;
}
return unit == 0 ? $"{bytes} B" : $"{value:0.##} {units[unit]}";
}
}
public readonly record struct FolderStatusTotals(int Count, int Files, long KnownBytes, bool HasKnownSize);