Skip to content

Commit

Permalink
Merge branch 'master' of github.com:Mpdreamz/shellprogressbar
Browse files Browse the repository at this point in the history
  • Loading branch information
Mpdreamz committed Jan 29, 2021
2 parents 6a41c4e + 50cc691 commit 7606766
Show file tree
Hide file tree
Showing 9 changed files with 143 additions and 20 deletions.
13 changes: 7 additions & 6 deletions src/ShellProgressBar.Example/Examples/PersistMessageExample.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,29 @@ protected override void Start()
WriteQueuedMessage = o =>
{
var writer = o.Error ? Console.Error : Console.Out;
var c = o.Error ? ConsoleColor.DarkRed : ConsoleColor.Blue;
if (o.Line.StartsWith("Report 500"))
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.ForegroundColor = ConsoleColor.Yellow;
writer.WriteLine("Add an extra message, because why not");

Console.ForegroundColor = ConsoleColor.Blue;
Console.ForegroundColor = c;
writer.WriteLine(o.Line);
return 2; //signal to the progressbar we wrote two messages
}
Console.ForegroundColor = ConsoleColor.Blue;
Console.ForegroundColor = c;
writer.WriteLine(o.Line);
return 1;
}
};
var wait = TimeSpan.FromSeconds(5);
var wait = TimeSpan.FromSeconds(6);
using (var pbar = new FixedDurationBar(wait, "", options))
{
var t = new Thread(()=> LongRunningTask(pbar));
t.Start();

if (!pbar.CompletedHandle.WaitOne(wait))
Console.Error.WriteLine($"{nameof(FixedDurationBar)} did not signal {nameof(FixedDurationBar.CompletedHandle)} after {wait}");
if (!pbar.CompletedHandle.WaitOne(wait.Subtract(TimeSpan.FromSeconds(.5))))
pbar.WriteErrorLine($"{nameof(FixedDurationBar)} did not signal {nameof(FixedDurationBar.CompletedHandle)} after {wait}");

}
}
Expand Down
3 changes: 1 addition & 2 deletions src/ShellProgressBar.Example/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ class Program
{
private static readonly IList<IProgressBarExample> TestCases = new List<IProgressBarExample>
{
new IndeterminateProgressExample(),
new PersistMessageExample(),
new FixedDurationExample(),
new DeeplyNestedProgressBarTreeExample(),
Expand All @@ -27,6 +26,7 @@ class Program
new UpdatesMaxTicksExample(),
new NeverTicksExample(),
new EstimatedDurationExample(),
new IndeterminateProgressExample(),
};

private static readonly IList<IProgressBarExample> Examples = new List<IProgressBarExample>
Expand Down Expand Up @@ -96,7 +96,6 @@ private static async Task RunTestCases(CancellationToken token)
await example.Start(token);
i++;
}

Console.Write("Shown all examples!");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ public Task Start(CancellationToken token)

