From 2af91d2380e77bd6d6f84fc12a4a0a53a88bd9ea Mon Sep 17 00:00:00 2001 From: aptmcl Date: Wed, 30 Oct 2024 10:05:29 +0000 Subject: [PATCH] Reified PNG and PDF files so that they can be viewed in VSCode. --- src/Utils.jl | 44 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/src/Utils.jl b/src/Utils.jl index 2f4f3b9..acdcec8 100644 --- a/src/Utils.jl +++ b/src/Utils.jl @@ -95,7 +95,7 @@ cull(template, as) = # To create paths from paths export path_replace_suffix path_replace_suffix(path::String, suffix::String) = - let (base, old_suffix) = splitext(path) + let (base, _) = splitext(path) base * suffix end @@ -327,3 +327,45 @@ Base.cat(lst::List, lsts::List...) = # Lists can be converted to Arrays Base.convert(::Type{Array{S,1}}, l::List{T}) where {S, T <: S} = collect(T, l) + +# We need a functional way of creating shallow copies of structs where some fields are changed. +copy_with(t::T; kwargs... ) where T = + let fieldnames = fieldnames(T), + nt = NamedTuple{fieldnames, Tuple{fieldtypes(T)...}}([getfield(t, name) for name in fieldnames]) + T(; merge(nt, kwargs.data)...) +end + + +# Different outputs can be generated from the backends +# but we can integrate them with the Julia display system. +export PNGFile, PDFFile + +struct PNGFile path end +struct PDFFile path end + +Base.show(io::IO, ::MIME"image/png", f::PNGFile) = + write(io, read(f.path)) + +Base.show(io::IO, ::MIME"image/svg+xml", f::PDFFile) = + let path = f.path + ! isfile(path) ? + error("Inexisting file $path") : + let svgpath = path_replace_suffix(path, ".svg"), + needs_update = ! isfile(svgpath) || mtime(path) > mtime(svgpath) + if needs_update + let pdftocairo = Sys.which("pdftocairo") + if isnothing(pdftocairo) + error("Could not find pdftocairo. Do you have MikTeX installed?") + else + try + println("Generating $svgpath from $path") + run(`$(pdftocairo) -svg -l 1 $(path) $(svgpath)`, wait=true) + catch e + error("Could not process $path to generate $svgpath.") + end + end + end + end + write(io, read(svgpath)) + end + end