diff --git a/README.md b/README.md index 496c479..3a5a52c 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,80 @@ Progress: 34%|███▃ | ETA: 0:00:02 where the last bar is not yet fully filled. +### Customizing the status line + +The status line is made of *elements*, which can be rearranged or extended by passing a +tuple as `elements`. The elements live in the exported module `Elements` (`using +ProgressMeter.Elements` brings their names into scope). Every element is a subtype of +`Elements.AbstractProgressElement` that returns its text from +`Elements.print_element(element, p)`, where `p` is the progress meter. Besides its usual +fields (`p.counter`, `p.desc`, ...), `p.tcurrent` holds the `time()` of the redraw, `p.tinit` +the time the meter was created and `p.finished` whether this is the final redraw. Plain +strings can be used as separators. `print_element` is only called when the meter is +redrawn (at most every `dt` seconds), so elements can compute what they show on the fly. + +This is most useful to show information about the computation whose progress is being +tracked, e.g. a statistic of the data being processed or a diagnostic of a running +simulation. Give the element a reference to that data when constructing it, and it will +show the current state on every redraw. Here `MaxValue` holds the vector `data` that the +loop fills, so the line shows its maximum so far: + +```julia +mutable struct MaxValue <: Elements.AbstractProgressElement + data::Vector{Float64} +end + +Elements.print_element(e::MaxValue, p) = " max = $(round(maximum(e.data), digits=2))" + +data = zeros(100) +p = Progress(length(data); desc = "Sampling:", barlen = 20, + elements = (Elements.Description(), Elements.Percentage(), + Elements.Bar(), Elements.ETA(), MaxValue(data))) +for i in eachindex(data) + data[i] = i / 10 + next!(p) +end +``` + +``` +Sampling: 42%|████████▍ | ETA: 0:00:01 max = 4.2 +``` + +The built-in elements are + +| Element | Shows | Meters | +|---|---|---| +| `Description()` | `desc`, followed by a space | all | +| `Percentage()` | ` 42%` | `Progress` | +| `Bar()` | the bar; `barlen=nothing` fills the width the other elements leave | `Progress` | +| `ETA()` | ` ETA: 0:00:01`, or ` Time: 0:00:02` once finished | `Progress` | +| `Speed()` | ` (12.34 ms/it)` | all | +| `ElapsedTime()` | `0:00:02` | all | +| `Counter()` | the number of iterations | all | +| `Threshold()` | `(thresh = 0.1, value = 0.5)` | `ProgressThresh` | +| `Spinner()` | a spinning character | `ProgressUnknown` | +| `Colored(element, color)` | `element` in `color` | all | + +All elements are printed in the meter's `color`, unless wrapped in `Colored`. `color` is a +`Symbol` or an `Int` (0-255) as for `printstyled`, e.g. + +```julia +using ProgressMeter.Elements +p = Progress(100; elements = (Colored(Description(), :blue), Percentage(), + Bar(), Colored(ETA(), :light_black))) +``` + +Without `elements` the layout is determined by `desc`, `showspeed` and, for +`ProgressUnknown`, `spinner`. For example, `Progress(n; showspeed=true)` corresponds to + +```julia +Progress(n; elements = (Elements.Description(), Elements.Percentage(), + Elements.Bar(), Elements.ETA(), Elements.Speed())) +``` + +except that the default bar length is estimated rather than measured, so the bar may differ +in length by a few characters. + ### Progress meters for tasks with a target threshold Some tasks only terminate when some criterion is satisfied, for diff --git a/src/ProgressMeter.jl b/src/ProgressMeter.jl index 5557166..78256af 100644 --- a/src/ProgressMeter.jl +++ b/src/ProgressMeter.jl @@ -2,7 +2,7 @@ module ProgressMeter using Printf: @sprintf -export Progress, ProgressThresh, ProgressUnknown, BarGlyphs, next!, update!, cancel, finish!, @showprogress, progress_map, progress_pmap, ijulia_behavior +export Progress, ProgressThresh, ProgressUnknown, BarGlyphs, next!, update!, cancel, finish!, @showprogress, progress_map, progress_pmap, ijulia_behavior, Elements """ `ProgressMeter` contains a suite of utilities for displaying progress @@ -74,6 +74,7 @@ Base.@kwdef mutable struct ProgressCore{O<:IO} offset::Int = 0 # position offset of progress bar (default is 0) output::O = stderr # output stream into which the progress is written showspeed::Bool = false # should the output include average time per iteration + elements::Union{Nothing,Tuple} = nothing # elements of the status line, `nothing` for the default layout # internals check_iterations::Int = 1 # number of iterations to check time for counter::Int = 0 # current iteration @@ -86,12 +87,14 @@ Base.@kwdef mutable struct ProgressCore{O<:IO} tinit::Float64 = time() # time meter was initialized tlast::Float64 = time() # time of last update tsecond::Float64 = time() # ignore the first loop given usually uncharacteristically slow + tcurrent::Float64 = time() # time of the current redraw, read by the elements + finished::Bool = false # true while drawing the final status line end # the default outer constructor of a parametric struct does not convert its # arguments, unlike the parametrized one: route through it so that `dt=1` or # `offset=Int16(2)` keep working -ProgressCore(color, desc, dt, enabled, offset, output::O, showspeed, internals::Vararg{Any,11}) where O<:IO = - ProgressCore{O}(color, desc, dt, enabled, offset, output, showspeed, internals...) +ProgressCore(color, desc, dt, enabled, offset, output::O, showspeed, elements, internals::Vararg{Any,13}) where O<:IO = + ProgressCore{O}(color, desc, dt, enabled, offset, output, showspeed, elements, internals...) # `stderr` is a typed global of *abstract* type `IO`, so parametrizing on # `typeof(stderr)` would make the default constructors type-unstable and turn @@ -113,6 +116,9 @@ iteration takes longer than `dt`. `desc` is a description of the current task. Optionally you can disable the progress bar by setting `enabled=false`. You can also append a per-iteration average duration like "(12.34 ms/it)" to the description by setting `showspeed=true`. +To customize the status line pass a tuple of `elements`, e.g. +`elements=(Elements.Description(), Elements.Bar(), " ", MyElement())`, +see [`ProgressMeter.Elements`](@ref). """ mutable struct Progress{O<:IO} <: AbstractProgress n::Int # total number of iterations @@ -151,7 +157,8 @@ apart, and perhaps longer if each iteration takes longer than `dt`. `desc` is a description of the current task. Optionally you can disable the progress meter by setting `enabled=false`. You can also append a per-iteration average duration like "(12.34 ms/it)" to the description by -setting `showspeed=true`. +setting `showspeed=true`. The status line can be customized with `elements`, +see [`ProgressMeter.Elements`](@ref). """ mutable struct ProgressThresh{T<:Real, O<:IO} <: AbstractProgress thresh::T # termination threshold @@ -170,6 +177,11 @@ function ProgressThresh{T}(thresh; val::T=typemax(T), triggered::Bool=false, out end ProgressThresh(thresh::Real; kwargs...) = ProgressThresh{typeof(thresh)}(thresh; kwargs...) +const spinner_chars = ['◐','◓','◑','◒'] +const spinner_done = '✓' +# spinner characters can be given as a single character, a string or a vector of characters +const SpinnerTypes = Union{AbstractChar,AbstractString,AbstractVector{<:AbstractChar}} + """ `prog = ProgressUnknown(; dt=0.1, desc="Progress: ", color=:green, output=stderr)` creates a progress meter for a task @@ -181,17 +193,20 @@ the progress meter by setting `enabled=false`. You can also append a per-iteration average duration like "(12.34 ms/it)" to the description by setting `showspeed=true`. Instead of displaying a counter, it can optionally display a spinning ball by passing `spinner=true`. +The status line can be customized with `elements`, see +[`ProgressMeter.Elements`](@ref). """ mutable struct ProgressUnknown{O<:IO} <: AbstractProgress # internals done::Bool # is the task done? spinner::Bool # show a spinner spincounter::Int # counter for spinner + spinnerchars::SpinnerTypes # spinner characters of the current update core::ProgressCore{O} # common properties and internals function ProgressUnknown(spinner::Bool, core::ProgressCore{O}) where O<:IO CLEAR_IJULIA[] = clear_ijulia() - new{O}(false, spinner, 0, core) + new{O}(false, spinner, 0, spinner_chars, core) end end function ProgressUnknown(; spinner::Bool=false, output::Union{IO,Nothing}=nothing, kwargs...) @@ -237,6 +252,56 @@ function calc_check_iterations(p, t) return round(Int, clamp(iterations_per_dt, 1, p.check_iterations * 10)) end +# Print the `text => color` segments of a line over the current line, followed by +# `showvalues`. `keep` decides what happens at the end: `true` moves to a new line, `false` +# moves back up to the meter, `nothing` (meter still running) moves back up unless +# `guard_ijulia` is set and IJulia output is being cleared +function draw!(p::AbstractProgress, segments; showvalues = (), + valuecolor = :blue, truncate_lines = false, + keep::Union{Bool,Nothing}, guard_ijulia::Bool) + skip_newlines = guard_ijulia && CLEAR_IJULIA[] + skip_newlines || print_repeat(p.output, "\n", p.offset + p.numprintedvalues) + move_cursor_up_while_clearing_lines(p.output, p.numprintedvalues) + printover(p.output, segments) + printvalues!(p, showvalues; color = valuecolor, truncate = truncate_lines) + if keep === true + println(p.output) + elseif keep === false || !skip_newlines + print_repeat(p.output, "\r\u1b[A", p.offset + p.numprintedvalues) + end + flush(p.output) + return nothing +end + +function draw_finished!(p::AbstractProgress; draw_options...) + p.tcurrent = time() + p.finished = true + draw!(p, render_line(p); draw_options...) +end + +# redraw a running meter if enough iterations and time have passed since the last redraw +function draw_running!(p::AbstractProgress, force::Bool, ignore_predictor::Bool, can_draw::Bool = true; + draw_options...) + if force || ignore_predictor || predicted_updates_per_dt_have_passed(p) + t = time() + if p.counter > 2 + p.check_iterations = calc_check_iterations(p, t) + end + if force || (t > p.tlast + p.dt && can_draw) + p.tcurrent = t + p.finished = false + draw!(p, render_line(p); keep = nothing, draw_options...) + # Compensate for any overhead of printing. This can be + # especially important if you're running over a slow network + # connection. + p.tlast = t + 2*(time()-t) + p.printed = true + p.prev_update_count = p.counter + end + end + return nothing +end + # improve performance by checking if enabled before dealing with the options function updateProgress!(p::AbstractProgress; options...) !p.enabled && return nothing @@ -262,73 +327,14 @@ function _updateProgress!(p::Progress; showvalues = (), p.offset = offset p.color = color p.n = max_steps + draw_options = (; showvalues, valuecolor, truncate_lines, guard_ijulia = true) if p.counter >= p.n if p.counter == p.n && p.printed - t = time() - barlen = p.barlen isa Nothing ? tty_width(p.desc, p.output, p.showspeed) : p.barlen - percentage_complete = 100.0 * p.counter / p.n - percentage_rounded = 100 - bar = barstring(barlen, percentage_complete, barglyphs=p.barglyphs) - elapsed_time = t - p.tinit - dur = durationstring(elapsed_time) - prefix = description_prefix(p.desc) - msg = @sprintf "%s%3u%%%s Time: %s" prefix percentage_rounded bar dur - if p.showspeed - sec_per_iter = elapsed_time / (p.counter - p.start) - msg = @sprintf "%s (%s)" msg speedstring(sec_per_iter) - end - CLEAR_IJULIA[] || print_repeat(p.output, "\n", p.offset + p.numprintedvalues) - move_cursor_up_while_clearing_lines(p.output, p.numprintedvalues) - printover(p.output, msg, p.color) - printvalues!(p, showvalues; color = valuecolor, truncate = truncate_lines) - if keep - println(p.output) - else - print_repeat(p.output, "\r\u1b[A", p.offset + p.numprintedvalues) - end - flush(p.output) + draw_finished!(p; keep, draw_options...) end return nothing end - if force || ignore_predictor || predicted_updates_per_dt_have_passed(p) - t = time() - if p.counter > 2 - p.check_iterations = calc_check_iterations(p, t) - end - if force || (t > p.tlast+p.dt) - barlen = p.barlen isa Nothing ? tty_width(p.desc, p.output, p.showspeed) : p.barlen - percentage_complete = 100.0 * p.counter / p.n - percentage_rounded = min(99, round(Int, percentage_complete)) # don't round up to 100% if not finished (#300) - bar = barstring(barlen, percentage_complete, barglyphs=p.barglyphs) - elapsed_time = t - p.tinit - est_total_time = elapsed_time * (p.n - p.start) / (p.counter - p.start) - if 0 <= est_total_time <= typemax(Int) - eta_sec = round(Int, est_total_time - elapsed_time ) - eta = durationstring(eta_sec) - else - eta = "N/A" - end - prefix = description_prefix(p.desc) - msg = @sprintf "%s%3u%%%s ETA: %s" prefix percentage_rounded bar eta - if p.showspeed - sec_per_iter = elapsed_time / (p.counter - p.start) - msg = @sprintf "%s (%s)" msg speedstring(sec_per_iter) - end - CLEAR_IJULIA[] || print_repeat(p.output, "\n", p.offset + p.numprintedvalues) - move_cursor_up_while_clearing_lines(p.output, p.numprintedvalues) - printover(p.output, msg, p.color) - printvalues!(p, showvalues; color = valuecolor, truncate = truncate_lines) - CLEAR_IJULIA[] || print_repeat(p.output, "\r\u1b[A", p.offset + p.numprintedvalues) - flush(p.output) - # Compensate for any overhead of printing. This can be - # especially important if you're running over a slow network - # connection. - p.tlast = t + 2*(time()-t) - p.printed = true - p.prev_update_count = p.counter - end - end - return nothing + draw_running!(p, force, ignore_predictor; draw_options...) end function _updateProgress!(p::ProgressThresh; showvalues = (), @@ -341,64 +347,15 @@ function _updateProgress!(p::ProgressThresh; showvalues = (), p.thresh = thresh p.color = color p.desc = desc + draw_options = (; showvalues, valuecolor, truncate_lines, guard_ijulia = false) if p.val <= p.thresh && !p.triggered p.triggered = true - if p.printed - t = time() - elapsed_time = t - p.tinit - p.triggered = true - dur = durationstring(elapsed_time) - msg = @sprintf "%s Time: %s (%d iterations)" p.desc dur p.counter - if p.showspeed - sec_per_iter = elapsed_time / p.counter - msg = @sprintf "%s (%s)" msg speedstring(sec_per_iter) - end - print_repeat(p.output, "\n", p.offset + p.numprintedvalues) - move_cursor_up_while_clearing_lines(p.output, p.numprintedvalues) - printover(p.output, msg, p.color) - printvalues!(p, showvalues; color = valuecolor, truncate = truncate_lines) - if keep - println(p.output) - else - print_repeat(p.output, "\r\u1b[A", p.offset + p.numprintedvalues) - end - flush(p.output) - end + p.printed && draw_finished!(p; keep, draw_options...) return nothing end - - if force || ignore_predictor || predicted_updates_per_dt_have_passed(p) - t = time() - if p.counter > 2 - p.check_iterations = calc_check_iterations(p, t) - end - if force || (t > p.tlast+p.dt && !p.triggered) - msg = @sprintf "%s (thresh = %g, value = %g)" p.desc p.thresh p.val - if p.showspeed - elapsed_time = t - p.tinit - sec_per_iter = elapsed_time / p.counter - msg = @sprintf "%s (%s)" msg speedstring(sec_per_iter) - end - print_repeat(p.output, "\n", p.offset + p.numprintedvalues) - move_cursor_up_while_clearing_lines(p.output, p.numprintedvalues) - printover(p.output, msg, p.color) - printvalues!(p, showvalues; color = valuecolor, truncate = truncate_lines) - print_repeat(p.output, "\r\u1b[A", p.offset + p.numprintedvalues) - flush(p.output) - # Compensate for any overhead of printing. This can be - # especially important if you're running over a slow network - # connection. - p.tlast = t + 2*(time()-t) - p.printed = true - p.prev_update_count = p.counter - end - end - return nothing + draw_running!(p, force, ignore_predictor, !p.triggered; draw_options...) end -const spinner_chars = ['◐','◓','◑','◒'] -const spinner_done = '✓' - spinner_char(p::ProgressUnknown, spinner::AbstractChar) = spinner spinner_char(p::ProgressUnknown, spinner::AbstractVector{<:AbstractChar}) = p.done ? spinner_done : spinner[p.spincounter % length(spinner) + firstindex(spinner)] @@ -408,73 +365,19 @@ spinner_char(p::ProgressUnknown, spinner::AbstractString) = function _updateProgress!(p::ProgressUnknown; showvalues = (), truncate_lines = false, valuecolor = :blue, desc = p.desc, ignore_predictor = false, force::Bool = false, - spinner::Union{AbstractChar,AbstractString,AbstractVector{<:AbstractChar}} = spinner_chars, + spinner::SpinnerTypes = spinner_chars, offset::Integer = p.offset, keep = (offset == 0), color = p.color) p.offset = offset p.color = color p.desc = desc + p.spinnerchars = spinner + draw_options = (; showvalues, valuecolor, truncate_lines, guard_ijulia = false) if p.done - if p.printed - t = time() - elapsed_time = t - p.tinit - dur = durationstring(elapsed_time) - if p.spinner - msg = @sprintf "%c %s Time: %s" spinner_char(p, spinner) p.desc dur - p.spincounter += 1 - else - msg = @sprintf "%s %d Time: %s" p.desc p.counter dur - end - if p.showspeed - sec_per_iter = elapsed_time / p.counter - msg = @sprintf "%s (%s)" msg speedstring(sec_per_iter) - end - print_repeat(p.output, "\n", p.offset + p.numprintedvalues) - move_cursor_up_while_clearing_lines(p.output, p.numprintedvalues) - printover(p.output, msg, p.color) - printvalues!(p, showvalues; color = valuecolor, truncate = truncate_lines) - if keep - println(p.output) - else - print_repeat(p.output, "\r\u1b[A", p.offset + p.numprintedvalues) - end - flush(p.output) - end + p.printed && draw_finished!(p; keep, draw_options...) return nothing end - if force || ignore_predictor || predicted_updates_per_dt_have_passed(p) - t = time() - if p.counter > 2 - p.check_iterations = calc_check_iterations(p, t) - end - if force || (t > p.tlast+p.dt) - dur = durationstring(t-p.tinit) - if p.spinner - msg = @sprintf "%c %s Time: %s" spinner_char(p, spinner) p.desc dur - p.spincounter += 1 - else - msg = @sprintf "%s %d Time: %s" p.desc p.counter dur - end - if p.showspeed - elapsed_time = t - p.tinit - sec_per_iter = elapsed_time / p.counter - msg = @sprintf "%s (%s)" msg speedstring(sec_per_iter) - end - print_repeat(p.output, "\n", p.offset + p.numprintedvalues) - move_cursor_up_while_clearing_lines(p.output, p.numprintedvalues) - printover(p.output, msg, p.color) - printvalues!(p, showvalues; color = valuecolor, truncate = truncate_lines) - print_repeat(p.output, "\r\u1b[A", p.offset + p.numprintedvalues) - flush(p.output) - # Compensate for any overhead of printing. This can be - # especially important if you're running over a slow network - # connection. - p.tlast = t + 2*(time()-t) - p.printed = true - p.prev_update_count = p.counter - end - end - return nothing + draw_running!(p, force, ignore_predictor; draw_options...) end predicted_updates_per_dt_have_passed(p::AbstractProgress) = p.counter - p.prev_update_count >= p.check_iterations @@ -564,15 +467,7 @@ function cancel(p::AbstractProgress, msg::AbstractString = "Aborted before all t lock_if_threading(p) do p.offset = offset if p.printed - print_repeat(p.output, "\n", p.offset + p.numprintedvalues) - move_cursor_up_while_clearing_lines(p.output, p.numprintedvalues) - printover(p.output, msg, color) - printvalues!(p, showvalues; color = valuecolor, truncate = truncate_lines) - if keep - println(p.output) - else - print_repeat(p.output, "\r\u1b[A", p.offset + p.numprintedvalues) - end + draw!(p, (msg => color,); showvalues, valuecolor, truncate_lines, keep, guard_ijulia = false) end end return nothing @@ -642,10 +537,10 @@ function move_cursor_up_while_clearing_lines(io, numlinesup) end # `printstyled` cannot be compiled under `--trim`: `with_output_color` calls an -# untyped `f::Function`. this reproduces its output for a plain color: escape -# codes only when `io` advertises color support, applied per line, skipping -# empty lines -function printcolored(io::IO, s::AbstractString, color::Symbol) +# untyped `f::Function`. this reproduces its output for a plain color (a `Symbol` +# or an `Int` 0-255): escape codes only when `io` advertises color support, +# applied per line, skipping empty lines +function printcolored(io::IO, s::AbstractString, color::Union{Symbol,Int}) if !get(io, :color, false)::Bool print(io, s) return nothing @@ -662,9 +557,17 @@ function printcolored(io::IO, s::AbstractString, color::Symbol) return nothing end -function printover(io::IO, s::AbstractString, color::Symbol = :color_normal) - print(io, "\r") - printcolored(io, s, color) +printover(io::IO, s::AbstractString, color::Symbol = :color_normal) = printover(io, (s => color,)) + +# print `text => color` segments over the current line +function printover(io::IO, segments) + # color the segments in a buffer so that the line is written at once + buffer = IOContext(IOBuffer(), :color => get(io, :color, false)::Bool) + print(buffer, "\r") + for (text, color) in segments + printcolored(buffer, text, color) + end + write(io, take!(buffer.io)) if isdefined(Main, :IJulia) # issue #76: circumvent IJulia I/O throttling if pkgversion(Main.IJulia) < v"1.30" @@ -1149,6 +1052,7 @@ function __init__() end end +include("elements.jl") include("deprecated.jl") end # module diff --git a/src/elements.jl b/src/elements.jl new file mode 100644 index 0000000..2383797 --- /dev/null +++ b/src/elements.jl @@ -0,0 +1,213 @@ +""" + ProgressMeter.Elements + +The pieces that make up the status line of a progress meter. Pass a tuple of them as +`elements` to `Progress`, `ProgressThresh` or `ProgressUnknown` to rearrange or extend the +status line, e.g. + +```julia +using ProgressMeter +p = Progress(100; elements = (Elements.Description(), Elements.Percentage(), + Elements.Bar(), Elements.Colored(Elements.ETA(), :blue))) +``` + +`using ProgressMeter.Elements` brings the element names into scope. Define a subtype of +[`AbstractProgressElement`](@ref) with a [`print_element`](@ref) method for a custom element. +""" +module Elements + +using Printf: @sprintf +using ..ProgressMeter: ProgressMeter, AbstractProgress, Progress, ProgressThresh, ProgressUnknown + +export AbstractProgressElement, print_element, Colored, Description, Percentage, Bar, ETA, + Speed, ElapsedTime, Counter, Threshold, Spinner + +""" + AbstractProgressElement + +Supertype for the pieces that make up the status line of a progress meter. A progress +meter concatenates the strings returned by [`print_element`](@ref) for each of its +`elements`. Define a subtype and a `print_element` method to show custom information: + +```julia +mutable struct Accepted <: Elements.AbstractProgressElement + count::Int +end +Elements.print_element(e::Accepted, p) = " accepted: \$(e.count)" + +accepted = Accepted(0) +p = Progress(100; elements = (Elements.Description(), Elements.Percentage(), + Elements.Bar(), Elements.ETA(), accepted)) +``` +""" +abstract type AbstractProgressElement end + +""" + print_element(element, p::AbstractProgress) -> String + +Return the text of `element` for the progress meter `p`. Called once per element each time +the meter is redrawn (at most every `dt` seconds), so this is the place to compute +whatever the element shows. Besides the fields of the meter (e.g. `p.counter`, `p.desc`), +`p.tcurrent` is the `time()` of the redraw, `p.tinit` the time the meter was created and +`p.finished` whether this is the final redraw. Strings are elements that print themselves. +""" +function print_element end +# strings in `elements` act as separators, e.g. " " or " Time: " in the default layouts +print_element(s::AbstractString, ::AbstractProgress) = s + +# seconds since the meter was created, as of the current redraw +elapsed(p::AbstractProgress) = p.tcurrent - p.tinit + +""" + Colored(element, color) + +Print `element` in `color` instead of the color of the meter. `color` is a `Symbol` or an +`Int` (0-255) as accepted by `printstyled`, e.g. `Colored(ETA(), :blue)`. +""" +struct Colored{E} <: AbstractProgressElement + element::E + color::Union{Symbol,Int} +end +print_element(c::Colored, p::AbstractProgress) = print_element(c.element, p) + +element_color(element, p::AbstractProgress) = p.color +element_color(c::Colored, ::AbstractProgress) = c.color + +"""Description of the progress meter (`desc`), followed by a space unless it already ends with one.""" +struct Description <: AbstractProgressElement + pad::Bool # false: print `desc` verbatim +end +Description() = Description(true) +print_element(e::Description, p::AbstractProgress) = e.pad ? ProgressMeter.description_prefix(p.desc) : p.desc + +"""Percentage of completed steps of a `Progress`, e.g. ` 42%`.""" +struct Percentage <: AbstractProgressElement end +function print_element(::Percentage, p::Progress) + # don't round up to 100% if not finished (#300) + percentage = p.finished ? 100 : min(99, round(Int, 100.0 * p.counter / p.n)) + return @sprintf "%3u%%" percentage +end + +""" +The bar of a `Progress`, drawn with the meter's `barglyphs`. Its length is the meter's +`barlen`, or, if that is `nothing`, the terminal width left over by the other elements. +""" +struct Bar <: AbstractProgressElement + legacy_width::Bool # true: estimate the width of the default elements instead of measuring +end +Bar() = Bar(false) +print_element(b::Bar, p::Progress) = render_bar(b, p, 0, 1) + +# the bar inside an element, `nothing` if it isn't a bar; bars are rendered after the other elements +bar(element) = nothing +bar(b::Bar) = b +bar(c::Colored) = bar(c.element) + +function render_bar(b::Bar, p::Progress, width_used::Int, nbars::Int) + barlen = if p.barlen !== nothing + p.barlen + elseif b.legacy_width + ProgressMeter.tty_width(p.desc, p.output, p.showspeed) + else + # leave the last column free so the line doesn't wrap, the two bar ends need 2 columns + max(0, ((displaysize(p.output)::Tuple{Int,Int})[2] - width_used - 1) ÷ nbars - 2) + end + percentage_complete = p.finished ? 100.0 : 100.0 * p.counter / p.n + return ProgressMeter.barstring(barlen, percentage_complete; barglyphs = p.barglyphs) +end + +"""Estimated remaining time of a `Progress`, or the total time once finished.""" +struct ETA <: AbstractProgressElement end +function print_element(::ETA, p::Progress) + elapsed_time = elapsed(p) + p.finished && return " Time: " * ProgressMeter.durationstring(elapsed_time) + est_total_time = elapsed_time * (p.n - p.start) / (p.counter - p.start) + if 0 <= est_total_time <= typemax(Int) + eta = ProgressMeter.durationstring(round(Int, est_total_time - elapsed_time)) + else + eta = "N/A" + end + return " ETA: " * eta +end + +"""Average time per iteration, e.g. ` (12.34 ms/it)`.""" +struct Speed <: AbstractProgressElement end +print_element(::Speed, p::AbstractProgress) = + " (" * ProgressMeter.speedstring(elapsed(p) / iterations(p)) * ")" + +iterations(p::Progress) = p.counter - p.start +iterations(p::AbstractProgress) = p.counter + +"""Time elapsed since the progress meter was created.""" +struct ElapsedTime <: AbstractProgressElement end +print_element(::ElapsedTime, p::AbstractProgress) = ProgressMeter.durationstring(elapsed(p)) + +"""Number of iterations so far.""" +struct Counter <: AbstractProgressElement end +print_element(::Counter, p::AbstractProgress) = string(p.counter) + +"""Threshold and current value of a `ProgressThresh`, or the time and iterations taken once finished.""" +struct Threshold <: AbstractProgressElement end +function print_element(::Threshold, p::ProgressThresh) + p.finished && return @sprintf "Time: %s (%d iterations)" ProgressMeter.durationstring(elapsed(p)) p.counter + return @sprintf "(thresh = %g, value = %g)" p.thresh p.val +end + +"""Spinning character of a `ProgressUnknown`, a check mark once done.""" +struct Spinner <: AbstractProgressElement end +function print_element(::Spinner, p::ProgressUnknown) + c = ProgressMeter.spinner_char(p, p.spinnerchars) + p.spincounter += 1 + return string(c) +end + +end # module Elements + +using .Elements: Elements, Description, Percentage, Bar, ETA, Speed, ElapsedTime, Counter, + Threshold, Spinner, print_element, element_color, bar, render_bar + +# elements reproducing the layout from before elements were introduced; built on every redraw +# so that changes to e.g. `p.showspeed` take effect +function default_elements(p::Progress) + elements = (Description(), Percentage(), Bar(true), ETA()) + return p.showspeed ? (elements..., Speed()) : elements +end + +function default_elements(p::ProgressThresh) + elements = (Description(false), " ", Threshold()) + return p.showspeed ? (elements..., Speed()) : elements +end + +function default_elements(p::ProgressUnknown) + elements = p.spinner ? + (Spinner(), " ", Description(false), " Time: ", ElapsedTime()) : + (Description(false), " ", Counter(), " Time: ", ElapsedTime()) + return p.showspeed ? (elements..., Speed()) : elements +end + +const Segment = Pair{String,Union{Symbol,Int}} + +# Assemble the status line as `text => color` segments; `p.tcurrent` and `p.finished` must be +# set for the current redraw +function render_line(p::AbstractProgress) + elements = something(p.elements, default_elements(p)) + # call `print_element` of every element (built-in or user-defined) to assemble the line; + # bars fill the width the other elements leave, so render those afterwards + texts = map(e -> bar(e) === nothing ? print_element(e, p)::AbstractString : "", elements) + nbars = count(e -> bar(e) !== nothing, elements) + if nbars > 0 + width_used = sum(textwidth, texts; init = 0) + texts = map((e, s) -> bar(e) === nothing ? s : render_bar(bar(e), p, width_used, nbars), elements, texts) + end + # merge neighbouring elements of the same color into one segment + segments = Segment[] + for (e, text) in zip(elements, texts) + color = element_color(e, p) + if !isempty(segments) && last(segments[end]) == color + segments[end] = Segment(first(segments[end]) * text, color) + else + push!(segments, Segment(text, color)) + end + end + return segments +end diff --git a/test/golden_cases.jl b/test/golden_cases.jl new file mode 100644 index 0000000..63b85e6 --- /dev/null +++ b/test/golden_cases.jl @@ -0,0 +1,69 @@ +# Cases rendering progress meters into a fixed-size buffer; used to check that output stays stable. +function capture(f; width = 80, color = false) + io = IOBuffer() + f(IOContext(io, :displaysize => (24, width), :color => color)) + s = String(take!(io)) + # elapsed times and speeds depend on the machine + s = replace(s, r"\d+:\d\d:\d\d" => "H:MM:SS") + s = replace(s, r"(N/A|\s?\d+\.\d\d|>100) +(ns|μs|ms|s|m|hr|d)/it" => "SPEED/it") + return s +end + +# the default glyphs differ on Windows (no partial blocks), pin the non-Windows ones +const GLYPHS = BarGlyphs('|', '█', ['▏', '▎', '▍', '▌', '▋', '▊', '▉'], ' ', '|') + +const GOLDEN_CASES = [ + "progress" => io -> begin + p = Progress(10; desc = "Working:", output = io, barglyphs = GLYPHS) + update!(p, 3; force = true); next!(p; force = true); finish!(p) + end, + "progress_showspeed" => io -> begin + p = Progress(10; desc = "Working:", output = io, showspeed = true, barglyphs = GLYPHS) + update!(p, 3; force = true); finish!(p) + end, + "progress_glyphs_barlen" => io -> begin + p = Progress(10; output = io, barlen = 20, barglyphs = BarGlyphs("[=> ]")) + update!(p, 3; force = true); update!(p, 7; force = true); finish!(p) + end, + "progress_desc_change" => io -> begin + p = Progress(10; desc = "A", output = io, barlen = 30, barglyphs = GLYPHS) + update!(p, 3; force = true); update!(p, 5; desc = "Longer description", force = true); finish!(p) + end, + "progress_nobar_start" => io -> begin + p = Progress(10; output = io, barlen = 0, start = 2, showspeed = true, barglyphs = GLYPHS) + update!(p, 4; force = true); finish!(p) + end, + "progress_max_steps" => io -> begin + p = Progress(10; output = io, barglyphs = GLYPHS) + update!(p, 4; force = true, max_steps = 20); update!(p, 20) + end, + "progress_showvalues_offset" => io -> begin + p = Progress(10; output = io, offset = 1, barglyphs = GLYPHS) + update!(p, 3; force = true, showvalues = [(:a, 1), (:bbb, "x")]) + update!(p, 10; showvalues = () -> [(:a, 2)]) + end, + "progress_cancel" => io -> begin + p = Progress(10; output = io, barglyphs = GLYPHS) + update!(p, 3; force = true); cancel(p) + end, + "progress_color" => io -> begin + p = Progress(10; output = io, color = :red, barlen = 10, barglyphs = GLYPHS) + update!(p, 3; force = true); finish!(p; color = :yellow) + end, + "thresh" => io -> begin + p = ProgressThresh(0.1; desc = "Minimizing:", output = io) + update!(p, 0.5; force = true); update!(p, 0.2; force = true); update!(p, 0.05) + end, + "thresh_showspeed" => io -> begin + p = ProgressThresh(0.1; output = io, showspeed = true) + update!(p, 0.5; force = true); finish!(p) + end, + "unknown" => io -> begin + p = ProgressUnknown(; desc = "Reading:", output = io) + next!(p; force = true); next!(p; force = true); finish!(p) + end, + "unknown_spinner_speed" => io -> begin + p = ProgressUnknown(; desc = "Spinning:", output = io, spinner = true, showspeed = true) + next!(p; force = true); next!(p; force = true, spinner = "ab"); finish!(p) + end, +] diff --git a/test/golden_outputs.jl b/test/golden_outputs.jl new file mode 100644 index 0000000..20f7ace --- /dev/null +++ b/test/golden_outputs.jl @@ -0,0 +1,16 @@ +# Generated from ProgressMeter v1.11.0 output; the refactor must reproduce these exactly. +const GOLDEN_OUTPUTS = Dict( + "progress" => "\rWorking: 30%|████████████▋ | ETA: H:MM:SS\e[K\rWorking: 40%|████████████████▊ | ETA: H:MM:SS\e[K\rWorking: 100%|██████████████████████████████████████████| Time: H:MM:SS\e[K\n", + "progress_showspeed" => "\rWorking: 30%|████████▍ | ETA: H:MM:SS (SPEED/it)\e[K\rWorking: 100%|████████████████████████████| Time: H:MM:SS (SPEED/it)\e[K\n", + "progress_glyphs_barlen" => "\rProgress: 30%[======> ] ETA: H:MM:SS\e[K\rProgress: 70%[==============> ] ETA: H:MM:SS\e[K\rProgress: 100%[====================] Time: H:MM:SS\e[K\n", + "progress_desc_change" => "\rA 30%|█████████ | ETA: H:MM:SS\e[K\rLonger description 50%|██████▌ | ETA: H:MM:SS\e[K\rLonger description 100%|█████████████| Time: H:MM:SS\e[K\n", + "progress_nobar_start" => "\rProgress: 40% ETA: H:MM:SS (SPEED/it)\e[K\rProgress: 100% Time: H:MM:SS (SPEED/it)\e[K\n", + "progress_max_steps" => "\rProgress: 20%|████████▎ | ETA: H:MM:SS\e[K\rProgress: 100%|█████████████████████████████████████████| Time: H:MM:SS\e[K\n", + "progress_showvalues_offset" => "\n\rProgress: 30%|████████████▎ | ETA: H:MM:SS\e[K\r\n a: 1\e[K\r\n bbb: x\e[K\r\e[A\r\e[A\r\e[A\n\n\n\r\e[K\e[A\r\e[K\e[A\rProgress: 100%|█████████████████████████████████████████| Time: H:MM:SS\e[K\r\n a: 2\e[K\r\e[A\r\e[A", + "progress_cancel" => "\rProgress: 30%|████████████▎ | ETA: H:MM:SS\e[K\rAborted before all tasks were completed\e[K\n", + "progress_color" => "\r\e[31mProgress: 30%|███ | ETA: H:MM:SS\e[39m\e[K\r\e[33mProgress: 100%|██████████| Time: H:MM:SS\e[39m\e[K\n", + "thresh" => "\rMinimizing: (thresh = 0.1, value = 0.5)\e[K\rMinimizing: (thresh = 0.1, value = 0.2)\e[K\rMinimizing: Time: H:MM:SS (3 iterations)\e[K\n", + "thresh_showspeed" => "\rProgress: (thresh = 0.1, value = 0.5) (SPEED/it)\e[K\rProgress: Time: H:MM:SS (2 iterations) (SPEED/it)\e[K\n", + "unknown" => "\rReading: 1 Time: H:MM:SS\e[K\rReading: 2 Time: H:MM:SS\e[K\rReading: 2 Time: H:MM:SS\e[K\n", + "unknown_spinner_speed" => "\r◐ Spinning: Time: H:MM:SS (SPEED/it)\e[K\rb Spinning: Time: H:MM:SS (SPEED/it)\e[K\r✓ Spinning: Time: H:MM:SS (SPEED/it)\e[K\n", +) diff --git a/test/runtests.jl b/test/runtests.jl index 95358c8..db84fa6 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -22,6 +22,9 @@ end @testset "Threading" begin include("test_threads.jl") end +@testset "Elements" begin + include("test_elements.jl") +end @testset "Deprecated" begin include("deprecated.jl") end diff --git a/test/test_elements.jl b/test/test_elements.jl new file mode 100644 index 0000000..a4d9081 --- /dev/null +++ b/test/test_elements.jl @@ -0,0 +1,90 @@ +include("golden_cases.jl") +include("golden_outputs.jl") + +@testset "default layout unchanged: $name" for (name, case) in GOLDEN_CASES + @test capture(case; color = name == "progress_color") == GOLDEN_OUTPUTS[name] +end + +mutable struct CountingElement <: Elements.AbstractProgressElement + calls::Int +end +function Elements.print_element(e::CountingElement, p::ProgressMeter.AbstractProgress) + e.calls += 1 + return p.finished ? " done" : " calls=$(e.calls)" +end + +@testset "custom elements" begin + e = CountingElement(0) + out = capture() do io + p = Progress(10; output = io, desc = "Custom:", dt = 1e6, + elements = (Elements.Description(), "[", Elements.Counter(), "]", e)) + for _ in 1:3 + next!(p) # dt too large to redraw + end + @test e.calls == 0 + next!(p; force = true) + @test e.calls == 1 + finish!(p) + end + @test out == "\rCustom: [4] calls=1\e[K\rCustom: [10] done\e[K\n" + + # elements can be set after construction, and work for all progress types + out = capture() do io + p = ProgressThresh(1.0; output = io, elements = (Elements.Threshold(),)) + update!(p, 2.0; force = true) + p.elements = (Elements.Counter(), " iterations") + update!(p, 3.0; force = true) + end + @test out == "\r(thresh = 1, value = 2)\e[K\r2 iterations\e[K" + + out = capture() do io + p = ProgressUnknown(; output = io, elements = (Elements.Spinner(), Elements.Counter())) + next!(p; force = true); finish!(p) + end + @test out == "\r◐1\e[K\r✓1\e[K\n" +end + +@testset "bar width" begin + elements = (Elements.Description(), Elements.Bar(), Elements.Percentage()) + for width in (40, 80) + out = capture(; width) do io + p = Progress(10; output = io, desc = "Bar:", elements) + update!(p, 5; force = true) + end + line = split(out, '\r')[2] + # the bar fills the line except for the last column + @test textwidth(replace(line, "\e[K" => "")) == width - 1 + end + + # a fixed barlen takes precedence + out = capture() do io + p = Progress(10; output = io, barlen = 4, barglyphs = BarGlyphs("[=> ]"), elements) + update!(p, 5; force = true) + end + @test out == "\rProgress: [==> ] 50%\e[K" + + # two bars share the remaining width + out = capture(; width = 31) do io + p = Progress(10; output = io, elements = (Elements.Bar(), "|", Elements.Bar())) + update!(p, 5; force = true) + end + @test textwidth(replace(split(out, '\r')[2], "\e[K" => "")) == 29 +end + +@testset "colors" begin + using ProgressMeter.Elements: Colored, Description, Percentage, Bar + elements = (Colored(Description(), :blue), Percentage(), Colored(Bar(), 208)) + out = capture(; color = true) do io + p = Progress(10; output = io, desc = "Color:", barlen = 4, barglyphs = BarGlyphs("[=> ]"), elements) + update!(p, 5; force = true) + end + # neighbouring elements of the same color share one escape sequence + @test out == "\r\e[34mColor: \e[39m\e[32m 50%\e[39m\e[38;5;208m[==> ]\e[39m\e[K" + + # elements without a color follow the meter's color, also when changed on update + out = capture(; color = true) do io + p = Progress(10; output = io, desc = "Color:", barlen = 0, elements = (Colored(Description(), :blue), Percentage())) + update!(p, 5; force = true, color = :red) + end + @test out == "\r\e[34mColor: \e[39m\e[31m 50%\e[39m\e[K" +end