Skip to content

Commit

Permalink
Implement showable to check that all components are finite (#470)
Browse files Browse the repository at this point in the history
This is useful to avoid conversion errors in advance.
Since `NaN`/`Inf` may be caused by bugs, implicit clamping is not performed.
  • Loading branch information
kimikage authored Apr 10, 2021
1 parent 7e196c2 commit 007a8c8
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Colors.jl
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Base.@deprecate_binding RGB4 RGBX


import Base: ==, +, -, *, /
import Base: convert, eltype, isless, range, show, typemin, typemax
import Base: convert, eltype, isless, range, show, showable, typemin, typemax

# Additional exports, not exported by ColorTypes
export weighted_color_mean,
Expand Down
9 changes: 9 additions & 0 deletions src/display.jl
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@ const max_height = 150
const max_swatch_size = 25
const default_max_swatches = 128 * 128

_isfinite(c::Colorant) = mapreducec(isfinite, &, true, c)

Base.showable(::MIME"image/svg+xml", c::Colorant) = _isfinite(c)
# Note that ImageShow.jl overloads `showable` for `AbstractMatrix{<:Color}`
function Base.showable(::MIME"image/svg+xml", cs::Union{AbstractVector{<:Colorant},
AbstractMatrix{<:Color}})
all(_isfinite, cs)
end

function Base.show(io::IO, mime::MIME"image/svg+xml", c::Color)
write_declaration(io, mime)
write(io,
Expand Down
18 changes: 18 additions & 0 deletions test/display.jl
Original file line number Diff line number Diff line change
@@ -1,4 +1,22 @@
using Test, Colors
using FixedPointNumbers

@testset "Display" begin
@testset "showable" begin
@test showable("image/svg+xml", RGB24(1, 0.5, 0))
@test showable("image/svg+xml", Lab(50.0, 0.0, NaN)) === false
@test showable("image/svg+xml", colormap("Reds", 4))
@test showable("image/svg+xml", [HSVA(30, 1, 1, a) for a = 0.0:0.1:1.0])
@test showable("image/svg+xml", [rand(Gray, 4); Gray(Inf)]) === false
@test showable("image/svg+xml", rand(RGB, 2, 2))
@test showable("image/svg+xml", rand(ARGB, 2, 2)) === false
@test showable("image/svg+xml", rand(HSV, 2, 2, 2)) === false
@test showable("image/svg+xml", Color[RGB(0, 0, 0) HSV(0, 0, 0);
XYZ(0, 0, 0) Luv(0, 0, 0)])
@test showable("image/svg+xml", Color[RGB(0, 0, 0) HSV(0, 0, 0);
XYZ(0, 0, 0) Luv(0, 0, NaN)]) === false
end

function count_element(pattern::Regex, svg::AbstractString)
n = 0
i = firstindex(svg)
Expand Down

0 comments on commit 007a8c8

Please sign in to comment.