-
Notifications
You must be signed in to change notification settings - Fork 236
/
draw_target.rs
470 lines (426 loc) · 14.9 KB
/
draw_target.rs
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
use std::io;
use std::sync::{Arc, RwLock, RwLockWriteGuard};
use std::time::Instant;
use console::Term;
use crate::multi::{MultiProgressAlignment, MultiProgressState};
use crate::TermLike;
/// Target for draw operations
///
/// This tells a progress bar or a multi progress object where to paint to.
/// The draw target is a stateful wrapper over a drawing destination and
/// internally optimizes how often the state is painted to the output
/// device.
#[derive(Debug)]
pub struct ProgressDrawTarget {
kind: ProgressDrawTargetKind,
}
impl ProgressDrawTarget {
/// Draw to a buffered stdout terminal at a max of 15 times a second.
///
/// For more information see `ProgressDrawTarget::to_term`.
pub fn stdout() -> ProgressDrawTarget {
ProgressDrawTarget::term(Term::buffered_stdout(), 15)
}
/// Draw to a buffered stderr terminal at a max of 15 times a second.
///
/// This is the default draw target for progress bars. For more
/// information see `ProgressDrawTarget::to_term`.
pub fn stderr() -> ProgressDrawTarget {
ProgressDrawTarget::term(Term::buffered_stderr(), 15)
}
/// Draw to a buffered stdout terminal at a max of `refresh_rate` times a second.
///
/// For more information see `ProgressDrawTarget::to_term`.
pub fn stdout_with_hz(refresh_rate: u64) -> ProgressDrawTarget {
ProgressDrawTarget::term(Term::buffered_stdout(), refresh_rate)
}
/// Draw to a buffered stderr terminal at a max of `refresh_rate` times a second.
///
/// For more information see `ProgressDrawTarget::to_term`.
pub fn stderr_with_hz(refresh_rate: u64) -> ProgressDrawTarget {
ProgressDrawTarget::term(Term::buffered_stderr(), refresh_rate)
}
/// Draw to a buffered stdout terminal without max framerate.
///
/// This is useful when data is known to come in very slowly and
/// not rendering some updates would be a problem (for instance
/// when messages are used extensively).
///
/// For more information see `ProgressDrawTarget::to_term`.
pub fn stdout_nohz() -> ProgressDrawTarget {
ProgressDrawTarget::term(Term::buffered_stdout(), None)
}
/// Draw to a buffered stderr terminal without max framerate.
///
/// This is useful when data is known to come in very slowly and
/// not rendering some updates would be a problem (for instance
/// when messages are used extensively).
///
/// For more information see `ProgressDrawTarget::to_term`.
pub fn stderr_nohz() -> ProgressDrawTarget {
ProgressDrawTarget::term(Term::buffered_stderr(), None)
}
pub(crate) fn new_remote(state: Arc<RwLock<MultiProgressState>>, idx: usize) -> Self {
Self {
kind: ProgressDrawTargetKind::Remote { state, idx },
}
}
/// Draw to a terminal, optionally with a specific refresh rate.
///
/// Progress bars are by default drawn to terminals however if the
/// terminal is not user attended the entire progress bar will be
/// hidden. This is done so that piping to a file will not produce
/// useless escape codes in that file.
///
/// Will panic if refresh_rate is `Some(0)`. To disable rate limiting use `None` instead.
#[allow(clippy::wrong_self_convention)]
#[deprecated(since = "0.16.0", note = "Use `ProgressDrawTarget::term` instead")]
pub fn to_term(term: Term, refresh_rate: impl Into<Option<u64>>) -> ProgressDrawTarget {
ProgressDrawTarget::term(term, refresh_rate)
}
/// Draw to a terminal, optionally with a specific refresh rate.
///
/// Progress bars are by default drawn to terminals however if the
/// terminal is not user attended the entire progress bar will be
/// hidden. This is done so that piping to a file will not produce
/// useless escape codes in that file.
///
/// Will panic if refresh_rate is `Some(0)`. To disable rate limiting use `None` instead.
pub fn term(term: Term, refresh_rate: impl Into<Option<u64>>) -> ProgressDrawTarget {
ProgressDrawTarget {
kind: ProgressDrawTargetKind::Term {
term,
last_line_count: 0,
leaky_bucket: refresh_rate.into().map(|rate| LeakyBucket {
bucket: MAX_GROUP_SIZE,
leak_rate: rate as f64,
last_update: Instant::now(),
}),
draw_state: ProgressDrawState::new(Vec::new(), false),
},
}
}
/// Draw to a boxed object that implements the [`TermLike`] trait.
pub fn term_like(term_like: Box<dyn TermLike>) -> ProgressDrawTarget {
ProgressDrawTarget {
kind: ProgressDrawTargetKind::TermLike {
inner: term_like,
last_line_count: 0,
draw_state: ProgressDrawState::new(Vec::new(), false),
},
}
}
/// A hidden draw target.
///
/// This forces a progress bar to be not rendered at all.
pub fn hidden() -> ProgressDrawTarget {
ProgressDrawTarget {
kind: ProgressDrawTargetKind::Hidden,
}
}
/// Returns true if the draw target is hidden.
///
/// This is internally used in progress bars to figure out if overhead
/// from drawing can be prevented.
pub fn is_hidden(&self) -> bool {
match self.kind {
ProgressDrawTargetKind::Hidden => true,
ProgressDrawTargetKind::Term { ref term, .. } => !term.is_term(),
_ => false,
}
}
/// Returns the current width of the draw target.
pub(crate) fn width(&self) -> usize {
match self.kind {
ProgressDrawTargetKind::Term { ref term, .. } => term.size().1 as usize,
ProgressDrawTargetKind::Remote { ref state, .. } => state.read().unwrap().width(),
ProgressDrawTargetKind::Hidden => 0,
ProgressDrawTargetKind::TermLike { ref inner, .. } => inner.width(),
}
}
/// Apply the given draw state (draws it).
pub(crate) fn drawable(&mut self, force_draw: bool) -> Option<Drawable<'_>> {
match &mut self.kind {
ProgressDrawTargetKind::Term {
term,
last_line_count,
leaky_bucket,
draw_state,
} => {
let has_capacity = leaky_bucket
.as_mut()
.map(|b| b.try_add_work())
.unwrap_or(true);
draw_state.force_draw = force_draw;
match force_draw || has_capacity {
true => Some(Drawable::Term {
term,
last_line_count,
draw_state,
}),
false => None, // rate limited
}
}
ProgressDrawTargetKind::Remote { idx, state, .. } => {
let state = state.write().unwrap();
Some(Drawable::Multi {
idx: *idx,
state,
force_draw,
})
}
ProgressDrawTargetKind::TermLike {
inner,
last_line_count,
draw_state,
} => {
draw_state.force_draw = force_draw;
Some(Drawable::TermLike {
term_like: &**inner,
last_line_count,
draw_state,
})
}
// Hidden, finished, or no need to refresh yet
_ => None,
}
}
/// Properly disconnects from the draw target
pub(crate) fn disconnect(&self) {
match self.kind {
ProgressDrawTargetKind::Term { .. } => {}
ProgressDrawTargetKind::Remote { idx, ref state, .. } => {
let state = state.write().unwrap();
let _ = Drawable::Multi {
state,
idx,
force_draw: true,
}
.clear();
}
ProgressDrawTargetKind::Hidden => {}
ProgressDrawTargetKind::TermLike { .. } => {}
};
}
pub(crate) fn remote(&self) -> Option<(&Arc<RwLock<MultiProgressState>>, usize)> {
match &self.kind {
ProgressDrawTargetKind::Remote { state, idx } => Some((state, *idx)),
_ => None,
}
}
}
#[derive(Debug)]
enum ProgressDrawTargetKind {
Term {
term: Term,
last_line_count: usize,
leaky_bucket: Option<LeakyBucket>,
draw_state: ProgressDrawState,
},
Remote {
state: Arc<RwLock<MultiProgressState>>,
idx: usize,
},
Hidden,
TermLike {
inner: Box<dyn TermLike>,
last_line_count: usize,
draw_state: ProgressDrawState,
},
}
pub(crate) enum Drawable<'a> {
Term {
term: &'a Term,
last_line_count: &'a mut usize,
draw_state: &'a mut ProgressDrawState,
},
Multi {
state: RwLockWriteGuard<'a, MultiProgressState>,
idx: usize,
force_draw: bool,
},
TermLike {
term_like: &'a dyn TermLike,
last_line_count: &'a mut usize,
draw_state: &'a mut ProgressDrawState,
},
}
impl<'a> Drawable<'a> {
pub(crate) fn state(&mut self) -> DrawStateWrapper<'_> {
let mut state = match self {
Drawable::Term { draw_state, .. } => DrawStateWrapper::for_term(draw_state),
Drawable::Multi { state, idx, .. } => state.draw_state(*idx),
Drawable::TermLike { draw_state, .. } => DrawStateWrapper::for_term(draw_state),
};
state.reset();
state
}
pub(crate) fn clear(mut self) -> io::Result<()> {
let state = self.state();
drop(state);
self.draw()
}
pub(crate) fn draw(self) -> io::Result<()> {
match self {
Drawable::Term {
term,
last_line_count,
draw_state,
} => draw_state.draw_to_term(term, last_line_count),
Drawable::Multi {
mut state,
force_draw,
..
} => state.draw(force_draw),
Drawable::TermLike {
term_like,
last_line_count,
draw_state,
} => draw_state.draw_to_term(term_like, last_line_count),
}
}
}
pub(crate) struct DrawStateWrapper<'a> {
state: &'a mut ProgressDrawState,
orphan_lines: Option<&'a mut Vec<String>>,
}
impl<'a> DrawStateWrapper<'a> {
pub(crate) fn for_term(state: &'a mut ProgressDrawState) -> Self {
Self {
state,
orphan_lines: None,
}
}
pub(crate) fn for_multi(
state: &'a mut ProgressDrawState,
orphan_lines: &'a mut Vec<String>,
) -> Self {
Self {
state,
orphan_lines: Some(orphan_lines),
}
}
}
impl std::ops::Deref for DrawStateWrapper<'_> {
type Target = ProgressDrawState;
fn deref(&self) -> &Self::Target {
self.state
}
}
impl std::ops::DerefMut for DrawStateWrapper<'_> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.state
}
}
impl Drop for DrawStateWrapper<'_> {
fn drop(&mut self) {
if let Some(orphaned) = &mut self.orphan_lines {
orphaned.extend(self.state.lines.drain(..self.state.orphan_lines));
self.state.orphan_lines = 0;
}
}
}
#[derive(Debug)]
struct LeakyBucket {
leak_rate: f64,
last_update: Instant,
bucket: f64,
}
/// Rate limit but allow occasional bursts above desired rate
impl LeakyBucket {
/// try to add some work to the bucket
/// return false if the bucket is already full and the work should be skipped
fn try_add_work(&mut self) -> bool {
self.leak();
if self.bucket < MAX_GROUP_SIZE {
self.bucket += 1.0;
true
} else {
false
}
}
fn leak(&mut self) {
let ticks = self.last_update.elapsed().as_secs_f64() * self.leak_rate;
self.bucket -= ticks;
if self.bucket < 0.0 {
self.bucket = 0.0;
}
self.last_update = Instant::now();
}
}
const MAX_GROUP_SIZE: f64 = 32.0;
/// The drawn state of an element.
#[derive(Clone, Debug)]
pub(crate) struct ProgressDrawState {
/// The lines to print (can contain ANSI codes)
pub(crate) lines: Vec<String>,
/// The number of lines that shouldn't be reaped by the next tick.
pub(crate) orphan_lines: usize,
/// True if drawing should be forced.
force_draw: bool,
/// True if we should move the cursor up when possible instead of clearing lines.
pub(crate) move_cursor: bool,
/// Controls how the multi progress is aligned if some of its progress bars get removed, default is `Top`
pub(crate) alignment: MultiProgressAlignment,
}
impl ProgressDrawState {
pub(crate) fn new(lines: Vec<String>, force_draw: bool) -> Self {
Self {
lines,
orphan_lines: 0,
force_draw,
move_cursor: false,
alignment: Default::default(),
}
}
fn draw_to_term(
&mut self,
term: &(impl TermLike + ?Sized),
last_line_count: &mut usize,
) -> io::Result<()> {
if !self.lines.is_empty() && self.move_cursor {
term.move_cursor_up(*last_line_count)?;
} else {
// Fork of console::clear_last_lines that assumes that the last line doesn't contain a '\n'
let n = *last_line_count;
term.move_cursor_up(n.saturating_sub(1))?;
for i in 0..n {
term.clear_line()?;
if i + 1 != n {
term.move_cursor_down(1)?;
}
}
term.move_cursor_up(n.saturating_sub(1))?;
}
let shift = match self.alignment {
MultiProgressAlignment::Bottom if self.lines.len() < *last_line_count => {
let shift = *last_line_count - self.lines.len();
for _ in 0..shift {
term.write_line("")?;
}
shift
}
_ => 0,
};
let len = self.lines.len();
for (idx, line) in self.lines.iter().enumerate() {
if idx + 1 != len {
term.write_line(line)?;
} else {
// Don't append a '\n' if this is the last line
term.write_str(line)?;
// Keep the cursor on the right terminal side
// So that next user writes/prints will happen on the next line
let line_width = console::measure_text_width(line);
term.write_str(&" ".repeat(term.width().saturating_sub(line_width)))?;
}
}
term.flush()?;
*last_line_count = self.lines.len() - self.orphan_lines + shift;
Ok(())
}
fn reset(&mut self) {
self.lines.clear();
self.orphan_lines = 0;
}
}