use super::svg::Svg;
pub(super) type Rgb = [u8; 3];
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct Pen {
pub(super) color: Rgb,
pub(super) width: f32,
}
#[derive(Debug, Clone, PartialEq)]
pub(super) struct Font {
pub(super) height: f32,
pub(super) weight: i32,
pub(super) italic: bool,
pub(super) underline: bool,
pub(super) escapement: f32,
pub(super) face: String,
}
impl Default for Font {
fn default() -> Self {
Font {
height: -12.0,
weight: 400,
italic: false,
underline: false,
escapement: 0.0,
face: "Arial".into(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub(super) enum Object {
Pen(Option<Pen>),
Brush(Option<Rgb>),
Font(Font),
Other,
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub(super) struct TextAlign {
pub(super) flags: u32,
}
const TA_BASELINE: u32 = 24;
const TA_BOTTOM: u32 = 8;
const TA_CENTER: u32 = 6;
const TA_RIGHT: u32 = 2;
pub(super) const TA_UPDATECP: u32 = 1;
const CELL_TO_EM_RATIO: f32 = 0.87;
const ASCENT_RATIO: f32 = 0.9;
const DESCENT_RATIO: f32 = 0.22;
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct Matrix {
pub(super) coefficients: [f32; 6],
}
impl Matrix {
pub(super) const IDENTITY: Matrix = Matrix {
coefficients: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
};
pub(super) fn apply(self, x: f32, y: f32) -> (f32, f32) {
let [xx, yx, xy, yy, dx, dy] = self.coefficients;
(xx * x + xy * y + dx, yx * x + yy * y + dy)
}
pub(super) fn then(self, then: Matrix) -> Matrix {
let [a1, b1, c1, d1, e1, f1] = self.coefficients;
let [a2, b2, c2, d2, e2, f2] = then.coefficients;
Matrix {
coefficients: [
a1 * a2 + b1 * c2,
a1 * b2 + b1 * d2,
c1 * a2 + d1 * c2,
c1 * b2 + d1 * d2,
e1 * a2 + f1 * c2 + e2,
e1 * b2 + f1 * d2 + f2,
],
}
}
pub(super) fn scale(self) -> f32 {
let [xx, yx, xy, yy, _, _] = self.coefficients;
((xx * yy - yx * xy).abs()).sqrt()
}
}
#[derive(Debug, Clone)]
pub(super) struct State {
pub(super) pen: Option<Pen>,
pub(super) brush: Option<Rgb>,
pub(super) font: Font,
pub(super) text_color: Rgb,
pub(super) text_align: TextAlign,
pub(super) even_odd: bool,
pub(super) window_org: (f32, f32),
pub(super) window_ext: Option<(f32, f32)>,
pub(super) viewport_org: (f32, f32),
pub(super) viewport_ext: Option<(f32, f32)>,
pub(super) world: Matrix,
pub(super) fixed_scale: Option<(f32, f32)>,
pub(super) position: (f32, f32),
}
impl Default for State {
fn default() -> Self {
State {
pen: Some(Pen {
color: [0, 0, 0],
width: 0.0,
}),
brush: Some([255, 255, 255]),
font: Font::default(),
text_color: [0, 0, 0],
text_align: TextAlign::default(),
even_odd: true,
window_org: (0.0, 0.0),
window_ext: None,
viewport_org: (0.0, 0.0),
viewport_ext: None,
world: Matrix::IDENTITY,
fixed_scale: None,
position: (0.0, 0.0),
}
}
}
pub(super) struct Dc {
pub(super) state: State,
saved: Vec<State>,
pub(super) objects: Vec<Option<Object>>,
pub(super) path: Option<String>,
pub(super) in_path: bool,
pub(super) svg: Svg,
}
impl Dc {
pub(super) fn new() -> Self {
Dc {
state: State::default(),
saved: Vec::new(),
objects: Vec::new(),
path: None,
in_path: false,
svg: Svg::default(),
}
}
pub(super) fn save(&mut self) {
self.saved.push(self.state.clone());
}
pub(super) fn restore(&mut self, relative: i32) {
let count = self.saved.len() as i32;
let target = if relative < 0 { count + relative } else { relative - 1 };
if target < 0 || target >= count {
return;
}
self.saved.truncate(target as usize + 1);
if let Some(state) = self.saved.pop() {
self.state = state;
}
}
pub(super) fn create(&mut self, object: Object, index: Option<usize>) {
let index = index.unwrap_or_else(|| {
self.objects
.iter()
.position(Option::is_none)
.unwrap_or(self.objects.len())
});
if self.objects.len() <= index {
self.objects.resize(index + 1, None);
}
self.objects[index] = Some(object);
}
pub(super) fn select(&mut self, index: usize) {
if let Some(Some(object)) = self.objects.get(index).cloned() {
self.select_object(object);
}
}
pub(super) fn select_object(&mut self, object: Object) {
match object {
Object::Pen(pen) => self.state.pen = pen,
Object::Brush(brush) => self.state.brush = brush,
Object::Font(font) => self.state.font = font,
Object::Other => {}
}
}
pub(super) fn delete(&mut self, index: usize) {
if let Some(slot) = self.objects.get_mut(index) {
*slot = None;
}
}
pub(super) fn transform(&self) -> Matrix {
let state = &self.state;
let (wx, wy) = state.window_org;
let (vx, vy) = state.viewport_org;
let (sx, sy) = match (state.fixed_scale, state.window_ext, state.viewport_ext) {
(Some(scale), _, _) => scale,
(None, Some((wex, wey)), Some((vex, vey))) if wex != 0.0 && wey != 0.0 => (vex / wex, vey / wey),
_ => (1.0, 1.0),
};
let mapping = Matrix {
coefficients: [sx, 0.0, 0.0, sy, vx - wx * sx, vy - wy * sy],
};
state.world.then(mapping)
}
pub(super) fn point(&self, x: f32, y: f32) -> (f32, f32) {
self.transform().apply(x, y)
}
pub(super) fn length(&self, length: f32) -> f32 {
length * self.transform().scale()
}
pub(super) fn poly_data(&self, points: &[(f32, f32)], close: bool) -> String {
let mut data = String::new();
for (at, &(x, y)) in points.iter().enumerate() {
let (px, py) = self.point(x, y);
data.push_str(&format!("{}{} {} ", if at == 0 { 'M' } else { 'L' }, num(px), num(py)));
}
if close && !points.is_empty() {
data.push('Z');
}
data
}
pub(super) fn bezier_data(&self, start: Option<(f32, f32)>, points: &[(f32, f32)]) -> String {
let mut data = String::new();
let mut rest = points;
if let Some((x, y)) = start {
let (px, py) = self.point(x, y);
data.push_str(&format!("M{} {} ", num(px), num(py)));
}
while rest.len() >= 3 {
data.push('C');
for &(x, y) in &rest[..3] {
let (px, py) = self.point(x, y);
data.push_str(&format!("{} {} ", num(px), num(py)));
}
rest = &rest[3..];
}
data
}
pub(super) fn draw(&mut self, data: &str, fill: bool) {
if self.in_path {
self.path.get_or_insert_with(String::new).push_str(data);
return;
}
let brush = if fill { self.state.brush } else { None };
let pen = self.state.pen.map(|pen| (pen.color, self.length(pen.width)));
self.svg.path(data, brush, pen, self.state.even_odd);
}
pub(super) fn draw_path(&mut self, fill: bool, stroke: bool) {
let Some(data) = self.path.take() else { return };
let brush = if fill { self.state.brush } else { None };
let pen = if stroke {
self.state.pen.map(|pen| (pen.color, self.length(pen.width)))
} else {
None
};
self.svg.path(&data, brush, pen, self.state.even_odd);
}
pub(super) fn ellipse_data(&self, bounds: [f32; 4]) -> String {
let [left, top, right, bottom] = bounds;
let (cx, cy) = ((left + right) / 2.0, (top + bottom) / 2.0);
let (rx, ry) = ((right - left).abs() / 2.0, (bottom - top).abs() / 2.0);
let kappa = 0.552_284_8;
let points = [
(cx + rx, cy + ry * kappa),
(cx + rx * kappa, cy + ry),
(cx, cy + ry),
(cx - rx * kappa, cy + ry),
(cx - rx, cy + ry * kappa),
(cx - rx, cy),
(cx - rx, cy - ry * kappa),
(cx - rx * kappa, cy - ry),
(cx, cy - ry),
(cx + rx * kappa, cy - ry),
(cx + rx, cy - ry * kappa),
(cx + rx, cy),
];
let mut data = self.bezier_data(Some((cx + rx, cy)), &points);
data.push('Z');
data
}
pub(super) fn arc_data(
&self,
bounds: [f32; 4],
start: (f32, f32),
end: (f32, f32),
pie: bool,
close: bool,
) -> String {
let [left, top, right, bottom] = bounds;
let (cx, cy) = ((left + right) / 2.0, (top + bottom) / 2.0);
let (rx, ry) = ((right - left).abs() / 2.0, (bottom - top).abs() / 2.0);
let angle = |(x, y): (f32, f32)| (-(y - cy) / ry.max(1e-6)).atan2((x - cx) / rx.max(1e-6));
let from = angle(start);
let mut to = angle(end);
if to <= from {
to += std::f32::consts::TAU;
}
let steps = (((to - from) / 0.1).ceil() as usize).clamp(2, 400);
let mut points: Vec<(f32, f32)> = (0..=steps)
.map(|step| {
let theta = from + (to - from) * step as f32 / steps as f32;
(cx + rx * theta.cos(), cy - ry * theta.sin())
})
.collect();
if pie {
points.push((cx, cy));
}
self.poly_data(&points, pie || close)
}
pub(super) fn text(&mut self, x: f32, y: f32, text: &str, dx: &[f32]) {
if text.trim().is_empty() {
return;
}
let font = self.state.font.clone();
let size = if font.height < 0.0 {
-font.height
} else {
font.height * CELL_TO_EM_RATIO
};
let flags = self.state.text_align.flags;
let (mut x, y) = if flags & TA_UPDATECP != 0 {
self.state.position
} else {
(x, y)
};
let total: f32 = if dx.is_empty() {
text.chars().count() as f32 * size * 0.5
} else {
dx.iter().sum()
};
if flags & TA_CENTER == TA_CENTER {
x -= total / 2.0;
} else if flags & TA_RIGHT != 0 {
x -= total;
}
let baseline = if flags & TA_BASELINE == TA_BASELINE {
y
} else if flags & TA_BOTTOM != 0 {
y - size * DESCENT_RATIO
} else {
y + size * ASCENT_RATIO
};
if flags & TA_UPDATECP != 0 {
self.state.position.0 = x + total;
}
let mut positions = Vec::new();
let mut pen_x = x;
for (at, _) in text.chars().enumerate() {
positions.push(self.point(pen_x, baseline));
pen_x += dx.get(at).copied().unwrap_or(size * 0.5);
}
let picture_size = self.length(size);
let color = self.state.text_color;
self.svg
.text(text, &positions, picture_size, &font, color, !dx.is_empty());
}
}
pub(super) const ROP_NOP: u32 = 0x00AA_0029;
const ROP_PATCOPY: u32 = 0x00F0_0021;
const ROP_BLACKNESS: u32 = 0x0000_0042;
const ROP_WHITENESS: u32 = 0x00FF_0062;
impl Dc {
pub(super) fn fill_blit(&mut self, rop: u32, bounds: [f32; 4]) {
let fill = match rop {
ROP_PATCOPY => self.state.brush,
ROP_BLACKNESS => Some([0, 0, 0]),
ROP_WHITENESS => Some([255, 255, 255]),
_ => return,
};
let [x, y, width, height] = bounds;
let data = self.poly_data(
&[(x, y), (x + width, y), (x + width, y + height), (x, y + height)],
true,
);
self.svg.path(&data, fill, None, false);
}
}
pub(super) fn num(value: f32) -> String {
let rounded = (value * 100.0).round() / 100.0;
if rounded == rounded.trunc() {
format!("{}", rounded as i64)
} else {
format!("{rounded}")
}
}