Use file scoped namespace declarations

This commit is contained in:
Patrik Svensson
2021-12-21 11:06:46 +01:00
committed by Phil Scott
parent 1dbaf50935
commit ec1188b837
607 changed files with 28739 additions and 29245 deletions

View File

@@ -2,40 +2,39 @@ using System;
using System.Globalization;
using Spectre.Console.Rendering;
namespace Spectre.Console
namespace Spectre.Console;
/// <summary>
/// A column showing download progress.
/// </summary>
public sealed class DownloadedColumn : ProgressColumn
{
/// <summary>
/// A column showing download progress.
/// Gets or sets the <see cref="CultureInfo"/> to use.
/// </summary>
public sealed class DownloadedColumn : ProgressColumn
public CultureInfo? Culture { get; set; }
/// <inheritdoc/>
public override IRenderable Render(RenderContext context, ProgressTask task, TimeSpan deltaTime)
{
/// <summary>
/// Gets or sets the <see cref="CultureInfo"/> to use.
/// </summary>
public CultureInfo? Culture { get; set; }
var total = new FileSize(task.MaxValue);
/// <inheritdoc/>
public override IRenderable Render(RenderContext context, ProgressTask task, TimeSpan deltaTime)
if (task.IsFinished)
{
var total = new FileSize(task.MaxValue);
return new Markup(string.Format(
"[green]{0} {1}[/]",
total.Format(Culture),
total.Suffix));
}
else
{
var downloaded = new FileSize(task.Value, total.Unit);
if (task.IsFinished)
{
return new Markup(string.Format(
"[green]{0} {1}[/]",
total.Format(Culture),
total.Suffix));
}
else
{
var downloaded = new FileSize(task.Value, total.Unit);
return new Markup(string.Format(
"{0}[grey]/[/]{1} [grey]{2}[/]",
downloaded.Format(Culture),
total.Format(Culture),
total.Suffix));
}
return new Markup(string.Format(
"{0}[grey]/[/]{1} [grey]{2}[/]",
downloaded.Format(Culture),
total.Format(Culture),
total.Suffix));
}
}
}
}

View File

@@ -1,42 +1,41 @@
using System;
using System;
using Spectre.Console.Rendering;
namespace Spectre.Console
namespace Spectre.Console;
/// <summary>
/// A column showing the elapsed time of a task.
/// </summary>
public sealed class ElapsedTimeColumn : ProgressColumn
{
/// <inheritdoc/>
protected internal override bool NoWrap => true;
/// <summary>
/// A column showing the elapsed time of a task.
/// Gets or sets the style of the remaining time text.
/// </summary>
public sealed class ElapsedTimeColumn : ProgressColumn
public Style Style { get; set; } = new Style(foreground: Color.Blue);
/// <inheritdoc/>
public override IRenderable Render(RenderContext context, ProgressTask task, TimeSpan deltaTime)
{
/// <inheritdoc/>
protected internal override bool NoWrap => true;
/// <summary>
/// Gets or sets the style of the remaining time text.
/// </summary>
public Style Style { get; set; } = new Style(foreground: Color.Blue);
/// <inheritdoc/>
public override IRenderable Render(RenderContext context, ProgressTask task, TimeSpan deltaTime)
var elapsed = task.ElapsedTime;
if (elapsed == null)
{
var elapsed = task.ElapsedTime;
if (elapsed == null)
{
return new Markup("--:--:--");
}
if (elapsed.Value.TotalHours > 99)
{
return new Markup("**:**:**");
}
return new Text($"{elapsed.Value:hh\\:mm\\:ss}", Style ?? Style.Plain);
return new Markup("--:--:--");
}
/// <inheritdoc/>
public override int? GetColumnWidth(RenderContext context)
if (elapsed.Value.TotalHours > 99)
{
return 8;
return new Markup("**:**:**");
}
return new Text($"{elapsed.Value:hh\\:mm\\:ss}", Style ?? Style.Plain);
}
}
/// <inheritdoc/>
public override int? GetColumnWidth(RenderContext context)
{
return 8;
}
}

View File

@@ -1,35 +1,34 @@
using System;
using Spectre.Console.Rendering;
namespace Spectre.Console
namespace Spectre.Console;
/// <summary>
/// A column showing task progress in percentage.
/// </summary>
public sealed class PercentageColumn : ProgressColumn
{
/// <summary>
/// A column showing task progress in percentage.
/// Gets or sets the style for a non-complete task.
/// </summary>
public sealed class PercentageColumn : ProgressColumn
public Style Style { get; set; } = Style.Plain;
/// <summary>
/// Gets or sets the style for a completed task.
/// </summary>
public Style CompletedStyle { get; set; } = new Style(foreground: Color.Green);
/// <inheritdoc/>
public override IRenderable Render(RenderContext context, ProgressTask task, TimeSpan deltaTime)
{
/// <summary>
/// Gets or sets the style for a non-complete task.
/// </summary>
public Style Style { get; set; } = Style.Plain;
/// <summary>
/// Gets or sets the style for a completed task.
/// </summary>
public Style CompletedStyle { get; set; } = new Style(foreground: Color.Green);
/// <inheritdoc/>
public override IRenderable Render(RenderContext context, ProgressTask task, TimeSpan deltaTime)
{
var percentage = (int)task.Percentage;
var style = percentage == 100 ? CompletedStyle : Style ?? Style.Plain;
return new Text($"{percentage}%", style).RightAligned();
}
/// <inheritdoc/>
public override int? GetColumnWidth(RenderContext context)
{
return 4;
}
var percentage = (int)task.Percentage;
var style = percentage == 100 ? CompletedStyle : Style ?? Style.Plain;
return new Text($"{percentage}%", style).RightAligned();
}
}
/// <inheritdoc/>
public override int? GetColumnWidth(RenderContext context)
{
return 4;
}
}

View File

@@ -1,52 +1,51 @@
using System;
using Spectre.Console.Rendering;
namespace Spectre.Console
namespace Spectre.Console;
/// <summary>
/// A column showing task progress as a progress bar.
/// </summary>
public sealed class ProgressBarColumn : ProgressColumn
{
/// <summary>
/// A column showing task progress as a progress bar.
/// Gets or sets the width of the column.
/// </summary>
public sealed class ProgressBarColumn : ProgressColumn
public int? Width { get; set; } = 40;
/// <summary>
/// Gets or sets the style of completed portions of the progress bar.
/// </summary>
public Style CompletedStyle { get; set; } = new Style(foreground: Color.Yellow);
/// <summary>
/// Gets or sets the style of a finished progress bar.
/// </summary>
public Style FinishedStyle { get; set; } = new Style(foreground: Color.Green);
/// <summary>
/// Gets or sets the style of remaining portions of the progress bar.
/// </summary>
public Style RemainingStyle { get; set; } = new Style(foreground: Color.Grey);
/// <summary>
/// Gets or sets the style of an indeterminate progress bar.
/// </summary>
public Style IndeterminateStyle { get; set; } = ProgressBar.DefaultPulseStyle;
/// <inheritdoc/>
public override IRenderable Render(RenderContext context, ProgressTask task, TimeSpan deltaTime)
{
/// <summary>
/// Gets or sets the width of the column.
/// </summary>
public int? Width { get; set; } = 40;
/// <summary>
/// Gets or sets the style of completed portions of the progress bar.
/// </summary>
public Style CompletedStyle { get; set; } = new Style(foreground: Color.Yellow);
/// <summary>
/// Gets or sets the style of a finished progress bar.
/// </summary>
public Style FinishedStyle { get; set; } = new Style(foreground: Color.Green);
/// <summary>
/// Gets or sets the style of remaining portions of the progress bar.
/// </summary>
public Style RemainingStyle { get; set; } = new Style(foreground: Color.Grey);
/// <summary>
/// Gets or sets the style of an indeterminate progress bar.
/// </summary>
public Style IndeterminateStyle { get; set; } = ProgressBar.DefaultPulseStyle;
/// <inheritdoc/>
public override IRenderable Render(RenderContext context, ProgressTask task, TimeSpan deltaTime)
return new ProgressBar
{
return new ProgressBar
{
MaxValue = task.MaxValue,
Value = task.Value,
Width = Width,
CompletedStyle = CompletedStyle,
FinishedStyle = FinishedStyle,
RemainingStyle = RemainingStyle,
IndeterminateStyle = IndeterminateStyle,
IsIndeterminate = task.IsIndeterminate,
};
}
MaxValue = task.MaxValue,
Value = task.Value,
Width = Width,
CompletedStyle = CompletedStyle,
FinishedStyle = FinishedStyle,
RemainingStyle = RemainingStyle,
IndeterminateStyle = IndeterminateStyle,
IsIndeterminate = task.IsIndeterminate,
};
}
}
}

