From 1c2c6f43c856a0f9daaedac953b2a364c2ee20ba Mon Sep 17 00:00:00 2001 From: Milan Kloewer's L3-37 Date: Mon, 5 Oct 2026 12:03:33 +0000 Subject: [PATCH 1/4] Modular, extensible status line via AbstractProgressElement The status line of all progress meters is now assembled from elements (Description, Percentage, Bar, ETA, Speed, ...) rendered by one shared code path instead of six format strings. Users can pass their own elements to customize what is shown without overriding internals (#357). The default layout is unchanged, checked byte for byte by new golden output tests recorded from v1.11.0. --- README.md | 48 +++++ src/ProgressMeter.jl | 415 +++++++++++++++++++++++------------------ test/golden_cases.jl | 66 +++++++ test/golden_outputs.jl | 16 ++ test/runtests.jl | 3 + test/test_elements.jl | 72 +++++++ 6 files changed, 437 insertions(+), 183 deletions(-) create mode 100644 test/golden_cases.jl create mode 100644 test/golden_outputs.jl create mode 100644 test/test_elements.jl diff --git a/README.md b/README.md index 496c479..91451c6 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,54 @@ 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`. Every element is a subtype of `ProgressMeter.AbstractProgressElement` +that returns its text from `ProgressMeter.print_element(element, p, status)`, where `p` is the +progress meter and `status::ProgressMeter.ProgressStatus` holds the time `t` of the +redraw, the `elapsed` seconds and whether the meter is `finished`. 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: + +```julia +mutable struct MaxValue <: ProgressMeter.AbstractProgressElement + data::Vector{Float64} +end + +ProgressMeter.print_element(e::MaxValue, p, status) = " max = $(round(maximum(e.data), digits=2))" + +data = zeros(100) +p = Progress(length(data); desc = "Sampling:", barlen = 20, + elements = (ProgressMeter.Description(), ProgressMeter.Percentage(), + ProgressMeter.Bar(), ProgressMeter.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` | + +Without `elements` the layout is the same as before and determined by `desc`, `showspeed` +and, for `ProgressUnknown`, `spinner`. + ### 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 83795a3..167ce27 100644 --- a/src/ProgressMeter.jl +++ b/src/ProgressMeter.jl @@ -3,6 +3,9 @@ module ProgressMeter using Printf: @sprintf export Progress, ProgressThresh, ProgressUnknown, BarGlyphs, next!, update!, cancel, finish!, @showprogress, progress_map, progress_pmap, ijulia_behavior +@static if VERSION >= v"1.11.0-DEV.469" + eval(Meta.parse("public AbstractProgressElement, ProgressStatus, print_element, Description, Percentage, Bar, ETA, Speed, ElapsedTime, Counter, Threshold, Spinner")) +end """ `ProgressMeter` contains a suite of utilities for displaying progress @@ -73,6 +76,7 @@ Base.@kwdef mutable struct ProgressCore offset::Int = 0 # position offset of progress bar (default is 0) output::IO = 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 @@ -96,6 +100,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=(ProgressMeter.Description(), ProgressMeter.Bar(), " ", MyElement())`, +see [`ProgressMeter.AbstractProgressElement`](@ref). """ mutable struct Progress <: AbstractProgress n::Int # total number of iterations @@ -126,7 +133,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.AbstractProgressElement`](@ref). """ mutable struct ProgressThresh{T<:Real} <: AbstractProgress thresh::T # termination threshold @@ -154,18 +162,24 @@ 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.AbstractProgressElement`](@ref). """ +const spinner_chars = ['◐','◓','◑','◒'] +const spinner_done = '✓' + mutable struct ProgressUnknown <: AbstractProgress # internals done::Bool # is the task done? spinner::Bool # show a spinner spincounter::Int # counter for spinner + spinnerchars::Union{AbstractChar,AbstractString,AbstractVector{<:AbstractChar}} # spinner characters of the current update core::ProgressCore # common properties and internals function ProgressUnknown(; spinner::Bool=false, kwargs...) CLEAR_IJULIA[] = clear_ijulia() core = ProgressCore(;kwargs...) - new(false, spinner, 0, core) + new(false, spinner, 0, spinner_chars, core) end end @@ -208,6 +222,211 @@ function calc_check_iterations(p, t) return round(Int, clamp(iterations_per_dt, 1, p.check_iterations * 10)) end +""" + 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 ProgressMeter.print_element) +for each of its `elements`. Define a subtype and a `print_element` method to show custom +information: + +```julia +mutable struct Accepted <: ProgressMeter.AbstractProgressElement + count::Int +end +ProgressMeter.print_element(e::Accepted, p, status) = " accepted: \$(e.count)" + +accepted = Accepted(0) +p = Progress(100; elements = (ProgressMeter.Description(), ProgressMeter.Percentage(), + ProgressMeter.Bar(), ProgressMeter.ETA(), accepted)) +``` +""" +abstract type AbstractProgressElement end + +""" + ProgressStatus + +Passed to every [`print_element`](@ref ProgressMeter.print_element) call of a redraw. +Fields: `t` (`time()` of the redraw), `elapsed` (seconds since the meter was created) and +`finished` (whether this is the final redraw). +""" +struct ProgressStatus + t::Float64 + elapsed::Float64 + finished::Bool +end +ProgressStatus(p::AbstractProgress, t::Float64, finished::Bool) = ProgressStatus(t, t - p.tinit, finished) + +""" + print_element(element, p::AbstractProgress, status::ProgressStatus) -> 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. Strings are elements that print themselves. +""" +function print_element end +print_element(s::AbstractString, ::AbstractProgress, ::ProgressStatus) = s + +"""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, ::ProgressStatus) = e.pad ? 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, status::ProgressStatus) + # don't round up to 100% if not finished (#300) + percentage = status.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, status::ProgressStatus) = render_bar(b, p, status, 0, 1) + +function render_bar(b::Bar, p::Progress, status::ProgressStatus, width_used::Int, nbars::Int) + barlen = if p.barlen !== nothing + p.barlen + elseif b.legacy_width + 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 = status.finished ? 100.0 : 100.0 * p.counter / p.n + return 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, status::ProgressStatus) + status.finished && return " Time: " * durationstring(status.elapsed) + est_total_time = status.elapsed * (p.n - p.start) / (p.counter - p.start) + if 0 <= est_total_time <= typemax(Int) + eta = durationstring(round(Int, est_total_time - status.elapsed)) + 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, status::ProgressStatus) = + " (" * speedstring(status.elapsed / 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, ::AbstractProgress, status::ProgressStatus) = durationstring(status.elapsed) + +"""Number of iterations so far.""" +struct Counter <: AbstractProgressElement end +print_element(::Counter, p::AbstractProgress, ::ProgressStatus) = 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, status::ProgressStatus) + status.finished && return @sprintf "Time: %s (%d iterations)" durationstring(status.elapsed) 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, ::ProgressStatus) + c = spinner_char(p, p.spinnerchars) + p.spincounter += 1 + return string(c) +end + +# 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 + +function render_line(p::AbstractProgress, status::ProgressStatus) + elements = something(p.elements, default_elements(p)) + # bars fill the width the other elements leave, so render those first + parts = map(e -> e isa Bar ? "" : print_element(e, p, status)::AbstractString, elements) + nbars = count(e -> e isa Bar, elements) + if nbars > 0 + width_used = sum(textwidth, parts; init = 0) + parts = map((e, s) -> e isa Bar ? render_bar(e, p, status, width_used, nbars) : s, elements, parts) + end + return join(parts) +end + +# Print `msg` 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, msg::AbstractString; color = p.color, showvalues = (), + valuecolor = :blue, truncate_lines = false, + keep::Union{Bool,Nothing}, guard_ijulia::Bool) + skip_newlines = guard_ijulia && CLEAR_IJULIA[] + skip_newlines || print(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 === true + println(p.output) + elseif keep === false || !skip_newlines + print(p.output, "\r\u1b[A" ^ (p.offset + p.numprintedvalues)) + end + flush(p.output) + return nothing +end + +function draw_finished!(p::AbstractProgress; draw_options...) + msg = render_line(p, ProgressStatus(p, time(), true)) + draw!(p, msg; 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) + msg = render_line(p, ProgressStatus(p, t, false)) + draw!(p, msg; 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 @@ -233,73 +452,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(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(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(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(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 = (), @@ -312,64 +472,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(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(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(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(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)] @@ -385,67 +496,13 @@ function _updateProgress!(p::ProgressUnknown; showvalues = (), truncate_lines = 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(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(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(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(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 @@ -535,15 +592,7 @@ function cancel(p::AbstractProgress, msg::AbstractString = "Aborted before all t lock_if_threading(p) do p.offset = offset if p.printed - print(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(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 diff --git a/test/golden_cases.jl b/test/golden_cases.jl new file mode 100644 index 0000000..7c07cfa --- /dev/null +++ b/test/golden_cases.jl @@ -0,0 +1,66 @@ +# 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 + +const GOLDEN_CASES = [ + "progress" => io -> begin + p = Progress(10; desc = "Working:", output = io) + 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) + 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) + 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) + update!(p, 4; force = true); finish!(p) + end, + "progress_max_steps" => io -> begin + p = Progress(10; output = io) + update!(p, 4; force = true, max_steps = 20); update!(p, 20) + end, + "progress_showvalues_offset" => io -> begin + p = Progress(10; output = io, offset = 1) + 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) + update!(p, 3; force = true); cancel(p) + end, + "progress_color" => io -> begin + p = Progress(10; output = io, color = :red, barlen = 10) + 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..059ea92 --- /dev/null +++ b/test/test_elements.jl @@ -0,0 +1,72 @@ +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 <: ProgressMeter.AbstractProgressElement + calls::Int +end +function ProgressMeter.print_element(e::CountingElement, p::ProgressMeter.AbstractProgress, status::ProgressMeter.ProgressStatus) + e.calls += 1 + return status.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 = (ProgressMeter.Description(), "[", ProgressMeter.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 = (ProgressMeter.Threshold(),)) + update!(p, 2.0; force = true) + p.elements = (ProgressMeter.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 = (ProgressMeter.Spinner(), ProgressMeter.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 = (ProgressMeter.Description(), ProgressMeter.Bar(), ProgressMeter.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 = (ProgressMeter.Bar(), "|", ProgressMeter.Bar())) + update!(p, 5; force = true) + end + @test textwidth(replace(split(out, '\r')[2], "\e[K" => "")) == 29 +end From b3ab9616ebc9c8c19b155adddafcb8cdd12677bf Mon Sep 17 00:00:00 2001 From: Milan Kloewer's L3-37 Date: Mon, 5 Oct 2026 12:03:33 +0000 Subject: [PATCH 2/4] Address review: SpinnerTypes, comments, README motivation, fix ProgressUnknown docstring The spinner constants sat between the ProgressUnknown docstring and the struct, so the docstring was attached to spinner_chars instead. --- README.md | 20 +++++++++++++++++--- src/ProgressMeter.jl | 14 +++++++++----- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 91451c6..f6b936a 100644 --- a/README.md +++ b/README.md @@ -189,7 +189,13 @@ that returns its text from `ProgressMeter.print_element(element, p, status)`, wh progress meter and `status::ProgressMeter.ProgressStatus` holds the time `t` of the redraw, the `elapsed` seconds and whether the meter is `finished`. 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: +`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 <: ProgressMeter.AbstractProgressElement @@ -226,8 +232,16 @@ The built-in elements are | `Threshold()` | `(thresh = 0.1, value = 0.5)` | `ProgressThresh` | | `Spinner()` | a spinning character | `ProgressUnknown` | -Without `elements` the layout is the same as before and determined by `desc`, `showspeed` -and, for `ProgressUnknown`, `spinner`. +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 = (ProgressMeter.Description(), ProgressMeter.Percentage(), + ProgressMeter.Bar(), ProgressMeter.ETA(), ProgressMeter.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 diff --git a/src/ProgressMeter.jl b/src/ProgressMeter.jl index 167ce27..27f5d54 100644 --- a/src/ProgressMeter.jl +++ b/src/ProgressMeter.jl @@ -151,6 +151,11 @@ mutable struct ProgressThresh{T<:Real} <: AbstractProgress 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 @@ -165,15 +170,12 @@ can optionally display a spinning ball by passing `spinner=true`. The status line can be customized with `elements`, see [`ProgressMeter.AbstractProgressElement`](@ref). """ -const spinner_chars = ['◐','◓','◑','◒'] -const spinner_done = '✓' - mutable struct ProgressUnknown <: AbstractProgress # internals done::Bool # is the task done? spinner::Bool # show a spinner spincounter::Int # counter for spinner - spinnerchars::Union{AbstractChar,AbstractString,AbstractVector{<:AbstractChar}} # spinner characters of the current update + spinnerchars::SpinnerTypes # spinner characters of the current update core::ProgressCore # common properties and internals function ProgressUnknown(; spinner::Bool=false, kwargs...) @@ -265,6 +267,7 @@ the meter is redrawn (at most every `dt` seconds), so this is the place to compu whatever the element shows. 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, ::ProgressStatus) = s """Description of the progress meter (`desc`), followed by a space unless it already ends with one.""" @@ -370,6 +373,7 @@ end function render_line(p::AbstractProgress, status::ProgressStatus) 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 first parts = map(e -> e isa Bar ? "" : print_element(e, p, status)::AbstractString, elements) nbars = count(e -> e isa Bar, elements) @@ -490,7 +494,7 @@ 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 From 5bdde06190ac148471b8c2b81562ffed8aa72da2 Mon Sep 17 00:00:00 2001 From: Milan Kloewer's L3-37 Date: Mon, 5 Oct 2026 12:03:33 +0000 Subject: [PATCH 3/4] Address review: Elements module in own file, ProgressStatus merged into ProgressCore, Colored element - Move elements, default_elements and render_line to src/elements.jl, inside an exported submodule Elements that exports the element names - Remove ProgressStatus: ProgressCore gets tcurrent and finished, set before each redraw; print_element(element, p) now takes two arguments - Add Elements.Colored(element, color); render_line returns text => color segments, merged when neighbours share a color, so the default output is unchanged - printover styles the segments into a buffer and writes the line at once --- README.md | 36 ++++--- src/ProgressMeter.jl | 213 +++++++----------------------------------- src/elements.jl | 213 ++++++++++++++++++++++++++++++++++++++++++ test/test_elements.jl | 36 +++++-- 4 files changed, 296 insertions(+), 202 deletions(-) create mode 100644 src/elements.jl diff --git a/README.md b/README.md index f6b936a..3a5a52c 100644 --- a/README.md +++ b/README.md @@ -184,12 +184,14 @@ 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`. Every element is a subtype of `ProgressMeter.AbstractProgressElement` -that returns its text from `ProgressMeter.print_element(element, p, status)`, where `p` is the -progress meter and `status::ProgressMeter.ProgressStatus` holds the time `t` of the -redraw, the `elapsed` seconds and whether the meter is `finished`. 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. +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 @@ -198,16 +200,16 @@ show the current state on every redraw. Here `MaxValue` holds the vector `data` loop fills, so the line shows its maximum so far: ```julia -mutable struct MaxValue <: ProgressMeter.AbstractProgressElement +mutable struct MaxValue <: Elements.AbstractProgressElement data::Vector{Float64} end -ProgressMeter.print_element(e::MaxValue, p, status) = " max = $(round(maximum(e.data), digits=2))" +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 = (ProgressMeter.Description(), ProgressMeter.Percentage(), - ProgressMeter.Bar(), ProgressMeter.ETA(), MaxValue(data))) + elements = (Elements.Description(), Elements.Percentage(), + Elements.Bar(), Elements.ETA(), MaxValue(data))) for i in eachindex(data) data[i] = i / 10 next!(p) @@ -231,13 +233,23 @@ The built-in elements are | `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 = (ProgressMeter.Description(), ProgressMeter.Percentage(), - ProgressMeter.Bar(), ProgressMeter.ETA(), ProgressMeter.Speed())) +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 diff --git a/src/ProgressMeter.jl b/src/ProgressMeter.jl index 27f5d54..3bbcaac 100644 --- a/src/ProgressMeter.jl +++ b/src/ProgressMeter.jl @@ -2,10 +2,7 @@ module ProgressMeter using Printf: @sprintf -export Progress, ProgressThresh, ProgressUnknown, BarGlyphs, next!, update!, cancel, finish!, @showprogress, progress_map, progress_pmap, ijulia_behavior -@static if VERSION >= v"1.11.0-DEV.469" - eval(Meta.parse("public AbstractProgressElement, ProgressStatus, print_element, Description, Percentage, Bar, ETA, Speed, ElapsedTime, Counter, Threshold, Spinner")) -end +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 @@ -89,6 +86,8 @@ Base.@kwdef mutable struct ProgressCore 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 """ @@ -101,8 +100,8 @@ 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=(ProgressMeter.Description(), ProgressMeter.Bar(), " ", MyElement())`, -see [`ProgressMeter.AbstractProgressElement`](@ref). +`elements=(Elements.Description(), Elements.Bar(), " ", MyElement())`, +see [`ProgressMeter.Elements`](@ref). """ mutable struct Progress <: AbstractProgress n::Int # total number of iterations @@ -134,7 +133,7 @@ apart, and perhaps longer if each iteration takes longer than 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`. The status line can be customized with `elements`, -see [`ProgressMeter.AbstractProgressElement`](@ref). +see [`ProgressMeter.Elements`](@ref). """ mutable struct ProgressThresh{T<:Real} <: AbstractProgress thresh::T # termination threshold @@ -168,7 +167,7 @@ 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.AbstractProgressElement`](@ref). +[`ProgressMeter.Elements`](@ref). """ mutable struct ProgressUnknown <: AbstractProgress # internals @@ -224,176 +223,17 @@ function calc_check_iterations(p, t) return round(Int, clamp(iterations_per_dt, 1, p.check_iterations * 10)) end -""" - 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 ProgressMeter.print_element) -for each of its `elements`. Define a subtype and a `print_element` method to show custom -information: - -```julia -mutable struct Accepted <: ProgressMeter.AbstractProgressElement - count::Int -end -ProgressMeter.print_element(e::Accepted, p, status) = " accepted: \$(e.count)" - -accepted = Accepted(0) -p = Progress(100; elements = (ProgressMeter.Description(), ProgressMeter.Percentage(), - ProgressMeter.Bar(), ProgressMeter.ETA(), accepted)) -``` -""" -abstract type AbstractProgressElement end - -""" - ProgressStatus - -Passed to every [`print_element`](@ref ProgressMeter.print_element) call of a redraw. -Fields: `t` (`time()` of the redraw), `elapsed` (seconds since the meter was created) and -`finished` (whether this is the final redraw). -""" -struct ProgressStatus - t::Float64 - elapsed::Float64 - finished::Bool -end -ProgressStatus(p::AbstractProgress, t::Float64, finished::Bool) = ProgressStatus(t, t - p.tinit, finished) - -""" - print_element(element, p::AbstractProgress, status::ProgressStatus) -> 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. 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, ::ProgressStatus) = s - -"""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, ::ProgressStatus) = e.pad ? 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, status::ProgressStatus) - # don't round up to 100% if not finished (#300) - percentage = status.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, status::ProgressStatus) = render_bar(b, p, status, 0, 1) - -function render_bar(b::Bar, p::Progress, status::ProgressStatus, width_used::Int, nbars::Int) - barlen = if p.barlen !== nothing - p.barlen - elseif b.legacy_width - 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 = status.finished ? 100.0 : 100.0 * p.counter / p.n - return 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, status::ProgressStatus) - status.finished && return " Time: " * durationstring(status.elapsed) - est_total_time = status.elapsed * (p.n - p.start) / (p.counter - p.start) - if 0 <= est_total_time <= typemax(Int) - eta = durationstring(round(Int, est_total_time - status.elapsed)) - 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, status::ProgressStatus) = - " (" * speedstring(status.elapsed / 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, ::AbstractProgress, status::ProgressStatus) = durationstring(status.elapsed) - -"""Number of iterations so far.""" -struct Counter <: AbstractProgressElement end -print_element(::Counter, p::AbstractProgress, ::ProgressStatus) = 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, status::ProgressStatus) - status.finished && return @sprintf "Time: %s (%d iterations)" durationstring(status.elapsed) 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, ::ProgressStatus) - c = spinner_char(p, p.spinnerchars) - p.spincounter += 1 - return string(c) -end - -# 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 - -function render_line(p::AbstractProgress, status::ProgressStatus) - 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 first - parts = map(e -> e isa Bar ? "" : print_element(e, p, status)::AbstractString, elements) - nbars = count(e -> e isa Bar, elements) - if nbars > 0 - width_used = sum(textwidth, parts; init = 0) - parts = map((e, s) -> e isa Bar ? render_bar(e, p, status, width_used, nbars) : s, elements, parts) - end - return join(parts) -end - -# Print `msg` 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, msg::AbstractString; color = p.color, showvalues = (), +# 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(p.output, "\n" ^ (p.offset + p.numprintedvalues)) move_cursor_up_while_clearing_lines(p.output, p.numprintedvalues) - printover(p.output, msg, color) + printover(p.output, segments) printvalues!(p, showvalues; color = valuecolor, truncate = truncate_lines) if keep === true println(p.output) @@ -405,8 +245,9 @@ function draw!(p::AbstractProgress, msg::AbstractString; color = p.color, showva end function draw_finished!(p::AbstractProgress; draw_options...) - msg = render_line(p, ProgressStatus(p, time(), true)) - draw!(p, msg; 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 @@ -418,8 +259,9 @@ function draw_running!(p::AbstractProgress, force::Bool, ignore_predictor::Bool, p.check_iterations = calc_check_iterations(p, t) end if force || (t > p.tlast + p.dt && can_draw) - msg = render_line(p, ProgressStatus(p, t, false)) - draw!(p, msg; keep = nothing, draw_options...) + 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. @@ -596,7 +438,7 @@ function cancel(p::AbstractProgress, msg::AbstractString = "Aborted before all t lock_if_threading(p) do p.offset = offset if p.printed - draw!(p, msg; color, showvalues, valuecolor, truncate_lines, keep, guard_ijulia = false) + draw!(p, (msg => color,); showvalues, valuecolor, truncate_lines, keep, guard_ijulia = false) end end return nothing @@ -667,9 +509,17 @@ function move_cursor_up_while_clearing_lines(io, numlinesup) end end -function printover(io::IO, s::AbstractString, color::Symbol = :color_normal) - print(io, "\r") - printstyled(io, s; color=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) + # style the segments in a buffer so that the line is written at once + buffer = IOContext(IOBuffer(), :color => get(io, :color, false)) + print(buffer, "\r") + for (text, color) in segments + printstyled(buffer, text; color=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" @@ -1145,6 +995,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/test_elements.jl b/test/test_elements.jl index 059ea92..a4d9081 100644 --- a/test/test_elements.jl +++ b/test/test_elements.jl @@ -5,19 +5,19 @@ include("golden_outputs.jl") @test capture(case; color = name == "progress_color") == GOLDEN_OUTPUTS[name] end -mutable struct CountingElement <: ProgressMeter.AbstractProgressElement +mutable struct CountingElement <: Elements.AbstractProgressElement calls::Int end -function ProgressMeter.print_element(e::CountingElement, p::ProgressMeter.AbstractProgress, status::ProgressMeter.ProgressStatus) +function Elements.print_element(e::CountingElement, p::ProgressMeter.AbstractProgress) e.calls += 1 - return status.finished ? " done" : " calls=$(e.calls)" + 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 = (ProgressMeter.Description(), "[", ProgressMeter.Counter(), "]", e)) + elements = (Elements.Description(), "[", Elements.Counter(), "]", e)) for _ in 1:3 next!(p) # dt too large to redraw end @@ -30,22 +30,22 @@ end # elements can be set after construction, and work for all progress types out = capture() do io - p = ProgressThresh(1.0; output = io, elements = (ProgressMeter.Threshold(),)) + p = ProgressThresh(1.0; output = io, elements = (Elements.Threshold(),)) update!(p, 2.0; force = true) - p.elements = (ProgressMeter.Counter(), " iterations") + 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 = (ProgressMeter.Spinner(), ProgressMeter.Counter())) + 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 = (ProgressMeter.Description(), ProgressMeter.Bar(), ProgressMeter.Percentage()) + 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) @@ -65,8 +65,26 @@ end # two bars share the remaining width out = capture(; width = 31) do io - p = Progress(10; output = io, elements = (ProgressMeter.Bar(), "|", ProgressMeter.Bar())) + 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 From 5f5f073d7a76ddf2bc61ac9acf2752818ffa985d Mon Sep 17 00:00:00 2001 From: milankl-claude Date: Mon, 26 Oct 2026 16:29:26 +0000 Subject: [PATCH 4/4] Pin bar glyphs in golden test cases so they pass on Windows --- test/golden_cases.jl | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/test/golden_cases.jl b/test/golden_cases.jl index 7c07cfa..63b85e6 100644 --- a/test/golden_cases.jl +++ b/test/golden_cases.jl @@ -9,13 +9,16 @@ function capture(f; width = 80, color = false) 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) + 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) + p = Progress(10; desc = "Working:", output = io, showspeed = true, barglyphs = GLYPHS) update!(p, 3; force = true); finish!(p) end, "progress_glyphs_barlen" => io -> begin @@ -23,28 +26,28 @@ const GOLDEN_CASES = [ 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) + 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) + 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) + 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) + 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) + 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) + p = Progress(10; output = io, color = :red, barlen = 10, barglyphs = GLYPHS) update!(p, 3; force = true); finish!(p; color = :yellow) end, "thresh" => io -> begin