Skip to content

Commit

Permalink
add optional callback (#72)
Browse files Browse the repository at this point in the history
  • Loading branch information
t-bltg authored Sep 20, 2022
1 parent 54ec9ea commit d8521be
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
15 changes: 8 additions & 7 deletions src/ImageInTerminal.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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...)
Expand Down
13 changes: 13 additions & 0 deletions test/tst_imshow.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit d8521be

Please sign in to comment.