View File

@@ -1,42 +1,41 @@
using System;
using Spectre.Console.Rendering;
namespace Spectre.Console
namespace Spectre.Console;
/// <summary>
/// A column showing the remaining time of a task.
/// </summary>
public sealed class RemainingTimeColumn : ProgressColumn
{
/// <inheritdoc/>
protected internal override bool NoWrap => true;
/// <summary>
/// A column showing the remaining time of a task.
/// Gets or sets the style of the remaining time text.
/// </summary>
public sealed class RemainingTimeColumn : ProgressColumn
public Style Style { get; set; } = new Style(foreground: Color.Blue);
/// <inheritdoc/>
public override IRenderable Render(RenderContext context, ProgressTask task, TimeSpan deltaTime)
{
/// <inheritdoc/>
protected internal override bool NoWrap => true;
/// <summary>
/// Gets or sets the style of the remaining time text.
/// </summary>
public Style Style { get; set; } = new Style(foreground: Color.Blue);
/// <inheritdoc/>
public override IRenderable Render(RenderContext context, ProgressTask task, TimeSpan deltaTime)
var remaining = task.RemainingTime;
if (remaining == null)
{
var remaining = task.RemainingTime;
if (remaining == null)
{
return new Markup("--:--:--");
}
if (remaining.Value.TotalHours > 99)
{
return new Markup("**:**:**");
}
return new Text($"{remaining.Value:hh\\:mm\\:ss}", Style ?? Style.Plain);
return new Markup("--:--:--");
}
/// <inheritdoc/>
public override int? GetColumnWidth(RenderContext context)
if (remaining.Value.TotalHours > 99)
{
return 8;
return new Markup("**:**:**");
}
return new Text($"{remaining.Value:hh\\:mm\\:ss}", Style ?? Style.Plain);
}
}
/// <inheritdoc/>
public override int? GetColumnWidth(RenderContext context)
{
return 8;
}
}

View File

@@ -2,154 +2,153 @@ using System;
using System.Linq;
using Spectre.Console.Rendering;
namespace Spectre.Console
namespace Spectre.Console;
/// <summary>
/// A column showing a spinner.
/// </summary>
public sealed class SpinnerColumn : ProgressColumn
{
private const string ACCUMULATED = "SPINNER_ACCUMULATED";
private const string INDEX = "SPINNER_INDEX";
private readonly object _lock;
private Spinner _spinner;
private int? _maxWidth;
private string? _completed;
private string? _pending;
/// <inheritdoc/>
protected internal override bool NoWrap => true;
/// <summary>
/// A column showing a spinner.
/// Gets or sets the <see cref="Console.Spinner"/>.
/// </summary>
public sealed class SpinnerColumn : ProgressColumn
public Spinner Spinner
{
private const string ACCUMULATED = "SPINNER_ACCUMULATED";
private const string INDEX = "SPINNER_INDEX";
private readonly object _lock;
private Spinner _spinner;
private int? _maxWidth;
private string? _completed;
private string? _pending;
/// <inheritdoc/>
protected internal override bool NoWrap => true;
/// <summary>
/// Gets or sets the <see cref="Console.Spinner"/>.
/// </summary>
public Spinner Spinner
{
get => _spinner;
set
{
lock (_lock)
{
_spinner = value ?? Spinner.Known.Default;
_maxWidth = null;
}
}
}
/// <summary>
/// Gets or sets the text that should be shown instead
/// of the spinner once a task completes.
/// </summary>
public string? CompletedText
{
get => _completed;
set
{
_completed = value;
_maxWidth = null;
}
}
/// <summary>
/// Gets or sets the text that should be shown instead
/// of the spinner before a task begins.
/// </summary>
public string? PendingText
{
get => _pending;
set
{
_pending = value;
_maxWidth = null;
}
}
/// <summary>
/// Gets or sets the completed style.
/// </summary>
public Style? CompletedStyle { get; set; }
/// <summary>
/// Gets or sets the pending style.
/// </summary>
public Style? PendingStyle { get; set; }
/// <summary>
/// Gets or sets the style of the spinner.
/// </summary>
public Style? Style { get; set; } = new Style(foreground: Color.Yellow);
/// <summary>
/// Initializes a new instance of the <see cref="SpinnerColumn"/> class.
/// </summary>
public SpinnerColumn()
: this(Spinner.Known.Default)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SpinnerColumn"/> class.
/// </summary>
/// <param name="spinner">The spinner to use.</param>
public SpinnerColumn(Spinner spinner)
{
_spinner = spinner ?? throw new ArgumentNullException(nameof(spinner));
_lock = new object();
}
/// <inheritdoc/>
public override IRenderable Render(RenderContext context, ProgressTask task, TimeSpan deltaTime)
{
var useAscii = !context.Unicode && _spinner.IsUnicode;
var spinner = useAscii ? Spinner.Known.Ascii : _spinner ?? Spinner.Known.Default;
if (!task.IsStarted)
{
return new Markup(PendingText ?? " ", PendingStyle ?? Style.Plain);
}
if (task.IsFinished)
{
return new Markup(CompletedText ?? " ", CompletedStyle ?? Style.Plain);
}
var accumulated = task.State.Update<double>(ACCUMULATED, acc => acc + deltaTime.TotalMilliseconds);
if (accumulated >= spinner.Interval.TotalMilliseconds)
{
task.State.Update<double>(ACCUMULATED, _ => 0);
task.State.Update<int>(INDEX, index => index + 1);
}
var index = task.State.Get<int>(INDEX);
var frame = spinner.Frames[index % spinner.Frames.Count];
return new Markup(frame.EscapeMarkup(), Style ?? Style.Plain);
}
/// <inheritdoc/>
public override int? GetColumnWidth(RenderContext context)
{
return GetMaxWidth(context);
}
private int GetMaxWidth(RenderContext context)
get => _spinner;
set
{
lock (_lock)
{
if (_maxWidth == null)
{
var useAscii = !context.Unicode && _spinner.IsUnicode;
var spinner = useAscii ? Spinner.Known.Ascii : _spinner ?? Spinner.Known.Default;
_maxWidth = Math.Max(
Math.Max(
((IRenderable)new Markup(PendingText ?? " ")).Measure(context, int.MaxValue).Max,
((IRenderable)new Markup(CompletedText ?? " ")).Measure(context, int.MaxValue).Max),
spinner.Frames.Max(frame => Cell.GetCellLength(frame)));
}
return _maxWidth.Value;
_spinner = value ?? Spinner.Known.Default;
_maxWidth = null;
}
}
}
}
/// <summary>
/// Gets or sets the text that should be shown instead
/// of the spinner once a task completes.
/// </summary>
public string? CompletedText
{
get => _completed;
set
{
_completed = value;
_maxWidth = null;
}
}
/// <summary>
/// Gets or sets the text that should be shown instead
/// of the spinner before a task begins.
/// </summary>
public string? PendingText
{
get => _pending;
set
{
_pending = value;
_maxWidth = null;
}
}
/// <summary>
/// Gets or sets the completed style.
/// </summary>
public Style? CompletedStyle { get; set; }
/// <summary>
/// Gets or sets the pending style.
/// </summary>
public Style? PendingStyle { get; set; }
/// <summary>
/// Gets or sets the style of the spinner.
/// </summary>
public Style? Style { get; set; } = new Style(foreground: Color.Yellow);
/// <summary>
/// Initializes a new instance of the <see cref="SpinnerColumn"/> class.
/// </summary>
public SpinnerColumn()
: this(Spinner.Known.Default)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SpinnerColumn"/> class.
/// </summary>
/// <param name="spinner">The spinner to use.</param>
public SpinnerColumn(Spinner spinner)
{
_spinner = spinner ?? throw new ArgumentNullException(nameof(spinner));
_lock = new object();
}
/// <inheritdoc/>
public override IRenderable Render(RenderContext context, ProgressTask task, TimeSpan deltaTime)
{
var useAscii = !context.Unicode && _spinner.IsUnicode;
var spinner = useAscii ? Spinner.Known.Ascii : _spinner ?? Spinner.Known.Default;
if (!task.IsStarted)
{
return new Markup(PendingText ?? " ", PendingStyle ?? Style.Plain);
}
if (task.IsFinished)
{
return new Markup(CompletedText ?? " ", CompletedStyle ?? Style.Plain);
}
var accumulated = task.State.Update<double>(ACCUMULATED, acc => acc + deltaTime.TotalMilliseconds);
if (accumulated >= spinner.Interval.TotalMilliseconds)
{
task.State.Update<double>(ACCUMULATED, _ => 0);
task.State.Update<int>(INDEX, index => index + 1);
}
var index = task.State.Get<int>(INDEX);
var frame = spinner.Frames[index % spinner.Frames.Count];
return new Markup(frame.EscapeMarkup(), Style ?? Style.Plain);
}
/// <inheritdoc/>
public override int? GetColumnWidth(RenderContext context)
{
return GetMaxWidth(context);
}
private int GetMaxWidth(RenderContext context)
{
lock (_lock)
{
if (_maxWidth == null)
{
var useAscii = !context.Unicode && _spinner.IsUnicode;
var spinner = useAscii ? Spinner.Known.Ascii : _spinner ?? Spinner.Known.Default;
_maxWidth = Math.Max(
Math.Max(
((IRenderable)new Markup(PendingText ?? " ")).Measure(context, int.MaxValue).Max,
((IRenderable)new Markup(CompletedText ?? " ")).Measure(context, int.MaxValue).Max),
spinner.Frames.Max(frame => Cell.GetCellLength(frame)));
}
return _maxWidth.Value;
}
}
}

