From d8521be9d270817bb5c78baff799f722990c46ee Mon Sep 17 00:00:00 2001 From: t-bltg Date: Tue, 20 Sep 2022 19:25:03 +0200 Subject: [PATCH] add optional `callback` (#72) --- src/ImageInTerminal.jl | 15 ++++++++------- test/tst_imshow.jl | 13 +++++++++++++ 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/src/ImageInTerminal.jl b/src/ImageInTerminal.jl index 15954ce..cdedfd0 100644 --- a/src/ImageInTerminal.jl +++ b/src/ImageInTerminal.jl @@ -107,24 +107,25 @@ Supported encoding: - ascii (`XTermColors` backend) """ -function imshow(io::IO, img::AbstractArray{<:Colorant}, maxsize::Tuple=displaysize(io)) +function imshow( + io::IO, img::AbstractArray{<:Colorant}, maxsize::Tuple=displaysize(io); kw... +) buf = IOContext(PipeBuffer(), :color => get(io, :color, false)) if choose_sixel(img) sixel_encode(buf, img) else + print_func = (io, x) -> ascii_show(io, x, COLORMODE[], :auto, maxsize; kw...) if ndims(img) > 2 - Base.show_nd( - buf, img, (buf, x) -> ascii_show(buf, x, COLORMODE[], :auto, maxsize), true - ) + Base.show_nd(buf, img, print_func, true) else - ascii_show(buf, img, COLORMODE[], :auto, maxsize) + print_func(buf, img) end end write(io, read(buf, String)) end -imshow(img::AbstractArray{<:Colorant}, args...) = imshow(stdout, img, args...) -imshow(img, args...) = +imshow(img::AbstractArray{<:Colorant}, args...; kw...) = imshow(stdout, img, args...; kw...) +imshow(img, args...; kw...) = throw(ArgumentError("imshow only supports colorant arrays with 1 or 2 dimensions")) sixel_encode(args...; kwargs...) = Sixel.sixel_encode(args...; kwargs...) diff --git a/test/tst_imshow.jl b/test/tst_imshow.jl index dee5d8c..6f0fb45 100644 --- a/test/tst_imshow.jl +++ b/test/tst_imshow.jl @@ -92,4 +92,17 @@ end end end +@testset "callback" begin + img = imresize(mandril, 10, 10) + io = PipeBuffer() + fgcols, bgcols = [], [] + callback(I, fgcol, bgcol, chars...) = begin + push!(fgcols, fgcol) + push!(bgcols, bgcol) + end + @ensurecolor imshow(io, img; callback=callback) + @test length(fgcols) == prod(size(img)) + @test all(ismissing.(bgcols)) +end + set_colormode(8) # reset to default state