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 match self.ui.icon(name) {
60 Some(icon) => icon.draw(canvas, rect, color),
61 None => warn_missing_icon(self.ui, name, self.design),
62 }
63 }
64
65 pub fn look(&self) -> crate::theme::Look {
67 self.theme.look
68 }
69
70 pub fn variant(&self) -> &str {
72 self.ui.control(self.id).map_or("", |c| c.style())
73 }
74
75 pub fn text_style(&self) -> TextStyle {
77 TextStyle { font: self.style.font.clone(), color: self.style.text, ..Default::default() }
78 }
79
80 pub fn font(&self, size: f32) -> crate::FontSpec {
83 let cb = self.ui.control(self.id);
84 let own = cb.and_then(|c| c.font().size);
85 let scale = cb.map_or(1.0, |c| c.text_scale());
87 crate::FontSpec { size: own.unwrap_or(size) * scale, ..self.style.font.clone() }
88 }
89
90 pub fn monospace_font(&self, size: f32) -> crate::FontSpec {
93 let mut font = self.font(size);
94 let mut current = Some(self.id);
95 while let Some(id) = current {
96 if self.ui.control(id).is_some_and(|c| !c.font().family.is_empty()) {
97 return font;
98 }
99 current = self.ui.parent(id);
100 }
101 font.family = "monospace".into();
102 font
103 }
104
105 pub fn request_frame_at(&self, time: f64) {
109 let next = self.wake_at.get().map_or(time, |t| t.min(time));
110 self.wake_at.set(Some(next));
111 let mut timed = self.ui.timed_frames.borrow_mut();
113 let at = timed.get(&self.id).map_or(time, |t| t.min(time));
114 timed.insert(self.id, at);
115 }
116
117 pub fn request_frame(&self) {
120 self.frame_request.set(true);
121 self.ui.frame_ids.borrow_mut().push(self.id);
123 }
124
125 pub fn overlay(&self, draw: impl FnOnce(&mut dyn Canvas)) {
129 let mut rec = crate::pages::RecordingCanvas::new(None);
130 draw(&mut rec);
131 let at = self.ui.absolute_rect(self.id).map_or(PointF::default(), |r| r.origin());
132 self.ui.overlays.borrow_mut().push((at, crate::pages::Page { ops: rec.ops }));
133 self.ui.overlay_users.borrow_mut().insert(self.id);
134 }
135}
136
137#[derive(Clone, Debug, Default)]
139pub(crate) struct Visual {
140 state: Option<ControlState>,
141 pub(crate) shown: Option<ResolvedStyle>,
142 from: Option<ResolvedStyle>,
143 start: f64,
144 pub(crate) reach: Option<f32>,
147 pub(crate) ink: Option<RectF>,
150 pub(crate) drawing: Option<u64>,
153 pub(crate) shift: PointF,
156 pub(crate) version: u64,
159 pub(crate) covers: bool,
163 pub(crate) plain: crate::ink::Plain,
166 pub(crate) layer_key: Option<u64>,
170}
171
172const SPILL_SLACK: f32 = 0.01;
175
176const RGBA_MARGIN: u32 = 16;
178
179#[derive(Clone, Copy, Debug)]
181pub(crate) struct Backdrop {
182 parent: Option<ComponentId>,
184 version: u64,
186 builds: u32,
188}
189
190const BACKDROP_BUILDS: u32 = 2;
194
195struct Look<'t> {
197 enabled: bool,
198 state: ControlState,
199 inherited: &'t Theme,
201 mixed: &'t Theme,
202 recolored: Option<std::rc::Rc<Theme>>,
203 colors: crate::component::ColorOverride,
204 style: ResolvedStyle,
205 transitioning: bool,
206 paint_fill: bool,
207 font: crate::component::FontOverride,
208 reach: f32,
209}
210
211impl Look<'_> {
212 fn theme(&self) -> &Theme {
214 self.recolored.as_deref().unwrap_or(self.mixed)
215 }
216}
217
218impl Visual {
219 fn update(&mut self, state: ControlState, target: ResolvedStyle, now: f64) -> (ResolvedStyle, bool) {
222 let duration = target.transition_ms as f64 / 1000.0;
223 if self.state.is_some_and(|s| s != state) && duration > 0.0 && self.shown.as_ref().is_some_and(|s| *s != target) {
226 if let Some(shown) = self.shown.take() {
227 self.from = Some(shown);
228 self.start = now;
229 }
230 }
231 self.state = Some(state);
232 let (style, running) = match &self.from {
233 Some(from) if duration > 0.0 => {
234 let t = ((now - self.start) / duration) as f32;
235 if t >= 1.0 {
236 (target, false)
237 } else {
238 (from.lerp(&target, Easing::OutQuad.apply(t)), true)
239 }
240 }
241 _ => (target, false),
242 };
243 if !running {
244 self.from = None;
245 }
246 self.shown = Some(style.clone());
247 (style, running)
248 }
249}
250
251pub const DRAG_LABEL_MARGIN: f32 = 8.0;
253
254impl Ui {
255 pub fn render_png(&mut self, id: ComponentId, width: f32, height: f32, scale: f32) -> Option<Vec<u8>> {
265 let service = self.services_mut().offscreen.take()?;
266 if let Some(cb) = self.control_mut(id) {
267 cb.set_position(0.0, 0.0).set_size(width, height);
268 }
269 self.layout();
270 for _ in 0..4 {
273 if !self.needs_layout() {
274 break;
275 }
276 self.layout();
277 }
278 let background = self.theme().color("background");
279 let png = service.render_png(width.ceil() as u32, height.ceil() as u32, scale, background, &mut |canvas| self.paint(id, canvas));
280 self.services_mut().offscreen = Some(service);
281 png
282 }
283
284 pub fn snapshot(&self, id: ComponentId, scale: f32) -> Option<crate::Image> {
289 let service = self.services().offscreen.as_ref()?;
290 let cb = self.cb(id)?;
291 let (place, size) = {
292 let b = cb.bounds();
293 let t = cb.translate();
294 (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))
295 };
296 let enabled = self.ancestors_enabled(id);
297 let png = service.render_png(size.0, size.1, scale, crate::Color::TRANSPARENT, &mut |canvas| {
298 canvas.translate(-place.x, -place.y);
300 let mut classes = Vec::new();
301 self.paint_node(id, canvas, enabled, &mut classes, &self.theme, &Default::default(), None);
302 })?;
303 Some(crate::Image::encoded(png))
304 }
305
306 pub fn render_rgba(&mut self, id: ComponentId, rect: RectF, scale: f32) -> Option<(u32, u32, Vec<u8>)> {
320 if !(scale > 0.0 && rect.width > 0.0 && rect.height > 0.0) {
321 return None;
322 }
323 let (w, h) = ((rect.width * scale).ceil() as u32, (rect.height * scale).ceil() as u32);
324 crate::image::checked_size(w, h).ok()?;
325 self.cb(id)?;
326 let (mw, mh) = (w + 2 * RGBA_MARGIN, h + 2 * RGBA_MARGIN);
330 crate::image::checked_size(mw, mh).ok()?;
331 let margin = RGBA_MARGIN as f32 / scale;
332 let service = self.services_mut().offscreen.take()?;
333 self.update_layout();
334 let rgba = if self.parent(id).is_none() {
335 let origin = self.cb(id).map(|cb| cb.bounds().origin()).unwrap_or_default();
336 let area = rect.offset(origin.x, origin.y);
337 let painted = RectF::new(area.x - margin, area.y - margin, area.width + 2.0 * margin, area.height + 2.0 * margin);
338 let background = self.theme().color("background");
339 let pending = self.repaint_requested;
341 let out = service.render_rgba(mw, mh, scale, background, &mut |canvas| {
342 canvas.translate(-painted.x, -painted.y);
343 self.paint_regions_in(id, canvas, &[painted], true);
344 });
345 self.repaint_requested |= pending;
346 out
347 } else {
348 let place = {
349 let cb = self.cb(id)?;
350 let (b, t) = (cb.bounds(), cb.translate());
351 PointF::new(b.x + t.x + rect.x - margin, b.y + t.y + rect.y - margin)
352 };
353 let enabled = self.ancestors_enabled(id);
354 service.render_rgba(mw, mh, scale, crate::Color::TRANSPARENT, &mut |canvas| {
355 canvas.translate(-place.x, -place.y);
356 let mut classes = Vec::new();
357 self.paint_node(id, canvas, enabled, &mut classes, &self.theme, &Default::default(), None);
358 })
359 };
360 self.services_mut().offscreen = Some(service);
361 let rgba = rgba?;
362 let (row, stride, m) = (w as usize * 4, mw as usize * 4, RGBA_MARGIN as usize);
363 let pixels = (0..h as usize).flat_map(|y| {
364 let start = (y + m) * stride + m * 4;
365 rgba[start..start + row].iter().copied()
366 });
367 Some((w, h, pixels.collect()))
368 }
369
370 pub(crate) fn invoke_render_rgba(&mut self, id: ComponentId, args: &[crate::PropValue]) -> std::result::Result<crate::PropValue, String> {
374 let number = |i: usize| args.get(i).and_then(|v| v.to_f64().ok()).map(|v| v as f32);
375 let (Some(x), Some(y), Some(width), Some(height)) = (number(0), number(1), number(2), number(3)) else {
376 return Err("render_rgba pede x, y, width, height e, se quiser, scale".into());
377 };
378 let scale = number(4).unwrap_or(1.0);
379 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")?;
380 Ok(crate::PropValue::String(crate::image::encode_base64(&rgba)))
381 }
382
383 fn ancestors_enabled(&self, id: ComponentId) -> bool {
385 let mut cur = self.parent(id);
386 while let Some(c) = cur {
387 if self.cb(c).is_some_and(|cb| !cb.enabled()) {
388 return false;
389 }
390 cur = self.parent(c);
391 }
392 true
393 }
394
395 pub fn paint(&mut self, root: ComponentId, canvas: &mut dyn Canvas) {
396 self.paint_region(root, canvas, None);
397 }
398
399 pub fn paint_region(&mut self, root: ComponentId, canvas: &mut dyn Canvas, area: Option<RectF>) {
403 match area {
404 Some(a) => self.paint_regions(root, canvas, &[a]),
405 None => self.paint_regions(root, canvas, &[]),
406 }
407 }
408
409 pub fn paint_regions(&mut self, root: ComponentId, canvas: &mut dyn Canvas, areas: &[RectF]) {
414 self.paint_regions_in(root, canvas, areas, areas.is_empty());
415 }
416
417 pub(crate) fn paint_regions_in(&mut self, root: ComponentId, canvas: &mut dyn Canvas, areas: &[RectF], whole: bool) {
420 let area = areas.iter().copied().reduce(|a, b| a.union(b));
421 let _profile = crate::profile::scope(crate::profile::Lane::Paint, || format!("pintura {}", self.path_of(root)));
422 self.update_layout();
423 self.style_animating.set(false);
424 self.wake_at.set(None);
425 let mut classes = Vec::new();
426 self.overlays.borrow_mut().clear();
427 if whole {
428 self.overlay_users.borrow_mut().clear();
429 self.layer_epoch.set(self.layer_epoch.get() + 1);
431 }
432 for key in self.dead_layers.borrow_mut().drain(..) {
435 canvas.forget_cached(key);
436 }
437 {
440 let mut movers = self.movers.borrow_mut();
441 movers.clear();
442 movers.extend(self.placement_movers().filter_map(|m| self.parent(m).map(|p| (p, m))));
443 if !self.backdrops.borrow().is_empty() {
444 self.backdrops.borrow_mut().retain(|&id, b| {
445 let keep = movers.iter().any(|&(p, _)| Some(p) == b.parent);
446 if !keep {
447 let own = self.control(id).is_some_and(|cb| cb.cache_layer()) || self.in_transition(id);
448 if let Some(key) = self.entry(id).filter(|_| !own).and_then(|e| e.visual.borrow_mut().layer_key.take()) {
449 canvas.forget_cached(key);
450 }
451 }
452 keep
453 });
454 }
455 }
456 self.backdrop_next.set(false);
457 let caching = match self.get_prop(root, "layer_cache") {
460 Ok(crate::PropValue::Enum(name)) => <crate::LayerCaching as crate::prop::PropEnum>::from_name(&name).unwrap_or_default(),
461 _ => crate::LayerCaching::Project,
462 };
463 self.auto_layers.set(caching.enabled());
464 let visible: Option<Vec<RectF>> = self.control(root).map(|cb| match area {
466 Some(_) => areas.iter().map(|a| intersection(cb.bounds(), *a)).filter(|r| r.width > 0.0 && r.height > 0.0).collect(),
467 None => vec![cb.bounds()],
468 });
469 let visible = visible.as_deref();
470 self.spilled.set(false);
471 self.paint_area.set(area);
472 self.paint_form.set(self.control(root).map(|cb| cb.bounds()));
473 self.paint_count.set(0);
474 let mut ink = crate::ink::InkCanvas::new(&mut *canvas, &self.ink, &self.plain);
475 if self.text_mode == crate::textcore::TextMode::Native {
477 self.paint_node(root, &mut ink, true, &mut classes, &self.theme, &Default::default(), visible);
478 } else {
479 let mut text = crate::textcore::TextCanvas { inner: &mut ink, mode: self.text_mode };
480 self.paint_node(root, &mut text, true, &mut classes, &self.theme, &Default::default(), visible);
481 }
482 self.flush_paint_failures();
483 let origin = self.absolute_rect(root).map_or(PointF::default(), |r| r.origin());
485 for (at, page) in self.overlays.borrow_mut().drain(..) {
486 canvas.save();
487 canvas.translate(at.x - origin.x, at.y - origin.y);
488 page.replay(canvas);
489 canvas.restore();
490 }
491 if let Some((strip, color)) = self.status_strip(root) {
492 canvas.fill_rect(strip, 0.0, &crate::Brush::Solid(color));
493 }
494 self.paint_drag(root, canvas);
495 self.paint_middle_mark(root, canvas);
496 self.paint_hint(root, canvas);
497 self.paint_busy(root, canvas);
498 self.frame_requests.borrow_mut().insert(root, (self.style_animating.get(), self.wake_at.get()));
499 crate::profile::sample("controles pintados", self.paint_count.get() as f64);
501 self.repaint_requested = false;
502 if area.is_some() && self.spilled.get() {
505 self.request_repaint();
506 }
507 }
508
509 pub fn last_paint_count(&self) -> usize {
512 self.paint_count.get()
513 }
514
515 pub fn paint_overflow(&mut self, root: ComponentId, canvas: &mut dyn Canvas) {
518 self.update_layout();
519 let Some(cb) = self.cb(root) else { return };
520 let inherited = match cb.theme_name() {
521 "" => &self.theme,
522 name => self.theme_named(name).unwrap_or(&self.theme),
523 };
524 let enabled = cb.enabled();
525 let size = self.form_area(root);
526 let mut classes = Vec::new();
527 let children: Vec<ComponentId> = self.children(root).iter().copied().filter(|&c| self.sticks_out(c, size)).collect();
530 for child in children {
531 self.paint_node(child, canvas, enabled, &mut classes, inherited, &cb.font, None);
532 }
533 }
534
535 pub fn overflows(&self, root: ComponentId) -> bool {
538 let area = self.form_area(root);
539 self.children(root).iter().any(|&c| self.sticks_out(c, area))
540 }
541
542 fn form_area(&self, root: ComponentId) -> RectF {
544 let origin = self.absolute_rect(root).unwrap_or_default();
545 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()))
546 }
547
548 fn sticks_out(&self, id: ComponentId, area: RectF) -> bool {
550 let Some(cb) = self.cb(id) else { return false };
551 if !cb.visible() {
552 return false;
553 }
554 let Some(r) = self.absolute_rect(id) else { return false };
555 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;
557 outside || (!cb.clip_children() && self.children(id).iter().any(|&c| self.sticks_out(c, area)))
558 }
559
560 fn paint_drag(&self, root: ComponentId, canvas: &mut dyn Canvas) {
563 let Some((label, at, target)) = self.drag_view(root) else { return };
564 let origin = self.absolute_rect(root).map_or(PointF::default(), |r| r.origin());
565 let data = self.drag_data(root).unwrap_or_default();
568 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)));
569 if let Some(r) = target.and_then(|t| self.absolute_rect(t)) {
570 let r = RectF::new(r.x - origin.x, r.y - origin.y, r.width, r.height);
571 canvas.stroke_rect(r.inflate(1.0), 6.0, &crate::canvas::Stroke::new(self.theme.color("primary"), 2.0));
572 }
573 let visual = self.drag_visual(root).map(|(v, _)| v);
575 let mut label_at = PointF::new(at.x + 14.0, at.y + 14.0);
576 if let Some(v) = visual {
577 let r = RectF::new(at.x - v.hotspot.x, at.y - v.hotspot.y, v.size.width, v.size.height);
578 if !self.native_drag_image {
579 if let Some(size) = canvas.image_size(&v.image) {
580 canvas.save();
581 canvas.clip_round_rect(r, 6.0);
582 let (src, dest) = crate::ImageFit::Cover.place(size, r);
583 canvas.draw_image(&v.image, src, dest, v.opacity);
584 canvas.restore();
585 }
586 }
587 label_at = PointF::new(r.x, r.bottom() + 4.0);
589 }
590 if label.is_empty() || self.native_drag_image {
593 return;
594 }
595 self.paint_drag_label(canvas, &label, label_at);
596 }
597
598 fn drag_label_layout(&self, label: &str, measure: impl FnOnce(&str, &TextStyle) -> f32) -> (ResolvedStyle, TextStyle, crate::geometry::SizeF) {
601 let style = self.theme.resolve(&["Hint"], "", ControlState::default());
602 let mut ts = crate::canvas::TextStyle { font: style.font.clone(), color: style.text, ..Default::default() };
603 ts.trimming = crate::text::Trimming::Character;
604 let pad = style.padding;
605 let w = measure(label, &ts).min(320.0) + pad.left + pad.right + 1.0;
606 let h = (ts.font.size * 1.4).round() + pad.top + pad.bottom;
607 (style, ts, crate::geometry::SizeF::new(w, h))
608 }
609
610 fn paint_drag_label(&self, canvas: &mut dyn Canvas, label: &str, at: PointF) {
612 let (style, ts, size) = self.drag_label_layout(label, |l, ts| canvas.measure_text(l, ts).width);
613 let pad = style.padding;
614 let rect = RectF::new(at.x, at.y, size.width, size.height);
615 if let Some(shadow) = &style.shadow {
616 canvas.draw_shadow(rect, style.radius, shadow);
617 }
618 canvas.fill_rect(rect, style.radius, &crate::canvas::Brush::Solid(style.fill.with_opacity(0.92)));
619 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);
620 }
621
622 pub fn render_drag_label(&self, label: &str, scale: f32) -> Option<(u32, u32, Vec<u8>)> {
629 if label.is_empty() || !(scale > 0.0) {
630 return None;
631 }
632 let service = self.services().offscreen.as_ref()?;
633 let (_, _, size) = self.drag_label_layout(label, |l, ts| self.measure_text(l, ts).width);
634 let m = DRAG_LABEL_MARGIN;
635 let (w, h) = (((size.width + 2.0 * m) * scale).ceil() as u32, ((size.height + 2.0 * m) * scale).ceil() as u32);
636 crate::image::checked_size(w, h).ok()?;
637 let rgba = service.render_rgba(w, h, scale, crate::Color::TRANSPARENT, &mut |canvas| self.paint_drag_label(canvas, label, PointF::new(m, m)))?;
638 Some((w, h, rgba))
639 }
640
641 fn paint_hint(&self, root: ComponentId, canvas: &mut dyn Canvas) {
643 let Some((text, at)) = self.visible_hint(root) else { return };
644 let Some(form) = self.control(root).map(|cb| cb.bounds()) else { return };
645 let style = self.theme.resolve(&["Hint"], "", ControlState::default());
646 let mut ts = crate::canvas::TextStyle { font: style.font.clone(), color: style.text, ..Default::default() };
647 ts.v_align = crate::canvas::TextAlign::Leading;
648 let max = 280.0f32.min(form.width - 16.0).max(40.0);
649 let mut measure = |s: &str| canvas.measure_text(s, &ts).width;
650 let lines = crate::text::layout_lines(&text, max, 12, true, crate::text::Trimming::Word, &mut measure);
651 let width = lines.iter().map(|l| measure(l)).fold(0.0f32, f32::max);
652 let lh = (ts.font.size * 1.4).round();
653 let pad = style.padding;
654 let w = width + pad.left + pad.right + 1.0;
655 let h = lines.len() as f32 * lh + pad.top + pad.bottom;
656 let mut x = at.x + 4.0;
657 let mut y = at.y + 22.0;
658 if x + w > form.width - 4.0 {
659 x = (form.width - 4.0 - w).max(4.0);
660 }
661 if y + h > form.height - 4.0 {
662 y = (at.y - h - 8.0).max(4.0);
663 }
664 let rect = RectF::new(x, y, w, h);
665 if let Some(shadow) = &style.shadow {
666 canvas.draw_shadow(rect, style.radius, shadow);
667 }
668 canvas.fill_rect(rect, style.radius, &crate::canvas::Brush::Solid(style.fill));
669 if style.border_width > 0.0 && !style.border_color.is_transparent() {
671 canvas.stroke_rect(rect, style.radius, &style.border_stroke(style.border_color, style.border_width));
672 }
673 let mut ly = y + pad.top;
674 for line in &lines {
675 canvas.draw_text(line, RectF::new(x + pad.left, ly, width + 1.0, lh), &ts);
676 ly += lh;
677 }
678 }
679
680 #[allow(clippy::too_many_arguments)]
684 fn look<'t>(
685 &'t self,
686 id: ComponentId,
687 component: &dyn crate::Component,
688 cb: &crate::ControlBase,
689 visual: &std::cell::RefCell<Visual>,
690 parent_enabled: bool,
691 classes: &mut Vec<&'static str>,
692 inherited: &'t Theme,
693 parent_font: &crate::component::FontOverride,
694 peek: bool,
695 ) -> Look<'t> {
696 let enabled = parent_enabled && cb.enabled();
697 let mut state = cb.state();
698 state.disabled = !enabled;
699 if let Some(checked) = component.checked_state() {
700 state.checked = checked;
701 }
702 if self.still_picture {
703 state.hover = false;
704 state.pressed = false;
705 state.focused = false;
706 }
707 if cb.inherit_state() {
709 let mut up = self.parent(id);
710 while let Some(p) = up {
711 let Some(pcb) = self.cb(p) else { break };
712 if !pcb.inherit_state() {
713 let ps = pcb.state();
714 state.hover |= ps.hover;
715 state.pressed |= ps.pressed;
716 state.checked |= self.component(p).and_then(|c| c.checked_state()).unwrap_or(ps.checked);
717 break;
718 }
719 up = self.parent(p);
720 }
721 }
722 if state.focused && !component.accepts_text() && self.focus_from_pointer(self.root_of(id)) {
725 state.focused = false;
726 }
727
728 classes.clear();
729 component.class_chain(classes);
730 let inherited = match cb.theme_name() {
732 "" => inherited,
733 name => self.theme_named(name).unwrap_or(inherited),
734 };
735 let mixed = self.mixed_theme(inherited, classes);
736 let colors = cb.colors;
739 let recolored = colors.recolors_theme().then(|| {
740 let key = (mixed.name.clone(), colors);
741 self.recolored.borrow_mut().entry(key).or_insert_with(|| std::rc::Rc::new(colors.apply_theme(mixed))).clone()
742 });
743 let (target, reach) = {
744 let theme: &Theme = recolored.as_deref().unwrap_or(mixed);
745 (theme.resolve(classes, cb.style(), state), theme.reach(classes, cb.style()).max(cb.shadow().map_or(0.0, |s| s.reach())))
746 };
747 let (mut style, transitioning) = if self.design_mode {
749 (target, false)
750 } else if peek {
751 visual.borrow().clone().update(state, target, self.time)
752 } else {
753 visual.borrow_mut().update(state, target, self.time)
754 };
755 let font = if cb.font.is_empty() { parent_font.clone() } else { cb.font.over(parent_font) };
757 if !font.is_empty() {
758 font.apply(&mut style.font);
759 }
760 if cb.text_scale() != 1.0 {
762 style.font.size *= cb.text_scale();
763 }
764 if !self.font_names().is_empty() {
766 style.font.family = self.resolve_font(&style.font.family);
767 }
768 let paint_fill = colors.fill.is_some() && component.transparent_background();
771 if let Some(fill) = colors.fill {
772 let toward = if crate::component::luminance(fill) < 0.5 { crate::Color::WHITE } else { crate::Color::BLACK };
775 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 };
776 style.fill = fill.lerp(toward.with_opacity(fill.a as f32 / 255.0), amount);
777 }
778 if let Some(border) = colors.border {
779 style.border_color = border;
780 style.border_width = style.border_width.max(1.0);
781 }
782 if let Some(text) = colors.text {
783 style.text = text;
784 }
785 Look { enabled, state, inherited, mixed, recolored, colors, style, transitioning, paint_fill, font, reach }
786 }
787
788 pub(crate) fn drawing_unchanged(&self, id: ComponentId) -> bool {
793 let Some(entry) = self.entry(id) else { return false };
794 let Some(component) = entry.component.as_deref() else { return false };
795 let Some(cb) = component.control() else { return false };
796 let Some(before) = entry.visual.borrow().drawing else { return false };
797 if !component.paint_is_pure() || entry.paint_hook.is_some() || self.paint_failed(id) || self.flips_content(id) || cb.rotation() != 0.0 {
798 return false;
799 }
800 let mut chain = Vec::new();
802 let mut current = self.parent(id);
803 while let Some(p) = current {
804 chain.push(p);
805 current = self.parent(p);
806 }
807 let (mut enabled, mut inherited, mut font) = (true, &*self.theme, crate::component::FontOverride::default());
808 for &a in chain.iter().rev() {
809 let Some(acb) = self.control(a) else { continue };
810 enabled &= acb.enabled();
811 if !acb.theme_name().is_empty() {
812 inherited = self.theme_named(acb.theme_name()).unwrap_or(inherited);
813 }
814 if !acb.font.is_empty() {
815 font = acb.font.over(&font);
816 }
817 }
818 let mut classes = Vec::new();
819 let look = self.look(id, component, cb, &entry.visual, enabled, &mut classes, inherited, &font, true);
820 if look.transitioning {
822 return false;
823 }
824 let (requested, wake) = (Cell::new(false), Cell::new(None));
825 let ctx = PaintCtx {
826 ui: self,
827 id,
828 rect: RectF::from_size(cb.bounds().size()),
829 state: look.state,
830 style: &look.style,
831 theme: look.theme(),
832 time: self.time,
833 design: self.design_mode,
834 colors: look.colors,
835 frame_request: &requested,
836 wake_at: &wake,
837 resources: self.services().resources.as_deref(),
838 };
839 let ghost = if self.design_mode && cb.design_hidden { 0.35 } else { 1.0 };
840 let opacity = cb.opacity() * look.style.opacity * ghost;
841 if opacity <= 0.0 {
842 return false;
843 }
844 let mut hasher = std::hash::DefaultHasher::new();
845 std::hash::Hash::hash(&opacity.to_bits(), &mut hasher);
846 std::hash::Hash::hash(&cb.blend_mode(), &mut hasher);
847 let text = self.services().text.as_deref();
848 let mut trace = crate::trace::TraceCanvas::new(None, text, &mut hasher);
849 let painted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
850 self.paint_own(&mut trace, component, &ctx, look.paint_fill, cb.shadow().as_ref());
851 component.paint_after(&mut trace, &ctx);
852 }));
853 let volatile = trace.volatile;
854 painted.is_ok() && !volatile && !requested.get() && std::hash::Hasher::finish(&hasher) == before
855 }
856
857 fn paint_own(&self, canvas: &mut dyn Canvas, component: &dyn crate::Component, ctx: &PaintCtx<'_>, paint_fill: bool, shadow: Option<&crate::Shadow>) {
860 let style = ctx.style;
861 let shape = component.clip_shape();
863 let radius = shape.as_ref().map_or(style.radius, |s| s.radius(ctx.rect));
864 if let Some(shadow) = shadow.or(style.shadow.as_ref()) {
865 canvas.draw_shadow(ctx.rect, radius, shadow);
866 }
867 if let Some(fill) = ctx.colors.fill.filter(|_| paint_fill) {
868 match shape {
869 Some(s) => s.fill(canvas, ctx.rect, &crate::Brush::Solid(fill)),
870 None => canvas.fill_rect(ctx.rect, radius, &crate::Brush::Solid(fill)),
871 }
872 }
873 if style.material != crate::theme::Material::None {
875 canvas.backdrop_blur(ctx.rect, radius, style.material.blur());
876 }
877 component.paint(canvas, ctx);
878 if style.material == crate::theme::Material::Glass {
879 paint_glass_light(canvas, ctx.rect, radius, ctx.theme.dark);
880 }
881 }
882
883 fn paint_reveal(&self, canvas: &mut dyn Canvas, ctx: &PaintCtx<'_>, shape: Option<crate::ClipShape>) {
888 let reveal = ctx.style.reveal;
889 let id = ctx.id;
890 if !reveal.on() {
891 if !self.reveal_ids.borrow().is_empty() {
892 self.reveal_ids.borrow_mut().remove(&id);
893 }
894 return;
895 }
896 self.reveal_ids.borrow_mut().insert(id, reveal.radius);
897 let Some(at) = self.pointer_position(self.root_of(id)) else { return };
898 let p = self.local_point(id, at);
899 let rect = ctx.rect;
900 let dx = (rect.x - p.x).max(p.x - rect.right()).max(0.0);
901 let dy = (rect.y - p.y).max(p.y - rect.bottom()).max(0.0);
902 if dx.hypot(dy) >= reveal.radius {
903 return;
904 }
905 let light = |color: crate::Color| crate::Brush::Radial {
906 center: p,
907 radius: reveal.radius,
908 stops: vec![crate::canvas::GradientStop::new(0.0, color), crate::canvas::GradientStop::new(1.0, color.with_opacity(0.0))],
909 };
910 let radius = shape.as_ref().map_or(ctx.style.radius, |s| s.radius(rect));
911 if reveal.background && rect.contains(p) {
912 let brush = light(reveal.color.with_opacity(0.55));
913 match &shape {
914 Some(s) => s.fill(canvas, rect, &brush),
915 None => canvas.fill_rect(rect, radius, &brush),
916 }
917 }
918 if reveal.border {
919 let width = ctx.style.border_width.max(1.0);
920 let half = width / 2.0;
921 let inner = crate::RectF::new(rect.x + half, rect.y + half, (rect.width - width).max(0.0), (rect.height - width).max(0.0));
922 let stroke = crate::canvas::Stroke::new(light(reveal.color), width);
923 match &shape {
924 Some(s) => canvas.stroke_path(&s.outline(inner), &stroke),
925 None => canvas.stroke_rect(inner, (radius - half).max(0.0), &stroke),
926 }
927 }
928 }
929
930 #[allow(clippy::too_many_arguments)]
933 fn paint_own_with_hook(
934 &self,
935 canvas: &mut dyn Canvas,
936 id: ComponentId,
937 entry: &crate::ui::Entry,
938 component: &dyn crate::Component,
939 ctx: &PaintCtx<'_>,
940 paint_fill: bool,
941 shadow: Option<&crate::Shadow>,
942 flip: bool,
943 ) {
944 let style = ctx.style;
945 let shape = component.clip_shape();
947 let radius = shape.as_ref().map_or(style.radius, |s| s.radius(ctx.rect));
948 if let Some(shadow) = shadow.or(style.shadow.as_ref()) {
949 canvas.draw_shadow(ctx.rect, radius, shadow);
950 }
951 if let Some(fill) = ctx.colors.fill.filter(|_| paint_fill) {
952 match shape {
953 Some(s) => s.fill(canvas, ctx.rect, &crate::Brush::Solid(fill)),
954 None => canvas.fill_rect(ctx.rect, radius, &crate::Brush::Solid(fill)),
955 }
956 }
957 if style.material != crate::theme::Material::None {
959 canvas.backdrop_blur(ctx.rect, radius, style.material.blur());
960 }
961 if flip {
962 canvas.save();
963 canvas.translate(ctx.rect.width, 0.0);
964 }
965 {
966 let mut mirror;
967 let target: &mut dyn Canvas = if flip {
968 mirror = Mirror { inner: &mut *canvas };
969 &mut mirror
970 } else {
971 &mut *canvas
972 };
973 if self.paint_failed(id) {
976 paint_failure(target, ctx.rect);
977 } else {
978 let painted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match &entry.paint_hook {
979 Some(hook) => hook(target, ctx, &|c: &mut dyn Canvas, x: &PaintCtx<'_>| component.paint(c, x)),
980 None => component.paint(target, ctx),
981 }));
982 if let Err(payload) = painted {
983 self.note_paint_failure(id, payload.as_ref());
984 }
985 }
986 }
987 if flip {
988 canvas.restore();
989 }
990 if style.material == crate::theme::Material::Glass {
991 paint_glass_light(canvas, ctx.rect, radius, ctx.theme.dark);
992 }
993 }
994
995 fn paint_node(
996 &self,
997 id: ComponentId,
998 canvas: &mut dyn Canvas,
999 parent_enabled: bool,
1000 classes: &mut Vec<&'static str>,
1001 inherited: &Theme,
1002 parent_font: &crate::component::FontOverride,
1003 visible: Option<&[RectF]>,
1004 ) {
1005 let behind_mover = self.backdrop_next.replace(false);
1008 let Some(entry) = self.entry(id) else { return };
1009 let Some(component) = entry.component.as_deref() else { return };
1010 let Some(cb) = component.control() else { return };
1011 if !cb.visible() || (cb.design_only && !self.design_mode) {
1012 return;
1013 }
1014 let place = {
1019 let b = cb.bounds();
1020 let t = cb.translate();
1021 RectF::new(b.x + t.x, b.y + t.y, b.width, b.height)
1022 };
1023 let contained = cb.clip_children() || entry.children.is_empty();
1024 let away = cb.rotation() == 0.0
1028 && visible.is_some_and(|v| !v.iter().any(|r| place.inflate(CULL_MARGIN).intersects(*r)))
1029 && !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)));
1030 if away && (contained || !self.descendants_reach(id, place, visible.unwrap_or(&[]))) {
1031 return;
1032 }
1033 self.paint_count.set(self.paint_count.get() + 1);
1034 let look = self.look(id, component, cb, &entry.visual, parent_enabled, classes, inherited, parent_font, false);
1035 entry.visual.borrow_mut().reach = Some(look.reach);
1036 let (enabled, state, inherited, colors, paint_fill) = (look.enabled, look.state, look.inherited, look.colors, look.paint_fill);
1037 let (theme, style, font) = (look.theme(), &look.style, &look.font);
1038 if look.transitioning {
1039 self.style_animating.set(true);
1040 self.frame_ids.borrow_mut().push(id);
1041 }
1042 let ghost = if self.design_mode && cb.design_hidden { 0.35 } else { 1.0 };
1044 let opacity = cb.opacity() * style.opacity * ghost;
1045 if opacity <= 0.0 {
1046 entry.visual.borrow_mut().drawing = None;
1047 return;
1048 }
1049 let outer_ink = self.ink.borrow_mut().take();
1052 let outer_plain = self.plain.replace(crate::ink::Plain::Nothing);
1053 let bounds = cb.bounds();
1054 {
1057 let mut timed = self.timed_frames.borrow_mut();
1058 if !timed.is_empty() {
1059 timed.remove(&id);
1060 }
1061 }
1062 let scale = cb.scale();
1065 let ctx = PaintCtx {
1066 ui: self,
1067 id,
1068 rect: RectF::from_size(cb.inner_size()),
1069 state,
1070 style: &style,
1071 theme,
1072 time: self.time,
1073 design: self.design_mode,
1074 colors,
1075 frame_request: &self.style_animating,
1076 wake_at: &self.wake_at,
1077 resources: self.services().resources.as_deref(),
1078 };
1079
1080 let flip = self.flips_content(id);
1082 let automatic = self.auto_layers.get()
1092 && !entry.children.is_empty()
1093 && ((cb.clip_children() && (self.animates_placement(id) || (behind_mover && self.backdrop_worth(id, entry.visual.borrow().version)))) || self.in_transition(id));
1094 let blend = cb.blend_mode();
1096 let pulled = self.overscroll_pull(id).and_then(|p| self.overscroll_of(id).map(|s| (p, s)));
1099 let shifts = pulled.is_some_and(|(_, s)| matches!(s, crate::Overscroll::Stretch | crate::Overscroll::Bounce));
1100 let cached = !flip && !shifts && blend == crate::BlendMode::Normal && (cb.cache_layer() || automatic);
1101 let skip_own = away && !cached && !flip;
1106
1107 canvas.save();
1108 let shift = cb.translate();
1109 let drawn = if cached && shift != PointF::ZERO {
1113 let s = canvas.device_scale().max(f32::EPSILON);
1114 PointF::new((shift.x * s).round() / s, (shift.y * s).round() / s)
1115 } else {
1116 shift
1117 };
1118 canvas.translate(bounds.x + drawn.x, bounds.y + drawn.y);
1119 let rotation = cb.rotation();
1120 if rotation != 0.0 {
1121 canvas.translate(bounds.width / 2.0, bounds.height / 2.0);
1122 canvas.rotate(rotation);
1123 canvas.translate(-bounds.width / 2.0, -bounds.height / 2.0);
1124 }
1125 if scale != 1.0 {
1126 canvas.scale(scale, scale);
1127 }
1128 if let Some((p, style)) = pulled.filter(|_| shifts) {
1129 canvas.save();
1130 canvas.clip_rect(ctx.rect);
1131 overscroll_shift(canvas, ctx.rect, p, style);
1132 }
1133 let layer = opacity < 1.0 || blend != crate::BlendMode::Normal;
1134 if blend != crate::BlendMode::Normal {
1135 canvas.save_layer_blend(opacity, blend, ctx.rect.inflate(look.reach + 1.0));
1136 } else if layer {
1137 canvas.save_layer(opacity);
1138 }
1139
1140 let traced = component.paint_is_pure() && entry.paint_hook.is_none() && !flip && rotation == 0.0 && !self.paint_failed(id);
1143 let mut hasher = std::hash::DefaultHasher::new();
1144 std::hash::Hash::hash(&opacity.to_bits(), &mut hasher);
1145 std::hash::Hash::hash(&blend, &mut hasher);
1146 let mut volatile = false;
1147 let layer_key = cached.then(|| {
1148 let mut key = std::hash::DefaultHasher::new();
1149 let version = entry.visual.borrow().version;
1150 std::hash::Hash::hash(&(id, version, self.layer_epoch.get(), self.design_mode), &mut key);
1151 std::hash::Hasher::finish(&key)
1152 });
1153 let old_key = std::mem::replace(&mut entry.visual.borrow_mut().layer_key, layer_key);
1156 if let Some(old) = old_key.filter(|old| Some(*old) != layer_key) {
1157 canvas.forget_cached(old);
1158 }
1159 let cache_hit = layer_key.is_some_and(|key| canvas.begin_cached(key, ctx.rect.inflate(look.reach + 1.0)));
1160 if !cache_hit {
1161 if skip_own {
1162 } else if traced {
1163 let mut trace = crate::trace::TraceCanvas::new(Some(&mut *canvas), None, &mut hasher);
1164 let painted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.paint_own(&mut trace, component, &ctx, paint_fill, cb.shadow().as_ref())));
1165 volatile |= trace.volatile;
1166 if let Err(payload) = painted {
1167 self.note_paint_failure(id, payload.as_ref());
1168 }
1169 } else {
1170 self.paint_own_with_hook(canvas, id, entry, component, &ctx, paint_fill, cb.shadow().as_ref(), flip);
1171 }
1172 if !skip_own {
1173 self.paint_reveal(canvas, &ctx, component.painted_shape());
1174 }
1175
1176 let scrolled_form = cb.scroll_offset().y > 0.0 && self.parent(id).is_none();
1178 let shape = component.clip_shape();
1180 let clip = cb.clip_children() || scrolled_form || shape.is_some();
1181 if clip {
1182 canvas.save();
1183 let r = if scrolled_form {
1184 let s = cb.safe_area;
1185 crate::RectF::new(ctx.rect.x, ctx.rect.y + s.top, ctx.rect.width, (ctx.rect.height - s.top - s.bottom).max(0.0))
1186 } else {
1187 ctx.rect
1188 };
1189 canvas.clip_rect(r);
1190 if let Some(s) = shape {
1191 s.clip(canvas, ctx.rect);
1192 }
1193 }
1194 let inner: Option<Vec<RectF>> = match visible.filter(|_| rotation == 0.0 && !cached) {
1198 Some(v) => Some(
1199 v.iter()
1200 .map(|r| r.offset(-place.x, -place.y))
1201 .map(|r| if scale == 1.0 { r } else { RectF::new(r.x / scale, r.y / scale, r.width / scale, r.height / scale) })
1203 .map(|local| if clip { intersection(local, ctx.rect) } else { local })
1204 .filter(|r| r.width > 0.0 && r.height > 0.0)
1205 .collect(),
1206 ),
1207 None if clip && rotation == 0.0 => Some(vec![ctx.rect]),
1208 None => None,
1209 };
1210 let hidden = self.covered_children(&entry.children, inner.as_deref());
1211 let mover_at = if self.auto_layers.get() {
1213 self.movers.borrow().iter().filter(|&&(p, _)| p == id).filter_map(|&(_, m)| entry.children.iter().position(|&c| c == m)).max()
1214 } else {
1215 None
1216 };
1217 for (k, &child) in entry.children.iter().enumerate() {
1218 if hidden.get(k).copied().unwrap_or(false) {
1219 continue;
1220 }
1221 self.backdrop_next.set(mover_at.is_some_and(|m| k < m));
1222 self.paint_node(child, canvas, enabled, classes, inherited, &font, inner.as_deref());
1223 }
1224 if clip {
1225 canvas.restore();
1226 }
1227 if self.paint_failed(id) || skip_own {
1228 } else if flip {
1230 canvas.save();
1231 canvas.translate(ctx.rect.width, 0.0);
1232 let after = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| component.paint_after(&mut Mirror { inner: &mut *canvas }, &ctx)));
1233 canvas.restore();
1234 if let Err(payload) = after {
1235 self.note_paint_failure(id, payload.as_ref());
1236 }
1237 } else if traced {
1238 let mut trace = crate::trace::TraceCanvas::new(Some(&mut *canvas), None, &mut hasher);
1239 let after = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| component.paint_after(&mut trace, &ctx)));
1240 volatile |= trace.volatile;
1241 if let Err(payload) = after {
1242 self.note_paint_failure(id, payload.as_ref());
1243 }
1244 } else if let Err(payload) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| component.paint_after(canvas, &ctx))) {
1245 self.note_paint_failure(id, payload.as_ref());
1246 }
1247 if cached {
1248 canvas.end_cached();
1249 }
1250 }
1251
1252 if layer {
1253 canvas.restore();
1254 }
1255 if shifts {
1256 canvas.restore();
1257 }
1258 if let Some((p, crate::Overscroll::Glow)) = pulled {
1259 overscroll_glow(canvas, ctx.rect, p, self.theme.color("primary"));
1260 }
1261 canvas.restore();
1262 let ink = std::mem::replace(&mut *self.ink.borrow_mut(), outer_ink);
1263 let plain = self.plain.replace(outer_plain);
1264 let mut visual = entry.visual.borrow_mut();
1265 if skip_own {
1266 visual.shift = shift;
1268 drop(visual);
1269 return;
1270 }
1271 if let (Some(new), Some(area)) = (ink, self.paint_area.get()) {
1272 let seen = self.paint_form.get().map_or(new, |form| intersection(new, form));
1278 let outside = seen.width > 0.0 && seen.height > 0.0 && !area.inflate(SPILL_SLACK).contains_rect(seen);
1279 if outside && !visual.ink.is_some_and(|old| old.inflate(SPILL_SLACK).contains_rect(seen)) {
1280 self.spilled.set(true);
1281 }
1282 }
1283 visual.ink = ink;
1284 visual.plain = plain.after(visual.plain);
1285 visual.shift = shift;
1286 visual.drawing = (traced && !cache_hit && !volatile && !self.paint_failed(id)).then(|| std::hash::Hasher::finish(&hasher));
1287 let whole = opacity >= 1.0 && rotation == 0.0 && !flip && !self.paint_failed(id) && component.clip_shape().is_none();
1290 drop(visual);
1291 let own = component.opaque(&style) || paint_fill && colors.fill.is_some_and(|f| f.a == 255) && style.radius <= 0.0;
1292 let by_child = || {
1293 entry.children.iter().any(|&c| {
1294 self.entry(c).is_some_and(|e| {
1295 e.visual.borrow().covers
1296 && e.component.as_deref().and_then(|c| c.control()).is_some_and(|ccb| ccb.visible() && place_of(ccb).contains_rect(ctx.rect))
1297 })
1298 })
1299 };
1300 let covers = whole && (own || by_child());
1301 let was = std::mem::replace(&mut entry.visual.borrow_mut().covers, covers);
1302 if was && !covers {
1303 self.style_animating.set(true);
1306 self.frame_ids.borrow_mut().push(id);
1307 }
1308 }
1309
1310 fn backdrop_worth(&self, id: ComponentId, version: u64) -> bool {
1314 let parent = self.parent(id);
1315 let mut backdrops = self.backdrops.borrow_mut();
1316 let b = backdrops.entry(id).or_insert(Backdrop { parent, version, builds: 1 });
1317 if b.version != version {
1318 b.version = version;
1319 b.builds += 1;
1320 }
1321 b.builds <= BACKDROP_BUILDS
1322 }
1323
1324 fn covered_children(&self, children: &[ComponentId], inner: Option<&[RectF]>) -> Vec<bool> {
1329 let mut hidden = Vec::new();
1330 let mut covers: Vec<RectF> = Vec::new();
1333 for (k, &child) in children.iter().enumerate().rev() {
1334 let Some(entry) = self.entry(child) else { continue };
1335 let Some(cb) = entry.component.as_deref().and_then(|c| c.control()) else { continue };
1336 if !cb.visible() {
1337 continue;
1338 }
1339 let place = place_of(cb);
1340 if !covers.is_empty() {
1341 let reach = entry.visual.borrow().reach.unwrap_or(CULL_MARGIN);
1342 let own = place.inflate(reach);
1343 let contained = !entry.children.is_empty() && !cb.clip_children();
1344 let gone = covers.iter().any(|c| {
1345 c.contains_rect(own) && (!contained || inner.is_some_and(|areas| !areas.is_empty() && areas.iter().all(|a| c.contains_rect(*a))))
1346 });
1347 if gone {
1348 if hidden.is_empty() {
1349 hidden = vec![false; children.len()];
1350 }
1351 hidden[k] = true;
1352 continue;
1353 }
1354 }
1355 if entry.visual.borrow().covers {
1356 covers.push(place);
1357 if covers.len() > 4 {
1358 covers.sort_by(|a, b| (b.width * b.height).total_cmp(&(a.width * a.height)));
1359 covers.truncate(4);
1360 }
1361 }
1362 }
1363 hidden
1364 }
1365}
1366
1367fn overscroll_shift(canvas: &mut dyn Canvas, rect: RectF, p: PointF, style: crate::Overscroll) {
1371 if style == crate::Overscroll::Bounce {
1372 canvas.translate(p.x, p.y);
1373 return;
1374 }
1375 let sx = 1.0 + p.x.abs() / rect.width.max(1.0);
1376 let sy = 1.0 + p.y.abs() / rect.height.max(1.0);
1377 let ax = if p.x > 0.0 { rect.x } else { rect.right() };
1379 let ay = if p.y > 0.0 { rect.y } else { rect.bottom() };
1380 canvas.translate(ax, ay);
1381 canvas.scale(sx, sy);
1382 canvas.translate(-ax, -ay);
1383}
1384
1385fn overscroll_glow(canvas: &mut dyn Canvas, rect: RectF, p: PointF, color: crate::Color) {
1387 canvas.save();
1388 canvas.clip_rect(rect);
1389 let tint = |k: f32| crate::Color::rgba(color.r, color.g, color.b, (40.0 + 90.0 * k).min(255.0) as u8);
1390 if p.y != 0.0 {
1391 let k = (p.y.abs() / (rect.height * 0.2).max(1.0)).min(1.0);
1392 let depth = (rect.width * 0.25).min(rect.height * 0.5) * (0.3 + 0.7 * k);
1393 let y = if p.y > 0.0 { rect.y - depth } else { rect.bottom() - depth };
1394 canvas.fill_ellipse(RectF::new(rect.x - rect.width * 0.25, y, rect.width * 1.5, depth * 2.0), &crate::Brush::Solid(tint(k)));
1395 }
1396 if p.x != 0.0 {
1397 let k = (p.x.abs() / (rect.width * 0.2).max(1.0)).min(1.0);
1398 let depth = (rect.height * 0.25).min(rect.width * 0.5) * (0.3 + 0.7 * k);
1399 let x = if p.x > 0.0 { rect.x - depth } else { rect.right() - depth };
1400 canvas.fill_ellipse(RectF::new(x, rect.y - rect.height * 0.25, depth * 2.0, rect.height * 1.5), &crate::Brush::Solid(tint(k)));
1401 }
1402 canvas.restore();
1403}
1404
1405fn place_of(cb: &crate::component::ControlBase) -> RectF {
1406 let b = cb.bounds();
1407 let t = cb.translate();
1408 RectF::new(b.x + t.x, b.y + t.y, b.width, b.height)
1409}
1410
1411fn paint_failure(canvas: &mut dyn Canvas, rect: RectF) {
1415 let red = crate::color::Color::rgb(220, 38, 38);
1416 canvas.fill_rect(rect, 0.0, &crate::canvas::Brush::Solid(red.with_opacity(0.12)));
1417 let stroke = crate::canvas::Stroke::new(red, 2.0);
1418 canvas.stroke_rect(rect.inflate(-1.0), 0.0, &stroke);
1419 canvas.draw_line(rect.origin(), PointF::new(rect.right(), rect.bottom()), &stroke);
1420 canvas.draw_line(PointF::new(rect.right(), rect.y), PointF::new(rect.x, rect.bottom()), &stroke);
1421}
1422
1423pub fn paint_glass_light(canvas: &mut dyn Canvas, rect: crate::RectF, radius: f32, dark: bool) {
1424 use crate::canvas::{Brush, GradientStop, Stroke};
1425 use crate::{Color, PointF};
1426 if rect.width <= 2.0 || rect.height <= 2.0 {
1427 return;
1428 }
1429 let shine = if dark { 0.16 } else { 0.42 };
1430 canvas.fill_rect(
1431 rect,
1432 radius,
1433 &Brush::Linear {
1434 start: PointF::new(0.0, rect.y),
1435 end: PointF::new(0.0, rect.y + rect.height * 0.6),
1436 stops: vec![GradientStop::new(0.0, Color::WHITE.with_opacity(shine)), GradientStop::new(1.0, Color::WHITE.with_opacity(0.0))],
1437 },
1438 );
1439 let edge = Brush::Linear {
1440 start: PointF::new(rect.x, rect.y),
1441 end: PointF::new(rect.x + rect.width * 0.35, rect.bottom()),
1442 stops: vec![
1443 GradientStop::new(0.0, Color::WHITE.with_opacity(if dark { 0.45 } else { 0.95 })),
1444 GradientStop::new(0.55, Color::WHITE.with_opacity(if dark { 0.10 } else { 0.35 })),
1445 GradientStop::new(1.0, if dark { Color::WHITE.with_opacity(0.18) } else { Color::BLACK.with_opacity(0.10) }),
1446 ],
1447 };
1448 let r = (radius - 0.5).max(0.0);
1449 canvas.stroke_rect(rect.inflate(-0.5), r, &Stroke::new(edge, 1.0));
1450}
1451
1452pub(crate) struct Mirror<'a> {
1456 pub(crate) inner: &'a mut dyn Canvas,
1457}
1458
1459impl Mirror<'_> {
1460 fn x(x: f32) -> f32 {
1461 -x
1462 }
1463
1464 fn point(p: crate::PointF) -> crate::PointF {
1465 crate::PointF::new(-p.x, p.y)
1466 }
1467
1468 fn rect(r: crate::RectF) -> crate::RectF {
1469 crate::RectF::new(-r.right(), r.y, r.width, r.height)
1470 }
1471
1472 fn path(p: &crate::Path) -> crate::Path {
1473 p.map_points(Self::point)
1474 }
1475
1476 fn brush(b: &crate::Brush) -> crate::Brush {
1477 use crate::Brush;
1478 match b {
1479 Brush::Solid(c) => Brush::Solid(*c),
1480 Brush::Linear { start, end, stops } => Brush::Linear { start: Self::point(*start), end: Self::point(*end), stops: stops.clone() },
1481 Brush::Radial { center, radius, stops } => Brush::Radial { center: Self::point(*center), radius: *radius, stops: stops.clone() },
1482 Brush::Sweep { center, start_angle, stops } => Brush::Sweep {
1484 center: Self::point(*center),
1485 start_angle: 180.0 - start_angle,
1486 stops: stops.iter().rev().map(|s| crate::GradientStop::new(1.0 - s.offset, s.color)).collect(),
1487 },
1488 }
1489 }
1490
1491 fn stroke(s: &crate::Stroke) -> crate::Stroke {
1492 crate::Stroke { brush: Self::brush(&s.brush), ..s.clone() }
1493 }
1494}
1495
1496impl Canvas for Mirror<'_> {
1497 fn save(&mut self) {
1498 self.inner.save();
1499 }
1500 fn restore(&mut self) {
1501 self.inner.restore();
1502 }
1503 fn translate(&mut self, dx: f32, dy: f32) {
1504 self.inner.translate(Self::x(dx), dy);
1505 }
1506 fn scale(&mut self, sx: f32, sy: f32) {
1507 self.inner.scale(sx, sy);
1508 }
1509 fn rotate(&mut self, degrees: f32) {
1510 self.inner.rotate(-degrees);
1511 }
1512 fn clip_rect(&mut self, rect: crate::RectF) {
1513 self.inner.clip_rect(Self::rect(rect));
1514 }
1515 fn save_layer(&mut self, opacity: f32) {
1516 self.inner.save_layer(opacity);
1517 }
1518 fn save_layer_blend(&mut self, opacity: f32, mode: crate::BlendMode, bounds: crate::RectF) {
1519 self.inner.save_layer_blend(opacity, mode, Self::rect(bounds));
1520 }
1521 fn fill_rect(&mut self, rect: crate::RectF, radius: f32, brush: &crate::Brush) {
1522 self.inner.fill_rect(Self::rect(rect), radius, &Self::brush(brush));
1523 }
1524 fn stroke_rect(&mut self, rect: crate::RectF, radius: f32, stroke: &crate::Stroke) {
1525 self.inner.stroke_rect(Self::rect(rect), radius, &Self::stroke(stroke));
1526 }
1527 fn fill_ellipse(&mut self, rect: crate::RectF, brush: &crate::Brush) {
1528 self.inner.fill_ellipse(Self::rect(rect), &Self::brush(brush));
1529 }
1530 fn stroke_ellipse(&mut self, rect: crate::RectF, stroke: &crate::Stroke) {
1531 self.inner.stroke_ellipse(Self::rect(rect), &Self::stroke(stroke));
1532 }
1533 fn draw_line(&mut self, from: crate::PointF, to: crate::PointF, stroke: &crate::Stroke) {
1534 self.inner.draw_line(Self::point(from), Self::point(to), &Self::stroke(stroke));
1535 }
1536 fn draw_text(&mut self, text: &str, rect: crate::RectF, style: &TextStyle) {
1537 use crate::TextAlign;
1538 let mut style = style.clone();
1539 style.h_align = match style.h_align {
1540 TextAlign::Leading => TextAlign::Trailing,
1541 TextAlign::Trailing => TextAlign::Leading,
1542 other => other,
1543 };
1544 self.inner.draw_text(text, Self::rect(rect), &style);
1545 }
1546 fn measure_text(&mut self, text: &str, style: &TextStyle) -> crate::SizeF {
1547 self.inner.measure_text(text, style)
1548 }
1549 fn measure_text_wrapped(&mut self, text: &str, style: &TextStyle, max_width: f32) -> crate::SizeF {
1550 self.inner.measure_text_wrapped(text, style, max_width)
1551 }
1552 fn draw_image(&mut self, image: &crate::Image, src: crate::RectF, dest: crate::RectF, opacity: f32) {
1553 self.inner.draw_image(image, src, Self::rect(dest), opacity);
1554 }
1555 fn image_size(&mut self, image: &crate::Image) -> Option<crate::SizeF> {
1556 self.inner.image_size(image)
1557 }
1558 fn clip_round_rect(&mut self, rect: crate::RectF, radius: f32) {
1559 self.inner.clip_round_rect(Self::rect(rect), radius);
1560 }
1561 fn fill_path(&mut self, path: &crate::Path, brush: &crate::Brush) {
1562 self.inner.fill_path(&Self::path(path), &Self::brush(brush));
1563 }
1564 fn clip_path(&mut self, path: &crate::Path, inverse: bool) {
1565 self.inner.clip_path(&Self::path(path), inverse);
1566 }
1567 fn backdrop_blur(&mut self, rect: crate::RectF, radius: f32, blur: f32) -> bool {
1568 self.inner.backdrop_blur(Self::rect(rect), radius, blur)
1569 }
1570 fn begin_masked(&mut self, inverse: bool) -> bool {
1571 self.inner.begin_masked(inverse)
1572 }
1573 fn begin_mask(&mut self) {
1574 self.inner.begin_mask();
1575 }
1576 fn begin_luminance_mask(&mut self) {
1577 self.inner.begin_luminance_mask();
1578 }
1579 fn end_mask(&mut self) {
1580 self.inner.end_mask();
1581 }
1582 fn stroke_path(&mut self, path: &crate::Path, stroke: &crate::Stroke) {
1583 self.inner.stroke_path(&Self::path(path), &Self::stroke(stroke));
1584 }
1585 fn draw_shadow(&mut self, rect: crate::RectF, radius: f32, shadow: &crate::Shadow) {
1586 let mut shadow = shadow.clone();
1587 shadow.offset.x = -shadow.offset.x;
1588 self.inner.draw_shadow(Self::rect(rect), radius, &shadow);
1589 }
1590 fn device_scale(&self) -> f32 {
1591 self.inner.device_scale()
1592 }
1593 fn gpu_device(&self) -> Option<crate::GpuDevice> {
1594 self.inner.gpu_device()
1595 }
1596 fn draw_gpu_surface(&mut self, dest: crate::RectF, surface: &crate::GpuSurface) -> bool {
1597 self.inner.draw_gpu_surface(Self::rect(dest), surface)
1598 }
1599}
1600
1601impl Ui {
1602 fn descendants_reach(&self, id: ComponentId, place: RectF, visible: &[RectF]) -> bool {
1609 let Some(abs) = self.absolute_rect(id) else { return true };
1611 let (ox, oy) = (place.x - abs.x, place.y - abs.y);
1612 let hits = |r: RectF| visible.iter().any(|a| r.intersects(*a));
1613 let mut stack: Vec<(ComponentId, PointF)> = self.children(id).iter().map(|&c| (c, place.origin())).collect();
1614 while let Some((c, origin)) = stack.pop() {
1615 let Some(entry) = self.entry(c) else { continue };
1616 let Some(cb) = entry.component.as_deref().and_then(|c| c.control()) else { continue };
1617 if !cb.visible() || (cb.design_only && !self.design_mode) {
1618 continue;
1619 }
1620 if cb.rotation() != 0.0 || cb.scale() != 1.0 || cb.translate() != PointF::ZERO {
1621 return true;
1622 }
1623 let r = cb.bounds().offset(origin.x, origin.y);
1624 let visual = entry.visual.borrow();
1625 if hits(r.inflate(CULL_MARGIN)) || visual.ink.is_some_and(|ink| hits(ink.offset(ox, oy))) {
1626 return true;
1627 }
1628 if !cb.clip_children() {
1630 stack.extend(entry.children.iter().map(|&k| (k, r.origin())));
1631 }
1632 }
1633 false
1634 }
1635}
1636
1637const CULL_MARGIN: f32 = 48.0;
1640
1641fn intersection(a: RectF, b: RectF) -> RectF {
1643 let x = a.x.max(b.x);
1644 let y = a.y.max(b.y);
1645 RectF::new(x, y, (a.right().min(b.right()) - x).max(0.0), (a.bottom().min(b.bottom()) - y).max(0.0))
1646}
1647
1648fn warn_missing_icon(ui: &crate::Ui, name: &str, design: bool) {
1653 if design || !cfg!(debug_assertions) {
1654 return;
1655 }
1656 let Some((pack, _)) = name.split_once(':') else { return };
1659 thread_local! {
1660 static WARNED: std::cell::RefCell<std::collections::HashSet<String>> = Default::default();
1661 }
1662 if WARNED.with(|w| w.borrow().contains(name)) || !ui.has_icon_pack(pack) {
1663 return;
1664 }
1665 if WARNED.with(|w| w.borrow_mut().insert(name.to_string())) {
1666 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)");
1667 }
1668}