View File

@@ -1,26 +1,25 @@
using System;
using Spectre.Console.Rendering;
namespace Spectre.Console
namespace Spectre.Console;
/// <summary>
/// A column showing the task description.
/// </summary>
public sealed class TaskDescriptionColumn : ProgressColumn
{
/// <inheritdoc/>
protected internal override bool NoWrap => true;
/// <summary>
/// A column showing the task description.
/// Gets or sets the alignment of the task description.
/// </summary>
public sealed class TaskDescriptionColumn : ProgressColumn
public Justify Alignment { get; set; } = Justify.Right;
/// <inheritdoc/>
public override IRenderable Render(RenderContext context, ProgressTask task, TimeSpan deltaTime)
{
/// <inheritdoc/>
protected internal override bool NoWrap => true;
/// <summary>
/// Gets or sets the alignment of the task description.
/// </summary>
public Justify Alignment { get; set; } = Justify.Right;
/// <inheritdoc/>
public override IRenderable Render(RenderContext context, ProgressTask task, TimeSpan deltaTime)
{
var text = task.Description?.RemoveNewLines()?.Trim();
return new Markup(text ?? string.Empty).Overflow(Overflow.Ellipsis).Alignment(Alignment);
}
var text = task.Description?.RemoveNewLines()?.Trim();
return new Markup(text ?? string.Empty).Overflow(Overflow.Ellipsis).Alignment(Alignment);
}
}
}

View File

@@ -2,28 +2,27 @@ using System;
using System.Globalization;
using Spectre.Console.Rendering;
namespace Spectre.Console
namespace Spectre.Console;
/// <summary>
/// A column showing transfer speed.
/// </summary>
public sealed class TransferSpeedColumn : ProgressColumn
{
/// <summary>
/// A column showing transfer speed.
/// Gets or sets the <see cref="CultureInfo"/> to use.
/// </summary>
public sealed class TransferSpeedColumn : ProgressColumn
public CultureInfo? Culture { get; set; }
/// <inheritdoc/>
public override IRenderable Render(RenderContext context, ProgressTask task, TimeSpan deltaTime)
{
/// <summary>
/// Gets or sets the <see cref="CultureInfo"/> to use.
/// </summary>
public CultureInfo? Culture { get; set; }
/// <inheritdoc/>
public override IRenderable Render(RenderContext context, ProgressTask task, TimeSpan deltaTime)
if (task.Speed == null)
{
if (task.Speed == null)
{
return new Text("?/s");
}
var size = new FileSize(task.Speed.Value);
return new Markup(string.Format("{0}/s", size.ToString(suffix: true, Culture)));
return new Text("?/s");
}
var size = new FileSize(task.Speed.Value);
return new Markup(string.Format("{0}/s", size.ToString(suffix: true, Culture)));
}
}
}

View File

@@ -3,172 +3,171 @@ using System.Collections.Generic;
using System.Threading.Tasks;
using Spectre.Console.Rendering;
namespace Spectre.Console
namespace Spectre.Console;
/// <summary>
/// Represents a task list.
/// </summary>
public sealed class Progress
{
private readonly IAnsiConsole _console;
/// <summary>
/// Represents a task list.
/// Gets or sets a value indicating whether or not task list should auto refresh.
/// Defaults to <c>true</c>.
/// </summary>
public sealed class Progress
public bool AutoRefresh { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether or not the task list should
/// be cleared once it completes.
/// Defaults to <c>false</c>.
/// </summary>
public bool AutoClear { get; set; }
/// <summary>
/// Gets or sets a value indicating whether or not the task list should
/// only include tasks not completed
/// Defaults to <c>false</c>.
/// </summary>
public bool HideCompleted { get; set; }
/// <summary>
/// Gets or sets the refresh rate if <c>AutoRefresh</c> is enabled.
/// Defaults to 10 times/second.
/// </summary>
public TimeSpan RefreshRate { get; set; } = TimeSpan.FromMilliseconds(100);
internal List<ProgressColumn> Columns { get; }
internal ProgressRenderer? FallbackRenderer { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Progress"/> class.
/// </summary>
/// <param name="console">The console to render to.</param>
public Progress(IAnsiConsole console)
{
private readonly IAnsiConsole _console;
_console = console ?? throw new ArgumentNullException(nameof(console));
/// <summary>
/// Gets or sets a value indicating whether or not task list should auto refresh.
/// Defaults to <c>true</c>.
/// </summary>
public bool AutoRefresh { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether or not the task list should
/// be cleared once it completes.
/// Defaults to <c>false</c>.
/// </summary>
public bool AutoClear { get; set; }
/// <summary>
/// Gets or sets a value indicating whether or not the task list should
/// only include tasks not completed
/// Defaults to <c>false</c>.
/// </summary>
public bool HideCompleted { get; set; }
/// <summary>
/// Gets or sets the refresh rate if <c>AutoRefresh</c> is enabled.
/// Defaults to 10 times/second.
/// </summary>
public TimeSpan RefreshRate { get; set; } = TimeSpan.FromMilliseconds(100);
internal List<ProgressColumn> Columns { get; }
internal ProgressRenderer? FallbackRenderer { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Progress"/> class.
/// </summary>
/// <param name="console">The console to render to.</param>
public Progress(IAnsiConsole console)
{
_console = console ?? throw new ArgumentNullException(nameof(console));
// Initialize with default columns
Columns = new List<ProgressColumn>
// Initialize with default columns
Columns = new List<ProgressColumn>
{
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn(),
};
}
/// <summary>
/// Starts the progress task list.
/// </summary>
/// <param name="action">The action to execute.</param>
public void Start(Action<ProgressContext> action)
{
var task = StartAsync(ctx =>
{
action(ctx);
return Task.CompletedTask;
});
task.GetAwaiter().GetResult();
}
/// <summary>
/// Starts the progress task list and returns a result.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="func">he action to execute.</param>
/// <returns>The result.</returns>
public T Start<T>(Func<ProgressContext, T> func)
{
var task = StartAsync(ctx => Task.FromResult(func(ctx)));
return task.GetAwaiter().GetResult();
}
/// <summary>
/// Starts the progress task list.
/// </summary>
/// <param name="action">The action to execute.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task StartAsync(Func<ProgressContext, Task> action)
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
/// <summary>
/// Starts the progress task list.
/// </summary>
/// <param name="action">The action to execute.</param>
public void Start(Action<ProgressContext> action)
_ = await StartAsync<object?>(async progressContext =>
{
var task = StartAsync(ctx =>
{
action(ctx);
return Task.CompletedTask;
});
await action(progressContext).ConfigureAwait(false);
return default;
}).ConfigureAwait(false);
}
task.GetAwaiter().GetResult();
/// <summary>
/// Starts the progress task list and returns a result.
/// </summary>
/// <param name="action">The action to execute.</param>
/// <typeparam name="T">The result type of task.</typeparam>
/// <returns>A <see cref="Task{T}"/> representing the asynchronous operation.</returns>
public async Task<T> StartAsync<T>(Func<ProgressContext, Task<T>> action)
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
/// <summary>
/// Starts the progress task list and returns a result.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="func">he action to execute.</param>
/// <returns>The result.</returns>
public T Start<T>(Func<ProgressContext, T> func)
return await _console.RunExclusive(async () =>
{
var task = StartAsync(ctx => Task.FromResult(func(ctx)));
return task.GetAwaiter().GetResult();
}
var renderer = CreateRenderer();
renderer.Started();
/// <summary>
/// Starts the progress task list.
/// </summary>
/// <param name="action">The action to execute.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task StartAsync(Func<ProgressContext, Task> action)
{
if (action is null)
T result;
try
{
throw new ArgumentNullException(nameof(action));
}
_ = await StartAsync<object?>(async progressContext =>
{
await action(progressContext).ConfigureAwait(false);
return default;
}).ConfigureAwait(false);
}
/// <summary>
/// Starts the progress task list and returns a result.
/// </summary>
/// <param name="action">The action to execute.</param>
/// <typeparam name="T">The result type of task.</typeparam>
/// <returns>A <see cref="Task{T}"/> representing the asynchronous operation.</returns>
public async Task<T> StartAsync<T>(Func<ProgressContext, Task<T>> action)
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
return await _console.RunExclusive(async () =>
{
var renderer = CreateRenderer();
renderer.Started();
T result;
try
using (new RenderHookScope(_console, renderer))
{
using (new RenderHookScope(_console, renderer))
{
var context = new ProgressContext(_console, renderer);
var context = new ProgressContext(_console, renderer);
if (AutoRefresh)
{
using (var thread = new ProgressRefreshThread(context, renderer.RefreshRate))
{
result = await action(context).ConfigureAwait(false);
}
}
else
if (AutoRefresh)
{
using (var thread = new ProgressRefreshThread(context, renderer.RefreshRate))
{
result = await action(context).ConfigureAwait(false);
}
context.Refresh();
}
}
finally
{
renderer.Completed(AutoClear);
}
else
{
result = await action(context).ConfigureAwait(false);
}
return result;
}).ConfigureAwait(false);
}
context.Refresh();
}
}
finally
{
renderer.Completed(AutoClear);
}
private ProgressRenderer CreateRenderer()
return result;
}).ConfigureAwait(false);
}
private ProgressRenderer CreateRenderer()
{
var caps = _console.Profile.Capabilities;
var interactive = caps.Interactive && caps.Ansi;
if (interactive)
{
var caps = _console.Profile.Capabilities;
var interactive = caps.Interactive && caps.Ansi;
if (interactive)
{
var columns = new List<ProgressColumn>(Columns);
return new DefaultProgressRenderer(_console, columns, RefreshRate, HideCompleted);
}
else
{
return FallbackRenderer ?? new FallbackProgressRenderer();
}
var columns = new List<ProgressColumn>(Columns);
return new DefaultProgressRenderer(_console, columns, RefreshRate, HideCompleted);
}
else
{
return FallbackRenderer ?? new FallbackProgressRenderer();
}
}
}
}

