Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing the use of Ghostscript gs command #68

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@
/docs/site/
/docs/Manifest.toml
test/test_images
examples/out
13 changes: 13 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Examples

To run those examples, clone the project, resolve Julia dependencies and run from the root of this directory:

Example 1:
```
julia examples/readme_example_2.jl
```

Example 2:
```
julia examples/readme_example_2.jl
```
39 changes: 39 additions & 0 deletions examples/readme_example_1.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using Makie
include("../src/MakieTeX.jl")
using .MakieTeX
using CairoMakie # or whichever other backend

# Get Ghostscript path from the environment variable
ghostscript_path = get(ENV, "GHOSTSCRIPT_PATH", "/usr/bin/gs") # Fallback to a default path if not set

# Set MakieTeX to use the custom Ghostscript path
MakieTeX.Ghostscript_jll.gs() = ghostscript_path

# Print to confirm the overridden path
println("Using Ghostscript at: ", MakieTeX.Ghostscript_jll.gs())

fig = Figure()
l1 = LTeX(
fig[1, 1], L"A \emph{convex} function $f \in C$ is \textcolor{blue}{denoted} as \tikz{\draw[line width=1pt, >->] (0, -2pt) arc (-180:0:8pt);}";
tellwidth = false, tellheight = true
)
ax1 = Axis(
fig[2, 1];
)
heatmap!(ax1, Makie.peaks())

display(fig)

# Save the figure to a file in the current directory
output_dir = "examples/out"
output_filename = "output_image_1.png"
img_output_path = joinpath(output_dir, output_filename)

# Check if the directory exists, else create it
if !isdir(output_dir)
println("Directory $output_dir does not exist. Creating it...")
mkdir(output_dir)
end

println("Saving the figure to $img_output_path")
save(img_output_path, fig)
37 changes: 37 additions & 0 deletions examples/readme_example_2.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using Makie
include("../src/MakieTeX.jl")
using .MakieTeX
using CairoMakie # or whichever other backend

println("testing MakieTeX")

# log which tex engine is being used
println("Using TeX engine: $(MakieTeX.CURRENT_TEX_ENGINE[])")

fig = Figure(size = (400, 300), pt_per_unit = 2);
tex1 = LTeX(
fig[1, 1],
L"\int \mathbf E \cdot d\mathbf a = \frac{Q_{encl}}{4\pi\epsilon_0}",
scale=1,
render_density = 2,
);
tex2 = LTeX(
fig[2, 1],
L"\int \mathbf E \cdot d\mathbf a = \frac{Q_{encl}}{4\pi\epsilon_0}",
scale=2,
render_density = 2,
);

# Save the figure to a file in the current directory
output_dir = "examples/out"
output_filename = "output_image_2.png"
img_output_path = joinpath(output_dir, output_filename)

# Check if the directory exists, else create it
if !isdir(output_dir)
println("Directory $output_dir does not exist. Creating it...")
mkdir(output_dir)
end

println("Saving the figure to $img_output_path")
save(img_output_path, fig)
61 changes: 61 additions & 0 deletions flake.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

41 changes: 41 additions & 0 deletions flake.nix
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
description = "Julia environment";

inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-unstable";
flake-utils.url = github:numtide/flake-utils;
};

outputs = { self, nixpkgs, flake-utils, ... }:
flake-utils.lib.eachDefaultSystem (system:
let
# Override the Nix package set to allow unfree packages
pkgs = import nixpkgs {
system = system;
config.allowUnfree = true;
};
# WARN: Nix packaging system doesn't support all packages, so rely on Julia package manager instead.
# Use Julia in REPL mode, then package mode and install packages that way.
julia = pkgs.julia-bin.overrideDerivation (oldAttrs: { doInstallCheck = false; });
in
{
# development environment
devShells.default = pkgs.mkShell {
packages = [
julia
pkgs.ghostscript
# LaTeX
pkgs.texlive.combined.scheme-full
];

shellHook = ''
export JULIA_NUM_THREADS="auto"
export JULIA_PROJECT="."
export JULIA_BINDIR=${julia}/bin
export JULIA_EDITOR="code"
echo "Nix shell loaded."
'';
};
}
);
}
11 changes: 10 additions & 1 deletion src/MakieTeX.jl
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ using DocStringExtensions
using Poppler_jll, Ghostscript_jll, Glib_jll, tectonic_jll
using Rsvg, Cairo

