61 lines
1.7 KiB
Plaintext
61 lines
1.7 KiB
Plaintext
#! Contains lengths, in user units: numbers, with a unit or as a percentage of
|
|
#! the viewport, and fractions, as offsets and opacities are written.
|
|
|
|
import std::math;
|
|
module image::svg;
|
|
|
|
|
|
# The size percentages are of, and that of the viewport's diagonal, as the user
|
|
# space being drawn in measures them.
|
|
struct viewport {
|
|
var width: f64;
|
|
var height: f64;
|
|
}
|
|
|
|
def viewport::diagonal(&this): f64 {
|
|
return math::sqrt((this.width * this.width + this.height * this.height) / 2);
|
|
}
|
|
|
|
# Which length a percentage is of.
|
|
enum axis: u8 {
|
|
x,
|
|
y,
|
|
diagonal,
|
|
}
|
|
|
|
# Reads a length, in user units: a number, with a unit or a percentage of the
|
|
# viewport.
|
|
def parse_length(text: strview, view: &viewport, along: axis): maybe<f64> {
|
|
val trimmed := text.trim();
|
|
val read := number_at(trimmed, 0) else { return nothing {}; };
|
|
val unit := trimmed.substr(read.end, trimmed.length - read.end).trim();
|
|
val scale: f64 = match unit {
|
|
"" => 1.0,
|
|
"px" => 1.0,
|
|
"pt" => 4.0 / 3.0,
|
|
"pc" => 16.0,
|
|
"mm" => 96.0 / 25.4,
|
|
"cm" => 96.0 / 2.54,
|
|
"in" => 96.0,
|
|
"em" => 16.0,
|
|
"ex" => 8.0,
|
|
"%" => (along == axis::x ? view.width : (along == axis::y ? view.height : view.diagonal())) / 100,
|
|
else => -1.0,
|
|
};
|
|
if scale < 0 {
|
|
return nothing {};
|
|
}
|
|
return read.value * scale;
|
|
}
|
|
|
|
# Reads a number, or a percentage of 1, as offsets and opacities are written.
|
|
def parse_fraction(text: strview): maybe<f64> {
|
|
val trimmed := text.trim();
|
|
val read := number_at(trimmed, 0) else { return nothing {}; };
|
|
val rest := trimmed.substr(read.end, trimmed.length - read.end).trim();
|
|
if rest == "%" {
|
|
return read.value / 100;
|
|
}
|
|
return rest.length == 0 ? read.value : nothing {};
|
|
}
|