-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathProgressBar.cs
97 lines (79 loc) · 3.15 KB
/
ProgressBar.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using System;
using System.Text;
using System.Threading;
namespace UnrealBatchImporter
{
public class ProgressBar : IDisposable, IProgress<double>
{
private const int BlockCount = 10;
private const string Animation = @"|/-\";
private readonly TimeSpan _animationInterval = TimeSpan.FromSeconds(1.0 / 8);
private readonly Timer _timer;
private int _animationIndex;
private double _currentProgress;
private string _currentText = string.Empty;
private bool _disposed;
public string TimeRemainingText;
public ProgressBar()
{
_timer = new Timer(TimerHandler);
// A progress bar is only for temporary display in a console window.
// If the console output is redirected to a file, draw nothing.
// Otherwise, we'll end up with a lot of garbage in the target file.
if (!Console.IsOutputRedirected) ResetTimer();
}
public void Dispose()
{
lock (_timer)
{
_disposed = true;
UpdateText(string.Empty);
}
}
public void Report(double value)
{
// Make sure value is in [0..1] range
value = Math.Max(0, Math.Min(1, value));
Interlocked.Exchange(ref _currentProgress, value);
}
private void TimerHandler(object state)
{
lock (_timer)
{
if (_disposed) return;
var progressBlockCount = (int) (_currentProgress * BlockCount);
var percent = (int) (_currentProgress * 100);
var text =
$"[{new string('#', progressBlockCount)}{new string('-', BlockCount - progressBlockCount)}] {percent,3}% {Animation[_animationIndex++ % Animation.Length]} - Time remaining: {TimeRemainingText}";
UpdateText(text);
ResetTimer();
}
}
private void UpdateText(string text)
{
// Get length of common portion
var commonPrefixLength = 0;
var commonLength = Math.Min(_currentText.Length, text.Length);
while (commonPrefixLength < commonLength && text[commonPrefixLength] == _currentText[commonPrefixLength])
commonPrefixLength++;
// Backtrack to the first differing character
var outputBuilder = new StringBuilder();
outputBuilder.Append('\b', _currentText.Length - commonPrefixLength);
// Output new suffix
outputBuilder.Append(text.Substring(commonPrefixLength));
// If the new text is shorter than the old one: delete overlapping characters
var overlapCount = _currentText.Length - text.Length;
if (overlapCount > 0)
{
outputBuilder.Append(' ', overlapCount);
outputBuilder.Append('\b', overlapCount);
}
Console.Write(outputBuilder);
_currentText = text;
}
private void ResetTimer()
{
_timer.Change(_animationInterval, TimeSpan.FromMilliseconds(-1));
}
}
}