View File

@@ -1,35 +1,34 @@
using System;
using Spectre.Console.Rendering;
namespace Spectre.Console
namespace Spectre.Console;
/// <summary>
/// Represents a progress column.
/// </summary>
public abstract class ProgressColumn
{
/// <summary>
/// Represents a progress column.
/// Gets a value indicating whether or not content should not wrap.
/// </summary>
public abstract class ProgressColumn
protected internal virtual bool NoWrap { get; }
/// <summary>
/// Gets a renderable representing the column.
/// </summary>
/// <param name="context">The render context.</param>
/// <param name="task">The task.</param>
/// <param name="deltaTime">The elapsed time since last call.</param>
/// <returns>A renderable representing the column.</returns>
public abstract IRenderable Render(RenderContext context, ProgressTask task, TimeSpan deltaTime);
/// <summary>
/// Gets the width of the column.
/// </summary>
/// <param name="context">The context.</param>
/// <returns>The width of the column, or <c>null</c> to calculate.</returns>
public virtual int? GetColumnWidth(RenderContext context)
{
/// <summary>
/// Gets a value indicating whether or not content should not wrap.
/// </summary>
protected internal virtual bool NoWrap { get; }
/// <summary>
/// Gets a renderable representing the column.
/// </summary>
/// <param name="context">The render context.</param>
/// <param name="task">The task.</param>
/// <param name="deltaTime">The elapsed time since last call.</param>
/// <returns>A renderable representing the column.</returns>
public abstract IRenderable Render(RenderContext context, ProgressTask task, TimeSpan deltaTime);
/// <summary>
/// Gets the width of the column.
/// </summary>
/// <param name="context">The context.</param>
/// <returns>The width of the column, or <c>null</c> to calculate.</returns>
public virtual int? GetColumnWidth(RenderContext context)
{
return null;
}
return null;
}
}
}

View File

@@ -2,86 +2,85 @@ using System;
using System.Collections.Generic;
using System.Linq;
namespace Spectre.Console
namespace Spectre.Console;
/// <summary>
/// Represents a context that can be used to interact with a <see cref="Progress"/>.
/// </summary>
public sealed class ProgressContext
{
private readonly List<ProgressTask> _tasks;
private readonly object _taskLock;
private readonly IAnsiConsole _console;
private readonly ProgressRenderer _renderer;
private int _taskId;
/// <summary>
/// Represents a context that can be used to interact with a <see cref="Progress"/>.
/// Gets a value indicating whether or not all started tasks have completed.
/// </summary>
public sealed class ProgressContext
public bool IsFinished => _tasks.Where(x => x.IsStarted).All(task => task.IsFinished);
internal ProgressContext(IAnsiConsole console, ProgressRenderer renderer)
{
private readonly List<ProgressTask> _tasks;
private readonly object _taskLock;
private readonly IAnsiConsole _console;
private readonly ProgressRenderer _renderer;
private int _taskId;
_tasks = new List<ProgressTask>();
_taskLock = new object();
_console = console ?? throw new ArgumentNullException(nameof(console));
_renderer = renderer ?? throw new ArgumentNullException(nameof(renderer));
}
/// <summary>
/// Gets a value indicating whether or not all started tasks have completed.
/// </summary>
public bool IsFinished => _tasks.Where(x => x.IsStarted).All(task => task.IsFinished);
internal ProgressContext(IAnsiConsole console, ProgressRenderer renderer)
/// <summary>
/// Adds a task.
/// </summary>
/// <param name="description">The task description.</param>
/// <param name="autoStart">Whether or not the task should start immediately.</param>
/// <param name="maxValue">The task's max value.</param>
/// <returns>The newly created task.</returns>
public ProgressTask AddTask(string description, bool autoStart = true, double maxValue = 100)
{
return AddTask(description, new ProgressTaskSettings
{
_tasks = new List<ProgressTask>();
_taskLock = new object();
_console = console ?? throw new ArgumentNullException(nameof(console));
_renderer = renderer ?? throw new ArgumentNullException(nameof(renderer));
AutoStart = autoStart,
MaxValue = maxValue,
});
}
/// <summary>
/// Adds a task.
/// </summary>
/// <param name="description">The task description.</param>
/// <param name="settings">The task settings.</param>
/// <returns>The newly created task.</returns>
public ProgressTask AddTask(string description, ProgressTaskSettings settings)
{
if (settings is null)
{
throw new ArgumentNullException(nameof(settings));
}
/// <summary>
/// Adds a task.
/// </summary>
/// <param name="description">The task description.</param>
/// <param name="autoStart">Whether or not the task should start immediately.</param>
/// <param name="maxValue">The task's max value.</param>
/// <returns>The newly created task.</returns>
public ProgressTask AddTask(string description, bool autoStart = true, double maxValue = 100)
lock (_taskLock)
{
return AddTask(description, new ProgressTaskSettings
{
AutoStart = autoStart,
MaxValue = maxValue,
});
}
var task = new ProgressTask(_taskId++, description, settings.MaxValue, settings.AutoStart);
/// <summary>
/// Adds a task.
/// </summary>
/// <param name="description">The task description.</param>
/// <param name="settings">The task settings.</param>
/// <returns>The newly created task.</returns>
public ProgressTask AddTask(string description, ProgressTaskSettings settings)
{
if (settings is null)
{
throw new ArgumentNullException(nameof(settings));
}
_tasks.Add(task);
lock (_taskLock)
{
var task = new ProgressTask(_taskId++, description, settings.MaxValue, settings.AutoStart);
_tasks.Add(task);
return task;
}
}
/// <summary>
/// Refreshes the current progress.
/// </summary>
public void Refresh()
{
_renderer.Update(this);
_console.Write(new ControlCode(string.Empty));
}
internal IReadOnlyList<ProgressTask> GetTasks()
{
lock (_taskLock)
{
return new List<ProgressTask>(_tasks);
}
return task;
}
}
}
/// <summary>
/// Refreshes the current progress.
/// </summary>
public void Refresh()
{
_renderer.Update(this);
_console.Write(new ControlCode(string.Empty));
}
internal IReadOnlyList<ProgressTask> GetTasks()
{
lock (_taskLock)
{
return new List<ProgressTask>(_tasks);
}
}
}

