-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathEasyProgressBar.java
More file actions
218 lines (186 loc) · 6.33 KB
/
EasyProgressBar.java
File metadata and controls
218 lines (186 loc) · 6.33 KB
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package roj.ui;
import org.jetbrains.annotations.NotNull;
import roj.concurrent.Timer;
import roj.concurrent.TimerTask;
import roj.optimizer.FastVarHandle;
import roj.reflect.Telescope;
import roj.text.CharList;
import roj.text.TextUtil;
import java.lang.invoke.VarHandle;
/**
* @author Roj234
* @since 2023/10/28 1:55
*/
@FastVarHandle
public class EasyProgressBar extends ProgressBar {
private String unit;
private volatile long completed, total;
private TimerTask updateTask;
private volatile long delta;
private long startTime, lastUpdateTime;
private double avgSpeed;
private static final double ALPHA = 0.2;
private static final int AVG_SPEED_WINDOW = 500;
private static final int INITIAL_THRESHOLD = 5;
private static final double STALE_DECAY_FACTOR = 15000; // ms for exponential decay (e.g., halves roughly every ~10s)
private static final VarHandle
DELTA = Telescope.lookup().findVarHandle(EasyProgressBar.class, "delta", long.class),
COMPLETED = Telescope.lookup().findVarHandle(EasyProgressBar.class, "completed", long.class),
TOTAL = Telescope.lookup().findVarHandle(EasyProgressBar.class, "total", long.class);
public EasyProgressBar() { this(""); }
public EasyProgressBar(String name) { super(name); this.unit = "it"; }
public EasyProgressBar(String name, String unit) { super(name); this.unit = unit; }
public void setUnit(String unit) { this.unit = unit; barTime = 0; }
private void scheduledUpdate() {
if (total == 0 || !Tty.hasBottomLine(line)) {
if (updateTask != null)
updateTask.cancel();
return;
}
increment(0);
}
public void reset() {setTotal(0);}
public void setIndeterminate() {setTotal(-1);}
public void setTotal(long total) {
completed = 0;
this.total = total;
barTime = 0;
startTime = lastUpdateTime = 0;
avgSpeed = Double.NaN;
isProgressUnknown = total < 0;
if (isProgressUnknown) {
prefix = "操作中";
showCenterString = false;
} else {
showCenterString = true;
}
}
public void addTotal(long total) {TOTAL.getAndAdd(this, total);}
public long getFinished() {return completed;}
public long getTotal() {return total;}
public void increment() {increment(1);}
public void increment(long count) {
long prevFin = (long) COMPLETED.getAndAdd(this, count);
long fin = prevFin + count;
long tot = total;
long now = System.currentTimeMillis();
if (count > 0) {
DELTA.getAndAdd(this, count);
// Initialize startTime on first real increment
if (startTime == 0) {
startTime = now;
}
// Update speed only on real progress (count > 0) and if window elapsed
if (now - lastUpdateTime > AVG_SPEED_WINDOW) {
long deltaVal = (long) DELTA.getAndSet(this, 0L);
double timeDiffSec = (now - lastUpdateTime) / 1000.0;
double instSpeed = (timeDiffSec > 0) ? deltaVal / timeDiffSec : 0.0;
if (Double.isNaN(avgSpeed)) {
avgSpeed = getAvgSpeed(now);
} else {
avgSpeed = ALPHA * instSpeed + (1 - ALPHA) * avgSpeed;
}
lastUpdateTime = now;
}
}
long t = barTime;
if (((tot >= 0 && fin < tot || prevFin >= tot) && now - t < BAR_DELAY) || !BAR_TIME.compareAndSet(this, t, now)) return;
if (updateTask == null || updateTask.isCancelled())
updateTask = Timer.getDefault().loop(this::scheduledUpdate, 1000);
setProgress(tot < 0 ? 1 : (double) fin / tot);
}
@Override
protected @NotNull String getCenterString(double progress) {
var fin = completed;
var tot = total;
return (tot < 0
? unit.equals("B") ? TextUtil.scaledNumber1024(fin) : String.valueOf(fin)
: unit.equals("B") ? TextUtil.scaledNumber1024(fin)+"/"+TextUtil.scaledNumber1024(tot) : fin+"/"+tot);
}
@Override
protected @NotNull String getCenterStringColor(boolean filled) {
return String.valueOf(filled ? Tty.BLUE : Tty.CYAN+Tty.HIGHLIGHT);
}
private double getAvgSpeed(long now) {
// Handle initial case or no speed yet: use total elapsed / completed for base speed
if (Double.isNaN(avgSpeed) || avgSpeed <= 0) {
if (completed > 0 && startTime > 0) {
double elapsedSec = (now - startTime) / 1000.0;
if (elapsedSec <= 0) return 0.0;
double baseSpeed = completed / elapsedSec; // items per second
// Apply conservative factor for small samples (slower estimated speed for longer ETA)
double conservativeFactor = 1.0;
if (completed <= INITIAL_THRESHOLD) {
conservativeFactor = 1.0 / (1.0 + (INITIAL_THRESHOLD - completed) * 0.2);
}
return baseSpeed * conservativeFactor * getStaleDecayFactor(now);
}
return 0.0;
}
// For established avgSpeed, apply stale decay if no recent updates
return avgSpeed * getStaleDecayFactor(now);
}
private double getStaleDecayFactor(long now) {
long staleMs = now - lastUpdateTime;
if (staleMs <= AVG_SPEED_WINDOW) {
return 1.0; // No decay if recent update
}
// Exponential decay for stale periods: speed decreases over time without progress
// Ensures ETA increases gradually when stuck, making it feel dynamic
double decayRate = staleMs / STALE_DECAY_FACTOR;
return Math.exp(-decayRate);
}
@Override
protected void renderRight(CharList sb, double progress) {
long now = System.currentTimeMillis();
double speed = getAvgSpeed(now);
String timeUnit = "s";
double displaySpeed = speed;
if (displaySpeed < 1) {
displaySpeed = speed * 60;
timeUnit = "m";
}
if (displaySpeed < 1) {
displaySpeed *= 60;
timeUnit = "h";
}
if (displaySpeed < 1) {
displaySpeed *= 24;
timeUnit = "d";
}
sb.append(" \u001B[92m");
if (unit.equals("B")) {
sb.append(TextUtil.scaledNumber1024((long) displaySpeed));
} else {
sb.append(
displaySpeed < 1000
? TextUtil.toFixed(displaySpeed, 2)
: TextUtil.scaledNumber(Math.round(displaySpeed))
).append(unit);
}
sb.append('/').append(timeUnit);
if (total >= 0) {
sb.append(" \u001B[93mETA: \u001B[94m");
long remaining = total - completed;
double etaSec = remaining / speed;
if (etaSec > 1000000) sb.append('∞');
else if (etaSec > 86400) sb.append(">1d");
else if (etaSec < 1) sb.append("<1s");
else {
int eta = (int) Math.ceil(etaSec);
if (eta >= 3600) {
sb.append(eta / 3600).append('h').append(eta / 60 % 60).append('m');
} else if (eta >= 60) {
sb.append(eta / 60 % 60).append('m').append(eta % 60).append('s');
} else {
sb.append(eta % 60).append('s');
}
}
}
}
@Override
public void end() {
setTotal(0);
super.end();
}
}