# Define some constants for configuration
# Define some constant references for configuration
"Render with Poppler pipeline (true) or Cairo pipeline (false)"
const RENDER_EXTRASAFE = Ref(false)
"The current `TeX` engine which MakieTeX uses."
Expand All @@ -27,6 +27,15 @@ const _PDFCROP_DEFAULT_MARGINS = Ref{Vector{UInt8}}([0,0,0,0])
"Default density when rendering images"
const RENDER_DENSITY = Ref(3)

# Runtime checks
"Boolean that determines whether the command `gs` (Ghostscript) is available in the shell or not."
const GHOSTSCRIPT_AVAILABLE = if isnothing(Sys.which("gs"))
@warn "Failed to find 'gs' in shell path. Defaulting to use Ghostscript_jll. If this fails, please include Ghostscript command `gs` in current shell."
false
else
true
end

@deprecate TEXT_RENDER_DENSITY RENDER_DENSITY


Expand Down
26 changes: 17 additions & 9 deletions src/rendering/pdf_utils.jl
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,18 @@ This file contains a common core for working with PDFs. It does not contain any
but functions from here are used in the PDF and TeX rendering pipelines.
=#

"""
ghostscript_gs(command_string::String)

Run a Ghostscript command string. If the `gs` command is available in the shell, it will be used. Otherwise, the Ghostscript executable from the `Ghostscript_jll` package will be used.
"""
function ghostscript_gs(command_string::Cmd)
if GHOSTSCRIPT_AVAILABLE
return `gs $command_string`
else
return `$(Ghostscript_jll.gs()) $command_string`
end
end

"""
pdf_num_pages(filename::String)::Int
Expand Down Expand Up @@ -89,11 +101,9 @@ function split_pdf(pdf::Union{Vector{UInt8}, String})
redirect_stderr(devnull) do
redirect_stdout(devnull) do
for i in 1:num_pages
Ghostscript_jll.gs() do gs
run(`$gs -q -dBATCH -dNOPAUSE -dFirstPage=$i -dLastPage=$i -sOutputFile=temp_$(lpad(i, 4, '0')).pdf -sDEVICE=pdfwrite temp.pdf`)
push!(pdfs, read("temp_$(lpad(i, 4, '0')).pdf"))
rm("temp_$(lpad(i, 4, '0')).pdf")
end
run(ghostscript_gs(`-q -dBATCH -dNOPAUSE -dFirstPage=$i -dLastPage=$i -sOutputFile=temp_$(lpad(i, 4, '0')).pdf -sDEVICE=pdfwrite temp.pdf`))
push!(pdfs, read("temp_$(lpad(i, 4, '0')).pdf"))
rm("temp_$(lpad(i, 4, '0')).pdf")
end
end
end
Expand All @@ -114,7 +124,7 @@ function get_pdf_bbox(path::String)
!isfile(path) && error("File $(path) does not exist!")
out = Pipe()
err = Pipe()
succ = success(pipeline(`$(Ghostscript_jll.gs()) -q -dBATCH -dNOPAUSE -sDEVICE=bbox $path`, stdout=out, stderr=err))
succ = success(pipeline(ghostscript_gs(`-q -dBATCH -dNOPAUSE -sDEVICE=bbox $path`), stdout=out, stderr=err))

close(out.in)
close(err.in)
Expand Down Expand Up @@ -164,9 +174,7 @@ function crop_pdf(path::String; margin = _PDFCROP_DEFAULT_MARGINS[])
try
redirect_stderr(err) do
redirect_stdout(out) do
Ghostscript_jll.gs() do gs_exe
run(`$gs_exe -o temp_cropped.pdf -sDEVICE=pdfwrite -c "[/CropBox [$crop_cmd]" -c "/PAGES pdfmark" -f $path`)
end
run(ghostscript_gs(`-o temp_cropped.pdf -sDEVICE=pdfwrite -c "[/CropBox [$crop_cmd]" -c "/PAGES pdfmark" -f $path`))
end
end
catch e
Expand Down
Loading