View File

@@ -1,58 +1,57 @@
using System;
using System.Threading;
namespace Spectre.Console
namespace Spectre.Console;
internal sealed class ProgressRefreshThread : IDisposable
{
internal sealed class ProgressRefreshThread : IDisposable
private readonly ProgressContext _context;
private readonly TimeSpan _refreshRate;
private readonly ManualResetEvent _running;
private readonly ManualResetEvent _stopped;
private readonly Thread? _thread;
public ProgressRefreshThread(ProgressContext context, TimeSpan refreshRate)
{
private readonly ProgressContext _context;
private readonly TimeSpan _refreshRate;
private readonly ManualResetEvent _running;
private readonly ManualResetEvent _stopped;
private readonly Thread? _thread;
_context = context ?? throw new ArgumentNullException(nameof(context));
_refreshRate = refreshRate;
_running = new ManualResetEvent(false);
_stopped = new ManualResetEvent(false);
public ProgressRefreshThread(ProgressContext context, TimeSpan refreshRate)
_thread = new Thread(Run);
_thread.IsBackground = true;
_thread.Start();
}
public void Dispose()
{
if (_thread == null || !_running.WaitOne(0))
{
_context = context ?? throw new ArgumentNullException(nameof(context));
_refreshRate = refreshRate;
_running = new ManualResetEvent(false);
_stopped = new ManualResetEvent(false);
_thread = new Thread(Run);
_thread.IsBackground = true;
_thread.Start();
return;
}
public void Dispose()
_stopped.Set();
_thread.Join();
_stopped.Dispose();
_running.Dispose();
}
private void Run()
{
_running.Set();
try
{
if (_thread == null || !_running.WaitOne(0))
while (!_stopped.WaitOne(_refreshRate))
{
return;
_context.Refresh();
}
_stopped.Set();
_thread.Join();
_stopped.Dispose();
_running.Dispose();
}
private void Run()
finally
{
_running.Set();
try
{
while (!_stopped.WaitOne(_refreshRate))
{
_context.Refresh();
}
}
finally
{
_stopped.Reset();
_running.Reset();
}
_stopped.Reset();
_running.Reset();
}
}
}
}

View File

@@ -2,21 +2,20 @@ using System;
using System.Collections.Generic;
using Spectre.Console.Rendering;
namespace Spectre.Console
namespace Spectre.Console;
internal abstract class ProgressRenderer : IRenderHook
{
internal abstract class ProgressRenderer : IRenderHook
public abstract TimeSpan RefreshRate { get; }
public virtual void Started()
{
public abstract TimeSpan RefreshRate { get; }
public virtual void Started()
{
}
public virtual void Completed(bool clear)
{
}
public abstract void Update(ProgressContext context);
public abstract IEnumerable<IRenderable> Process(RenderContext context, IEnumerable<IRenderable> renderables);
}
}
public virtual void Completed(bool clear)
{
}
public abstract void Update(ProgressContext context);
public abstract IEnumerable<IRenderable> Process(RenderContext context, IEnumerable<IRenderable> renderables);
}

View File

