1use std::cell::Cell;
4
5use crate::anim::Easing;
6use crate::canvas::{Canvas, TextStyle};
7use crate::component::{ComponentId, ControlState};
8use crate::geometry::{PointF, RectF};
9use crate::theme::{ResolvedStyle, Theme};
10use crate::ui::Ui;
11
12pub struct PaintCtx<'a> {
14 pub ui: &'a Ui,
16 pub id: ComponentId,
18 pub rect: RectF,
20 pub state: ControlState,
21 pub style: &'a ResolvedStyle,
24 pub theme: &'a Theme,
25 pub time: f64,
27 pub design: bool,
30 pub colors: crate::ColorOverride,
33 frame_request: &'a Cell<bool>,
34 wake_at: &'a Cell<Option<f64>>,
35 resources: Option<&'a dyn crate::platform::ResourceService>,
36}
37
38impl PaintCtx<'_> {
39 pub fn with_style<'b>(&'b self, style: &'b ResolvedStyle) -> PaintCtx<'b> {
42 PaintCtx { style, ..*self }
43 }
44
45 pub fn resource(&self, path: &str) -> Option<Vec<u8>> {
47 self.resources?.read(path)
48 }
49
50 pub fn resource_image(&self, path: &str) -> Option<crate::Image> {
53 self.resource(path).map(|bytes| crate::Image::shared_file(path, bytes))
54 }
55
56 pub fn draw_icon(&self, canvas: &mut dyn crate::Canvas, name: &str, rect: RectF, color: crate::Color) {
59 self.draw_icon_width(canvas, name, rect, color, 0.0);
60 }
61
62 pub fn draw_icon_width(&self, canvas: &mut dyn crate::Canvas, name: &str, rect: RectF, color: crate::Color, stroke_width: f32) {
65 match self.ui.icon(name) {
66 Some(icon) => icon.draw_with_width(canvas, rect, color, stroke_width),
67 None => warn_missing_icon(self.ui, name, self.design),
68 }
69 }
70
71 pub fn look(&self) -> crate::theme::Look {
73 self.theme.look
74 }
75
76 pub fn variant(&self) -> &str {
78 self.ui.control(self.id).map_or("", |c| c.style())
79 }
80
81 pub fn text_style(&self) -> TextStyle {
83 TextStyle { font: self.style.font.clone(), color: self.style.text, ..Default::default() }
84 }
85
86 pub fn font(&self, size: f32) -> crate::FontSpec {
89 let cb = self.ui.control(self.id);
90 let own = cb.and_then(|c| c.font().size);
91 let scale = cb.map_or(1.0, |c| c.text_scale());
93 crate::FontSpec { size: own.unwrap_or(size) * scale, ..self.style.font.clone() }
94 }
95
96 pub fn monospace_font(&self, size: f32) -> crate::FontSpec {
99 let mut font = self.font(size);
100 let mut current = Some(self.id);
101 while let Some(id) = current {
102 if self.ui.control(id).is_some_and(|c| !c.font().family.is_empty()) {
103 return font;
104 }
105 current = self.ui.parent(id);
106 }
107 font.family = "monospace".into();
108 font
109 }
110
111 pub fn request_frame_at(&self, time: f64) {
115 let next = self.wake_at.get().map_or(time, |t| t.min(time));
116 self.wake_at.set(Some(next));
117 let mut timed = self.ui.timed_frames.borrow_mut();
119 let at = timed.get(&self.id).map_or(time, |t| t.min(time));
120 timed.insert(self.id, at);
121 }
122
123 pub fn request_frame(&self) {
126 self.frame_request.set(true);
127 self.ui.frame_ids.borrow_mut().push(self.id);
129 }
130
131 pub fn overlay(&self, draw: impl FnOnce(&mut dyn Canvas)) {
135 let mut rec = crate::pages::RecordingCanvas::new(None);
136 draw(&mut rec);
137 let at = self.ui.absolute_rect(self.id).map_or(PointF::default(), |r| r.origin());
138 self.ui.overlays.borrow_mut().push((at, crate::pages::Page { ops: rec.ops }));
139 self.ui.overlay_users.borrow_mut().insert(self.id);
140 }
141}
142
143#[derive(Clone, Debug, Default)]
145pub(crate) struct Visual {
146 state: Option<ControlState>,
147 pub(crate) shown: Option<ResolvedStyle>,
148 from: Option<ResolvedStyle>,
149 start: f64,
150 pub(crate) reach: Option<f32>,
153 pub(crate) ink: Option<RectF>,
156 pub(crate) drawing: Option<u64>,
159 pub(crate) shift: PointF,
162 pub(crate) version: u64,
165 pub(crate) covers: bool,
169 pub(crate) plain: crate::ink::Plain,
172 pub(crate) layer_key: Option<u64>,
176}
177
178const SPILL_SLACK: f32 = 0.01;
181
182const RGBA_MARGIN: u32 = 16;
184
185#[derive(Clone, Copy, Debug)]
187pub(crate) struct Backdrop {
188 parent: Option<ComponentId>,
190 version: u64,
192 builds: u32,
194}
195
196const BACKDROP_BUILDS: u32 = 2;
200
201struct Look<'t> {
203 enabled: bool,
204 state: ControlState,
205 inherited: &'t Theme,
207 mixed: &'t Theme,
208 recolored: Option<std::rc::Rc<Theme>>,
209 colors: crate::component::ColorOverride,
210 style: ResolvedStyle,
211 transitioning: bool,
212 paint_fill: bool,
213 font: crate::component::FontOverride,
214 reach: f32,
215}
216
217impl Look<'_> {
218 fn theme(&self) -> &Theme {
220 self.recolored.as_deref().unwrap_or(self.mixed)
221 }
222}
223
224impl Visual {
225 fn update(&mut self, state: ControlState, target: ResolvedStyle, now: f64) -> (ResolvedStyle, bool) {
228 let duration = target.transition_ms as f64 / 1000.0;
229 if self.state.is_some_and(|s| s != state) && duration > 0.0 && self.shown.as_ref().is_some_and(|s| *s != target) {
232 if let Some(shown) = self.shown.take() {
233 self.from = Some(shown);
234 self.start = now;
235 }
236 }
237 self.state = Some(state);
238 let (style, running) = match &self.from {
239 Some(from) if duration > 0.0 => {
240 let t = ((now - self.start) / duration) as f32;
241 if t >= 1.0 {
242 (target, false)
243 } else {
244 (from.lerp(&target, Easing::OutQuad.apply(t)), true)
245 }
246 }
247 _ => (target, false),
248 };
249 if !running {
250 self.from = None;
251 }
252 self.shown = Some(style.clone());
253 (style, running)
254 }
255}
256
257pub const DRAG_LABEL_MARGIN: f32 = 8.0;
259
260impl Ui {
261 pub fn render_png(&mut self, id: ComponentId, width: f32, height: f32, scale: f32) -> Option<Vec<u8>> {
271 let service = self.services_mut().offscreen.take()?;
272 if let Some(cb) = self.control_mut(id) {
273 cb.set_position(0.0, 0.0).set_size(width, height);
274 }
275 self.layout();
276 for _ in 0..4 {
279 if !self.needs_layout() {
280 break;
281 }
282 self.layout();
283 }
284 let background = self.theme().color("background");
285 let png = service.render_png(width.ceil() as u32, height.ceil() as u32, scale, background, &mut |canvas| self.paint(id, canvas));
286 self.services_mut().offscreen = Some(service);
287 png
288 }
289
290 pub fn snapshot(&self, id: ComponentId, scale: f32) -> Option<crate::Image> {
295 let service = self.services().offscreen.as_ref()?;
296 let cb = self.cb(id)?;
297 let (place, size) = {
298 let b = cb.bounds();
299 let t = cb.translate();
300 (PointF::new(b.x + t.x, b.y + t.y), (b.width.ceil().max(1.0) as u32, b.height.ceil().max(1.0) as u32))
301 };
302 let enabled = self.ancestors_enabled(id);
303 let png = service.render_png(size.0, size.1, scale, crate::Color::TRANSPARENT, &mut |canvas| {
304 canvas.translate(-place.x, -place.y);
306 let mut classes = Vec::new();
307 self.paint_node(id, canvas, enabled, &mut classes, &self.theme, &Default::default(), None);
308 })?;
309 Some(crate::Image::encoded(png))
310 }
311
312 pub fn render_rgba(&mut self, id: ComponentId, rect: RectF, scale: f32) -> Option<(u32, u32, Vec<u8>)> {
326 if !(scale > 0.0 && rect.width > 0.0 && rect.height > 0.0) {
327 return None;
328 }
329 let (w, h) = ((rect.width * scale).ceil() as u32, (rect.height * scale).ceil() as u32);
330 crate::image::checked_size(w, h).ok()?;
331 self.cb(id)?;
332 let (mw, mh) = (w + 2 * RGBA_MARGIN, h + 2 * RGBA_MARGIN);
336 crate::image::checked_size(mw, mh).ok()?;
337 let margin = RGBA_MARGIN as f32 / scale;
338 let service = self.services_mut().offscreen.take()?;
339 self.update_layout();
340 let rgba = if self.parent(id).is_none() {
341 let origin = self.cb(id).map(|cb| cb.bounds().origin()).unwrap_or_default();
342 let area = rect.offset(origin.x, origin.y);
343 let painted = RectF::new(area.x - margin, area.y - margin, area.width + 2.0 * margin, area.height + 2.0 * margin);
344 let background = self.theme().color("background");
345 let pending = self.repaint_requested;
347 let out = service.render_rgba(mw, mh, scale, background, &mut |canvas| {
348 canvas.translate(-painted.x, -painted.y);
349 self.paint_regions_in(id, canvas, &[painted], true);
350 });
351 self.repaint_requested |= pending;
352 out
353 } else {
354 let place = {
355 let cb = self.cb(id)?;
356 let (b, t) = (cb.bounds(), cb.translate());
357 PointF::new(b.x + t.x + rect.x - margin, b.y + t.y + rect.y - margin)
358 };
359 let enabled = self.ancestors_enabled(id);
360 service.render_rgba(mw, mh, scale, crate::Color::TRANSPARENT, &mut |canvas| {
361 canvas.translate(-place.x, -place.y);
362 let mut classes = Vec::new();
363 self.paint_node(id, canvas, enabled, &mut classes, &self.theme, &Default::default(), None);
364 })
365 };
366 self.services_mut().offscreen = Some(service);
367 let rgba = rgba?;
368 let (row, stride, m) = (w as usize * 4, mw as usize * 4, RGBA_MARGIN as usize);
369 let pixels = (0..h as usize).flat_map(|y| {
370 let start = (y + m) * stride + m * 4;
371 rgba[start..start + row].iter().copied()
372 });
373 Some((w, h, pixels.collect()))
374 }
375
376 pub(crate) fn invoke_render_rgba(&mut self, id: ComponentId, args: &[crate::PropValue]) -> std::result::Result<crate::PropValue, String> {
380 let number = |i: usize| args.get(i).and_then(|v| v.to_f64().ok()).map(|v| v as f32);
381 let (Some(x), Some(y), Some(width), Some(height)) = (number(0), number(1), number(2), number(3)) else {
382 return Err("render_rgba pede x, y, width, height e, se quiser, scale".into());
383 };
384 let scale = number(4).unwrap_or(1.0);
385 let (_, _, rgba) = self.render_rgba(id, RectF::new(x, y, width, height), scale).ok_or("render_rgba: sem desenho fora da tela, ou o retângulo vazio ou grande demais")?;
386 Ok(crate::PropValue::String(crate::image::encode_base64(&rgba)))
387 }
388
389 fn ancestors_enabled(&self, id: ComponentId) -> bool {
391 let mut cur = self.parent(id);
392 while let Some(c) = cur {
393 if self.cb(c).is_some_and(|cb| !cb.enabled()) {
394 return false;
395 }
396 cur = self.parent(c);
397 }
398 true
399 }
400
401 pub fn paint(&mut self, root: ComponentId, canvas: &mut dyn Canvas) {
402 self.paint_region(root, canvas, None);
403 }
404
405 pub fn paint_region(&mut self, root: ComponentId, canvas: &mut dyn Canvas, area: Option<RectF>) {
409 match area {
410 Some(a) => self.paint_regions(root, canvas, &[a]),
411 None => self.paint_regions(root, canvas, &[]),
412 }
413 }
414
415 pub fn paint_regions(&mut self, root: ComponentId, canvas: &mut dyn Canvas, areas: &[RectF]) {
420 self.paint_regions_in(root, canvas, areas, areas.is_empty());
421 }
422
423 pub(crate) fn paint_regions_in(&mut self, root: ComponentId, canvas: &mut dyn Canvas, areas: &[RectF], whole: bool) {
426 let area = areas.iter().copied().reduce(|a, b| a.union(b));
427 let _profile = crate::profile::scope(crate::profile::Lane::Paint, || format!("pintura {}", self.path_of(root)));
428 self.update_layout();
429 self.style_animating.set(false);
430 self.wake_at.set(None);
431 let mut classes = Vec::new();
432 self.overlays.borrow_mut().clear();
433 if whole {
434 self.overlay_users.borrow_mut().clear();
435 self.layer_epoch.set(self.layer_epoch.get() + 1);
437 }
438 for key in self.dead_layers.borrow_mut().drain(..) {
441 canvas.forget_cached(key);
442 }
443 {
446 let mut movers = self.movers.borrow_mut();
447 movers.clear();
448 movers.extend(self.placement_movers().filter_map(|m| self.parent(m).map(|p| (p, m))));
449 if !self.backdrops.borrow().is_empty() {
450 self.backdrops.borrow_mut().retain(|&id, b| {
451 let keep = movers.iter().any(|&(p, _)| Some(p) == b.parent);
452 if !keep {
453 let own = self.control(id).is_some_and(|cb| cb.cache_layer()) || self.in_transition(id);
454 if let Some(key) = self.entry(id).filter(|_| !own).and_then(|e| e.visual.borrow_mut().layer_key.take()) {
455 canvas.forget_cached(key);
456 }
457 }
458 keep
459 });
460 }
461 }
462 self.backdrop_next.set(false);
463 let caching = match self.get_prop(root, "layer_cache") {
466 Ok(crate::PropValue::Enum(name)) => <crate::LayerCaching as crate::prop::PropEnum>::from_name(&name).unwrap_or_default(),
467 _ => crate::LayerCaching::Project,
468 };
469 self.auto_layers.set(caching.enabled());
470 let visible: Option<Vec<RectF>> = self.control(root).map(|cb| match area {
472 Some(_) => areas.iter().map(|a| intersection(cb.bounds(), *a)).filter(|r| r.width > 0.0 && r.height > 0.0).collect(),
473 None => vec![cb.bounds()],
474 });
475 let visible = visible.as_deref();
476 self.spilled.set(false);
477 self.paint_area.set(area);
478 self.paint_form.set(self.control(root).map(|cb| cb.bounds()));
479 self.paint_count.set(0);
480 let mut ink = crate::ink::InkCanvas::new(&mut *canvas, &self.ink, &self.plain);
481 if self.text_mode == crate::textcore::TextMode::Native {
483 self.paint_node(root, &mut ink, true, &mut classes, &self.theme, &Default::default(), visible);
484 } else {
485 let mut text = crate::textcore::TextCanvas { inner: &mut ink, mode: self.text_mode };
486 self.paint_node(root, &mut text, true, &mut classes, &self.theme, &Default::default(), visible);
487 }
488 self.flush_paint_failures();
489 let origin = self.absolute_rect(root).map_or(PointF::default(), |r| r.origin());
491 for (at, page) in self.overlays.borrow_mut().drain(..) {
492 canvas.save();
493 canvas.translate(at.x - origin.x, at.y - origin.y);
494 page.replay(canvas);
495 canvas.restore();
496 }
497 if let Some((strip, color)) = self.status_strip(root) {
498 canvas.fill_rect(strip, 0.0, &crate::Brush::Solid(color));
499 }
500 self.paint_drag(root, canvas);
501 self.paint_middle_mark(root, canvas);
502 self.paint_hint(root, canvas);
503 self.paint_busy(root, canvas);
504 self.frame_requests.borrow_mut().insert(root, (self.style_animating.get(), self.wake_at.get()));
505 crate::profile::sample("controles pintados", self.paint_count.get() as f64);
507 self.repaint_requested = false;
508 if area.is_some() && self.spilled.get() {
511 self.request_repaint();
512 }
513 }
514
515 pub fn last_paint_count(&self) -> usize {
518 self.paint_count.get()
519 }
520
521 pub fn paint_overflow(&mut self, root: ComponentId, canvas: &mut dyn Canvas) {
524 self.update_layout();
525 let Some(cb) = self.cb(root) else { return };
526 let inherited = match cb.theme_name() {
527 "" => &self.theme,
528 name => self.theme_named(name).unwrap_or(&self.theme),
529 };
530 let enabled = cb.enabled();
531 let size = self.form_area(root);
532 let mut classes = Vec::new();
533 let children: Vec<ComponentId> = self.children(root).iter().copied().filter(|&c| self.sticks_out(c, size)).collect();
536 for child in children {
537 self.paint_node(child, canvas, enabled, &mut classes, inherited, &cb.font, None);
538 }
539 }
540
541 pub fn overflows(&self, root: ComponentId) -> bool {
544 let area = self.form_area(root);
545 self.children(root).iter().any(|&c| self.sticks_out(c, area))
546 }
547
548 fn form_area(&self, root: ComponentId) -> RectF {
550 let origin = self.absolute_rect(root).unwrap_or_default();
551 RectF::new(origin.x, origin.y, self.cb(root).map_or(0.0, |cb| cb.width()), self.cb(root).map_or(0.0, |cb| cb.height()))
552 }
553
554 fn sticks_out(&self, id: ComponentId, area: RectF) -> bool {
556 let Some(cb) = self.cb(id) else { return false };
557 if !cb.visible() {
558 return false;
559 }
560 let Some(r) = self.absolute_rect(id) else { return false };
561 let outside = r.x < area.x - 1.0 || r.y < area.y - 1.0 || r.right() > area.right() + 1.0 || r.bottom() > area.bottom() + 1.0 || cb.rotation() != 0.0;
563 outside || (!cb.clip_children() && self.children(id).iter().any(|&c| self.sticks_out(c, area)))
564 }
565
566 fn paint_drag(&self, root: ComponentId, canvas: &mut dyn Canvas) {
569 let Some((label, at, target)) = self.drag_view(root) else { return };
570 let origin = self.absolute_rect(root).map_or(PointF::default(), |r| r.origin());
571 let data = self.drag_data(root).unwrap_or_default();
574 let target = target.filter(|&t| self.root_of(t) == root && !self.component(t).and_then(|c| c.drag_drop()).is_some_and(|d| d.drop_accepts(self, t, data)));
575 if let Some(r) = target.and_then(|t| self.absolute_rect(t)) {
576 let r = RectF::new(r.x - origin.x, r.y - origin.y, r.width, r.height);
577 canvas.stroke_rect(r.inflate(1.0), 6.0, &crate::canvas::Stroke::new(self.theme.color("primary"), 2.0));
578 }
579 let visual = self.drag_visual(root).map(|(v, _)| v);
581 let mut label_at = PointF::new(at.x + 14.0, at.y + 14.0);
582 if let Some(v) = visual {
583 let r = RectF::new(at.x - v.hotspot.x, at.y - v.hotspot.y, v.size.width, v.size.height);
584 if !self.native_drag_image {
585 if let Some(size) = canvas.image_size(&v.image) {
586 canvas.save();
587 canvas.clip_round_rect(r, 6.0);
588 let (src, dest) = crate::ImageFit::Cover.place(size, r);
589 canvas.draw_image(&v.image, src, dest, v.opacity);
590 canvas.restore();
591 }
592 }
593 label_at = PointF::new(r.x, r.bottom() + 4.0);
595 }
596 if label.is_empty() || self.native_drag_image {
599 return;
600 }
601 self.paint_drag_label(canvas, &label, label_at);
602 }
603
604 fn drag_label_layout(&self, label: &str, measure: impl FnOnce(&str, &TextStyle) -> f32) -> (ResolvedStyle, TextStyle, crate::geometry::SizeF) {
607 let style = self.theme.resolve(&["Hint"], "", ControlState::default());
608 let mut ts = crate::canvas::TextStyle { font: style.font.clone(), color: style.text, ..Default::default() };
609 ts.trimming = crate::text::Trimming::Character;
610 let pad = style.padding;
611 let w = measure(label, &ts).min(320.0) + pad.left + pad.right + 1.0;
612 let h = (ts.font.size * 1.4).round() + pad.top + pad.bottom;
613 (style, ts, crate::geometry::SizeF::new(w, h))
614 }
615
616 fn paint_drag_label(&self, canvas: &mut dyn Canvas, label: &str, at: PointF) {
618 let (style, ts, size) = self.drag_label_layout(label, |l, ts| canvas.measure_text(l, ts).width);
619 let pad = style.padding;
620 let rect = RectF::new(at.x, at.y, size.width, size.height);
621 if let Some(shadow) = &style.shadow {
622 canvas.draw_shadow(rect, style.radius, shadow);
623 }
624 canvas.fill_rect(rect, style.radius, &crate::canvas::Brush::Solid(style.fill.with_opacity(0.92)));
625 canvas.draw_text(label, RectF::new(rect.x + pad.left, rect.y + pad.top, size.width - pad.left - pad.right, size.height - pad.top - pad.bottom), &ts);
626 }
627
628 pub fn render_drag_label(&self, label: &str, scale: f32) -> Option<(u32, u32, Vec<u8>)> {
635 if label.is_empty() || !(scale > 0.0) {
636 return None;
637 }
638 let service = self.services().offscreen.as_ref()?;
639 let (_, _, size) = self.drag_label_layout(label, |l, ts| self.measure_text(l, ts).width);
640 let m = DRAG_LABEL_MARGIN;
641 let (w, h) = (((size.width + 2.0 * m) * scale).ceil() as u32, ((size.height + 2.0 * m) * scale).ceil() as u32);
642 crate::image::checked_size(w, h).ok()?;
643 let rgba = service.render_rgba(w, h, scale, crate::Color::TRANSPARENT, &mut |canvas| self.paint_drag_label(canvas, label, PointF::new(m, m)))?;
644 Some((w, h, rgba))
645 }
646
647 fn paint_hint(&self, root: ComponentId, canvas: &mut dyn Canvas) {
649 let Some((text, at)) = self.visible_hint(root) else { return };
650 let Some(form) = self.control(root).map(|cb| cb.bounds()) else { return };
651 let style = self.theme.resolve(&["Hint"], "", ControlState::default());
652 let mut ts = crate::canvas::TextStyle { font: style.font.clone(), color: style.text, ..Default::default() };
653 ts.v_align = crate::canvas::TextAlign::Leading;
654 let max = 280.0f32.min(form.width - 16.0).max(40.0);
655 let mut measure = |s: &str| canvas.measure_text(s, &ts).width;
656 let lines = crate::text::layout_lines(&text, max, 12, true, crate::text::Trimming::Word, &mut measure);
657 let width = lines.iter().map(|l| measure(l)).fold(0.0f32, f32::max);
658 let lh = (ts.font.size * 1.4).round();
659 let pad = style.padding;
660 let w = width + pad.left + pad.right + 1.0;
661 let h = lines.len() as f32 * lh + pad.top + pad.bottom;
662 let mut x = at.x + 4.0;
663 let mut y = at.y + 22.0;
664 if x + w > form.width - 4.0 {
665 x = (form.width - 4.0 - w).max(4.0);
666 }
667 if y + h > form.height - 4.0 {
668 y = (at.y - h - 8.0).max(4.0);
669 }
670 let rect = RectF::new(x, y, w, h);
671 if let Some(shadow) = &style.shadow {
672 canvas.draw_shadow(rect, style.radius, shadow);
673 }
674 canvas.fill_rect(rect, style.radius, &crate::canvas::Brush::Solid(style.fill));
675 if style.border_width > 0.0 && !style.border_color.is_transparent() {
677 canvas.stroke_rect(rect, style.radius, &style.border_stroke(style.border_color, style.border_width));
678 }
679 let mut ly = y + pad.top;
680 for line in &lines {
681 canvas.draw_text(line, RectF::new(x + pad.left, ly, width + 1.0, lh), &ts);
682 ly += lh;
683 }
684 }
685
686 #[allow(clippy::too_many_arguments)]
690 fn look<'t>(
691 &'t self,
692 id: ComponentId,
693 component: &dyn crate::Component,
694 cb: &crate::ControlBase,
695 visual: &std::cell::RefCell<Visual>,
696 parent_enabled: bool,
697 classes: &mut Vec<&'static str>,
698 inherited: &'t Theme,
699 parent_font: &crate::component::FontOverride,
700 peek: bool,
701 ) -> Look<'t> {
702 let enabled = parent_enabled && cb.enabled();
703 let mut state = cb.state();
704 state.disabled = !enabled;
705 if let Some(checked) = component.checked_state() {
706 state.checked = checked;
707 }
708 if self.still_picture {
709 state.hover = false;
710 state.pressed = false;
711 state.focused = false;
712 }
713 if cb.inherit_state() {
715 let mut up = self.parent(id);
716 while let Some(p) = up {
717 let Some(pcb) = self.cb(p) else { break };
718 if !pcb.inherit_state() {
719 let ps = pcb.state();
720 state.hover |= ps.hover;
721 state.pressed |= ps.pressed;
722 state.checked |= self.component(p).and_then(|c| c.checked_state()).unwrap_or(ps.checked);
723 break;
724 }
725 up = self.parent(p);
726 }
727 }
728 if state.focused && !component.accepts_text() && self.focus_from_pointer(self.root_of(id)) {
731 state.focused = false;
732 }
733
734 classes.clear();
735 component.class_chain(classes);
736 let inherited = match cb.theme_name() {
738 "" => inherited,
739 name => self.theme_named(name).unwrap_or(inherited),
740 };
741 let mixed = self.mixed_theme(inherited, classes);
742 let colors = cb.colors;
745 let recolored = colors.recolors_theme().then(|| {
746 let key = (mixed.name.clone(), colors);
747 self.recolored.borrow_mut().entry(key).or_insert_with(|| std::rc::Rc::new(colors.apply_theme(mixed))).clone()
748 });
749 let (target, reach) = {
750 let theme: &Theme = recolored.as_deref().unwrap_or(mixed);
751 (theme.resolve(classes, cb.style(), state), theme.reach(classes, cb.style()).max(cb.shadow().map_or(0.0, |s| s.reach())))
752 };
753 let (mut style, transitioning) = if self.design_mode {
755 (target, false)
756 } else if peek {
757 visual.borrow().clone().update(state, target, self.time)
758 } else {
759 visual.borrow_mut().update(state, target, self.time)
760 };
761 let font = if cb.font.is_empty() { parent_font.clone() } else { cb.font.over(parent_font) };
763 if !font.is_empty() {
764 font.apply(&mut style.font);
765 }
766 if cb.text_scale() != 1.0 {
768 style.font.size *= cb.text_scale();
769 }
770 if !self.font_names().is_empty() {
772 style.font.family = self.resolve_font(&style.font.family);
773 }
774 let paint_fill = colors.fill.is_some() && component.transparent_background();
777 if let Some(fill) = colors.fill {
778 let toward = if crate::component::luminance(fill) < 0.5 { crate::Color::WHITE } else { crate::Color::BLACK };
781 let amount = if !cb.can_focus() { 0.0 } else if state.pressed { 0.2 } else if state.hover || state.checked { 0.1 } else { 0.0 };
782 style.fill = fill.lerp(toward.with_opacity(fill.a as f32 / 255.0), amount);
783 }
784 if let Some(border) = colors.border {
785 style.border_color = border;
786 style.border_width = style.border_width.max(1.0);
787 }
788 if let Some(text) = colors.text {
789 style.text = text;
790 }
791 Look { enabled, state, inherited, mixed, recolored, colors, style, transitioning, paint_fill, font, reach }
792 }
793
794 pub(crate) fn drawing_unchanged(&self, id: ComponentId) -> bool {
799 let Some(entry) = self.entry(id) else { return false };
800 let Some(component) = entry.component.as_deref() else { return false };
801 let Some(cb) = component.control() else { return false };
802 let Some(before) = entry.visual.borrow().drawing else { return false };
803 if !component.paint_is_pure() || entry.paint_hook.is_some() || self.paint_failed(id) || self.flips_content(id) || cb.rotation() != 0.0 {
804 return false;
805 }
806 let mut chain = Vec::new();
808 let mut current = self.parent(id);
809 while let Some(p) = current {
810 chain.push(p);
811 current = self.parent(p);
812 }
813 let (mut enabled, mut inherited, mut font) = (true, &*self.theme, crate::component::FontOverride::default());
814 for &a in chain.iter().rev() {
815 let Some(acb) = self.control(a) else { continue };
816 enabled &= acb.enabled();
817 if !acb.theme_name().is_empty() {
818 inherited = self.theme_named(acb.theme_name()).unwrap_or(inherited);
819 }
820 if !acb.font.is_empty() {
821 font = acb.font.over(&font);
822 }
823 }
824 let mut classes = Vec::new();
825 let look = self.look(id, component, cb, &entry.visual, enabled, &mut classes, inherited, &font, true);
826 if look.transitioning {
828 return false;
829 }
830 let (requested, wake) = (Cell::new(false), Cell::new(None));
831 let ctx = PaintCtx {
832 ui: self,
833 id,
834 rect: RectF::from_size(cb.bounds().size()),
835 state: look.state,
836 style: &look.style,
837 theme: look.theme(),
838 time: self.time,
839 design: self.design_mode,
840 colors: look.colors,
841 frame_request: &requested,
842 wake_at: &wake,
843 resources: self.services().resources.as_deref(),
844 };
845 let ghost = if self.design_mode && cb.design_hidden { 0.35 } else { 1.0 };
846 let opacity = cb.opacity() * look.style.opacity * ghost;
847 if opacity <= 0.0 {
848 return false;
849 }
850 let mut hasher = std::hash::DefaultHasher::new();
851 std::hash::Hash::hash(&opacity.to_bits(), &mut hasher);
852 std::hash::Hash::hash(&cb.blend_mode(), &mut hasher);
853 let text = self.services().text.as_deref();
854 let mut trace = crate::trace::TraceCanvas::new(None, text, &mut hasher);
855 let painted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
856 self.paint_own(&mut trace, component, &ctx, look.paint_fill, cb.shadow().as_ref());
857 component.paint_after(&mut trace, &ctx);
858 }));
859 let volatile = trace.volatile;
860 painted.is_ok() && !volatile && !requested.get() && std::hash::Hasher::finish(&hasher) == before
861 }
862
863 fn paint_own(&self, canvas: &mut dyn Canvas, component: &dyn crate::Component, ctx: &PaintCtx<'_>, paint_fill: bool, shadow: Option<&crate::Shadow>) {
866 let style = ctx.style;
867 let shape = component.clip_shape();
869 let radius = shape.as_ref().map_or(style.radius, |s| s.radius(ctx.rect));
870 if let Some(shadow) = shadow.or(style.shadow.as_ref()) {
871 canvas.draw_shadow(ctx.rect, radius, shadow);
872 }
873 if let Some(fill) = ctx.colors.fill.filter(|_| paint_fill) {
874 match shape {
875 Some(s) => s.fill(canvas, ctx.rect, &crate::Brush::Solid(fill)),
876 None => canvas.fill_rect(ctx.rect, radius, &crate::Brush::Solid(fill)),
877 }
878 }
879 if style.material != crate::theme::Material::None {
881 canvas.backdrop_blur(ctx.rect, radius, style.material.blur());
882 }
883 component.paint(canvas, ctx);
884 if style.material == crate::theme::Material::Glass {
885 paint_glass_light(canvas, ctx.rect, radius, ctx.theme.dark);
886 }
887 }
888
889 fn paint_reveal(&self, canvas: &mut dyn Canvas, ctx: &PaintCtx<'_>, shape: Option<crate::ClipShape>) {
894 let reveal = ctx.style.reveal;
895 let id = ctx.id;
896 if !reveal.on() {
897 if !self.reveal_ids.borrow().is_empty() {
898 self.reveal_ids.borrow_mut().remove(&id);
899 }
900 return;
901 }
902 self.reveal_ids.borrow_mut().insert(id, reveal.radius);
903 let Some(at) = self.pointer_position(self.root_of(id)) else { return };
904 let p = self.local_point(id, at);
905 let rect = ctx.rect;
906 let dx = (rect.x - p.x).max(p.x - rect.right()).max(0.0);
907 let dy = (rect.y - p.y).max(p.y - rect.bottom()).max(0.0);
908 if dx.hypot(dy) >= reveal.radius {
909 return;
910 }
911 let light = |color: crate::Color| crate::Brush::Radial {
912 center: p,
913 radius: reveal.radius,
914 stops: vec![crate::canvas::GradientStop::new(0.0, color), crate::canvas::GradientStop::new(1.0, color.with_opacity(0.0))],
915 };
916 let radius = shape.as_ref().map_or(ctx.style.radius, |s| s.radius(rect));
917 if reveal.background && rect.contains(p) {
918 let brush = light(reveal.color.with_opacity(0.55));
919 match &shape {
920 Some(s) => s.fill(canvas, rect, &brush),
921 None => canvas.fill_rect(rect, radius, &brush),
922 }
923 }
924 if reveal.border {
925 let width = ctx.style.border_width.max(1.0);
926 let half = width / 2.0;
927 let inner = crate::RectF::new(rect.x + half, rect.y + half, (rect.width - width).max(0.0), (rect.height - width).max(0.0));
928 let stroke = crate::canvas::Stroke::new(light(reveal.color), width);
929 match &shape {
930 Some(s) => canvas.stroke_path(&s.outline(inner), &stroke),
931 None => canvas.stroke_rect(inner, (radius - half).max(0.0), &stroke),
932 }
933 }
934 }
935
936 #[allow(clippy::too_many_arguments)]
939 fn paint_own_with_hook(
940 &self,
941 canvas: &mut dyn Canvas,
942 id: ComponentId,
943 entry: &crate::ui::Entry,
944 component: &dyn crate::Component,
945 ctx: &PaintCtx<'_>,
946 paint_fill: bool,
947 shadow: Option<&crate::Shadow>,
948 flip: bool,
949 ) {
950 let style = ctx.style;
951 let shape = component.clip_shape();
953 let radius = shape.as_ref().map_or(style.radius, |s| s.radius(ctx.rect));
954 if let Some(shadow) = shadow.or(style.shadow.as_ref()) {
955 canvas.draw_shadow(ctx.rect, radius, shadow);
956 }
957 if let Some(fill) = ctx.colors.fill.filter(|_| paint_fill) {
958 match shape {
959 Some(s) => s.fill(canvas, ctx.rect, &crate::Brush::Solid(fill)),
960 None => canvas.fill_rect(ctx.rect, radius, &crate::Brush::Solid(fill)),
961 }
962 }
963 if style.material != crate::theme::Material::None {
965 canvas.backdrop_blur(ctx.rect, radius, style.material.blur());
966 }
967 if flip {
968 canvas.save();
969 canvas.translate(ctx.rect.width, 0.0);
970 }
971 {
972 let mut mirror;
973 let target: &mut dyn Canvas = if flip {
974 mirror = Mirror { inner: &mut *canvas };
975 &mut mirror
976 } else {
977 &mut *canvas
978 };
979 if self.paint_failed(id) {
982 paint_failure(target, ctx.rect);
983 } else {
984 let painted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match &entry.paint_hook {
985 Some(hook) => hook(target, ctx, &|c: &mut dyn Canvas, x: &PaintCtx<'_>| component.paint(c, x)),
986 None => component.paint(target, ctx),
987 }));
988 if let Err(payload) = painted {
989 self.note_paint_failure(id, payload.as_ref());
990 }
991 }
992 }
993 if flip {
994 canvas.restore();
995 }
996 if style.material == crate::theme::Material::Glass {
997 paint_glass_light(canvas, ctx.rect, radius, ctx.theme.dark);
998 }
999 }
1000
1001 fn paint_node(
1002 &self,
1003 id: ComponentId,
1004 canvas: &mut dyn Canvas,
1005 parent_enabled: bool,
1006 classes: &mut Vec<&'static str>,
1007 inherited: &Theme,
1008 parent_font: &crate::component::FontOverride,
1009 visible: Option<&[RectF]>,
1010 ) {
1011 let behind_mover = self.backdrop_next.replace(false);
1014 let Some(entry) = self.entry(id) else { return };
1015 let Some(component) = entry.component.as_deref() else { return };
1016 let Some(cb) = component.control() else { return };
1017 if !cb.visible() || (cb.design_only && !self.design_mode) {
1018 return;
1019 }
1020 let place = {
1025 let b = cb.bounds();
1026 let t = cb.translate();
1027 RectF::new(b.x + t.x, b.y + t.y, b.width, b.height)
1028 };
1029 let contained = cb.clip_children() || entry.children.is_empty();
1030 let away = cb.rotation() == 0.0
1034 && visible.is_some_and(|v| !v.iter().any(|r| place.inflate(CULL_MARGIN).intersects(*r)))
1035 && !entry.visual.borrow().ink.zip(self.absolute_rect(id)).zip(visible).is_some_and(|((ink, abs), v)| v.iter().any(|r| ink.offset(place.x - abs.x, place.y - abs.y).intersects(*r)));
1036 if away && (contained || !self.descendants_reach(id, place, visible.unwrap_or(&[]))) {
1037 return;
1038 }
1039 self.paint_count.set(self.paint_count.get() + 1);
1040 let look = self.look(id, component, cb, &entry.visual, parent_enabled, classes, inherited, parent_font, false);
1041 entry.visual.borrow_mut().reach = Some(look.reach);
1042 let (enabled, state, inherited, colors, paint_fill) = (look.enabled, look.state, look.inherited, look.colors, look.paint_fill);
1043 let (theme, style, font) = (look.theme(), &look.style, &look.font);
1044 if look.transitioning {
1045 self.style_animating.set(true);
1046 self.frame_ids.borrow_mut().push(id);
1047 }
1048 let ghost = if self.design_mode && cb.design_hidden { 0.35 } else { 1.0 };
1050 let opacity = cb.opacity() * style.opacity * ghost;
1051 if opacity <= 0.0 {
1052 entry.visual.borrow_mut().drawing = None;
1053 return;
1054 }
1055 let outer_ink = self.ink.borrow_mut().take();
1058 let outer_plain = self.plain.replace(crate::ink::Plain::Nothing);
1059 let bounds = cb.bounds();
1060 {
1063 let mut timed = self.timed_frames.borrow_mut();
1064 if !timed.is_empty() {
1065 timed.remove(&id);
1066 }
1067 }
1068 let scale = cb.scale();
1071 let ctx = PaintCtx {
1072 ui: self,
1073 id,
1074 rect: RectF::from_size(cb.inner_size()),
1075 state,
1076 style: &style,
1077 theme,
1078 time: self.time,
1079 design: self.design_mode,
1080 colors,
1081 frame_request: &self.style_animating,
1082 wake_at: &self.wake_at,
1083 resources: self.services().resources.as_deref(),
1084 };
1085
1086 let flip = self.flips_content(id);
1088 let automatic = self.auto_layers.get()
1098 && !entry.children.is_empty()
1099 && ((cb.clip_children() && (self.animates_placement(id) || (behind_mover && self.backdrop_worth(id, entry.visual.borrow().version)))) || self.in_transition(id));
1100 let blend = cb.blend_mode();
1102 let pulled = self.overscroll_pull(id).and_then(|p| self.overscroll_of(id).map(|s| (p, s)));
1105 let shifts = pulled.is_some_and(|(_, s)| matches!(s, crate::Overscroll::Stretch | crate::Overscroll::Bounce));
1106 let cached = !flip && !shifts && blend == crate::BlendMode::Normal && (cb.cache_layer() || automatic);
1107 let skip_own = away && !cached && !flip;
1112
1113 canvas.save();
1114 let shift = cb.translate();
1115 let drawn = if cached && shift != PointF::ZERO {
1119 let s = canvas.device_scale().max(f32::EPSILON);
1120 PointF::new((shift.x * s).round() / s, (shift.y * s).round() / s)
1121 } else {
1122 shift
1123 };
1124 canvas.translate(bounds.x + drawn.x, bounds.y + drawn.y);
1125 let rotation = cb.rotation();
1126 if rotation != 0.0 {
1127 canvas.translate(bounds.width / 2.0, bounds.height / 2.0);
1128 canvas.rotate(rotation);
1129 canvas.translate(-bounds.width / 2.0, -bounds.height / 2.0);
1130 }
1131 if scale != 1.0 {
1132 canvas.scale(scale, scale);
1133 }
1134 if let Some((p, style)) = pulled.filter(|_| shifts) {
1135 canvas.save();
1136 canvas.clip_rect(ctx.rect);
1137 overscroll_shift(canvas, ctx.rect, p, style);
1138 }
1139 let layer = opacity < 1.0 || blend != crate::BlendMode::Normal;
1140 if blend != crate::BlendMode::Normal {
1141 canvas.save_layer_blend(opacity, blend, ctx.rect.inflate(look.reach + 1.0));
1142 } else if layer {
1143 canvas.save_layer(opacity);
1144 }
1145
1146 let traced = component.paint_is_pure() && entry.paint_hook.is_none() && !flip && rotation == 0.0 && !self.paint_failed(id);
1149 let mut hasher = std::hash::DefaultHasher::new();
1150 std::hash::Hash::hash(&opacity.to_bits(), &mut hasher);
1151 std::hash::Hash::hash(&blend, &mut hasher);
1152 let mut volatile = false;
1153 let layer_key = cached.then(|| {
1154 let mut key = std::hash::DefaultHasher::new();
1155 let version = entry.visual.borrow().version;
1156 std::hash::Hash::hash(&(id, version, self.layer_epoch.get(), self.design_mode), &mut key);
1157 std::hash::Hasher::finish(&key)
1158 });
1159 let old_key = std::mem::replace(&mut entry.visual.borrow_mut().layer_key, layer_key);
1162 if let Some(old) = old_key.filter(|old| Some(*old) != layer_key) {
1163 canvas.forget_cached(old);
1164 }
1165 let cache_hit = layer_key.is_some_and(|key| canvas.begin_cached(key, ctx.rect.inflate(look.reach + 1.0)));
1166 if !cache_hit {
1167 if skip_own {
1168 } else if traced {
1169 let mut trace = crate::trace::TraceCanvas::new(Some(&mut *canvas), None, &mut hasher);
1170 let painted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.paint_own(&mut trace, component, &ctx, paint_fill, cb.shadow().as_ref())));
1171 volatile |= trace.volatile;
1172 if let Err(payload) = painted {
1173 self.note_paint_failure(id, payload.as_ref());
1174 }
1175 } else {
1176 self.paint_own_with_hook(canvas, id, entry, component, &ctx, paint_fill, cb.shadow().as_ref(), flip);
1177 }
1178 if !skip_own {
1179 self.paint_reveal(canvas, &ctx, component.painted_shape());
1180 }
1181
1182 let scrolled_form = cb.scroll_offset().y > 0.0 && self.parent(id).is_none();
1184 let shape = component.clip_shape();
1186 let clip = cb.clip_children() || scrolled_form || shape.is_some();
1187 if clip {
1188 canvas.save();
1189 let r = if scrolled_form {
1190 let s = cb.safe_area;
1191 crate::RectF::new(ctx.rect.x, ctx.rect.y + s.top, ctx.rect.width, (ctx.rect.height - s.top - s.bottom).max(0.0))
1192 } else {
1193 ctx.rect
1194 };
1195 canvas.clip_rect(r);
1196 if let Some(s) = shape {
1197 s.clip(canvas, ctx.rect);
1198 }
1199 }
1200 let inner: Option<Vec<RectF>> = match visible.filter(|_| rotation == 0.0 && !cached) {
1204 Some(v) => Some(
1205 v.iter()
1206 .map(|r| r.offset(-place.x, -place.y))
1207 .map(|r| if scale == 1.0 { r } else { RectF::new(r.x / scale, r.y / scale, r.width / scale, r.height / scale) })
1209 .map(|local| if clip { intersection(local, ctx.rect) } else { local })
1210 .filter(|r| r.width > 0.0 && r.height > 0.0)
1211 .collect(),
1212 ),
1213 None if clip && rotation == 0.0 => Some(vec![ctx.rect]),
1214 None => None,
1215 };
1216 let hidden = self.covered_children(&entry.children, inner.as_deref());
1217 let mover_at = if self.auto_layers.get() {
1219 self.movers.borrow().iter().filter(|&&(p, _)| p == id).filter_map(|&(_, m)| entry.children.iter().position(|&c| c == m)).max()
1220 } else {
1221 None
1222 };
1223 for (k, &child) in entry.children.iter().enumerate() {
1224 if hidden.get(k).copied().unwrap_or(false) {
1225 continue;
1226 }
1227 self.backdrop_next.set(mover_at.is_some_and(|m| k < m));
1228 self.paint_node(child, canvas, enabled, classes, inherited, &font, inner.as_deref());
1229 }
1230 if clip {
1231 canvas.restore();
1232 }
1233 if self.paint_failed(id) || skip_own {
1234 } else if flip {
1236 canvas.save();
1237 canvas.translate(ctx.rect.width, 0.0);
1238 let after = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| component.paint_after(&mut Mirror { inner: &mut *canvas }, &ctx)));
1239 canvas.restore();
1240 if let Err(payload) = after {
1241 self.note_paint_failure(id, payload.as_ref());
1242 }
1243 } else if traced {
1244 let mut trace = crate::trace::TraceCanvas::new(Some(&mut *canvas), None, &mut hasher);
1245 let after = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| component.paint_after(&mut trace, &ctx)));
1246 volatile |= trace.volatile;
1247 if let Err(payload) = after {
1248 self.note_paint_failure(id, payload.as_ref());
1249 }
1250 } else if let Err(payload) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| component.paint_after(canvas, &ctx))) {
1251 self.note_paint_failure(id, payload.as_ref());
1252 }
1253 if cached {
1254 canvas.end_cached();
1255 }
1256 }
1257
1258 if layer {
1259 canvas.restore();
1260 }
1261 if shifts {
1262 canvas.restore();
1263 }
1264 if let Some((p, crate::Overscroll::Glow)) = pulled {
1265 overscroll_glow(canvas, ctx.rect, p, self.theme.color("primary"));
1266 }
1267 canvas.restore();
1268 let ink = std::mem::replace(&mut *self.ink.borrow_mut(), outer_ink);
1269 let plain = self.plain.replace(outer_plain);
1270 let mut visual = entry.visual.borrow_mut();
1271 if skip_own {
1272 visual.shift = shift;
1274 drop(visual);
1275 return;
1276 }
1277 if let (Some(new), Some(area)) = (ink, self.paint_area.get()) {
1278 let seen = self.paint_form.get().map_or(new, |form| intersection(new, form));
1284 let outside = seen.width > 0.0 && seen.height > 0.0 && !area.inflate(SPILL_SLACK).contains_rect(seen);
1285 if outside && !visual.ink.is_some_and(|old| old.inflate(SPILL_SLACK).contains_rect(seen)) {
1286 self.spilled.set(true);
1287 }
1288 }
1289 visual.ink = ink;
1290 visual.plain = plain.after(visual.plain);
1291 visual.shift = shift;
1292 visual.drawing = (traced && !cache_hit && !volatile && !self.paint_failed(id)).then(|| std::hash::Hasher::finish(&hasher));
1293 let whole = opacity >= 1.0 && rotation == 0.0 && !flip && !self.paint_failed(id) && component.clip_shape().is_none();
1296 drop(visual);
1297 let own = component.opaque(&style) || paint_fill && colors.fill.is_some_and(|f| f.a == 255) && style.radius <= 0.0;
1298 let by_child = || {
1299 entry.children.iter().any(|&c| {
1300 self.entry(c).is_some_and(|e| {
1301 e.visual.borrow().covers
1302 && e.component.as_deref().and_then(|c| c.control()).is_some_and(|ccb| ccb.visible() && place_of(ccb).contains_rect(ctx.rect))
1303 })
1304 })
1305 };
1306 let covers = whole && (own || by_child());
1307 let was = std::mem::replace(&mut entry.visual.borrow_mut().covers, covers);
1308 if was && !covers {
1309 self.style_animating.set(true);
1312 self.frame_ids.borrow_mut().push(id);
1313 }
1314 }
1315
1316 fn backdrop_worth(&self, id: ComponentId, version: u64) -> bool {
1320 let parent = self.parent(id);
1321 let mut backdrops = self.backdrops.borrow_mut();
1322 let b = backdrops.entry(id).or_insert(Backdrop { parent, version, builds: 1 });
1323 if b.version != version {
1324 b.version = version;
1325 b.builds += 1;
1326 }
1327 b.builds <= BACKDROP_BUILDS
1328 }
1329
1330 fn covered_children(&self, children: &[ComponentId], inner: Option<&[RectF]>) -> Vec<bool> {
1335 let mut hidden = Vec::new();
1336 let mut covers: Vec<RectF> = Vec::new();
1339 for (k, &child) in children.iter().enumerate().rev() {
1340 let Some(entry) = self.entry(child) else { continue };
1341 let Some(cb) = entry.component.as_deref().and_then(|c| c.control()) else { continue };
1342 if !cb.visible() {
1343 continue;
1344 }
1345 let place = place_of(cb);
1346 if !covers.is_empty() {
1347 let reach = entry.visual.borrow().reach.unwrap_or(CULL_MARGIN);
1348 let own = place.inflate(reach);
1349 let contained = !entry.children.is_empty() && !cb.clip_children();
1350 let gone = covers.iter().any(|c| {
1351 c.contains_rect(own) && (!contained || inner.is_some_and(|areas| !areas.is_empty() && areas.iter().all(|a| c.contains_rect(*a))))
1352 });
1353 if gone {
1354 if hidden.is_empty() {
1355 hidden = vec![false; children.len()];
1356 }
1357 hidden[k] = true;
1358 continue;
1359 }
1360 }
1361 if entry.visual.borrow().covers {
1362 covers.push(place);
1363 if covers.len() > 4 {
1364 covers.sort_by(|a, b| (b.width * b.height).total_cmp(&(a.width * a.height)));
1365 covers.truncate(4);
1366 }
1367 }
1368 }
1369 hidden
1370 }
1371}
1372
1373fn overscroll_shift(canvas: &mut dyn Canvas, rect: RectF, p: PointF, style: crate::Overscroll) {
1377 if style == crate::Overscroll::Bounce {
1378 canvas.translate(p.x, p.y);
1379 return;
1380 }
1381 let sx = 1.0 + p.x.abs() / rect.width.max(1.0);
1382 let sy = 1.0 + p.y.abs() / rect.height.max(1.0);
1383 let ax = if p.x > 0.0 { rect.x } else { rect.right() };
1385 let ay = if p.y > 0.0 { rect.y } else { rect.bottom() };
1386 canvas.translate(ax, ay);
1387 canvas.scale(sx, sy);
1388 canvas.translate(-ax, -ay);
1389}
1390
1391fn overscroll_glow(canvas: &mut dyn Canvas, rect: RectF, p: PointF, color: crate::Color) {
1393 canvas.save();
1394 canvas.clip_rect(rect);
1395 let tint = |k: f32| crate::Color::rgba(color.r, color.g, color.b, (40.0 + 90.0 * k).min(255.0) as u8);
1396 if p.y != 0.0 {
1397 let k = (p.y.abs() / (rect.height * 0.2).max(1.0)).min(1.0);
1398 let depth = (rect.width * 0.25).min(rect.height * 0.5) * (0.3 + 0.7 * k);
1399 let y = if p.y > 0.0 { rect.y - depth } else { rect.bottom() - depth };
1400 canvas.fill_ellipse(RectF::new(rect.x - rect.width * 0.25, y, rect.width * 1.5, depth * 2.0), &crate::Brush::Solid(tint(k)));
1401 }
1402 if p.x != 0.0 {
1403 let k = (p.x.abs() / (rect.width * 0.2).max(1.0)).min(1.0);
1404 let depth = (rect.height * 0.25).min(rect.width * 0.5) * (0.3 + 0.7 * k);
1405 let x = if p.x > 0.0 { rect.x - depth } else { rect.right() - depth };
1406 canvas.fill_ellipse(RectF::new(x, rect.y - rect.height * 0.25, depth * 2.0, rect.height * 1.5), &crate::Brush::Solid(tint(k)));
1407 }
1408 canvas.restore();
1409}
1410
1411fn place_of(cb: &crate::component::ControlBase) -> RectF {
1412 let b = cb.bounds();
1413 let t = cb.translate();
1414 RectF::new(b.x + t.x, b.y + t.y, b.width, b.height)
1415}
1416
1417fn paint_failure(canvas: &mut dyn Canvas, rect: RectF) {
1421 let red = crate::color::Color::rgb(220, 38, 38);
1422 canvas.fill_rect(rect, 0.0, &crate::canvas::Brush::Solid(red.with_opacity(0.12)));
1423 let stroke = crate::canvas::Stroke::new(red, 2.0);
1424 canvas.stroke_rect(rect.inflate(-1.0), 0.0, &stroke);
1425 canvas.draw_line(rect.origin(), PointF::new(rect.right(), rect.bottom()), &stroke);
1426 canvas.draw_line(PointF::new(rect.right(), rect.y), PointF::new(rect.x, rect.bottom()), &stroke);
1427}
1428
1429pub fn paint_glass_light(canvas: &mut dyn Canvas, rect: crate::RectF, radius: f32, dark: bool) {
1430 use crate::canvas::{Brush, GradientStop, Stroke};
1431 use crate::{Color, PointF};
1432 if rect.width <= 2.0 || rect.height <= 2.0 {
1433 return;
1434 }
1435 let shine = if dark { 0.16 } else { 0.42 };
1436 canvas.fill_rect(
1437 rect,
1438 radius,
1439 &Brush::Linear {
1440 start: PointF::new(0.0, rect.y),
1441 end: PointF::new(0.0, rect.y + rect.height * 0.6),
1442 stops: vec![GradientStop::new(0.0, Color::WHITE.with_opacity(shine)), GradientStop::new(1.0, Color::WHITE.with_opacity(0.0))],
1443 },
1444 );
1445 let edge = Brush::Linear {
1446 start: PointF::new(rect.x, rect.y),
1447 end: PointF::new(rect.x + rect.width * 0.35, rect.bottom()),
1448 stops: vec![
1449 GradientStop::new(0.0, Color::WHITE.with_opacity(if dark { 0.45 } else { 0.95 })),
1450 GradientStop::new(0.55, Color::WHITE.with_opacity(if dark { 0.10 } else { 0.35 })),
1451 GradientStop::new(1.0, if dark { Color::WHITE.with_opacity(0.18) } else { Color::BLACK.with_opacity(0.10) }),
1452 ],
1453 };
1454 let r = (radius - 0.5).max(0.0);
1455 canvas.stroke_rect(rect.inflate(-0.5), r, &Stroke::new(edge, 1.0));
1456}
1457
1458pub(crate) struct Mirror<'a> {
1462 pub(crate) inner: &'a mut dyn Canvas,
1463}
1464
1465impl Mirror<'_> {
1466 fn x(x: f32) -> f32 {
1467 -x
1468 }
1469
1470 fn point(p: crate::PointF) -> crate::PointF {
1471 crate::PointF::new(-p.x, p.y)
1472 }
1473
1474 fn rect(r: crate::RectF) -> crate::RectF {
1475 crate::RectF::new(-r.right(), r.y, r.width, r.height)
1476 }
1477
1478 fn path(p: &crate::Path) -> crate::Path {
1479 p.map_points(Self::point)
1480 }
1481
1482 fn brush(b: &crate::Brush) -> crate::Brush {
1483 use crate::Brush;
1484 match b {
1485 Brush::Solid(c) => Brush::Solid(*c),
1486 Brush::Linear { start, end, stops } => Brush::Linear { start: Self::point(*start), end: Self::point(*end), stops: stops.clone() },
1487 Brush::Radial { center, radius, stops } => Brush::Radial { center: Self::point(*center), radius: *radius, stops: stops.clone() },
1488 Brush::Sweep { center, start_angle, stops } => Brush::Sweep {
1490 center: Self::point(*center),
1491 start_angle: 180.0 - start_angle,
1492 stops: stops.iter().rev().map(|s| crate::GradientStop::new(1.0 - s.offset, s.color)).collect(),
1493 },
1494 }
1495 }
1496
1497 fn stroke(s: &crate::Stroke) -> crate::Stroke {
1498 crate::Stroke { brush: Self::brush(&s.brush), ..s.clone() }
1499 }
1500}
1501
1502impl Canvas for Mirror<'_> {
1503 fn save(&mut self) {
1504 self.inner.save();
1505 }
1506 fn restore(&mut self) {
1507 self.inner.restore();
1508 }
1509 fn translate(&mut self, dx: f32, dy: f32) {
1510 self.inner.translate(Self::x(dx), dy);
1511 }
1512 fn scale(&mut self, sx: f32, sy: f32) {
1513 self.inner.scale(sx, sy);
1514 }
1515 fn rotate(&mut self, degrees: f32) {
1516 self.inner.rotate(-degrees);
1517 }
1518 fn clip_rect(&mut self, rect: crate::RectF) {
1519 self.inner.clip_rect(Self::rect(rect));
1520 }
1521 fn save_layer(&mut self, opacity: f32) {
1522 self.inner.save_layer(opacity);
1523 }
1524 fn save_layer_blend(&mut self, opacity: f32, mode: crate::BlendMode, bounds: crate::RectF) {
1525 self.inner.save_layer_blend(opacity, mode, Self::rect(bounds));
1526 }
1527 fn fill_rect(&mut self, rect: crate::RectF, radius: f32, brush: &crate::Brush) {
1528 self.inner.fill_rect(Self::rect(rect), radius, &Self::brush(brush));
1529 }
1530 fn stroke_rect(&mut self, rect: crate::RectF, radius: f32, stroke: &crate::Stroke) {
1531 self.inner.stroke_rect(Self::rect(rect), radius, &Self::stroke(stroke));
1532 }
1533 fn fill_ellipse(&mut self, rect: crate::RectF, brush: &crate::Brush) {
1534 self.inner.fill_ellipse(Self::rect(rect), &Self::brush(brush));
1535 }
1536 fn stroke_ellipse(&mut self, rect: crate::RectF, stroke: &crate::Stroke) {
1537 self.inner.stroke_ellipse(Self::rect(rect), &Self::stroke(stroke));
1538 }
1539 fn draw_line(&mut self, from: crate::PointF, to: crate::PointF, stroke: &crate::Stroke) {
1540 self.inner.draw_line(Self::point(from), Self::point(to), &Self::stroke(stroke));
1541 }
1542 fn draw_text(&mut self, text: &str, rect: crate::RectF, style: &TextStyle) {
1543 use crate::TextAlign;
1544 let mut style = style.clone();
1545 style.h_align = match style.h_align {
1546 TextAlign::Leading => TextAlign::Trailing,
1547 TextAlign::Trailing => TextAlign::Leading,
1548 other => other,
1549 };
1550 self.inner.draw_text(text, Self::rect(rect), &style);
1551 }
1552 fn measure_text(&mut self, text: &str, style: &TextStyle) -> crate::SizeF {
1553 self.inner.measure_text(text, style)
1554 }
1555 fn measure_text_wrapped(&mut self, text: &str, style: &TextStyle, max_width: f32) -> crate::SizeF {
1556 self.inner.measure_text_wrapped(text, style, max_width)
1557 }
1558 fn draw_image(&mut self, image: &crate::Image, src: crate::RectF, dest: crate::RectF, opacity: f32) {
1559 self.inner.draw_image(image, src, Self::rect(dest), opacity);
1560 }
1561 fn image_size(&mut self, image: &crate::Image) -> Option<crate::SizeF> {
1562 self.inner.image_size(image)
1563 }
1564 fn clip_round_rect(&mut self, rect: crate::RectF, radius: f32) {
1565 self.inner.clip_round_rect(Self::rect(rect), radius);
1566 }
1567 fn fill_path(&mut self, path: &crate::Path, brush: &crate::Brush) {
1568 self.inner.fill_path(&Self::path(path), &Self::brush(brush));
1569 }
1570 fn clip_path(&mut self, path: &crate::Path, inverse: bool) {
1571 self.inner.clip_path(&Self::path(path), inverse);
1572 }
1573 fn backdrop_blur(&mut self, rect: crate::RectF, radius: f32, blur: f32) -> bool {
1574 self.inner.backdrop_blur(Self::rect(rect), radius, blur)
1575 }
1576 fn begin_masked(&mut self, inverse: bool) -> bool {
1577 self.inner.begin_masked(inverse)
1578 }
1579 fn begin_mask(&mut self) {
1580 self.inner.begin_mask();
1581 }
1582 fn begin_luminance_mask(&mut self) {
1583 self.inner.begin_luminance_mask();
1584 }
1585 fn end_mask(&mut self) {
1586 self.inner.end_mask();
1587 }
1588 fn stroke_path(&mut self, path: &crate::Path, stroke: &crate::Stroke) {
1589 self.inner.stroke_path(&Self::path(path), &Self::stroke(stroke));
1590 }
1591 fn draw_shadow(&mut self, rect: crate::RectF, radius: f32, shadow: &crate::Shadow) {
1592 let mut shadow = shadow.clone();
1593 shadow.offset.x = -shadow.offset.x;
1594 self.inner.draw_shadow(Self::rect(rect), radius, &shadow);
1595 }
1596 fn device_scale(&self) -> f32 {
1597 self.inner.device_scale()
1598 }
1599 fn gpu_device(&self) -> Option<crate::GpuDevice> {
1600 self.inner.gpu_device()
1601 }
1602 fn draw_gpu_surface(&mut self, dest: crate::RectF, surface: &crate::GpuSurface) -> bool {
1603 self.inner.draw_gpu_surface(Self::rect(dest), surface)
1604 }
1605}
1606
1607impl Ui {
1608 fn descendants_reach(&self, id: ComponentId, place: RectF, visible: &[RectF]) -> bool {
1615 let Some(abs) = self.absolute_rect(id) else { return true };
1617 let (ox, oy) = (place.x - abs.x, place.y - abs.y);
1618 let hits = |r: RectF| visible.iter().any(|a| r.intersects(*a));
1619 let mut stack: Vec<(ComponentId, PointF)> = self.children(id).iter().map(|&c| (c, place.origin())).collect();
1620 while let Some((c, origin)) = stack.pop() {
1621 let Some(entry) = self.entry(c) else { continue };
1622 let Some(cb) = entry.component.as_deref().and_then(|c| c.control()) else { continue };
1623 if !cb.visible() || (cb.design_only && !self.design_mode) {
1624 continue;
1625 }
1626 if cb.rotation() != 0.0 || cb.scale() != 1.0 || cb.translate() != PointF::ZERO {
1627 return true;
1628 }
1629 let r = cb.bounds().offset(origin.x, origin.y);
1630 let visual = entry.visual.borrow();
1631 if hits(r.inflate(CULL_MARGIN)) || visual.ink.is_some_and(|ink| hits(ink.offset(ox, oy))) {
1632 return true;
1633 }
1634 if !cb.clip_children() {
1636 stack.extend(entry.children.iter().map(|&k| (k, r.origin())));
1637 }
1638 }
1639 false
1640 }
1641}
1642
1643const CULL_MARGIN: f32 = 48.0;
1646
1647fn intersection(a: RectF, b: RectF) -> RectF {
1649 let x = a.x.max(b.x);
1650 let y = a.y.max(b.y);
1651 RectF::new(x, y, (a.right().min(b.right()) - x).max(0.0), (a.bottom().min(b.bottom()) - y).max(0.0))
1652}
1653
1654fn warn_missing_icon(ui: &crate::Ui, name: &str, design: bool) {
1659 if design || !cfg!(debug_assertions) {
1660 return;
1661 }
1662 let Some((pack, _)) = name.split_once(':') else { return };
1665 thread_local! {
1666 static WARNED: std::cell::RefCell<std::collections::HashSet<String>> = Default::default();
1667 }
1668 if WARNED.with(|w| w.borrow().contains(name)) || !ui.has_icon_pack(pack) {
1669 return;
1670 }
1671 if WARNED.with(|w| w.borrow_mut().insert(name.to_string())) {
1672 crate::stderr_line!("aylis: aviso: o ícone {name} não está no app (cite o nome no form ou no código, ou ponha na lista `icons` do projeto)");
1673 }
1674}