Skip to content

Commit abfbae7

Browse files
authored
load fontdb in query_all so that we can measure text files (#55)
* load fontdb in query_all so that we can measure text files
1 parent 3bede6d commit abfbae7

File tree

3 files changed

+37
-1
lines changed

3 files changed

+37
-1
lines changed

native/resvg/src/lib.rs

+9-1
Original file line numberDiff line numberDiff line change
@@ -357,11 +357,19 @@ pub fn query_all<'a>(env: Env<'a>, in_svg: String, options: Options) -> NifResul
357357
env
358358
);
359359

360-
let tree = try_or_return_elixir_err!(
360+
let mut tree = try_or_return_elixir_err!(
361361
usvg::Tree::from_xmltree(&xml_tree, &parsed_options.usvg).map_err(|e| e.to_string()),
362362
env
363363
);
364364

365+
// fontdb initialization is pretty expensive, so perform it only when needed.
366+
if tree.has_text_nodes() {
367+
match load_fonts(&parsed_options) {
368+
Ok(fontdb) => tree.convert_text(&fontdb),
369+
Err(error) => return Ok((atoms::error(), error).encode(env)),
370+
};
371+
}
372+
365373
fn round_len(v: f32) -> f32 {
366374
(v * 1000.0).round() / 1000.0
367375
}

test/resvg_test.exs

+23
Original file line numberDiff line numberDiff line change
@@ -171,5 +171,28 @@ defmodule Resvg.Test do
171171
height: 613.6170043945312
172172
}
173173
end
174+
175+
test "measures text elements if the right font files are given" do
176+
roboto = font_file("Roboto/Roboto-Regular.ttf")
177+
178+
input = image_path("text-measurement.svg")
179+
180+
[node] = Resvg.query_all(input, font_files: [roboto], resources_dir: @tmp)
181+
182+
assert node ==
183+
%Resvg.Native.Node{
184+
id: "Text-Element-1",
185+
x: 0.28700000047683716,
186+
y: -8.531000137329102,
187+
width: 85.18399810791016,
188+
height: 8.64799976348877
189+
}
190+
end
191+
192+
test "doesn't measure text elements if the right font files are not given" do
193+
input = image_path("text-measurement.svg")
194+
195+
assert Resvg.query_all(input, font_files: []) == []
196+
end
174197
end
175198
end

test/support/text-measurement.svg

+5
Loading

0 commit comments

Comments
 (0)