@@ -1,16 +1,15 @@
using System;
namespace Spectre.Console
{
internal readonly struct ProgressSample
{
public double Value { get; }
public DateTime Timestamp { get; }
namespace Spectre.Console;
public ProgressSample(DateTime timestamp, double value)
{
Timestamp = timestamp;
Value = value;
}
internal readonly struct ProgressSample
{
public double Value { get; }
public DateTime Timestamp { get; }
public ProgressSample(DateTime timestamp, double value)
{
Timestamp = timestamp;
Value = value;
}
}
}

View File

@@ -2,312 +2,311 @@ using System;
using System.Collections.Generic;
using System.Linq;
namespace Spectre.Console
namespace Spectre.Console;
/// <summary>
/// Represents a progress task.
/// </summary>
public sealed class ProgressTask : IProgress<double>
{
private readonly List<ProgressSample> _samples;
private readonly object _lock;
private double _maxValue;
private string _description;
private double _value;
/// <summary>
/// Represents a progress task.
/// Gets the task ID.
/// </summary>
public sealed class ProgressTask : IProgress<double>
public int Id { get; }
/// <summary>
/// Gets or sets the task description.
/// </summary>
public string Description
{
private readonly List<ProgressSample> _samples;
private readonly object _lock;
get => _description;
set => Update(description: value);
}
private double _maxValue;
private string _description;
private double _value;
/// <summary>
/// Gets or sets the max value of the task.
/// </summary>
public double MaxValue
{
get => _maxValue;
set => Update(maxValue: value);
}
/// <summary>
/// Gets the task ID.
/// </summary>
public int Id { get; }
/// <summary>
/// Gets or sets the value of the task.
/// </summary>
public double Value
{
get => _value;
set => Update(value: value);
}
/// <summary>
/// Gets or sets the task description.
/// </summary>
public string Description
/// <summary>
/// Gets the start time of the task.
/// </summary>
public DateTime? StartTime { get; private set; }
/// <summary>
/// Gets the stop time of the task.
/// </summary>
public DateTime? StopTime { get; private set; }
/// <summary>
/// Gets the task state.
/// </summary>
public ProgressTaskState State { get; }
/// <summary>
/// Gets a value indicating whether or not the task has started.
/// </summary>
public bool IsStarted => StartTime != null;
/// <summary>
/// Gets a value indicating whether or not the task has finished.
/// </summary>
public bool IsFinished => StopTime != null || Value >= MaxValue;
/// <summary>
/// Gets the percentage done of the task.
/// </summary>
public double Percentage => GetPercentage();
/// <summary>
/// Gets the speed measured in steps/second.
/// </summary>
public double? Speed => GetSpeed();
/// <summary>
/// Gets the elapsed time.
/// </summary>
public TimeSpan? ElapsedTime => GetElapsedTime();
/// <summary>
/// Gets the remaining time.
/// </summary>
public TimeSpan? RemainingTime => GetRemainingTime();
/// <summary>
/// Gets or sets a value indicating whether the ProgressBar shows
/// actual values or generic, continuous progress feedback.
/// </summary>
public bool IsIndeterminate { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ProgressTask"/> class.
/// </summary>
/// <param name="id">The task ID.</param>
/// <param name="description">The task description.</param>
/// <param name="maxValue">The task max value.</param>
/// <param name="autoStart">Whether or not the task should start automatically.</param>
public ProgressTask(int id, string description, double maxValue, bool autoStart = true)
{
_samples = new List<ProgressSample>();
_lock = new object();
_maxValue = maxValue;
_value = 0;
_description = description?.RemoveNewLines()?.Trim() ??
throw new ArgumentNullException(nameof(description));
if (string.IsNullOrWhiteSpace(_description))
{
get => _description;
set => Update(description: value);
throw new ArgumentException("Task name cannot be empty", nameof(description));
}
/// <summary>
/// Gets or sets the max value of the task.
/// </summary>
public double MaxValue
Id = id;
State = new ProgressTaskState();
StartTime = autoStart ? DateTime.Now : null;
}
/// <summary>
/// Starts the task.
/// </summary>
public void StartTask()
{
lock (_lock)
{
get => _maxValue;
set => Update(maxValue: value);
}
/// <summary>
/// Gets or sets the value of the task.
/// </summary>
public double Value
{
get => _value;
set => Update(value: value);
}
/// <summary>
/// Gets the start time of the task.
/// </summary>
public DateTime? StartTime { get; private set; }
/// <summary>
/// Gets the stop time of the task.
/// </summary>
public DateTime? StopTime { get; private set; }
/// <summary>
/// Gets the task state.
/// </summary>
public ProgressTaskState State { get; }
/// <summary>
/// Gets a value indicating whether or not the task has started.
/// </summary>
public bool IsStarted => StartTime != null;
/// <summary>
/// Gets a value indicating whether or not the task has finished.
/// </summary>
public bool IsFinished => StopTime != null || Value >= MaxValue;
/// <summary>
/// Gets the percentage done of the task.
/// </summary>
public double Percentage => GetPercentage();
/// <summary>
/// Gets the speed measured in steps/second.
/// </summary>
public double? Speed => GetSpeed();
/// <summary>
/// Gets the elapsed time.
/// </summary>
public TimeSpan? ElapsedTime => GetElapsedTime();
/// <summary>
/// Gets the remaining time.
/// </summary>
public TimeSpan? RemainingTime => GetRemainingTime();
/// <summary>
/// Gets or sets a value indicating whether the ProgressBar shows
/// actual values or generic, continuous progress feedback.
/// </summary>
public bool IsIndeterminate { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ProgressTask"/> class.
/// </summary>
/// <param name="id">The task ID.</param>
/// <param name="description">The task description.</param>
/// <param name="maxValue">The task max value.</param>
/// <param name="autoStart">Whether or not the task should start automatically.</param>
public ProgressTask(int id, string description, double maxValue, bool autoStart = true)
{
_samples = new List<ProgressSample>();
_lock = new object();
_maxValue = maxValue;
_value = 0;
_description = description?.RemoveNewLines()?.Trim() ??
throw new ArgumentNullException(nameof(description));
if (string.IsNullOrWhiteSpace(_description))
if (StopTime != null)
{
throw new ArgumentException("Task name cannot be empty", nameof(description));
throw new InvalidOperationException("Stopped tasks cannot be restarted");
}
Id = id;
State = new ProgressTaskState();
StartTime = autoStart ? DateTime.Now : null;
}
/// <summary>
/// Starts the task.
/// </summary>
public void StartTask()
{
lock (_lock)
{
if (StopTime != null)
{
throw new InvalidOperationException("Stopped tasks cannot be restarted");
}
StartTime = DateTime.Now;
StopTime = null;
}
}
/// <summary>
/// Stops and marks the task as finished.
/// </summary>
public void StopTask()
{
lock (_lock)
{
var now = DateTime.Now;
StartTime ??= now;
StopTime = now;
}
}
/// <summary>
/// Increments the task's value.
/// </summary>
/// <param name="value">The value to increment with.</param>
public void Increment(double value)
{
Update(increment: value);
}
private void Update(
string? description = null,
double? maxValue = null,
double? increment = null,
double? value = null)
{
lock (_lock)
{
var startValue = Value;
if (description != null)
{
description = description?.RemoveNewLines()?.Trim();
if (string.IsNullOrWhiteSpace(description))
{
throw new InvalidOperationException("Task name cannot be empty.");
}
_description = description;
}
if (maxValue != null)
{
_maxValue = maxValue.Value;
}
if (increment != null)
{
_value += increment.Value;
}
if (value != null)
{
_value = value.Value;
}
// Need to cap the max value?
if (_value > _maxValue)
{
_value = _maxValue;
}
var timestamp = DateTime.Now;
var threshold = timestamp - TimeSpan.FromSeconds(30);
// Remove samples that's too old
while (_samples.Count > 0 && _samples[0].Timestamp < threshold)
{
_samples.RemoveAt(0);
}
// Keep maximum of 1000 samples
while (_samples.Count > 1000)
{
_samples.RemoveAt(0);
}
_samples.Add(new ProgressSample(timestamp, Value - startValue));
}
}
private double GetPercentage()
{
var percentage = (Value / MaxValue) * 100;
percentage = Math.Min(100, Math.Max(0, percentage));
return percentage;
}
private double? GetSpeed()
{
lock (_lock)
{
if (StartTime == null)
{
return null;
}
if (_samples.Count == 0)
{
return null;
}
var totalTime = _samples.Last().Timestamp - _samples[0].Timestamp;
if (totalTime == TimeSpan.Zero)
{
return null;
}
var totalCompleted = _samples.Sum(x => x.Value);
return totalCompleted / totalTime.TotalSeconds;
}
}
private TimeSpan? GetElapsedTime()
{
lock (_lock)
{
if (StartTime == null)
{
return null;
}
if (StopTime != null)
{
return StopTime - StartTime;
}
return DateTime.Now - StartTime;
}
}
private TimeSpan? GetRemainingTime()
{
lock (_lock)
{
if (IsFinished)
{
return TimeSpan.Zero;
}
var speed = GetSpeed();
if (speed == null || speed == 0)
{
return null;
}
// If the speed is near zero, the estimate below causes the
// TimeSpan creation to throw an OverflowException. Just return
// the maximum possible remaining time instead of overflowing.
var estimate = (MaxValue - Value) / speed.Value;
if (estimate > TimeSpan.MaxValue.TotalSeconds)
{
return TimeSpan.MaxValue;
}
return TimeSpan.FromSeconds(estimate);
}
}
/// <inheritdoc />
void IProgress<double>.Report(double value)
{
Update(increment: value - Value);
StartTime = DateTime.Now;
StopTime = null;
}
}
/// <summary>
/// Stops and marks the task as finished.
/// </summary>
public void StopTask()
{
lock (_lock)
{
var now = DateTime.Now;
StartTime ??= now;
StopTime = now;
}
}
/// <summary>
/// Increments the task's value.
/// </summary>
/// <param name="value">The value to increment with.</param>
public void Increment(double value)
{
Update(increment: value);
}
private void Update(
string? description = null,
double? maxValue = null,
double? increment = null,
double? value = null)
{
lock (_lock)
{
var startValue = Value;
if (description != null)
{
description = description?.RemoveNewLines()?.Trim();
if (string.IsNullOrWhiteSpace(description))
{
throw new InvalidOperationException("Task name cannot be empty.");
}
_description = description;
}
if (maxValue != null)
{
_maxValue = maxValue.Value;
}
if (increment != null)
{
_value += increment.Value;
}
if (value != null)
{
_value = value.Value;
}
// Need to cap the max value?
if (_value > _maxValue)
{
_value = _maxValue;
}
var timestamp = DateTime.Now;
var threshold = timestamp - TimeSpan.FromSeconds(30);
// Remove samples that's too old
while (_samples.Count > 0 && _samples[0].Timestamp < threshold)
{
_samples.RemoveAt(0);
}
// Keep maximum of 1000 samples
while (_samples.Count > 1000)
{
_samples.RemoveAt(0);
}
_samples.Add(new ProgressSample(timestamp, Value - startValue));
}
}
private double GetPercentage()
{
var percentage = (Value / MaxValue) * 100;
percentage = Math.Min(100, Math.Max(0, percentage));
return percentage;
}
private double? GetSpeed()
{
lock (_lock)
{
if (StartTime == null)
{
return null;
}
if (_samples.Count == 0)
{
return null;
}
var totalTime = _samples.Last().Timestamp - _samples[0].Timestamp;
if (totalTime == TimeSpan.Zero)
{
return null;
}
var totalCompleted = _samples.Sum(x => x.Value);
return totalCompleted / totalTime.TotalSeconds;
}
}
private TimeSpan? GetElapsedTime()
{
lock (_lock)
{
if (StartTime == null)
{
return null;
}
if (StopTime != null)
{
return StopTime - StartTime;
}
return DateTime.Now - StartTime;
}
}
private TimeSpan? GetRemainingTime()
{
lock (_lock)
{
if (IsFinished)
{
return TimeSpan.Zero;
}
var speed = GetSpeed();
if (speed == null || speed == 0)
{
return null;
}
// If the speed is near zero, the estimate below causes the
// TimeSpan creation to throw an OverflowException. Just return
// the maximum possible remaining time instead of overflowing.
var estimate = (MaxValue - Value) / speed.Value;
if (estimate > TimeSpan.MaxValue.TotalSeconds)
{
return TimeSpan.MaxValue;
}
return TimeSpan.FromSeconds(estimate);
}
}
/// <inheritdoc />
void IProgress<double>.Report(double value)
{
Update(increment: value - Value);
}
}

View File

@@ -1,25 +1,24 @@
namespace Spectre.Console
namespace Spectre.Console;
/// <summary>
/// Represents settings for a progress task.
/// </summary>
public sealed class ProgressTaskSettings
{
/// <summary>
/// Represents settings for a progress task.
/// Gets or sets the task's max value.
/// Defaults to <c>100</c>.
/// </summary>
public sealed class ProgressTaskSettings
{
/// <summary>
/// Gets or sets the task's max value.
/// Defaults to <c>100</c>.
/// </summary>
public double MaxValue { get; set; } = 100;
public double MaxValue { get; set; } = 100;
/// <summary>
/// Gets or sets a value indicating whether or not the task
/// will be auto started. Defaults to <c>true</c>.
/// </summary>
public bool AutoStart { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether or not the task
/// will be auto started. Defaults to <c>true</c>.
/// </summary>
public bool AutoStart { get; set; } = true;
/// <summary>
/// Gets the default progress task settings.
/// </summary>
internal static ProgressTaskSettings Default { get; } = new ProgressTaskSettings();
}
}
/// <summary>
/// Gets the default progress task settings.
/// </summary>
internal static ProgressTaskSettings Default { get; } = new ProgressTaskSettings();
}

View File

@@ -1,81 +1,80 @@
using System;
using System.Collections.Generic;
namespace Spectre.Console
namespace Spectre.Console;
/// <summary>
/// Represents progress task state.
/// </summary>
public sealed class ProgressTaskState
{
private readonly Dictionary<string, object> _state;
private readonly object _lock;
/// <summary>
/// Represents progress task state.
/// Initializes a new instance of the <see cref="ProgressTaskState"/> class.
/// </summary>
public sealed class ProgressTaskState
public ProgressTaskState()
{
private readonly Dictionary<string, object> _state;
private readonly object _lock;
_state = new Dictionary<string, object>();
_lock = new object();
}
/// <summary>
/// Initializes a new instance of the <see cref="ProgressTaskState"/> class.
/// </summary>
public ProgressTaskState()
/// <summary>
/// Gets the state value for the specified key.
/// </summary>
/// <typeparam name="T">The state value type.</typeparam>
/// <param name="key">The state key.</param>
/// <returns>The value for the specified key.</returns>
public T Get<T>(string key)
where T : struct
{
lock (_lock)
{
_state = new Dictionary<string, object>();
_lock = new object();
}
/// <summary>
/// Gets the state value for the specified key.
/// </summary>
/// <typeparam name="T">The state value type.</typeparam>
/// <param name="key">The state key.</param>
/// <returns>The value for the specified key.</returns>
public T Get<T>(string key)
where T : struct
{
lock (_lock)
if (!_state.TryGetValue(key, out var value))
{
if (!_state.TryGetValue(key, out var value))
{
return default;
}
return default;
}
if (!(value is T))
{
throw new InvalidOperationException("State value is of the wrong type.");
}
return (T)value;
}
}
/// <summary>
/// Updates a task state value.
/// </summary>
/// <typeparam name="T">The state value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="func">The transformation function.</param>
/// <returns>The updated value.</returns>
public T Update<T>(string key, Func<T, T> func)
where T : struct
{
lock (_lock)
{
if (func is null)
{
throw new ArgumentNullException(nameof(func));
}
var old = default(T);
if (_state.TryGetValue(key, out var value))
{
if (!(value is T))
{
throw new InvalidOperationException("State value is of the wrong type.");
}
return (T)value;
old = (T)value;
}
}
/// <summary>
/// Updates a task state value.
/// </summary>
/// <typeparam name="T">The state value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="func">The transformation function.</param>
/// <returns>The updated value.</returns>
public T Update<T>(string key, Func<T, T> func)
where T : struct
{
lock (_lock)
{
if (func is null)
{
throw new ArgumentNullException(nameof(func));
}
var old = default(T);
if (_state.TryGetValue(key, out var value))
{
if (!(value is T))
{
throw new InvalidOperationException("State value is of the wrong type.");
}
old = (T)value;
}
_state[key] = func(old);
return (T)_state[key];
}
_state[key] = func(old);
return (T)_state[key];
}
}
}
}

View File

@@ -4,126 +4,125 @@ using System.Diagnostics;
using System.Linq;
using Spectre.Console.Rendering;
namespace Spectre.Console
namespace Spectre.Console;
internal sealed class DefaultProgressRenderer : ProgressRenderer
{
internal sealed class DefaultProgressRenderer : ProgressRenderer
private readonly IAnsiConsole _console;
private readonly List<ProgressColumn> _columns;
private readonly LiveRenderable _live;
private readonly object _lock;
private readonly Stopwatch _stopwatch;
private readonly bool _hideCompleted;
private TimeSpan _lastUpdate;
public override TimeSpan RefreshRate { get; }
public DefaultProgressRenderer(IAnsiConsole console, List<ProgressColumn> columns, TimeSpan refreshRate, bool hideCompleted)
{
private readonly IAnsiConsole _console;
private readonly List<ProgressColumn> _columns;
private readonly LiveRenderable _live;
private readonly object _lock;
private readonly Stopwatch _stopwatch;
private readonly bool _hideCompleted;
private TimeSpan _lastUpdate;
_console = console ?? throw new ArgumentNullException(nameof(console));
_columns = columns ?? throw new ArgumentNullException(nameof(columns));
_live = new LiveRenderable(console);
_lock = new object();
_stopwatch = new Stopwatch();
_lastUpdate = TimeSpan.Zero;
_hideCompleted = hideCompleted;
public override TimeSpan RefreshRate { get; }
RefreshRate = refreshRate;
}
public DefaultProgressRenderer(IAnsiConsole console, List<ProgressColumn> columns, TimeSpan refreshRate, bool hideCompleted)
public override void Started()
{
_console.Cursor.Hide();
}
public override void Completed(bool clear)
{
lock (_lock)
{
_console = console ?? throw new ArgumentNullException(nameof(console));
_columns = columns ?? throw new ArgumentNullException(nameof(columns));
_live = new LiveRenderable(console);
_lock = new object();
_stopwatch = new Stopwatch();
_lastUpdate = TimeSpan.Zero;
_hideCompleted = hideCompleted;
RefreshRate = refreshRate;
}
public override void Started()
{
_console.Cursor.Hide();
}
public override void Completed(bool clear)
{
lock (_lock)
if (clear)
{
if (clear)
_console.Write(_live.RestoreCursor());
}
else
{
if (_live.HasRenderable && _live.DidOverflow)
{
// Redraw the whole live renderable
_console.Write(_live.RestoreCursor());
}
else
{
if (_live.HasRenderable && _live.DidOverflow)
{
// Redraw the whole live renderable
_console.Write(_live.RestoreCursor());
_live.Overflow = VerticalOverflow.Visible;
_console.Write(_live.Target);
}
_console.WriteLine();
_live.Overflow = VerticalOverflow.Visible;
_console.Write(_live.Target);
}
_console.Cursor.Show();
_console.WriteLine();
}
}
public override void Update(ProgressContext context)
{
lock (_lock)
{
if (!_stopwatch.IsRunning)
{
_stopwatch.Start();
}
var renderContext = new RenderContext(_console.Profile.Capabilities);
var delta = _stopwatch.Elapsed - _lastUpdate;
_lastUpdate = _stopwatch.Elapsed;
var grid = new Grid();
for (var columnIndex = 0; columnIndex < _columns.Count; columnIndex++)
{
var column = new GridColumn().PadRight(1);
var columnWidth = _columns[columnIndex].GetColumnWidth(renderContext);
if (columnWidth != null)
{
column.Width = columnWidth;
}
if (_columns[columnIndex].NoWrap)
{
column.NoWrap();
}
// Last column?
if (columnIndex == _columns.Count - 1)
{
column.PadRight(0);
}
grid.AddColumn(column);
}
// Add rows
foreach (var task in context.GetTasks().Where(tsk => !(_hideCompleted && tsk.IsFinished)))
{
var columns = _columns.Select(column => column.Render(renderContext, task, delta));
grid.AddRow(columns.ToArray());
}
_live.SetRenderable(new Padder(grid, new Padding(0, 1)));
}
}
public override IEnumerable<IRenderable> Process(RenderContext context, IEnumerable<IRenderable> renderables)
{
lock (_lock)
{
yield return _live.PositionCursor();
foreach (var renderable in renderables)
{
yield return renderable;
}
yield return _live;
}
_console.Cursor.Show();
}
}
}
public override void Update(ProgressContext context)
{
lock (_lock)
{
if (!_stopwatch.IsRunning)
{
_stopwatch.Start();
}
var renderContext = new RenderContext(_console.Profile.Capabilities);
var delta = _stopwatch.Elapsed - _lastUpdate;
_lastUpdate = _stopwatch.Elapsed;
var grid = new Grid();
for (var columnIndex = 0; columnIndex < _columns.Count; columnIndex++)
{
var column = new GridColumn().PadRight(1);
var columnWidth = _columns[columnIndex].GetColumnWidth(renderContext);
if (columnWidth != null)
{
column.Width = columnWidth;
}
if (_columns[columnIndex].NoWrap)
{
column.NoWrap();
}
// Last column?
if (columnIndex == _columns.Count - 1)
{
column.PadRight(0);
}
grid.AddColumn(column);
}
// Add rows
foreach (var task in context.GetTasks().Where(tsk => !(_hideCompleted && tsk.IsFinished)))
{
var columns = _columns.Select(column => column.Render(renderContext, task, delta));
grid.AddRow(columns.ToArray());
}
_live.SetRenderable(new Padder(grid, new Padding(0, 1)));
}
}
public override IEnumerable<IRenderable> Process(RenderContext context, IEnumerable<IRenderable> renderables)
{
lock (_lock)
{
yield return _live.PositionCursor();
foreach (var renderable in renderables)
{
yield return renderable;
}
yield return _live;
}
}
}

View File

@@ -2,124 +2,123 @@ using System;
using System.Collections.Generic;
using Spectre.Console.Rendering;
namespace Spectre.Console
namespace Spectre.Console;
internal sealed class FallbackProgressRenderer : ProgressRenderer
{
internal sealed class FallbackProgressRenderer : ProgressRenderer
private const double FirstMilestone = 25;
private static readonly double?[] _milestones = new double?[] { FirstMilestone, 50, 75, 95, 96, 97, 98, 99, 100 };
private readonly Dictionary<int, double> _taskMilestones;
private readonly object _lock;
private IRenderable? _renderable;
private DateTime _lastUpdate;
public override TimeSpan RefreshRate => TimeSpan.FromSeconds(1);
public FallbackProgressRenderer()
{
private const double FirstMilestone = 25;
private static readonly double?[] _milestones = new double?[] { FirstMilestone, 50, 75, 95, 96, 97, 98, 99, 100 };
_taskMilestones = new Dictionary<int, double>();
_lock = new object();
}
private readonly Dictionary<int, double> _taskMilestones;
private readonly object _lock;
private IRenderable? _renderable;
private DateTime _lastUpdate;
public override TimeSpan RefreshRate => TimeSpan.FromSeconds(1);
public FallbackProgressRenderer()
public override void Update(ProgressContext context)
{
lock (_lock)
{
_taskMilestones = new Dictionary<int, double>();
_lock = new object();
}
var hasStartedTasks = false;
var updates = new List<(string, double)>();
public override void Update(ProgressContext context)
{
lock (_lock)
foreach (var task in context.GetTasks())
{
var hasStartedTasks = false;
var updates = new List<(string, double)>();
if (!task.IsStarted || task.IsFinished)
{
continue;
}
hasStartedTasks = true;
if (TryAdvance(task.Id, task.Percentage))
{
updates.Add((task.Description, task.Percentage));
}
}
// Got started tasks but no updates for 30 seconds?
if (hasStartedTasks && updates.Count == 0 && (DateTime.Now - _lastUpdate) > TimeSpan.FromSeconds(30))
{
foreach (var task in context.GetTasks())
{
if (!task.IsStarted || task.IsFinished)
{
continue;
}
hasStartedTasks = true;
if (TryAdvance(task.Id, task.Percentage))
{
updates.Add((task.Description, task.Percentage));
}
}
// Got started tasks but no updates for 30 seconds?
if (hasStartedTasks && updates.Count == 0 && (DateTime.Now - _lastUpdate) > TimeSpan.FromSeconds(30))
{
foreach (var task in context.GetTasks())
{
updates.Add((task.Description, task.Percentage));
}
}
if (updates.Count > 0)
{
_lastUpdate = DateTime.Now;
}
_renderable = BuildTaskGrid(updates);
}
}
public override IEnumerable<IRenderable> Process(RenderContext context, IEnumerable<IRenderable> renderables)
{
lock (_lock)
{
var result = new List<IRenderable>();
result.AddRange(renderables);
if (_renderable != null)
{
result.Add(_renderable);
}
_renderable = null;
return result;
}
}
private bool TryAdvance(int task, double percentage)
{
if (!_taskMilestones.TryGetValue(task, out var milestone))
{
_taskMilestones.Add(task, FirstMilestone);
return true;
}
if (percentage > milestone)
{
var nextMilestone = GetNextMilestone(percentage);
if (nextMilestone != null && _taskMilestones[task] != nextMilestone)
{
_taskMilestones[task] = nextMilestone.Value;
return true;
updates.Add((task.Description, task.Percentage));
}
}
return false;
}
private static double? GetNextMilestone(double percentage)
{
return Array.Find(_milestones, p => p > percentage);
}
private static IRenderable? BuildTaskGrid(List<(string Name, double Percentage)> updates)
{
if (updates.Count > 0)
{
var renderables = new List<IRenderable>();
foreach (var (name, percentage) in updates)
{
renderables.Add(new Markup($"[blue]{name}[/]: {(int)percentage}%"));
}
return new Rows(renderables);
_lastUpdate = DateTime.Now;
}
return null;
_renderable = BuildTaskGrid(updates);
}
}
}
public override IEnumerable<IRenderable> Process(RenderContext context, IEnumerable<IRenderable> renderables)
{
lock (_lock)
{
var result = new List<IRenderable>();
result.AddRange(renderables);
if (_renderable != null)
{
result.Add(_renderable);
}
_renderable = null;
return result;
}
}
private bool TryAdvance(int task, double percentage)
{
if (!_taskMilestones.TryGetValue(task, out var milestone))
{
_taskMilestones.Add(task, FirstMilestone);
return true;
}
if (percentage > milestone)
{
var nextMilestone = GetNextMilestone(percentage);
if (nextMilestone != null && _taskMilestones[task] != nextMilestone)
{
_taskMilestones[task] = nextMilestone.Value;
return true;
}
}
return false;
}
private static double? GetNextMilestone(double percentage)
{
return Array.Find(_milestones, p => p > percentage);
}
private static IRenderable? BuildTaskGrid(List<(string Name, double Percentage)> updates)
{
if (updates.Count > 0)
{
var renderables = new List<IRenderable>();
foreach (var (name, percentage) in updates)
{
renderables.Add(new Markup($"[blue]{name}[/]: {(int)percentage}%"));
}
return new Rows(renderables);
}
return null;
}
}

