Skip to main content

aylis_web/
lib.rs

1//! # aylis-web
2//!
3//! Renderizador do aylis para navegadores: implementa o [`Canvas`] e o [`TextService`]
4//! sobre o Canvas 2D do HTML.
5//!
6//! O Skia nativo (`skia-safe`) não compila para `wasm32-unknown-unknown`. No Chrome, no
7//! Edge e no Firefox o próprio Canvas 2D é desenhado pelo Skia (no Safari, pelo Core
8//! Graphics), então o resultado fica muito próximo do desktop sem baixar nada extra.
9//!
10//! Diferenças conhecidas em relação ao `aylis-skia`:
11//! - `save_layer` aplica a opacidade a cada desenho (não compõe a camada inteira de uma
12//!   vez), o que só muda o resultado quando filhos semitransparentes se sobrepõem;
13//! - as fontes são as do navegador;
14//! - imagens codificadas (PNG, JPEG, WebP, SVG) são decodificadas pelo navegador, de
15//!   forma assíncrona: aparecem na repintura seguinte ao carregamento ([`on_image_loaded`]).
16
17use std::cell::RefCell;
18use std::collections::HashMap;
19use std::f64::consts::PI;
20
21use aylis_core::{
22    Brush, Canvas, Color, FontSpec, FontWeight, GradientStop, Image, ImageSource, PointF, RectF,
23    SizeF, Stroke, TextAlign, TextService, TextStyle,
24};
25use wasm_bindgen::closure::Closure;
26use wasm_bindgen::{Clamped, JsCast, JsValue};
27use web_sys::{CanvasGradient, CanvasRenderingContext2d, HtmlCanvasElement, HtmlImageElement, ImageData};
28
29// ---------------------------------------------------------------------------
30// Imagens
31
32/// Uma imagem pronta para o `drawImage` (ou ainda carregando).
33#[derive(Clone)]
34enum WebImage {
35    /// O navegador está decodificando (o `<img>` avisa quando terminar).
36    Loading,
37    Ready(HtmlImageElement),
38    /// Pixels (RGBA/BGRA) copiados para um canvas fora da tela.
39    Pixels(HtmlCanvasElement),
40    Failed,
41}
42
43/// As imagens prontas, nos limites do projeto: as de arquivo pela quantidade (`files`), as
44/// de pixels pelo tamanho (`pixels_mb`).
45struct ImageCache {
46    files: aylis_core::ImageCache<WebImage>,
47    pixels: aylis_core::ImageCache<WebImage>,
48    on_loaded: Option<std::rc::Rc<dyn Fn()>>,
49}
50
51impl Default for ImageCache {
52    fn default() -> Self {
53        Self {
54            files: aylis_core::ImageCache::named("Navegador · arquivos"),
55            pixels: aylis_core::ImageCache::named("Navegador · pixels"),
56            on_loaded: None,
57        }
58    }
59}
60
61impl ImageCache {
62    /// A imagem pronta (marcada como usada), se já estiver guardada.
63    fn get(&mut self, image: &Image) -> Option<WebImage> {
64        match image.source() {
65            ImageSource::Encoded(_) => self.files.get(image).cloned(),
66            _ => self.pixels.get(image).cloned(),
67        }
68    }
69
70    fn insert(&mut self, image: &Image, loaded: WebImage) {
71        let limits = aylis_core::image_cache::limits();
72        match image.source() {
73            ImageSource::Encoded(_) => self.files.insert(image, loaded, 0, limits.files as usize, usize::MAX),
74            ImageSource::Rgba { width, height, .. } | ImageSource::Bgra { width, height, .. } => {
75                self.pixels.insert(image, loaded, *width as usize * *height as usize * 4, usize::MAX, limits.pixels_bytes())
76            }
77        }
78    }
79}
80
81thread_local! {
82    static IMAGES: RefCell<ImageCache> = RefCell::new(ImageCache::default());
83}
84
85/// Chamado quando uma imagem termina de carregar (a plataforma pede uma repintura).
86pub fn on_image_loaded(f: impl Fn() + 'static) {
87    IMAGES.with(|c| c.borrow_mut().on_loaded = Some(std::rc::Rc::new(f)));
88}
89
90thread_local! {
91    static FONT_GENERATION: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
92}
93
94/// Fontes de arquivo registradas (`aylis_core::fonts`) viram `FontFace` no documento. Elas
95/// carregam de forma assíncrona: quando terminam, a plataforma repinta (o mesmo aviso das
96/// imagens, [`on_image_loaded`]).
97fn sync_fonts() {
98    let generation = aylis_core::fonts::generation();
99    if FONT_GENERATION.with(|g| g.replace(generation)) == generation {
100        return;
101    }
102    forget_widths();
103    let add = || -> Result<(), JsValue> {
104        let window = web_sys::window().ok_or("sem window")?;
105        let document = window.document().ok_or("sem document")?;
106        let set = js_sys::Reflect::get(&document, &"fonts".into())?;
107        let add: js_sys::Function = js_sys::Reflect::get(&set, &"add".into())?.dyn_into()?;
108        let ctor: js_sys::Function = js_sys::Reflect::get(&window, &"FontFace".into())?.dyn_into()?;
109        for font in aylis_core::fonts::registered() {
110            let data = js_sys::Uint8Array::from(&font.data[..]);
111            let args = js_sys::Array::of2(&font.family.as_str().into(), &data.buffer());
112            let face = js_sys::Reflect::construct(&ctor, &args)?;
113            add.call1(&set, &face)?;
114            let load: js_sys::Function = js_sys::Reflect::get(&face, &"load".into())?.dyn_into()?;
115            let promise: js_sys::Promise = load.call0(&face)?.dyn_into()?;
116            let done = Closure::<dyn FnMut(JsValue)>::new(move |_: JsValue| {
117                // A fonte chegou: as larguras medidas com a substituta não valem mais.
118                forget_widths();
119                if let Some(f) = IMAGES.with(|c| c.borrow().on_loaded.clone()) {
120                    f();
121                }
122            });
123            let _ = promise.then(&done);
124            done.forget();
125        }
126        Ok(())
127    };
128    let _ = add();
129}
130
131/// Começa a decodificar uma imagem codificada (um `<img>` com um blob).
132fn load_encoded(id: u64, bytes: &[u8]) -> WebImage {
133    let start = || -> Result<(), JsValue> {
134        let array = js_sys::Uint8Array::from(bytes);
135        let parts = js_sys::Array::of1(&array);
136        let blob = web_sys::Blob::new_with_u8_array_sequence(&parts)?;
137        let url = web_sys::Url::create_object_url_with_blob(&blob)?;
138        let img = HtmlImageElement::new()?;
139        let done_img = img.clone();
140        let done_url = url.clone();
141        let onload = Closure::once_into_js(move || {
142            let _ = web_sys::Url::revoke_object_url(&done_url);
143            let notify = IMAGES.with(|c| {
144                let mut cache = c.borrow_mut();
145                if let Some(slot) = cache.files.get_by_id_mut(id) {
146                    *slot = WebImage::Ready(done_img);
147                }
148                cache.on_loaded.clone()
149            });
150            // Fora do empréstimo: a repintura pode desenhar imagens na hora.
151            if let Some(f) = notify {
152                f();
153            }
154        });
155        let onerror = Closure::once_into_js(move || {
156            IMAGES.with(|c| {
157                if let Some(slot) = c.borrow_mut().files.get_by_id_mut(id) {
158                    *slot = WebImage::Failed;
159                }
160            });
161        });
162        img.set_onload(Some(onload.unchecked_ref()));
163        img.set_onerror(Some(onerror.unchecked_ref()));
164        img.set_src(&url);
165        Ok(())
166    };
167    if start().is_ok() { WebImage::Loading } else { WebImage::Failed }
168}
169
170/// Copia pixels para um canvas fora da tela (o `drawImage` aceita canvas).
171fn load_pixels(width: u32, height: u32, rgba: &[u8], bgra: bool) -> WebImage {
172    let make = || -> Result<HtmlCanvasElement, JsValue> {
173        let document = web_sys::window().and_then(|w| w.document()).ok_or("sem document")?;
174        let canvas: HtmlCanvasElement = document.create_element("canvas")?.dyn_into()?;
175        canvas.set_width(width);
176        canvas.set_height(height);
177        let ctx: CanvasRenderingContext2d = canvas.get_context("2d")?.ok_or("sem 2d")?.dyn_into()?;
178        let mut data = rgba.to_vec();
179        if bgra {
180            // O BGRA vem pré-multiplicado (o contrato do tipo); o `ImageData` quer sem.
181            for px in data.chunks_exact_mut(4) {
182                px.swap(0, 2);
183                let a = px[3] as u32;
184                if a > 0 && a < 255 {
185                    for c in &mut px[..3] {
186                        *c = ((*c as u32 * 255 + a / 2) / a).min(255) as u8;
187                    }
188                }
189            }
190        }
191        let image = ImageData::new_with_u8_clamped_array_and_sh(Clamped(&data), width, height)?;
192        ctx.put_image_data(&image, 0.0, 0.0)?;
193        Ok(canvas)
194    };
195    make().map_or(WebImage::Failed, WebImage::Pixels)
196}
197
198/// Garante a imagem no cache e roda `f` com ela.
199fn with_image<R>(image: &Image, f: impl FnOnce(&WebImage) -> R) -> R {
200    let ready = IMAGES.with(|c| {
201        if let Some(found) = c.borrow_mut().get(image) {
202            return found;
203        }
204        let loaded = match image.source() {
205            ImageSource::Encoded(bytes) => load_encoded(image.id(), bytes),
206            ImageSource::Rgba { width, height, pixels } => load_pixels(*width, *height, pixels, false),
207            ImageSource::Bgra { width, height, pixels } => load_pixels(*width, *height, pixels, true),
208        };
209        c.borrow_mut().insert(image, loaded.clone());
210        loaded
211    });
212    // Fora do empréstimo do cache (o desenho pode pedir outra imagem).
213    f(&ready)
214}
215
216thread_local! {
217    /// Os `<canvas>` de quem desenha por fora (o 3D), pelo número.
218    static GPU_CANVASES: RefCell<HashMap<u32, HtmlCanvasElement>> = RefCell::new(HashMap::new());
219}
220
221/// O `<canvas id="aylis-3d-<n>">` da página (guardado depois da primeira busca).
222fn gpu_canvas(n: u32) -> Option<HtmlCanvasElement> {
223    if let Some(c) = GPU_CANVASES.with(|m| m.borrow().get(&n).cloned()) {
224        return Some(c);
225    }
226    let document = web_sys::window()?.document()?;
227    let canvas: HtmlCanvasElement = document.get_element_by_id(&format!("aylis-3d-{n}"))?.dyn_into().ok()?;
228    GPU_CANVASES.with(|m| m.borrow_mut().insert(n, canvas.clone()));
229    Some(canvas)
230}
231
232thread_local! {
233    /// Se o Canvas 2D tem `filter` (o Safari não tem): lido uma vez.
234    static HAS_FILTER: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
235    /// Canvas fora da tela do desfoque sem `filter`.
236    static BLUR_SCRATCH: RefCell<Option<(HtmlCanvasElement, CanvasRenderingContext2d)>> = const { RefCell::new(None) };
237}
238
239/// O Canvas 2D aceita `filter: blur()`? Diagnóstico: `?aylis_blur=reduzir` na URL força o
240/// caminho sem filtro (o do Safari) em qualquer navegador.
241fn has_canvas_filter() -> bool {
242    HAS_FILTER.with(|cell| {
243        if let Some(v) = cell.get() {
244            return v;
245        }
246        let global = js_sys::global();
247        let get = |o: &JsValue, k: &str| js_sys::Reflect::get(o, &k.into()).ok();
248        let forced = get(&global, "location").and_then(|l| get(&l, "search")).and_then(|s| s.as_string()).is_some_and(|q| q.contains("aylis_blur=reduzir"));
249        let proto = get(&global, "CanvasRenderingContext2D").and_then(|c| get(&c, "prototype"));
250        let v = !forced && proto.is_some_and(|p| js_sys::Reflect::has(&p, &"filter".into()).unwrap_or(false));
251        cell.set(Some(v));
252        v
253    })
254}
255
256/// Desfoque sem `filter`: a região é reduzida em dois passos e ampliada de volta com
257/// suavização, o que fica perto de um gaussiano de desvio `sigma` (em pixels).
258fn blur_by_scaling(ctx: &CanvasRenderingContext2d, source: &HtmlCanvasElement, [x, y, w, h]: [f64; 4], sigma: f64) {
259    // Reduzir por k e ampliar com interpolação linear espalha cerca de k/2 de desvio; o
260    // passo intermediário (k/2) tira os "degraus" da ampliação direta.
261    let k = (sigma * 1.5).max(2.0);
262    let (sw, sh) = ((w / k).ceil().max(1.0), (h / k).ceil().max(1.0));
263    let (mw, mh) = ((sw * 2.0).min(w).max(1.0), (sh * 2.0).min(h).max(1.0));
264    BLUR_SCRATCH.with(|cell| {
265        let mut cell = cell.borrow_mut();
266        if cell.is_none() {
267            let canvas = web_sys::window()
268                .and_then(|w| w.document())
269                .and_then(|d| d.create_element("canvas").ok())
270                .and_then(|e| e.dyn_into::<HtmlCanvasElement>().ok());
271            let ctx = canvas.as_ref().and_then(|c| c.get_context("2d").ok().flatten()).and_then(|c| c.dyn_into::<CanvasRenderingContext2d>().ok());
272            if let (Some(canvas), Some(ctx)) = (canvas, ctx) {
273                *cell = Some((canvas, ctx));
274            }
275        }
276        let Some((scratch, sctx)) = cell.as_ref() else { return };
277        let (cw, ch) = ((sw + mw).ceil() as u32, mh.ceil() as u32);
278        if scratch.width() < cw || scratch.height() < ch {
279            scratch.set_width(cw.max(scratch.width()));
280            scratch.set_height(ch.max(scratch.height()));
281        }
282        let _ = js_sys::Reflect::set(sctx, &"imageSmoothingQuality".into(), &"high".into());
283        let _ = js_sys::Reflect::set(ctx, &"imageSmoothingQuality".into(), &"high".into());
284        sctx.set_image_smoothing_enabled(true);
285        ctx.set_image_smoothing_enabled(true);
286        sctx.clear_rect(0.0, 0.0, cw as f64, ch as f64);
287        // Fonte → meio (mw×mh, em x = sw) → pequeno (sw×sh, em x = 0) → meio → destino.
288        let _ = sctx.draw_image_with_html_canvas_element_and_sw_and_sh_and_dx_and_dy_and_dw_and_dh(source, x, y, w, h, sw, 0.0, mw, mh);
289        let _ = sctx.draw_image_with_html_canvas_element_and_sw_and_sh_and_dx_and_dy_and_dw_and_dh(scratch, sw, 0.0, mw, mh, 0.0, 0.0, sw, sh);
290        let _ = sctx.draw_image_with_html_canvas_element_and_sw_and_sh_and_dx_and_dy_and_dw_and_dh(scratch, 0.0, 0.0, sw, sh, sw, 0.0, mw, mh);
291        let _ = ctx.draw_image_with_html_canvas_element_and_sw_and_sh_and_dx_and_dy_and_dw_and_dh(scratch, sw, 0.0, mw, mh, x, y, w, h);
292    });
293}
294
295/// Canvas do aylis sobre um contexto 2D.
296pub struct Canvas2d<'a> {
297    ctx: CanvasRenderingContext2d,
298    /// Os `save` abertos por este canvas: um `restore` a mais (o Skia ignora) não pode
299    /// fechar o `save` de quem o criou, que guarda o recorte da área repintada.
300    depth: usize,
301    /// Os `begin_cached` abertos (`None`: não deu para guardar, desenha direto).
302    cached: Vec<Option<WebCache>>,
303    /// As camadas de `save_layer` abertas (a opacidade de um contêiner com os filhos).
304    layers: Vec<WebLayer>,
305    _life: std::marker::PhantomData<&'a CanvasRenderingContext2d>,
306}
307
308/// Uma camada de `save_layer`: o grupo é desenhado num canvas à parte, do tamanho do de
309/// baixo, e composto uma vez só com a opacidade no `restore`. Com o `globalAlpha` em cada
310/// desenho, o que os filhos cobrem uns dos outros aparecia por baixo (o fundo do painel através
311/// do botão), diferente do Skia e do Direct2D (o relatório do Tabernáculo, C24).
312struct WebLayer {
313    main: CanvasRenderingContext2d,
314    /// Os `save` de `main` abertos antes da camada.
315    depth: usize,
316    /// Quantos `begin_cached` estavam abertos: o `restore` só fecha a camada no mesmo nível.
317    cached: usize,
318    canvas: HtmlCanvasElement,
319    opacity: f64,
320    /// Como a camada se junta ao canvas de baixo (o `globalCompositeOperation`).
321    blend: aylis_core::BlendMode,
322}
323
324/// Um desenho sendo guardado: o contexto de antes e a imagem onde ele vai.
325struct WebCache {
326    main: CanvasRenderingContext2d,
327    depth: usize,
328    canvas: HtmlCanvasElement,
329    key: u64,
330    /// A chave do núcleo (para soltar pela `forget_cached`).
331    owner: u64,
332    at: (f64, f64),
333}
334
335thread_local! {
336    /// Os desenhos guardados (`Canvas::begin_cached`: o `cache_layer` de um controle, um
337    /// mapa parado), pela chave.
338    static LAYERS: RefCell<aylis_core::LayerCache<HtmlCanvasElement>> = RefCell::new(aylis_core::LayerCache::named("Canvas 2D · camadas guardadas"));
339    /// Os canvas das camadas de `save_layer` já usados, para o próximo quadro.
340    static SPARE_LAYERS: RefCell<Vec<HtmlCanvasElement>> = const { RefCell::new(Vec::new()) };
341}
342
343/// Um canvas `width` × `height` limpo, para uma camada (um guardado, se houver).
344fn layer_canvas(width: u32, height: u32) -> Option<(HtmlCanvasElement, CanvasRenderingContext2d)> {
345    let canvas = match SPARE_LAYERS.with(|s| s.borrow_mut().pop()) {
346        Some(c) => c,
347        None => web_sys::window()?.document()?.create_element("canvas").ok()?.dyn_into::<HtmlCanvasElement>().ok()?,
348    };
349    if canvas.width() != width || canvas.height() != height {
350        canvas.set_width(width);
351        canvas.set_height(height);
352    }
353    let ctx = canvas.get_context("2d").ok().flatten()?.dyn_into::<CanvasRenderingContext2d>().ok()?;
354    let _ = ctx.set_transform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
355    ctx.set_global_alpha(1.0);
356    ctx.clear_rect(0.0, 0.0, width as f64, height as f64);
357    Some((canvas, ctx))
358}
359
360/// Desenha `canvas` com o canto em `at`, em pixels (sem a transformação atual; o recorte vale).
361fn draw_at_device(ctx: &CanvasRenderingContext2d, canvas: &HtmlCanvasElement, at: (f64, f64)) {
362    ctx.save();
363    let _ = ctx.set_transform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
364    let _ = ctx.draw_image_with_html_canvas_element(canvas, at.0, at.1);
365    ctx.restore();
366}
367
368impl<'a> Canvas2d<'a> {
369    pub fn new(ctx: &'a CanvasRenderingContext2d) -> Self {
370        Self { ctx: ctx.clone(), depth: 0, cached: Vec::new(), layers: Vec::new(), _life: std::marker::PhantomData }
371    }
372
373    /// O contexto 2D por baixo, para desenhos que o trait não cobre.
374    pub fn context(&self) -> &CanvasRenderingContext2d {
375        &self.ctx
376    }
377
378    fn rect_path(&self, r: RectF, radius: f32) {
379        let ctx = &self.ctx.clone();
380        ctx.begin_path();
381        let (x, y, w, h) = (r.x as f64, r.y as f64, r.width as f64, r.height as f64);
382        let rad = (radius as f64).min(w / 2.0).min(h / 2.0).max(0.0);
383        if rad <= 0.0 {
384            ctx.rect(x, y, w, h);
385            return;
386        }
387        ctx.move_to(x + rad, y);
388        let _ = ctx.arc_to(x + w, y, x + w, y + h, rad);
389        let _ = ctx.arc_to(x + w, y + h, x, y + h, rad);
390        let _ = ctx.arc_to(x, y + h, x, y, rad);
391        let _ = ctx.arc_to(x, y, x + w, y, rad);
392        ctx.close_path();
393    }
394
395    fn ellipse_path(&self, r: RectF) {
396        self.ctx.begin_path();
397        let _ = self.ctx.ellipse(
398            (r.x + r.width / 2.0) as f64,
399            (r.y + r.height / 2.0) as f64,
400            (r.width / 2.0).max(0.0) as f64,
401            (r.height / 2.0).max(0.0) as f64,
402            0.0,
403            0.0,
404            2.0 * PI,
405        );
406    }
407
408    fn set_fill(&self, brush: &Brush) {
409        match paint_of(&self.ctx, brush) {
410            Paint::Color(c) => self.ctx.set_fill_style_str(&c),
411            Paint::Gradient(g) => self.ctx.set_fill_style_canvas_gradient(&g),
412        }
413    }
414
415    fn set_stroke(&self, stroke: &Stroke) {
416        match paint_of(&self.ctx, &stroke.brush) {
417            Paint::Color(c) => self.ctx.set_stroke_style_str(&c),
418            Paint::Gradient(g) => self.ctx.set_stroke_style_canvas_gradient(&g),
419        }
420        self.ctx.set_line_width(stroke.width as f64);
421        let dash = js_sys::Array::new();
422        for d in stroke.dash.iter().flatten() {
423            dash.push(&JsValue::from_f64(*d as f64));
424        }
425        let _ = self.ctx.set_line_dash(&dash);
426        self.ctx.set_line_cap(match stroke.cap {
427            aylis_core::LineCap::Butt => "butt",
428            aylis_core::LineCap::Round => "round",
429            aylis_core::LineCap::Square => "square",
430        });
431        self.ctx.set_line_join(match stroke.join {
432            aylis_core::LineJoin::Miter => "miter",
433            aylis_core::LineJoin::Round => "round",
434            aylis_core::LineJoin::Bevel => "bevel",
435        });
436    }
437
438    fn build_path(&self, path: &aylis_core::Path) {
439        use aylis_core::PathCmd;
440        let ctx = &self.ctx.clone();
441        ctx.begin_path();
442        for c in &path.cmds {
443            match *c {
444                PathCmd::MoveTo(p) => ctx.move_to(p.x as f64, p.y as f64),
445                PathCmd::LineTo(p) => ctx.line_to(p.x as f64, p.y as f64),
446                PathCmd::QuadTo(c, p) => ctx.quadratic_curve_to(c.x as f64, c.y as f64, p.x as f64, p.y as f64),
447                PathCmd::CubicTo(a, b, p) => {
448                    ctx.bezier_curve_to(a.x as f64, a.y as f64, b.x as f64, b.y as f64, p.x as f64, p.y as f64)
449                }
450                PathCmd::Close => ctx.close_path(),
451            }
452        }
453    }
454}
455
456impl Canvas for Canvas2d<'_> {
457    fn save(&mut self) {
458        self.depth += 1;
459        self.ctx.save();
460    }
461
462    fn restore(&mut self) {
463        if self.depth > 0 {
464            self.depth -= 1;
465            self.ctx.restore();
466        } else if self.layers.last().is_some_and(|l| l.cached == self.cached.len()) {
467            // Fecha a camada: o grupo vai para o canvas de baixo com a opacidade, no recorte
468            // de lá.
469            let Some(layer) = self.layers.pop() else { return };
470            self.ctx = layer.main;
471            self.depth = layer.depth;
472            self.ctx.save();
473            let _ = self.ctx.set_transform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
474            self.ctx.set_global_alpha(self.ctx.global_alpha() * layer.opacity);
475            if layer.blend != aylis_core::BlendMode::Normal {
476                let _ = self.ctx.set_global_composite_operation(layer.blend.css());
477            }
478            let _ = self.ctx.draw_image_with_html_canvas_element(&layer.canvas, 0.0, 0.0);
479            self.ctx.restore();
480            SPARE_LAYERS.with(|s| {
481                let mut spare = s.borrow_mut();
482                if spare.len() < 4 {
483                    spare.push(layer.canvas);
484                }
485            });
486        }
487    }
488
489    fn translate(&mut self, dx: f32, dy: f32) {
490        let _ = self.ctx.translate(dx as f64, dy as f64);
491    }
492
493    fn scale(&mut self, sx: f32, sy: f32) {
494        let _ = self.ctx.scale(sx as f64, sy as f64);
495    }
496
497    fn rotate(&mut self, degrees: f32) {
498        let _ = self.ctx.rotate((degrees as f64).to_radians());
499    }
500
501    fn clip_rect(&mut self, rect: RectF) {
502        self.rect_path(rect, 0.0);
503        self.ctx.clip();
504    }
505
506    fn save_layer(&mut self, opacity: f32) {
507        self.save_layer_blend(opacity, aylis_core::BlendMode::Normal, RectF::default());
508    }
509
510    // A camada já é um canvas à parte: ao fechar, ela se junta ao de baixo pelo
511    // `globalCompositeOperation` do modo (os mesmos nomes do CSS). Sem o canvas à parte, sem
512    // mistura.
513    fn save_layer_blend(&mut self, opacity: f32, blend: aylis_core::BlendMode, _bounds: RectF) {
514        // O grupo num canvas à parte, com a mesma transformação; o recorte de baixo vale ao
515        // compor. Sem como criar o canvas, o `globalAlpha` em cada desenho (o de antes).
516        let target = self.ctx.canvas().zip(self.ctx.get_transform().ok()).and_then(|(main, m)| Some((layer_canvas(main.width(), main.height())?, m)));
517        let Some(((canvas, target), m)) = target else {
518            self.depth += 1;
519            self.ctx.save();
520            self.ctx.set_global_alpha(self.ctx.global_alpha() * opacity as f64);
521            return;
522        };
523        let _ = target.set_transform(m.a(), m.b(), m.c(), m.d(), m.e(), m.f());
524        let main = std::mem::replace(&mut self.ctx, target);
525        let depth = std::mem::take(&mut self.depth);
526        self.layers.push(WebLayer { main, depth, cached: self.cached.len(), canvas, opacity: opacity as f64, blend });
527    }
528
529    fn fill_rect(&mut self, rect: RectF, radius: f32, brush: &Brush) {
530        self.set_fill(brush);
531        self.rect_path(rect, radius);
532        self.ctx.fill();
533    }
534
535    fn stroke_rect(&mut self, rect: RectF, radius: f32, stroke: &Stroke) {
536        if stroke.width <= 0.0 {
537            return;
538        }
539        self.set_stroke(stroke);
540        self.rect_path(rect.inflate(-stroke.width / 2.0), (radius - stroke.width / 2.0).max(0.0));
541        self.ctx.stroke();
542    }
543
544    fn fill_ellipse(&mut self, rect: RectF, brush: &Brush) {
545        self.set_fill(brush);
546        self.ellipse_path(rect);
547        self.ctx.fill();
548    }
549
550    fn stroke_ellipse(&mut self, rect: RectF, stroke: &Stroke) {
551        if stroke.width <= 0.0 {
552            return;
553        }
554        self.set_stroke(stroke);
555        self.ellipse_path(rect.inflate(-stroke.width / 2.0));
556        self.ctx.stroke();
557    }
558
559    fn draw_line(&mut self, from: PointF, to: PointF, stroke: &Stroke) {
560        self.set_stroke(stroke);
561        self.ctx.begin_path();
562        self.ctx.move_to(from.x as f64, from.y as f64);
563        self.ctx.line_to(to.x as f64, to.y as f64);
564        self.ctx.stroke();
565    }
566
567    fn fill_path(&mut self, path: &aylis_core::Path, brush: &Brush) {
568        self.set_fill(brush);
569        self.build_path(path);
570        if path.even_odd {
571            self.ctx.fill_with_canvas_winding_rule(web_sys::CanvasWindingRule::Evenodd);
572        } else {
573            self.ctx.fill();
574        }
575    }
576
577    fn begin_cached(&mut self, key: u64, r: RectF) -> bool {
578        use std::hash::{Hash, Hasher};
579        let Ok(m) = self.ctx.get_transform() else {
580            self.cached.push(None);
581            return false;
582        };
583        // Só sem giro: a imagem vai para a tela pixel a pixel.
584        let (a, d) = (m.a(), m.d());
585        if m.b() != 0.0 || m.c() != 0.0 || a <= 0.0 || d <= 0.0 {
586            self.cached.push(None);
587            return false;
588        }
589        let x0 = (r.x as f64 * a + m.e()).round();
590        let y0 = (r.y as f64 * d + m.f()).round();
591        let (w, h) = ((r.width as f64 * a).ceil(), (r.height as f64 * d).ceil());
592        if w < 1.0 || h < 1.0 || w > 8192.0 || h > 8192.0 {
593            self.cached.push(None);
594            return false;
595        }
596        let mut hasher = std::collections::hash_map::DefaultHasher::new();
597        (key, w as u32, h as u32, a.to_bits(), d.to_bits()).hash(&mut hasher);
598        let full = hasher.finish();
599        if let Some(canvas) = LAYERS.with(|l| l.borrow_mut().get(full).cloned()) {
600            draw_at_device(&self.ctx, &canvas, (x0, y0));
601            return true;
602        }
603        // Sem lugar no limite das camadas (`image_cache.layers_mb`): desenha direto.
604        if !aylis_core::LayerCache::<HtmlCanvasElement>::accepts(w as usize * h as usize * 4) {
605            self.cached.push(None);
606            return false;
607        }
608        let made = web_sys::window().and_then(|w| w.document()).and_then(|d| d.create_element("canvas").ok()).and_then(|e| e.dyn_into::<HtmlCanvasElement>().ok());
609        let Some(canvas) = made else {
610            self.cached.push(None);
611            return false;
612        };
613        canvas.set_width(w as u32);
614        canvas.set_height(h as u32);
615        let Some(target) = canvas.get_context("2d").ok().flatten().and_then(|c| c.dyn_into::<CanvasRenderingContext2d>().ok()) else {
616            self.cached.push(None);
617            return false;
618        };
619        // A mesma escala; a origem da imagem é o canto dela na tela.
620        let _ = target.set_transform(a, 0.0, 0.0, d, m.e() - x0, m.f() - y0);
621        let main = std::mem::replace(&mut self.ctx, target);
622        let depth = std::mem::take(&mut self.depth);
623        self.cached.push(Some(WebCache { main, depth, canvas, key: full, owner: key, at: (x0, y0) }));
624        false
625    }
626
627    fn end_cached(&mut self) {
628        let Some(state) = self.cached.pop().flatten() else { return };
629        self.ctx = state.main;
630        self.depth = state.depth;
631        draw_at_device(&self.ctx, &state.canvas, state.at);
632        // O limite é em bytes (`image_cache.layers_mb`): cada destaque novo de um mapa é uma
633        // imagem nova, e sai a usada há mais tempo.
634        let bytes = state.canvas.width() as usize * state.canvas.height() as usize * 4;
635        LAYERS.with(|l| l.borrow_mut().insert(state.owner, state.key, state.canvas, bytes));
636    }
637
638    fn forget_cached(&mut self, key: u64) {
639        LAYERS.with(|l| l.borrow_mut().forget(key));
640    }
641
642    fn backdrop_blur(&mut self, rect: RectF, radius: f32, blur: f32) -> bool {
643        // O próprio canvas desenhado sobre si, desfocado (`filter: blur()`), recortado
644        // nos cantos. Em pixels: lê a transformação atual.
645        let ctx = &self.ctx.clone();
646        let read = || -> Option<[f64; 6]> {
647            let f: js_sys::Function = js_sys::Reflect::get(ctx, &"getTransform".into()).ok()?.dyn_into().ok()?;
648            let m = f.call0(ctx).ok()?;
649            let g = |k: &str| js_sys::Reflect::get(&m, &k.into()).ok().and_then(|v| v.as_f64());
650            Some([g("a")?, g("b")?, g("c")?, g("d")?, g("e")?, g("f")?])
651        };
652        let (Some([a, _b, _c, d, e, f]), Some(canvas)) = (read(), ctx.canvas()) else { return false };
653        let pad = (blur as f64) * a.abs() * 3.0;
654        let x0 = (rect.x as f64 * a + e - pad).max(0.0);
655        let y0 = (rect.y as f64 * d + f - pad).max(0.0);
656        let x1 = ((rect.right() as f64) * a + e + pad).min(canvas.width() as f64);
657        let y1 = ((rect.bottom() as f64) * d + f + pad).min(canvas.height() as f64);
658        if x1 <= x0 || y1 <= y0 {
659            return false;
660        }
661        ctx.save();
662        self.rect_path(rect, radius);
663        ctx.clip();
664        let _ = ctx.set_transform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
665        let sigma = blur as f64 * a.abs();
666        if has_canvas_filter() {
667            ctx.set_filter(&format!("blur({sigma}px)"));
668            let _ = ctx.draw_image_with_html_canvas_element_and_sw_and_sh_and_dx_and_dy_and_dw_and_dh(&canvas, x0, y0, x1 - x0, y1 - y0, x0, y0, x1 - x0, y1 - y0);
669        } else {
670            blur_by_scaling(ctx, &canvas, [x0, y0, x1 - x0, y1 - y0], sigma);
671        }
672        ctx.restore();
673        true
674    }
675
676    fn clip_path(&mut self, path: &aylis_core::Path, inverse: bool) {
677        if inverse {
678            let mut p = aylis_core::Path::new();
679            p.rect(RectF::new(-1.0e6, -1.0e6, 2.0e6, 2.0e6), 0.0);
680            p.append(path);
681            self.build_path(&p);
682            self.ctx.clip_with_canvas_winding_rule(web_sys::CanvasWindingRule::Evenodd);
683        } else {
684            self.build_path(path);
685            let rule = if path.even_odd { web_sys::CanvasWindingRule::Evenodd } else { web_sys::CanvasWindingRule::Nonzero };
686            self.ctx.clip_with_canvas_winding_rule(rule);
687        }
688    }
689
690    fn stroke_path(&mut self, path: &aylis_core::Path, stroke: &Stroke) {
691        if stroke.width <= 0.0 {
692            return;
693        }
694        self.set_stroke(stroke);
695        self.build_path(path);
696        self.ctx.stroke();
697    }
698
699    /// A sombra do próprio canvas 2D: desenha a forma longe da área visível e só a
700    /// sombra (deslocada de volta) aparece.
701    fn draw_shadow(&mut self, rect: RectF, radius: f32, shadow: &aylis_core::Shadow) {
702        if shadow.color.a == 0 {
703            return;
704        }
705        const FAR: f32 = 100_000.0;
706        let ctx = &self.ctx.clone();
707        ctx.save();
708        // O deslocamento da sombra não segue a transformação: converte para pixels.
709        let (sx, sy) = canvas_scale(ctx);
710        ctx.set_shadow_color(&css_color(shadow.color));
711        ctx.set_shadow_blur((shadow.blur * sx) as f64);
712        ctx.set_shadow_offset_x(((shadow.offset.x + FAR) * sx) as f64);
713        ctx.set_shadow_offset_y((shadow.offset.y * sy) as f64);
714        ctx.set_fill_style_str("#000");
715        let r = rect.inflate(shadow.spread);
716        self.rect_path(RectF::new(r.x - FAR, r.y, r.width, r.height), (radius + shadow.spread).max(0.0));
717        ctx.fill();
718        ctx.restore();
719    }
720
721    fn draw_text(&mut self, text: &str, rect: RectF, style: &TextStyle) {
722        if text.is_empty() || rect.width <= 0.0 {
723            return;
724        }
725        sync_fonts();
726        let ctx = &self.ctx.clone();
727        let font = font_css(&style.font);
728        ctx.set_font(&font);
729        ctx.set_fill_style_str(&css_color(style.color));
730        ctx.set_text_baseline("middle");
731        // Quebra e reticências pela regra comum (iguais às do Skia).
732        let line_height = line_height(&style.font);
733        let max_lines = ((rect.height + 1.0) / line_height).floor().max(1.0) as usize;
734        let mut measure = |s: &str| text_width(ctx, &font, s);
735        let lines = aylis_core::text::layout_lines_marked(text, rect.width, max_lines, style.wrap, style.trimming, &mut measure);
736        let total = line_height * lines.len() as f32;
737        let top = match style.v_align {
738            TextAlign::Leading | TextAlign::Justify => rect.y,
739            TextAlign::Center => rect.y + (rect.height - total) / 2.0,
740            TextAlign::Trailing => rect.bottom() - total,
741        };
742        let (align, x) = match style.h_align {
743            TextAlign::Leading | TextAlign::Justify => ("left", rect.x),
744            TextAlign::Center => ("center", rect.x + rect.width / 2.0),
745            TextAlign::Trailing => ("right", rect.right()),
746        };
747        ctx.set_text_align(align);
748        for (i, (line, end)) in lines.iter().enumerate() {
749            let y = top + line_height * (i as f32 + 0.5);
750            // Justificado: cada palavra no lugar dela (a última linha do parágrafo fica à
751            // esquerda); o sublinhado vai de ponta a ponta.
752            let words = (style.h_align == TextAlign::Justify && !end).then(|| aylis_core::text::justify_line(line, rect.width, &mut measure)).flatten();
753            if let Some(words) = words {
754                for (wx, word) in &words {
755                    let _ = ctx.fill_text(word, (rect.x + wx) as f64, y as f64);
756                }
757                let right = words.last().map_or(0.0, |(wx, w)| wx + text_width(ctx, &font, w));
758                aylis_core::decorate_line(self, &style.font, style.color, rect.x, right, top + line_height * i as f32, line_height);
759                continue;
760            }
761            let _ = ctx.fill_text(line, x as f64, y as f64);
762            // Sublinhado e tachado: o canvas 2D não faz sozinho.
763            if style.font.underline || style.font.strikeout {
764                let w = text_width(ctx, &font, line);
765                let left = match style.h_align {
766                    TextAlign::Leading | TextAlign::Justify => x,
767                    TextAlign::Center => x - w / 2.0,
768                    TextAlign::Trailing => x - w,
769                };
770                aylis_core::decorate_line(self, &style.font, style.color, left, w, top + line_height * i as f32, line_height);
771            }
772        }
773    }
774
775    fn measure_text(&mut self, text: &str, style: &TextStyle) -> SizeF {
776        measure_line(&self.ctx, text, style)
777    }
778
779    fn device_scale(&self) -> f32 {
780        let (sx, sy) = canvas_scale(&self.ctx);
781        (sx * sy).abs().sqrt()
782    }
783
784    fn gpu_device(&self) -> Option<aylis_core::GpuDevice> {
785        Some(aylis_core::GpuDevice::Web)
786    }
787
788    fn draw_gpu_surface(&mut self, dest: RectF, surface: &aylis_core::GpuSurface) -> bool {
789        let aylis_core::GpuSurface::WebCanvas { element, .. } = *surface else { return false };
790        let Some(canvas) = gpu_canvas(element) else { return false };
791        // O navegador copia o canvas do WebGPU dentro da GPU.
792        self.ctx
793            .draw_image_with_html_canvas_element_and_dw_and_dh(&canvas, dest.x as f64, dest.y as f64, dest.width as f64, dest.height as f64)
794            .is_ok()
795    }
796
797    fn draw_image(&mut self, image: &Image, src: RectF, dest: RectF, opacity: f32) {
798        let ctx = &self.ctx.clone();
799        let (sx, sy, sw, sh) = (src.x as f64, src.y as f64, src.width as f64, src.height as f64);
800        let (dx, dy, dw, dh) = (dest.x as f64, dest.y as f64, dest.width as f64, dest.height as f64);
801        with_image(image, |img| {
802            ctx.save();
803            ctx.set_global_alpha(ctx.global_alpha() * opacity as f64);
804            ctx.set_image_smoothing_enabled(true);
805            let _ = match img {
806                WebImage::Ready(el) => ctx.draw_image_with_html_image_element_and_sw_and_sh_and_dx_and_dy_and_dw_and_dh(el, sx, sy, sw, sh, dx, dy, dw, dh),
807                WebImage::Pixels(el) => ctx.draw_image_with_html_canvas_element_and_sw_and_sh_and_dx_and_dy_and_dw_and_dh(el, sx, sy, sw, sh, dx, dy, dw, dh),
808                WebImage::Loading | WebImage::Failed => Ok(()),
809            };
810            ctx.restore();
811        });
812    }
813
814    fn image_size(&mut self, image: &Image) -> Option<SizeF> {
815        if let Some(size) = image.known_size() {
816            return Some(size);
817        }
818        with_image(image, |img| match img {
819            WebImage::Ready(el) if el.natural_width() > 0 => Some(SizeF::new(el.natural_width() as f32, el.natural_height() as f32)),
820            _ => None,
821        })
822    }
823
824    fn clip_round_rect(&mut self, rect: RectF, radius: f32) {
825        self.rect_path(rect, radius);
826        self.ctx.clip();
827    }
828}
829
830/// Medição de texto num canvas próprio, fora da tela.
831pub struct WebTextService {
832    ctx: CanvasRenderingContext2d,
833}
834
835impl WebTextService {
836    pub fn new() -> Result<Self, JsValue> {
837        let document = web_sys::window().and_then(|w| w.document()).ok_or("sem document")?;
838        let canvas: HtmlCanvasElement = document.create_element("canvas")?.dyn_into()?;
839        let ctx = canvas.get_context("2d")?.ok_or("sem contexto 2d")?.dyn_into()?;
840        Ok(Self { ctx })
841    }
842}
843
844impl TextService for WebTextService {
845    fn measure(&self, text: &str, style: &TextStyle, max_width: Option<f32>) -> SizeF {
846        sync_fonts();
847        match max_width {
848            None => measure_line(&self.ctx, text, style),
849            Some(width) => {
850                let font = font_css(&style.font);
851                let lines = wrap_lines(&self.ctx, &font, text, width);
852                let widest = lines.iter().map(|l| text_width(&self.ctx, &font, l)).fold(0.0, f32::max);
853                SizeF::new(widest.ceil(), line_height(&style.font) * lines.len() as f32)
854            }
855        }
856    }
857}
858
859// ---------------------------------------------------------------------------
860
861enum Paint {
862    Color(String),
863    Gradient(CanvasGradient),
864}
865
866fn paint_of(ctx: &CanvasRenderingContext2d, brush: &Brush) -> Paint {
867    let gradient = match brush {
868        Brush::Solid(c) => return Paint::Color(css_color(*c)),
869        Brush::Linear { start, end, .. } => {
870            Some(ctx.create_linear_gradient(start.x as f64, start.y as f64, end.x as f64, end.y as f64))
871        }
872        Brush::Radial { center, radius, .. } => ctx
873            .create_radial_gradient(
874                center.x as f64,
875                center.y as f64,
876                0.0,
877                center.x as f64,
878                center.y as f64,
879                *radius as f64,
880            )
881            .ok(),
882        Brush::Sweep { center, start_angle, .. } => conic_gradient(ctx, *start_angle, *center),
883    };
884    let stops: &[GradientStop] = match brush {
885        Brush::Linear { stops, .. } | Brush::Radial { stops, .. } | Brush::Sweep { stops, .. } => stops,
886        Brush::Solid(_) => &[],
887    };
888    match gradient {
889        Some(g) => {
890            for s in stops {
891                let _ = g.add_color_stop(s.offset.clamp(0.0, 1.0), &css_color(s.color));
892            }
893            Paint::Gradient(g)
894        }
895        // Navegador sem gradiente cônico: usa a primeira cor.
896        None => Paint::Color(css_color(stops.first().map_or(Color::TRANSPARENT, |s| s.color))),
897    }
898}
899
900/// `createConicGradient` ainda não está no web-sys; chama pelo nome.
901fn conic_gradient(ctx: &CanvasRenderingContext2d, start_angle: f32, center: PointF) -> Option<CanvasGradient> {
902    let function: js_sys::Function = js_sys::Reflect::get(ctx, &"createConicGradient".into()).ok()?.dyn_into().ok()?;
903    // No canvas o ângulo 0 aponta para a direita, como no Skia.
904    let angle = (start_angle as f64).to_radians();
905    function
906        .call3(ctx, &angle.into(), &(center.x as f64).into(), &(center.y as f64).into())
907        .ok()?
908        .dyn_into()
909        .ok()
910}
911
912/// Escala atual do contexto (`getTransform().a` e `.d`), pelo nome: o web-sys só tem
913/// esse método com a feature `DomMatrix`.
914fn canvas_scale(ctx: &CanvasRenderingContext2d) -> (f32, f32) {
915    let read = || -> Option<(f32, f32)> {
916        let f: js_sys::Function = js_sys::Reflect::get(ctx, &"getTransform".into()).ok()?.dyn_into().ok()?;
917        let m = f.call0(ctx).ok()?;
918        let a = js_sys::Reflect::get(&m, &"a".into()).ok()?.as_f64()?;
919        let d = js_sys::Reflect::get(&m, &"d".into()).ok()?.as_f64()?;
920        Some((a as f32, d as f32))
921    };
922    read().unwrap_or((1.0, 1.0))
923}
924
925fn css_color(c: Color) -> String {
926    format!("rgba({},{},{},{})", c.r, c.g, c.b, c.a as f32 / 255.0)
927}
928
929fn font_css(font: &FontSpec) -> String {
930    let weight = match font.weight {
931        FontWeight::Thin => 100,
932        FontWeight::Light => 300,
933        FontWeight::Normal => 400,
934        FontWeight::Medium => 500,
935        FontWeight::SemiBold => 600,
936        FontWeight::Bold => 700,
937        FontWeight::Black => 900,
938    };
939    let family = match font.family.as_str() {
940        "" | "sans-serif" => "system-ui, -apple-system, \"Segoe UI\", Roboto, \"Noto Sans\", sans-serif".to_string(),
941        "monospace" => "ui-monospace, \"Cascadia Mono\", Consolas, Menlo, monospace".to_string(),
942        family => format!("\"{family}\", sans-serif"),
943    };
944    let style = if font.italic { "italic " } else { "" };
945    format!("{style}{weight} {}px {family}", font.size)
946}
947
948fn line_height(font: &FontSpec) -> f32 {
949    (font.size * 1.3).ceil()
950}
951
952thread_local! {
953    /// As larguras já medidas, por fonte (o CSS dela) e texto. O `measureText` é uma ida ao
954    /// navegador, e o layout e a quebra das linhas medem os mesmos textos a cada quadro (a
955    /// Landing no celular: ~300 medidas por quadro de rolagem, cada texto umas 4 vezes).
956    static WIDTHS: RefCell<HashMap<String, HashMap<String, f32>>> = RefCell::new(HashMap::new());
957    static WIDTH_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
958}
959
960/// Acima disto, as larguras guardadas recomeçam (um editor com um texto enorme não cresce
961/// sem fim).
962const MAX_WIDTHS: usize = 20_000;
963
964fn forget_widths() {
965    WIDTHS.with(|w| w.borrow_mut().clear());
966    WIDTH_COUNT.with(|c| c.set(0));
967}
968
969/// A largura de `text` na fonte `font` (o CSS de [`font_css`]). Só mede (e só troca a fonte
970/// do contexto) na primeira vez.
971fn text_width(ctx: &CanvasRenderingContext2d, font: &str, text: &str) -> f32 {
972    if let Some(w) = WIDTHS.with(|w| w.borrow().get(font).and_then(|m| m.get(text)).copied()) {
973        return w;
974    }
975    ctx.set_font(font);
976    let width = ctx.measure_text(text).map_or(0.0, |m| m.width() as f32);
977    if WIDTH_COUNT.with(|c| c.replace(c.get() + 1)) >= MAX_WIDTHS {
978        forget_widths();
979    }
980    WIDTHS.with(|w| w.borrow_mut().entry(font.to_string()).or_default().insert(text.to_string(), width));
981    width
982}
983
984fn measure_line(ctx: &CanvasRenderingContext2d, text: &str, style: &TextStyle) -> SizeF {
985    SizeF::new(text_width(ctx, &font_css(&style.font), text), line_height(&style.font))
986}
987
988/// Quebra por palavras para caber em `width` na fonte `font`.
989fn wrap_lines(ctx: &CanvasRenderingContext2d, font: &str, text: &str, width: f32) -> Vec<String> {
990    let mut lines = Vec::new();
991    for paragraph in text.split('\n') {
992        let mut line = String::new();
993        for word in paragraph.split_whitespace() {
994            let candidate = if line.is_empty() { word.to_string() } else { format!("{line} {word}") };
995            if !line.is_empty() && text_width(ctx, font, &candidate) > width {
996                lines.push(std::mem::take(&mut line));
997                line = word.to_string();
998            } else {
999                line = candidate;
1000            }
1001        }
1002        lines.push(line);
1003    }
1004    lines
1005}