var overProgressOptions = new ProgressBarOptions
{
DenseProgressBar = true,
ProgressCharacter = '─',
BackgroundColor = ConsoleColor.DarkGray,
EnableTaskBarProgress = RuntimeInformation.IsOSPlatform(OSPlatform.Windows),
};
Expand All @@ -23,6 +25,7 @@ public Task Start(CancellationToken token)
{
var stepBarOptions = new ProgressBarOptions
{
DenseProgressBar = true,
ForegroundColor = ConsoleColor.Cyan,
ForegroundColorDone = ConsoleColor.DarkGreen,
ProgressCharacter = '─',
Expand All @@ -33,6 +36,7 @@ public Task Start(CancellationToken token)
{
var workBarOptions = new ProgressBarOptions
{
DenseProgressBar = true,
ForegroundColor = ConsoleColor.Yellow,
ProgressCharacter = '─',
BackgroundColor = ConsoleColor.DarkGray,
Expand Down
6 changes: 6 additions & 0 deletions src/ShellProgressBar.sln
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
..\README.md = ..\README.md
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShellProgressBar.Tests", "..\test\ShellProgressBar.Tests\ShellProgressBar.Tests.csproj", "{7F6B9B22-0375-46C4-ADEB-30F5BF6DB7B2}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -33,6 +35,10 @@ Global
{25EEC6B1-4113-41F4-8181-674E4855F40A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{25EEC6B1-4113-41F4-8181-674E4855F40A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{25EEC6B1-4113-41F4-8181-674E4855F40A}.Release|Any CPU.Build.0 = Release|Any CPU
{7F6B9B22-0375-46C4-ADEB-30F5BF6DB7B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7F6B9B22-0375-46C4-ADEB-30F5BF6DB7B2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7F6B9B22-0375-46C4-ADEB-30F5BF6DB7B2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7F6B9B22-0375-46C4-ADEB-30F5BF6DB7B2}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
5 changes: 3 additions & 2 deletions src/ShellProgressBar/FixedDurationBar.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ public class FixedDurationBar : ProgressBar

public FixedDurationBar(TimeSpan duration, string message, ConsoleColor color) : this(duration, message, new ProgressBarOptions {ForegroundColor = color}) { }

public FixedDurationBar(TimeSpan duration, string message, ProgressBarOptions options = null) : base((int)Math.Ceiling(duration.TotalSeconds), message, options)
public FixedDurationBar(TimeSpan duration, string message, ProgressBarOptions options = null)
: base((int)Math.Ceiling(duration.TotalSeconds) * 2, message, options)
{
if (!this.Options.DisplayTimeInRealTime)
throw new ArgumentException(
Expand All @@ -24,7 +25,7 @@ public FixedDurationBar(TimeSpan duration, string message, ProgressBarOptions o
protected override void OnTimerTick()
{
Interlocked.Increment(ref _seenTicks);
if (_seenTicks % 2 == 0) this.Tick();
this.Tick();
base.OnTimerTick();
}

Expand Down
83 changes: 73 additions & 10 deletions src/ShellProgressBar/ProgressBar.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,22 @@ public ProgressBar(int maxTicks, string message, ConsoleColor color)
public ProgressBar(int maxTicks, string message, ProgressBarOptions options = null)
: base(maxTicks, message, options)
{
_originalCursorTop = Console.CursorTop;
_originalWindowTop = Console.WindowTop;
_originalWindowHeight = Console.WindowHeight + _originalWindowTop;
_originalColor = Console.ForegroundColor;

_writeMessageToConsole = this.Options.WriteQueuedMessage ?? DefaultConsoleWrite;
_startedRedirected = Console.IsOutputRedirected;

try
{
_originalCursorTop = Console.CursorTop;
_originalWindowTop = Console.WindowTop;
_originalWindowHeight = Console.WindowHeight + _originalWindowTop;
_originalColor = Console.ForegroundColor;
}
catch
{
_startedRedirected = true;
}

if (!_startedRedirected)
Console.CursorVisible = false;

Expand Down Expand Up @@ -94,7 +102,8 @@ protected override void Grow(ProgressBarHeight direction)

private void EnsureMainProgressBarVisible(int extraBars = 0)
{
var neededPadding = Math.Min(_originalWindowHeight - 2, (1 + extraBars) * 2);
var pbarHeight = this.Options.DenseProgressBar ? 1 : 2;
var neededPadding = Math.Min(_originalWindowHeight - pbarHeight, (1 + extraBars) * pbarHeight);
var difference = _originalWindowHeight - _originalCursorTop;
var write = difference <= neededPadding ? Math.Max(0, Math.Max(neededPadding, difference)) : 0;

Expand Down Expand Up @@ -123,6 +132,38 @@ public Indentation(ConsoleColor color, bool lastChild)
public readonly bool LastChild;
}

private static void CondensedProgressBar(
double percentage,
string message,
char progressCharacter,
char? progressBackgroundCharacter,
ConsoleColor? backgroundColor,
Indentation[] indentation,
bool progressBarOnTop)
{
var depth = indentation.Length;
var messageWidth = 30;
var maxCharacterWidth = Console.WindowWidth - (depth * 2) + 2;
var truncatedMessage = StringExtensions.Excerpt(message, messageWidth - 2) + " ";
var width = (Console.WindowWidth - (depth * 2) + 2) - truncatedMessage.Length;


var newWidth = (int) ((width * percentage) / 100d);
var progBar = new string(progressCharacter, newWidth);
DrawBottomHalfPrefix(indentation, depth);
Console.Write(truncatedMessage);
Console.Write(progBar);
if (backgroundColor.HasValue)
{
Console.ForegroundColor = backgroundColor.Value;
Console.Write(new string(progressBackgroundCharacter ?? progressCharacter, width - newWidth));
}
else Console.Write(new string(' ', width - newWidth));

Console.ForegroundColor = indentation[depth - 1].ConsoleColor;
}


private static void ProgressBarBottomHalf(double percentage, DateTime startDate, DateTime? endDate,
string message, Indentation[] indentation, bool progressBarOnBottom, bool showEstimatedDuration,
TimeSpan estimatedDuration, bool disableBottomPercentage)
Expand Down Expand Up @@ -244,7 +285,6 @@ private void UpdateProgress()
for (var i = 0; i < 5 && _stickyMessages.TryDequeue(out var m); i++)
WriteConsoleLine(m);


if (_startedRedirected) return;

Console.CursorVisible = false;
Expand All @@ -265,8 +305,19 @@ void TopHalf()
);
}

if (this.Options.DenseProgressBar)
{
CondensedProgressBar(mainPercentage,
this.Message,
this.Options.ProgressCharacter,
this.Options.BackgroundCharacter,
this.Options.BackgroundColor,
indentation,
this.Options.ProgressBarOnBottom
);

if (this.Options.ProgressBarOnBottom)
}
else if (this.Options.ProgressBarOnBottom)
{
ProgressBarBottomHalf(mainPercentage, this._startDate, null, this.Message, indentation,
this.Options.ProgressBarOnBottom, Options.ShowEstimatedDuration, EstimatedDuration, this.Options.DisableBottomPercentage);
Expand Down Expand Up @@ -358,7 +409,18 @@ void TopHalf()

Console.SetCursorPosition(0, ++cursorTop);

if (child.Options.ProgressBarOnBottom)
if (child.Options.DenseProgressBar)
{
CondensedProgressBar(percentage,
child.Message,
child.Options.ProgressCharacter,
child.Options.BackgroundCharacter,
child.Options.BackgroundColor,
childIndentation,
child.Options.ProgressBarOnBottom
);
}
else if (child.Options.ProgressBarOnBottom)
{
ProgressBarBottomHalf(percentage, child.StartDate, child.EndTime, child.Message, childIndentation,
child.Options.ProgressBarOnBottom, child.Options.ShowEstimatedDuration,
Expand Down Expand Up @@ -423,8 +485,9 @@ public void Dispose()

try
{
var openDescendantsPadding = (_visibleDescendants * 2);
var newCursorTop = Math.Min(_originalWindowHeight, _originalCursorTop + 2 + openDescendantsPadding);
var pbarHeight = this.Options.DenseProgressBar ? 1 : 2;
var openDescendantsPadding = (_visibleDescendants * pbarHeight);
var newCursorTop = Math.Min(_originalWindowHeight, _originalCursorTop + pbarHeight + openDescendantsPadding);
Console.CursorVisible = true;
Console.SetCursorPosition(0, newCursorTop);
}
Expand Down
5 changes: 5 additions & 0 deletions src/ShellProgressBar/ProgressBarOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ public class ProgressBarOptions
/// </summary>
public bool ProgressBarOnBottom { get; set; }

/// <summary>
/// Progressbar is written on a single line
/// </summary>
public bool DenseProgressBar { get; set; }

/// <summary>
/// Whether to show the estimated time. It can be set when
/// <see cref="ProgressBarBase.Tick"/> is called or the property
Expand Down
28 changes: 28 additions & 0 deletions test/ShellProgressBar.Tests/ShellProgressBar.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>

<IsPackable>false</IsPackable>

<LangVersion>latest</LangVersion>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="1.3.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\ShellProgressBar\ShellProgressBar.csproj" />
</ItemGroup>

</Project>
16 changes: 16 additions & 0 deletions test/ShellProgressBar.Tests/UnitTest1.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;
using Xunit;

namespace ShellProgressBar.Tests
{
public class UnitTest1
{
[Fact]
public void Test1()
{
using var pbar = new ProgressBar(1000, "task");
pbar.Tick();
pbar.WriteLine("Asdad");
}
}
}

0 comments on commit 7606766

Please sign in to comment.