View File

@@ -3,58 +3,57 @@ using System.Collections.Generic;
using System.Linq;
using Spectre.Console.Rendering;
namespace Spectre.Console
namespace Spectre.Console;
internal sealed class FallbackStatusRenderer : ProgressRenderer
{
internal sealed class FallbackStatusRenderer : ProgressRenderer
private readonly object _lock;
private IRenderable? _renderable;
private string? _lastStatus;
public override TimeSpan RefreshRate => TimeSpan.FromMilliseconds(100);
public FallbackStatusRenderer()
{
private readonly object _lock;
private IRenderable? _renderable;
private string? _lastStatus;
_lock = new object();
}
public override TimeSpan RefreshRate => TimeSpan.FromMilliseconds(100);
public FallbackStatusRenderer()
public override void Update(ProgressContext context)
{
lock (_lock)
{
_lock = new object();
}
public override void Update(ProgressContext context)
{
lock (_lock)
var task = context.GetTasks().SingleOrDefault();
if (task != null)
{
var task = context.GetTasks().SingleOrDefault();
if (task != null)
// Not same description?
if (_lastStatus != task.Description)
{
// Not same description?
if (_lastStatus != task.Description)
{
_lastStatus = task.Description;
_renderable = new Markup(task.Description + Environment.NewLine);
return;
}
_lastStatus = task.Description;
_renderable = new Markup(task.Description + Environment.NewLine);
return;
}
_renderable = null;
return;
}
}
public override IEnumerable<IRenderable> Process(RenderContext context, IEnumerable<IRenderable> renderables)
{
lock (_lock)
{
var result = new List<IRenderable>();
result.AddRange(renderables);
if (_renderable != null)
{
result.Add(_renderable);
}
_renderable = null;
return result;
}
_renderable = null;
return;
}
}
}
public override IEnumerable<IRenderable> Process(RenderContext context, IEnumerable<IRenderable> renderables)
{
lock (_lock)
{
var result = new List<IRenderable>();
result.AddRange(renderables);
if (_renderable != null)
{
result.Add(_renderable);
}
_renderable = null;
return result;
}
}
}

View File

@@ -1,27 +1,26 @@
using System;
using System.Collections.Generic;
namespace Spectre.Console
namespace Spectre.Console;
/// <summary>
/// Represents a spinner used in a <see cref="SpinnerColumn"/>.
/// </summary>
public abstract partial class Spinner
{
/// <summary>
/// Represents a spinner used in a <see cref="SpinnerColumn"/>.
/// Gets the update interval for the spinner.
/// </summary>
public abstract partial class Spinner
{
/// <summary>
/// Gets the update interval for the spinner.
/// </summary>
public abstract TimeSpan Interval { get; }
public abstract TimeSpan Interval { get; }
/// <summary>
/// Gets a value indicating whether or not the spinner
/// uses Unicode characters.
/// </summary>
public abstract bool IsUnicode { get; }
/// <summary>
/// Gets a value indicating whether or not the spinner
/// uses Unicode characters.
/// </summary>
public abstract bool IsUnicode { get; }
/// <summary>
/// Gets the spinner frames.
/// </summary>
public abstract IReadOnlyList<string> Frames { get; }
}
}
/// <summary>
/// Gets the spinner frames.
/// </summary>
public abstract IReadOnlyList<string> Frames { get; }
}