1use 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#[derive(Clone)]
34enum WebImage {
35 Loading,
37 Ready(HtmlImageElement),
38 Pixels(HtmlCanvasElement),
40 Failed,
41}
42
43struct 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 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
85pub 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
94fn 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 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
131fn 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 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
170fn 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 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
198fn 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 f(&ready)
214}
215
216thread_local! {
217 static GPU_CANVASES: RefCell<HashMap<u32, HtmlCanvasElement>> = RefCell::new(HashMap::new());
219}
220
221fn 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 static HAS_FILTER: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
235 static BLUR_SCRATCH: RefCell<Option<(HtmlCanvasElement, CanvasRenderingContext2d)>> = const { RefCell::new(None) };
237}
238
239fn 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
256fn blur_by_scaling(ctx: &CanvasRenderingContext2d, source: &HtmlCanvasElement, [x, y, w, h]: [f64; 4], sigma: f64) {
259 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 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
295pub struct Canvas2d<'a> {
297 ctx: CanvasRenderingContext2d,
298 depth: usize,
301 cached: Vec<Option<WebCache>>,
303 layers: Vec<WebLayer>,
305 _life: std::marker::PhantomData<&'a CanvasRenderingContext2d>,
306}
307
308struct WebLayer {
313 main: CanvasRenderingContext2d,
314 depth: usize,
316 cached: usize,
318 canvas: HtmlCanvasElement,
319 opacity: f64,
320}
321
322struct WebCache {
324 main: CanvasRenderingContext2d,
325 depth: usize,
326 canvas: HtmlCanvasElement,
327 key: u64,
328 owner: u64,
330 at: (f64, f64),
331}
332
333thread_local! {
334 static LAYERS: RefCell<aylis_core::LayerCache<HtmlCanvasElement>> = RefCell::new(aylis_core::LayerCache::named("Canvas 2D · camadas guardadas"));
337 static SPARE_LAYERS: RefCell<Vec<HtmlCanvasElement>> = const { RefCell::new(Vec::new()) };
339}
340
341fn layer_canvas(width: u32, height: u32) -> Option<(HtmlCanvasElement, CanvasRenderingContext2d)> {
343 let canvas = match SPARE_LAYERS.with(|s| s.borrow_mut().pop()) {
344 Some(c) => c,
345 None => web_sys::window()?.document()?.create_element("canvas").ok()?.dyn_into::<HtmlCanvasElement>().ok()?,
346 };
347 if canvas.width() != width || canvas.height() != height {
348 canvas.set_width(width);
349 canvas.set_height(height);
350 }
351 let ctx = canvas.get_context("2d").ok().flatten()?.dyn_into::<CanvasRenderingContext2d>().ok()?;
352 let _ = ctx.set_transform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
353 ctx.set_global_alpha(1.0);
354 ctx.clear_rect(0.0, 0.0, width as f64, height as f64);
355 Some((canvas, ctx))
356}
357
358fn draw_at_device(ctx: &CanvasRenderingContext2d, canvas: &HtmlCanvasElement, at: (f64, f64)) {
360 ctx.save();
361 let _ = ctx.set_transform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
362 let _ = ctx.draw_image_with_html_canvas_element(canvas, at.0, at.1);
363 ctx.restore();
364}
365
366impl<'a> Canvas2d<'a> {
367 pub fn new(ctx: &'a CanvasRenderingContext2d) -> Self {
368 Self { ctx: ctx.clone(), depth: 0, cached: Vec::new(), layers: Vec::new(), _life: std::marker::PhantomData }
369 }
370
371 pub fn context(&self) -> &CanvasRenderingContext2d {
373 &self.ctx
374 }
375
376 fn rect_path(&self, r: RectF, radius: f32) {
377 let ctx = &self.ctx.clone();
378 ctx.begin_path();
379 let (x, y, w, h) = (r.x as f64, r.y as f64, r.width as f64, r.height as f64);
380 let rad = (radius as f64).min(w / 2.0).min(h / 2.0).max(0.0);
381 if rad <= 0.0 {
382 ctx.rect(x, y, w, h);
383 return;
384 }
385 ctx.move_to(x + rad, y);
386 let _ = ctx.arc_to(x + w, y, x + w, y + h, rad);
387 let _ = ctx.arc_to(x + w, y + h, x, y + h, rad);
388 let _ = ctx.arc_to(x, y + h, x, y, rad);
389 let _ = ctx.arc_to(x, y, x + w, y, rad);
390 ctx.close_path();
391 }
392
393 fn ellipse_path(&self, r: RectF) {
394 self.ctx.begin_path();
395 let _ = self.ctx.ellipse(
396 (r.x + r.width / 2.0) as f64,
397 (r.y + r.height / 2.0) as f64,
398 (r.width / 2.0).max(0.0) as f64,
399 (r.height / 2.0).max(0.0) as f64,
400 0.0,
401 0.0,
402 2.0 * PI,
403 );
404 }
405
406 fn set_fill(&self, brush: &Brush) {
407 match paint_of(&self.ctx, brush) {
408 Paint::Color(c) => self.ctx.set_fill_style_str(&c),
409 Paint::Gradient(g) => self.ctx.set_fill_style_canvas_gradient(&g),
410 }
411 }
412
413 fn set_stroke(&self, stroke: &Stroke) {
414 match paint_of(&self.ctx, &stroke.brush) {
415 Paint::Color(c) => self.ctx.set_stroke_style_str(&c),
416 Paint::Gradient(g) => self.ctx.set_stroke_style_canvas_gradient(&g),
417 }
418 self.ctx.set_line_width(stroke.width as f64);
419 let dash = js_sys::Array::new();
420 for d in stroke.dash.iter().flatten() {
421 dash.push(&JsValue::from_f64(*d as f64));
422 }
423 let _ = self.ctx.set_line_dash(&dash);
424 self.ctx.set_line_cap(match stroke.cap {
425 aylis_core::LineCap::Butt => "butt",
426 aylis_core::LineCap::Round => "round",
427 aylis_core::LineCap::Square => "square",
428 });
429 self.ctx.set_line_join(match stroke.join {
430 aylis_core::LineJoin::Miter => "miter",
431 aylis_core::LineJoin::Round => "round",
432 aylis_core::LineJoin::Bevel => "bevel",
433 });
434 }
435
436 fn build_path(&self, path: &aylis_core::Path) {
437 use aylis_core::PathCmd;
438 let ctx = &self.ctx.clone();
439 ctx.begin_path();
440 for c in &path.cmds {
441 match *c {
442 PathCmd::MoveTo(p) => ctx.move_to(p.x as f64, p.y as f64),
443 PathCmd::LineTo(p) => ctx.line_to(p.x as f64, p.y as f64),
444 PathCmd::QuadTo(c, p) => ctx.quadratic_curve_to(c.x as f64, c.y as f64, p.x as f64, p.y as f64),
445 PathCmd::CubicTo(a, b, p) => {
446 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)
447 }
448 PathCmd::Close => ctx.close_path(),
449 }
450 }
451 }
452}
453
454impl Canvas for Canvas2d<'_> {
455 fn save(&mut self) {
456 self.depth += 1;
457 self.ctx.save();
458 }
459
460 fn restore(&mut self) {
461 if self.depth > 0 {
462 self.depth -= 1;
463 self.ctx.restore();
464 } else if self.layers.last().is_some_and(|l| l.cached == self.cached.len()) {
465 let Some(layer) = self.layers.pop() else { return };
468 self.ctx = layer.main;
469 self.depth = layer.depth;
470 self.ctx.save();
471 let _ = self.ctx.set_transform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
472 self.ctx.set_global_alpha(self.ctx.global_alpha() * layer.opacity);
473 let _ = self.ctx.draw_image_with_html_canvas_element(&layer.canvas, 0.0, 0.0);
474 self.ctx.restore();
475 SPARE_LAYERS.with(|s| {
476 let mut spare = s.borrow_mut();
477 if spare.len() < 4 {
478 spare.push(layer.canvas);
479 }
480 });
481 }
482 }
483
484 fn translate(&mut self, dx: f32, dy: f32) {
485 let _ = self.ctx.translate(dx as f64, dy as f64);
486 }
487
488 fn scale(&mut self, sx: f32, sy: f32) {
489 let _ = self.ctx.scale(sx as f64, sy as f64);
490 }
491
492 fn rotate(&mut self, degrees: f32) {
493 let _ = self.ctx.rotate((degrees as f64).to_radians());
494 }
495
496 fn clip_rect(&mut self, rect: RectF) {
497 self.rect_path(rect, 0.0);
498 self.ctx.clip();
499 }
500
501 fn save_layer(&mut self, opacity: f32) {
502 let target = self.ctx.canvas().zip(self.ctx.get_transform().ok()).and_then(|(main, m)| Some((layer_canvas(main.width(), main.height())?, m)));
505 let Some(((canvas, target), m)) = target else {
506 self.depth += 1;
507 self.ctx.save();
508 self.ctx.set_global_alpha(self.ctx.global_alpha() * opacity as f64);
509 return;
510 };
511 let _ = target.set_transform(m.a(), m.b(), m.c(), m.d(), m.e(), m.f());
512 let main = std::mem::replace(&mut self.ctx, target);
513 let depth = std::mem::take(&mut self.depth);
514 self.layers.push(WebLayer { main, depth, cached: self.cached.len(), canvas, opacity: opacity as f64 });
515 }
516
517 fn fill_rect(&mut self, rect: RectF, radius: f32, brush: &Brush) {
518 self.set_fill(brush);
519 self.rect_path(rect, radius);
520 self.ctx.fill();
521 }
522
523 fn stroke_rect(&mut self, rect: RectF, radius: f32, stroke: &Stroke) {
524 if stroke.width <= 0.0 {
525 return;
526 }
527 self.set_stroke(stroke);
528 self.rect_path(rect.inflate(-stroke.width / 2.0), (radius - stroke.width / 2.0).max(0.0));
529 self.ctx.stroke();
530 }
531
532 fn fill_ellipse(&mut self, rect: RectF, brush: &Brush) {
533 self.set_fill(brush);
534 self.ellipse_path(rect);
535 self.ctx.fill();
536 }
537
538 fn stroke_ellipse(&mut self, rect: RectF, stroke: &Stroke) {
539 if stroke.width <= 0.0 {
540 return;
541 }
542 self.set_stroke(stroke);
543 self.ellipse_path(rect.inflate(-stroke.width / 2.0));
544 self.ctx.stroke();
545 }
546
547 fn draw_line(&mut self, from: PointF, to: PointF, stroke: &Stroke) {
548 self.set_stroke(stroke);
549 self.ctx.begin_path();
550 self.ctx.move_to(from.x as f64, from.y as f64);
551 self.ctx.line_to(to.x as f64, to.y as f64);
552 self.ctx.stroke();
553 }
554
555 fn fill_path(&mut self, path: &aylis_core::Path, brush: &Brush) {
556 self.set_fill(brush);
557 self.build_path(path);
558 if path.even_odd {
559 self.ctx.fill_with_canvas_winding_rule(web_sys::CanvasWindingRule::Evenodd);
560 } else {
561 self.ctx.fill();
562 }
563 }
564
565 fn begin_cached(&mut self, key: u64, r: RectF) -> bool {
566 use std::hash::{Hash, Hasher};
567 let Ok(m) = self.ctx.get_transform() else {
568 self.cached.push(None);
569 return false;
570 };
571 let (a, d) = (m.a(), m.d());
573 if m.b() != 0.0 || m.c() != 0.0 || a <= 0.0 || d <= 0.0 {
574 self.cached.push(None);
575 return false;
576 }
577 let x0 = (r.x as f64 * a + m.e()).round();
578 let y0 = (r.y as f64 * d + m.f()).round();
579 let (w, h) = ((r.width as f64 * a).ceil(), (r.height as f64 * d).ceil());
580 if w < 1.0 || h < 1.0 || w > 8192.0 || h > 8192.0 {
581 self.cached.push(None);
582 return false;
583 }
584 let mut hasher = std::collections::hash_map::DefaultHasher::new();
585 (key, w as u32, h as u32, a.to_bits(), d.to_bits()).hash(&mut hasher);
586 let full = hasher.finish();
587 if let Some(canvas) = LAYERS.with(|l| l.borrow_mut().get(full).cloned()) {
588 draw_at_device(&self.ctx, &canvas, (x0, y0));
589 return true;
590 }
591 if !aylis_core::LayerCache::<HtmlCanvasElement>::accepts(w as usize * h as usize * 4) {
593 self.cached.push(None);
594 return false;
595 }
596 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());
597 let Some(canvas) = made else {
598 self.cached.push(None);
599 return false;
600 };
601 canvas.set_width(w as u32);
602 canvas.set_height(h as u32);
603 let Some(target) = canvas.get_context("2d").ok().flatten().and_then(|c| c.dyn_into::<CanvasRenderingContext2d>().ok()) else {
604 self.cached.push(None);
605 return false;
606 };
607 let _ = target.set_transform(a, 0.0, 0.0, d, m.e() - x0, m.f() - y0);
609 let main = std::mem::replace(&mut self.ctx, target);
610 let depth = std::mem::take(&mut self.depth);
611 self.cached.push(Some(WebCache { main, depth, canvas, key: full, owner: key, at: (x0, y0) }));
612 false
613 }
614
615 fn end_cached(&mut self) {
616 let Some(state) = self.cached.pop().flatten() else { return };
617 self.ctx = state.main;
618 self.depth = state.depth;
619 draw_at_device(&self.ctx, &state.canvas, state.at);
620 let bytes = state.canvas.width() as usize * state.canvas.height() as usize * 4;
623 LAYERS.with(|l| l.borrow_mut().insert(state.owner, state.key, state.canvas, bytes));
624 }
625
626 fn forget_cached(&mut self, key: u64) {
627 LAYERS.with(|l| l.borrow_mut().forget(key));
628 }
629
630 fn backdrop_blur(&mut self, rect: RectF, radius: f32, blur: f32) -> bool {
631 let ctx = &self.ctx.clone();
634 let read = || -> Option<[f64; 6]> {
635 let f: js_sys::Function = js_sys::Reflect::get(ctx, &"getTransform".into()).ok()?.dyn_into().ok()?;
636 let m = f.call0(ctx).ok()?;
637 let g = |k: &str| js_sys::Reflect::get(&m, &k.into()).ok().and_then(|v| v.as_f64());
638 Some([g("a")?, g("b")?, g("c")?, g("d")?, g("e")?, g("f")?])
639 };
640 let (Some([a, _b, _c, d, e, f]), Some(canvas)) = (read(), ctx.canvas()) else { return false };
641 let pad = (blur as f64) * a.abs() * 3.0;
642 let x0 = (rect.x as f64 * a + e - pad).max(0.0);
643 let y0 = (rect.y as f64 * d + f - pad).max(0.0);
644 let x1 = ((rect.right() as f64) * a + e + pad).min(canvas.width() as f64);
645 let y1 = ((rect.bottom() as f64) * d + f + pad).min(canvas.height() as f64);
646 if x1 <= x0 || y1 <= y0 {
647 return false;
648 }
649 ctx.save();
650 self.rect_path(rect, radius);
651 ctx.clip();
652 let _ = ctx.set_transform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
653 let sigma = blur as f64 * a.abs();
654 if has_canvas_filter() {
655 ctx.set_filter(&format!("blur({sigma}px)"));
656 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);
657 } else {
658 blur_by_scaling(ctx, &canvas, [x0, y0, x1 - x0, y1 - y0], sigma);
659 }
660 ctx.restore();
661 true
662 }
663
664 fn clip_path(&mut self, path: &aylis_core::Path, inverse: bool) {
665 if inverse {
666 let mut p = aylis_core::Path::new();
667 p.rect(RectF::new(-1.0e6, -1.0e6, 2.0e6, 2.0e6), 0.0);
668 p.append(path);
669 self.build_path(&p);
670 self.ctx.clip_with_canvas_winding_rule(web_sys::CanvasWindingRule::Evenodd);
671 } else {
672 self.build_path(path);
673 let rule = if path.even_odd { web_sys::CanvasWindingRule::Evenodd } else { web_sys::CanvasWindingRule::Nonzero };
674 self.ctx.clip_with_canvas_winding_rule(rule);
675 }
676 }
677
678 fn stroke_path(&mut self, path: &aylis_core::Path, stroke: &Stroke) {
679 if stroke.width <= 0.0 {
680 return;
681 }
682 self.set_stroke(stroke);
683 self.build_path(path);
684 self.ctx.stroke();
685 }
686
687 fn draw_shadow(&mut self, rect: RectF, radius: f32, shadow: &aylis_core::Shadow) {
690 if shadow.color.a == 0 {
691 return;
692 }
693 const FAR: f32 = 100_000.0;
694 let ctx = &self.ctx.clone();
695 ctx.save();
696 let (sx, sy) = canvas_scale(ctx);
698 ctx.set_shadow_color(&css_color(shadow.color));
699 ctx.set_shadow_blur((shadow.blur * sx) as f64);
700 ctx.set_shadow_offset_x(((shadow.offset.x + FAR) * sx) as f64);
701 ctx.set_shadow_offset_y((shadow.offset.y * sy) as f64);
702 ctx.set_fill_style_str("#000");
703 let r = rect.inflate(shadow.spread);
704 self.rect_path(RectF::new(r.x - FAR, r.y, r.width, r.height), (radius + shadow.spread).max(0.0));
705 ctx.fill();
706 ctx.restore();
707 }
708
709 fn draw_text(&mut self, text: &str, rect: RectF, style: &TextStyle) {
710 if text.is_empty() || rect.width <= 0.0 {
711 return;
712 }
713 sync_fonts();
714 let ctx = &self.ctx.clone();
715 let font = font_css(&style.font);
716 ctx.set_font(&font);
717 ctx.set_fill_style_str(&css_color(style.color));
718 ctx.set_text_baseline("middle");
719 let line_height = line_height(&style.font);
721 let max_lines = ((rect.height + 1.0) / line_height).floor().max(1.0) as usize;
722 let mut measure = |s: &str| text_width(ctx, &font, s);
723 let lines = aylis_core::text::layout_lines_marked(text, rect.width, max_lines, style.wrap, style.trimming, &mut measure);
724 let total = line_height * lines.len() as f32;
725 let top = match style.v_align {
726 TextAlign::Leading | TextAlign::Justify => rect.y,
727 TextAlign::Center => rect.y + (rect.height - total) / 2.0,
728 TextAlign::Trailing => rect.bottom() - total,
729 };
730 let (align, x) = match style.h_align {
731 TextAlign::Leading | TextAlign::Justify => ("left", rect.x),
732 TextAlign::Center => ("center", rect.x + rect.width / 2.0),
733 TextAlign::Trailing => ("right", rect.right()),
734 };
735 ctx.set_text_align(align);
736 for (i, (line, end)) in lines.iter().enumerate() {
737 let y = top + line_height * (i as f32 + 0.5);
738 let words = (style.h_align == TextAlign::Justify && !end).then(|| aylis_core::text::justify_line(line, rect.width, &mut measure)).flatten();
741 if let Some(words) = words {
742 for (wx, word) in &words {
743 let _ = ctx.fill_text(word, (rect.x + wx) as f64, y as f64);
744 }
745 let right = words.last().map_or(0.0, |(wx, w)| wx + text_width(ctx, &font, w));
746 aylis_core::decorate_line(self, &style.font, style.color, rect.x, right, top + line_height * i as f32, line_height);
747 continue;
748 }
749 let _ = ctx.fill_text(line, x as f64, y as f64);
750 if style.font.underline || style.font.strikeout {
752 let w = text_width(ctx, &font, line);
753 let left = match style.h_align {
754 TextAlign::Leading | TextAlign::Justify => x,
755 TextAlign::Center => x - w / 2.0,
756 TextAlign::Trailing => x - w,
757 };
758 aylis_core::decorate_line(self, &style.font, style.color, left, w, top + line_height * i as f32, line_height);
759 }
760 }
761 }
762
763 fn measure_text(&mut self, text: &str, style: &TextStyle) -> SizeF {
764 measure_line(&self.ctx, text, style)
765 }
766
767 fn device_scale(&self) -> f32 {
768 let (sx, sy) = canvas_scale(&self.ctx);
769 (sx * sy).abs().sqrt()
770 }
771
772 fn gpu_device(&self) -> Option<aylis_core::GpuDevice> {
773 Some(aylis_core::GpuDevice::Web)
774 }
775
776 fn draw_gpu_surface(&mut self, dest: RectF, surface: &aylis_core::GpuSurface) -> bool {
777 let aylis_core::GpuSurface::WebCanvas { element, .. } = *surface else { return false };
778 let Some(canvas) = gpu_canvas(element) else { return false };
779 self.ctx
781 .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)
782 .is_ok()
783 }
784
785 fn draw_image(&mut self, image: &Image, src: RectF, dest: RectF, opacity: f32) {
786 let ctx = &self.ctx.clone();
787 let (sx, sy, sw, sh) = (src.x as f64, src.y as f64, src.width as f64, src.height as f64);
788 let (dx, dy, dw, dh) = (dest.x as f64, dest.y as f64, dest.width as f64, dest.height as f64);
789 with_image(image, |img| {
790 ctx.save();
791 ctx.set_global_alpha(ctx.global_alpha() * opacity as f64);
792 ctx.set_image_smoothing_enabled(true);
793 let _ = match img {
794 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),
795 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),
796 WebImage::Loading | WebImage::Failed => Ok(()),
797 };
798 ctx.restore();
799 });
800 }
801
802 fn image_size(&mut self, image: &Image) -> Option<SizeF> {
803 if let Some(size) = image.known_size() {
804 return Some(size);
805 }
806 with_image(image, |img| match img {
807 WebImage::Ready(el) if el.natural_width() > 0 => Some(SizeF::new(el.natural_width() as f32, el.natural_height() as f32)),
808 _ => None,
809 })
810 }
811
812 fn clip_round_rect(&mut self, rect: RectF, radius: f32) {
813 self.rect_path(rect, radius);
814 self.ctx.clip();
815 }
816}
817
818pub struct WebTextService {
820 ctx: CanvasRenderingContext2d,
821}
822
823impl WebTextService {
824 pub fn new() -> Result<Self, JsValue> {
825 let document = web_sys::window().and_then(|w| w.document()).ok_or("sem document")?;
826 let canvas: HtmlCanvasElement = document.create_element("canvas")?.dyn_into()?;
827 let ctx = canvas.get_context("2d")?.ok_or("sem contexto 2d")?.dyn_into()?;
828 Ok(Self { ctx })
829 }
830}
831
832impl TextService for WebTextService {
833 fn measure(&self, text: &str, style: &TextStyle, max_width: Option<f32>) -> SizeF {
834 sync_fonts();
835 match max_width {
836 None => measure_line(&self.ctx, text, style),
837 Some(width) => {
838 let font = font_css(&style.font);
839 let lines = wrap_lines(&self.ctx, &font, text, width);
840 let widest = lines.iter().map(|l| text_width(&self.ctx, &font, l)).fold(0.0, f32::max);
841 SizeF::new(widest.ceil(), line_height(&style.font) * lines.len() as f32)
842 }
843 }
844 }
845}
846
847enum Paint {
850 Color(String),
851 Gradient(CanvasGradient),
852}
853
854fn paint_of(ctx: &CanvasRenderingContext2d, brush: &Brush) -> Paint {
855 let gradient = match brush {
856 Brush::Solid(c) => return Paint::Color(css_color(*c)),
857 Brush::Linear { start, end, .. } => {
858 Some(ctx.create_linear_gradient(start.x as f64, start.y as f64, end.x as f64, end.y as f64))
859 }
860 Brush::Radial { center, radius, .. } => ctx
861 .create_radial_gradient(
862 center.x as f64,
863 center.y as f64,
864 0.0,
865 center.x as f64,
866 center.y as f64,
867 *radius as f64,
868 )
869 .ok(),
870 Brush::Sweep { center, start_angle, .. } => conic_gradient(ctx, *start_angle, *center),
871 };
872 let stops: &[GradientStop] = match brush {
873 Brush::Linear { stops, .. } | Brush::Radial { stops, .. } | Brush::Sweep { stops, .. } => stops,
874 Brush::Solid(_) => &[],
875 };
876 match gradient {
877 Some(g) => {
878 for s in stops {
879 let _ = g.add_color_stop(s.offset.clamp(0.0, 1.0), &css_color(s.color));
880 }
881 Paint::Gradient(g)
882 }
883 None => Paint::Color(css_color(stops.first().map_or(Color::TRANSPARENT, |s| s.color))),
885 }
886}
887
888fn conic_gradient(ctx: &CanvasRenderingContext2d, start_angle: f32, center: PointF) -> Option<CanvasGradient> {
890 let function: js_sys::Function = js_sys::Reflect::get(ctx, &"createConicGradient".into()).ok()?.dyn_into().ok()?;
891 let angle = (start_angle as f64).to_radians();
893 function
894 .call3(ctx, &angle.into(), &(center.x as f64).into(), &(center.y as f64).into())
895 .ok()?
896 .dyn_into()
897 .ok()
898}
899
900fn canvas_scale(ctx: &CanvasRenderingContext2d) -> (f32, f32) {
903 let read = || -> Option<(f32, f32)> {
904 let f: js_sys::Function = js_sys::Reflect::get(ctx, &"getTransform".into()).ok()?.dyn_into().ok()?;
905 let m = f.call0(ctx).ok()?;
906 let a = js_sys::Reflect::get(&m, &"a".into()).ok()?.as_f64()?;
907 let d = js_sys::Reflect::get(&m, &"d".into()).ok()?.as_f64()?;
908 Some((a as f32, d as f32))
909 };
910 read().unwrap_or((1.0, 1.0))
911}
912
913fn css_color(c: Color) -> String {
914 format!("rgba({},{},{},{})", c.r, c.g, c.b, c.a as f32 / 255.0)
915}
916
917fn font_css(font: &FontSpec) -> String {
918 let weight = match font.weight {
919 FontWeight::Thin => 100,
920 FontWeight::Light => 300,
921 FontWeight::Normal => 400,
922 FontWeight::Medium => 500,
923 FontWeight::SemiBold => 600,
924 FontWeight::Bold => 700,
925 FontWeight::Black => 900,
926 };
927 let family = match font.family.as_str() {
928 "" | "sans-serif" => "system-ui, -apple-system, \"Segoe UI\", Roboto, \"Noto Sans\", sans-serif".to_string(),
929 "monospace" => "ui-monospace, \"Cascadia Mono\", Consolas, Menlo, monospace".to_string(),
930 family => format!("\"{family}\", sans-serif"),
931 };
932 let style = if font.italic { "italic " } else { "" };
933 format!("{style}{weight} {}px {family}", font.size)
934}
935
936fn line_height(font: &FontSpec) -> f32 {
937 (font.size * 1.3).ceil()
938}
939
940thread_local! {
941 static WIDTHS: RefCell<HashMap<String, HashMap<String, f32>>> = RefCell::new(HashMap::new());
945 static WIDTH_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
946}
947
948const MAX_WIDTHS: usize = 20_000;
951
952fn forget_widths() {
953 WIDTHS.with(|w| w.borrow_mut().clear());
954 WIDTH_COUNT.with(|c| c.set(0));
955}
956
957fn text_width(ctx: &CanvasRenderingContext2d, font: &str, text: &str) -> f32 {
960 if let Some(w) = WIDTHS.with(|w| w.borrow().get(font).and_then(|m| m.get(text)).copied()) {
961 return w;
962 }
963 ctx.set_font(font);
964 let width = ctx.measure_text(text).map_or(0.0, |m| m.width() as f32);
965 if WIDTH_COUNT.with(|c| c.replace(c.get() + 1)) >= MAX_WIDTHS {
966 forget_widths();
967 }
968 WIDTHS.with(|w| w.borrow_mut().entry(font.to_string()).or_default().insert(text.to_string(), width));
969 width
970}
971
972fn measure_line(ctx: &CanvasRenderingContext2d, text: &str, style: &TextStyle) -> SizeF {
973 SizeF::new(text_width(ctx, &font_css(&style.font), text), line_height(&style.font))
974}
975
976fn wrap_lines(ctx: &CanvasRenderingContext2d, font: &str, text: &str, width: f32) -> Vec<String> {
978 let mut lines = Vec::new();
979 for paragraph in text.split('\n') {
980 let mut line = String::new();
981 for word in paragraph.split_whitespace() {
982 let candidate = if line.is_empty() { word.to_string() } else { format!("{line} {word}") };
983 if !line.is_empty() && text_width(ctx, font, &candidate) > width {
984 lines.push(std::mem::take(&mut line));
985 line = word.to_string();
986 } else {
987 line = candidate;
988 }
989 }
990 lines.push(line);
991 }
992 lines
993}