Skip to main content

aylis_core/
pages.rs

1//! Páginas gravadas: o que se desenha num [`RecordingCanvas`] vira uma lista de operações
2//! que se repete em qualquer canvas ([`Page::replay`], a visualização de um relatório) ou
3//! vira PDF pelo provedor de PDF ([`crate::providers::PdfProvider`]; o núcleo não escreve PDF).
4//!
5//! As medidas são em pontos (1/72 de polegada): uma página A4 tem 595 × 842.
6
7use crate::canvas::{Brush, Canvas, TextService, TextStyle};
8use crate::color::Color;
9use crate::geometry::{PointF, RectF, SizeF};
10use crate::image::Image;
11use crate::path::Path;
12use crate::FontWeight;
13
14/// Uma operação de desenho, já nas coordenadas da página.
15#[derive(Clone, Debug)]
16pub enum Op {
17    FillRect { rect: RectF, radius: f32, color: Color },
18    StrokeRect { rect: RectF, radius: f32, color: Color, width: f32, dash: Vec<f32> },
19    FillEllipse { rect: RectF, color: Color },
20    StrokeEllipse { rect: RectF, color: Color, width: f32 },
21    Line { from: PointF, to: PointF, color: Color, width: f32, dash: Vec<f32> },
22    /// Contornos (pontos e se fecha).
23    FillPath { contours: Vec<(Vec<PointF>, bool)>, color: Color },
24    StrokePath { contours: Vec<(Vec<PointF>, bool)>, color: Color, width: f32, dash: Vec<f32> },
25    Text { text: String, rect: RectF, style: TextStyle },
26    Image { image: Image, dest: RectF, opacity: f32 },
27    Clip(RectF),
28    Save,
29    Restore,
30}
31
32/// Uma página: as operações em ordem.
33#[derive(Clone, Debug, Default)]
34pub struct Page {
35    pub ops: Vec<Op>,
36}
37
38/// Páginas do mesmo tamanho (em pontos).
39#[derive(Clone, Debug, Default)]
40pub struct PageSet {
41    pub width: f32,
42    pub height: f32,
43    pub pages: Vec<Page>,
44}
45
46/// A cor de um pincel (o gradiente vira a cor do meio).
47fn brush_color(brush: &Brush) -> Color {
48    match brush {
49        Brush::Solid(c) => *c,
50        Brush::Linear { stops, .. } | Brush::Radial { stops, .. } | Brush::Sweep { stops, .. } => stops.get(stops.len() / 2).map_or(Color::BLACK, |s| s.color),
51    }
52}
53
54/// Um canvas que grava o que é desenhado (em vez de pintar). Translação e escala entram
55/// nas coordenadas gravadas; a rotação é ignorada.
56pub struct RecordingCanvas<'a> {
57    pub ops: Vec<Op>,
58    /// (dx, dy, sx, sy) de cada `save`.
59    stack: Vec<(f32, f32, f32, f32)>,
60    transform: (f32, f32, f32, f32),
61    measure: Option<&'a dyn TextService>,
62}
63
64impl<'a> RecordingCanvas<'a> {
65    /// `measure`: quem mede o texto (o serviço da plataforma); sem ele, uma estimativa.
66    pub fn new(measure: Option<&'a dyn TextService>) -> Self {
67        Self { ops: Vec::new(), stack: Vec::new(), transform: (0.0, 0.0, 1.0, 1.0), measure }
68    }
69
70    fn point(&self, p: PointF) -> PointF {
71        let (dx, dy, sx, sy) = self.transform;
72        PointF::new(p.x * sx + dx, p.y * sy + dy)
73    }
74
75    fn rect(&self, r: RectF) -> RectF {
76        let a = self.point(PointF::new(r.x, r.y));
77        let b = self.point(PointF::new(r.right(), r.bottom()));
78        RectF::from_points(a, b)
79    }
80
81    fn factor(&self) -> f32 {
82        (self.transform.2.abs() + self.transform.3.abs()) / 2.0
83    }
84
85    fn contours(&self, path: &Path) -> Vec<(Vec<PointF>, bool)> {
86        path.flatten(12).into_iter().map(|(pts, closed)| (pts.into_iter().map(|p| self.point(p)).collect(), closed)).collect()
87    }
88}
89
90impl Canvas for RecordingCanvas<'_> {
91    fn save(&mut self) {
92        self.stack.push(self.transform);
93        self.ops.push(Op::Save);
94    }
95
96    fn restore(&mut self) {
97        if let Some(t) = self.stack.pop() {
98            self.transform = t;
99            self.ops.push(Op::Restore);
100        }
101    }
102
103    fn translate(&mut self, dx: f32, dy: f32) {
104        let (x, y, sx, sy) = self.transform;
105        self.transform = (x + dx * sx, y + dy * sy, sx, sy);
106    }
107
108    fn scale(&mut self, sx: f32, sy: f32) {
109        let (x, y, a, b) = self.transform;
110        self.transform = (x, y, a * sx, b * sy);
111    }
112
113    fn rotate(&mut self, _degrees: f32) {}
114
115    fn clip_rect(&mut self, rect: RectF) {
116        let r = self.rect(rect);
117        self.ops.push(Op::Clip(r));
118    }
119
120    fn save_layer(&mut self, _opacity: f32) {
121        self.save();
122    }
123
124    fn fill_rect(&mut self, rect: RectF, radius: f32, brush: &Brush) {
125        let (rect, radius) = (self.rect(rect), radius * self.factor());
126        self.ops.push(Op::FillRect { rect, radius, color: brush_color(brush) });
127    }
128
129    fn stroke_rect(&mut self, rect: RectF, radius: f32, stroke: &crate::Stroke) {
130        let (rect, radius) = (self.rect(rect), radius * self.factor());
131        let width = stroke.width * self.factor();
132        self.ops.push(Op::StrokeRect { rect, radius, color: brush_color(&stroke.brush), width, dash: stroke.dash.clone().unwrap_or_default() });
133    }
134
135    fn fill_ellipse(&mut self, rect: RectF, brush: &Brush) {
136        let rect = self.rect(rect);
137        self.ops.push(Op::FillEllipse { rect, color: brush_color(brush) });
138    }
139
140    fn stroke_ellipse(&mut self, rect: RectF, stroke: &crate::Stroke) {
141        let rect = self.rect(rect);
142        let width = stroke.width * self.factor();
143        self.ops.push(Op::StrokeEllipse { rect, color: brush_color(&stroke.brush), width });
144    }
145
146    fn draw_line(&mut self, from: PointF, to: PointF, stroke: &crate::Stroke) {
147        let (from, to) = (self.point(from), self.point(to));
148        let width = stroke.width * self.factor();
149        self.ops.push(Op::Line { from, to, color: brush_color(&stroke.brush), width, dash: stroke.dash.clone().unwrap_or_default() });
150    }
151
152    fn draw_text(&mut self, text: &str, rect: RectF, style: &TextStyle) {
153        let rect = self.rect(rect);
154        let mut style = style.clone();
155        style.font.size *= self.factor();
156        self.ops.push(Op::Text { text: text.to_string(), rect, style });
157    }
158
159    fn measure_text(&mut self, text: &str, style: &TextStyle) -> SizeF {
160        match self.measure {
161            Some(m) => m.measure(text, style, None),
162            None => SizeF::new(text_width(text, style), style.font.size * 1.2),
163        }
164    }
165
166    fn draw_image(&mut self, image: &Image, _src: RectF, dest: RectF, opacity: f32) {
167        let dest = self.rect(dest);
168        self.ops.push(Op::Image { image: image.clone(), dest, opacity });
169    }
170
171    fn clip_round_rect(&mut self, rect: RectF, _radius: f32) {
172        self.clip_rect(rect);
173    }
174
175    fn fill_path(&mut self, path: &Path, brush: &Brush) {
176        let contours = self.contours(path);
177        self.ops.push(Op::FillPath { contours, color: brush_color(brush) });
178    }
179
180    fn stroke_path(&mut self, path: &Path, stroke: &crate::Stroke) {
181        let contours = self.contours(path);
182        let width = stroke.width * self.factor();
183        self.ops.push(Op::StrokePath { contours, color: brush_color(&stroke.brush), width, dash: stroke.dash.clone().unwrap_or_default() });
184    }
185}
186
187fn path_of(contours: &[(Vec<PointF>, bool)]) -> Path {
188    let mut p = Path::new();
189    for (pts, closed) in contours {
190        if let Some(first) = pts.first() {
191            p.move_to(first.x, first.y);
192            for q in &pts[1..] {
193                p.line_to(q.x, q.y);
194            }
195            if *closed {
196                p.close();
197            }
198        }
199    }
200    p
201}
202
203impl Page {
204    /// Desenha a página em `canvas` (nas coordenadas dela: use `translate`/`scale` antes).
205    pub fn replay(&self, canvas: &mut dyn Canvas) {
206        let stroke = |c: Color, w: f32, dash: &[f32]| {
207            let s = crate::Stroke::new(c, w);
208            if dash.is_empty() { s } else { s.dashed(dash.to_vec()) }
209        };
210        let mut depth = 0;
211        for op in &self.ops {
212            match op {
213                Op::FillRect { rect, radius, color } => canvas.fill_rect(*rect, *radius, &Brush::Solid(*color)),
214                Op::StrokeRect { rect, radius, color, width, dash } => canvas.stroke_rect(*rect, *radius, &stroke(*color, *width, dash)),
215                Op::FillEllipse { rect, color } => canvas.fill_ellipse(*rect, &Brush::Solid(*color)),
216                Op::StrokeEllipse { rect, color, width } => canvas.stroke_ellipse(*rect, &stroke(*color, *width, &[])),
217                Op::Line { from, to, color, width, dash } => canvas.draw_line(*from, *to, &stroke(*color, *width, dash)),
218                Op::FillPath { contours, color } => canvas.fill_path(&path_of(contours), &Brush::Solid(*color)),
219                Op::StrokePath { contours, color, width, dash } => canvas.stroke_path(&path_of(contours), &stroke(*color, *width, dash)),
220                Op::Text { text, rect, style } => canvas.draw_text(text, *rect, style),
221                Op::Image { image, dest, opacity } => {
222                    let size = canvas.image_size(image).unwrap_or(SizeF::new(dest.width, dest.height));
223                    canvas.draw_image(image, RectF::new(0.0, 0.0, size.width, size.height), *dest, *opacity);
224                }
225                Op::Clip(r) => canvas.clip_rect(*r),
226                Op::Save => {
227                    depth += 1;
228                    canvas.save();
229                }
230                Op::Restore if depth > 0 => {
231                    depth -= 1;
232                    canvas.restore();
233                }
234                Op::Restore => {}
235            }
236        }
237        for _ in 0..depth {
238            canvas.restore();
239        }
240    }
241
242    /// Todos os textos da página, na ordem (para conferir e para buscar).
243    pub fn texts(&self) -> Vec<&str> {
244        self.ops.iter().filter_map(|op| if let Op::Text { text, .. } = op { Some(text.as_str()) } else { None }).collect()
245    }
246}
247
248// ---------------------------------------------------------------------------
249// PDF
250
251/// Larguras da Helvetica (normal e negrito) dos caracteres 32 a 126, em milésimos do tamanho.
252const HELVETICA: [u16; 95] = [
253    278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556,
254    1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469,
255    556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584,
256];
257const HELVETICA_BOLD: [u16; 95] = [
258    278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611,
259    975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584,
260    556, 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584,
261];
262
263/// A letra sem acento (para a largura), e o byte no WinAnsi (`?` se não houver).
264fn win_ansi(c: char) -> (char, u8) {
265    let base = match c {
266        'á' | 'à' | 'â' | 'ã' | 'ä' | 'å' => 'a',
267        'Á' | 'À' | 'Â' | 'Ã' | 'Ä' | 'Å' => 'A',
268        'é' | 'è' | 'ê' | 'ë' => 'e',
269        'É' | 'È' | 'Ê' | 'Ë' => 'E',
270        'í' | 'ì' | 'î' | 'ï' => 'i',
271        'Í' | 'Ì' | 'Î' | 'Ï' => 'I',
272        'ó' | 'ò' | 'ô' | 'õ' | 'ö' => 'o',
273        'Ó' | 'Ò' | 'Ô' | 'Õ' | 'Ö' => 'O',
274        'ú' | 'ù' | 'û' | 'ü' => 'u',
275        'Ú' | 'Ù' | 'Û' | 'Ü' => 'U',
276        'ç' => 'c',
277        'Ç' => 'C',
278        'ñ' => 'n',
279        'Ñ' => 'N',
280        _ => c,
281    };
282    let byte = match c {
283        '€' => 0x80,
284        '‚' => 0x82,
285        '„' => 0x84,
286        '…' => 0x85,
287        '‘' => 0x91,
288        '’' => 0x92,
289        '“' => 0x93,
290        '”' => 0x94,
291        '•' => 0x95,
292        '–' => 0x96,
293        '—' => 0x97,
294        '™' => 0x99,
295        c if (c as u32) < 0x80 || ((c as u32) >= 0xA0 && (c as u32) <= 0xFF) => c as u32 as u8,
296        _ => b'?',
297    };
298    (base, byte)
299}
300
301fn char_width(c: char, bold: bool) -> f32 {
302    let (base, _) = win_ansi(c);
303    let table = if bold { &HELVETICA_BOLD } else { &HELVETICA };
304    let code = base as u32;
305    let w = if (32..=126).contains(&code) { table[(code - 32) as usize] } else { 556 };
306    w as f32 / 1000.0
307}
308
309fn is_bold(style: &TextStyle) -> bool {
310    matches!(style.font.weight, FontWeight::SemiBold | FontWeight::Bold | FontWeight::Black)
311}
312
313/// Largura aproximada do texto (pelas medidas da Helvetica), no tamanho do estilo: a medida do
314/// [`RecordingCanvas`] sem serviço de texto (sem janela).
315pub fn text_width(text: &str, style: &TextStyle) -> f32 {
316    let bold = is_bold(style);
317    text.chars().map(|c| char_width(c, bold)).sum::<f32>() * style.font.size
318}