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_hint(root, canvas);
496 self.paint_busy(root, canvas);
497 self.frame_requests.borrow_mut().insert(root, (self.style_animating.get(), self.wake_at.get()));
498 crate::profile::sample("controles pintados", self.paint_count.get() as f64);
500 self.repaint_requested = false;
501 if area.is_some() && self.spilled.get() {
504 self.request_repaint();
505 }
506 }
507
508 pub fn last_paint_count(&self) -> usize {
511 self.paint_count.get()
512 }
513
514 pub fn paint_overflow(&mut self, root: ComponentId, canvas: &mut dyn Canvas) {
517 self.update_layout();
518 let Some(cb) = self.cb(root) else { return };
519 let inherited = match cb.theme_name() {
520 "" => &self.theme,
521 name => self.theme_named(name).unwrap_or(&self.theme),
522 };
523 let enabled = cb.enabled();
524 let size = self.form_area(root);
525 let mut classes = Vec::new();
526 let children: Vec<ComponentId> = self.children(root).iter().copied().filter(|&c| self.sticks_out(c, size)).collect();
529 for child in children {
530 self.paint_node(child, canvas, enabled, &mut classes, inherited, &cb.font, None);
531 }
532 }
533
534 pub fn overflows(&self, root: ComponentId) -> bool {
537 let area = self.form_area(root);
538 self.children(root).iter().any(|&c| self.sticks_out(c, area))
539 }
540
541 fn form_area(&self, root: ComponentId) -> RectF {
543 let origin = self.absolute_rect(root).unwrap_or_default();
544 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()))
545 }
546
547 fn sticks_out(&self, id: ComponentId, area: RectF) -> bool {
549 let Some(cb) = self.cb(id) else { return false };
550 if !cb.visible() {
551 return false;
552 }
553 let Some(r) = self.absolute_rect(id) else { return false };
554 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;
556 outside || (!cb.clip_children() && self.children(id).iter().any(|&c| self.sticks_out(c, area)))
557 }
558
559 fn paint_drag(&self, root: ComponentId, canvas: &mut dyn Canvas) {
562 let Some((label, at, target)) = self.drag_view(root) else { return };
563 let origin = self.absolute_rect(root).map_or(PointF::default(), |r| r.origin());
564 let data = self.drag_data(root).unwrap_or_default();
567 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)));
568 if let Some(r) = target.and_then(|t| self.absolute_rect(t)) {
569 let r = RectF::new(r.x - origin.x, r.y - origin.y, r.width, r.height);
570 canvas.stroke_rect(r.inflate(1.0), 6.0, &crate::canvas::Stroke::new(self.theme.color("primary"), 2.0));
571 }
572 let visual = self.drag_visual(root).map(|(v, _)| v);
574 let mut label_at = PointF::new(at.x + 14.0, at.y + 14.0);
575 if let Some(v) = visual {
576 let r = RectF::new(at.x - v.hotspot.x, at.y - v.hotspot.y, v.size.width, v.size.height);
577 if !self.native_drag_image {
578 if let Some(size) = canvas.image_size(&v.image) {
579 canvas.save();
580 canvas.clip_round_rect(r, 6.0);
581 let (src, dest) = crate::ImageFit::Cover.place(size, r);
582 canvas.draw_image(&v.image, src, dest, v.opacity);
583 canvas.restore();
584 }
585 }
586 label_at = PointF::new(r.x, r.bottom() + 4.0);
588 }
589 if label.is_empty() || self.native_drag_image {
592 return;
593 }
594 self.paint_drag_label(canvas, &label, label_at);
595 }
596
597 fn drag_label_layout(&self, label: &str, measure: impl FnOnce(&str, &TextStyle) -> f32) -> (ResolvedStyle, TextStyle, crate::geometry::SizeF) {
600 let style = self.theme.resolve(&["Hint"], "", ControlState::default());
601 let mut ts = crate::canvas::TextStyle { font: style.font.clone(), color: style.text, ..Default::default() };
602 ts.trimming = crate::text::Trimming::Character;
603 let pad = style.padding;
604 let w = measure(label, &ts).min(320.0) + pad.left + pad.right + 1.0;
605 let h = (ts.font.size * 1.4).round() + pad.top + pad.bottom;
606 (style, ts, crate::geometry::SizeF::new(w, h))
607 }
608
609 fn paint_drag_label(&self, canvas: &mut dyn Canvas, label: &str, at: PointF) {
611 let (style, ts, size) = self.drag_label_layout(label, |l, ts| canvas.measure_text(l, ts).width);
612 let pad = style.padding;
613 let rect = RectF::new(at.x, at.y, size.width, size.height);
614 if let Some(shadow) = &style.shadow {
615 canvas.draw_shadow(rect, style.radius, shadow);
616 }
617 canvas.fill_rect(rect, style.radius, &crate::canvas::Brush::Solid(style.fill.with_opacity(0.92)));
618 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);
619 }
620
621 pub fn render_drag_label(&self, label: &str, scale: f32) -> Option<(u32, u32, Vec<u8>)> {
628 if label.is_empty() || !(scale > 0.0) {
629 return None;
630 }
631 let service = self.services().offscreen.as_ref()?;
632 let (_, _, size) = self.drag_label_layout(label, |l, ts| self.measure_text(l, ts).width);
633 let m = DRAG_LABEL_MARGIN;
634 let (w, h) = (((size.width + 2.0 * m) * scale).ceil() as u32, ((size.height + 2.0 * m) * scale).ceil() as u32);
635 crate::image::checked_size(w, h).ok()?;
636 let rgba = service.render_rgba(w, h, scale, crate::Color::TRANSPARENT, &mut |canvas| self.paint_drag_label(canvas, label, PointF::new(m, m)))?;
637 Some((w, h, rgba))
638 }
639
640 fn paint_hint(&self, root: ComponentId, canvas: &mut dyn Canvas) {
642 let Some((text, at)) = self.visible_hint(root) else { return };
643 let Some(form) = self.control(root).map(|cb| cb.bounds()) else { return };
644 let style = self.theme.resolve(&["Hint"], "", ControlState::default());
645 let mut ts = crate::canvas::TextStyle { font: style.font.clone(), color: style.text, ..Default::default() };
646 ts.v_align = crate::canvas::TextAlign::Leading;
647 let max = 280.0f32.min(form.width - 16.0).max(40.0);
648 let mut measure = |s: &str| canvas.measure_text(s, &ts).width;
649 let lines = crate::text::layout_lines(&text, max, 12, true, crate::text::Trimming::Word, &mut measure);
650 let width = lines.iter().map(|l| measure(l)).fold(0.0f32, f32::max);
651 let lh = (ts.font.size * 1.4).round();
652 let pad = style.padding;
653 let w = width + pad.left + pad.right + 1.0;
654 let h = lines.len() as f32 * lh + pad.top + pad.bottom;
655 let mut x = at.x + 4.0;
656 let mut y = at.y + 22.0;
657 if x + w > form.width - 4.0 {
658 x = (form.width - 4.0 - w).max(4.0);
659 }
660 if y + h > form.height - 4.0 {
661 y = (at.y - h - 8.0).max(4.0);
662 }
663 let rect = RectF::new(x, y, w, h);
664 if let Some(shadow) = &style.shadow {
665 canvas.draw_shadow(rect, style.radius, shadow);
666 }
667 canvas.fill_rect(rect, style.radius, &crate::canvas::Brush::Solid(style.fill));
668 if style.border_width > 0.0 && !style.border_color.is_transparent() {
670 canvas.stroke_rect(rect, style.radius, &style.border_stroke(style.border_color, style.border_width));
671 }
672 let mut ly = y + pad.top;
673 for line in &lines {
674 canvas.draw_text(line, RectF::new(x + pad.left, ly, width + 1.0, lh), &ts);
675 ly += lh;
676 }
677 }
678
679 #[allow(clippy::too_many_arguments)]
683 fn look<'t>(
684 &'t self,
685 id: ComponentId,
686 component: &dyn crate::Component,
687 cb: &crate::ControlBase,
688 visual: &std::cell::RefCell<Visual>,
689 parent_enabled: bool,
690 classes: &mut Vec<&'static str>,
691 inherited: &'t Theme,
692 parent_font: &crate::component::FontOverride,
693 peek: bool,
694 ) -> Look<'t> {
695 let enabled = parent_enabled && cb.enabled();
696 let mut state = cb.state();
697 state.disabled = !enabled;
698 if let Some(checked) = component.checked_state() {
699 state.checked = checked;
700 }
701 if self.still_picture {
702 state.hover = false;
703 state.pressed = false;
704 state.focused = false;
705 }
706 if cb.inherit_state() {
708 let mut up = self.parent(id);
709 while let Some(p) = up {
710 let Some(pcb) = self.cb(p) else { break };
711 if !pcb.inherit_state() {
712 let ps = pcb.state();
713 state.hover |= ps.hover;
714 state.pressed |= ps.pressed;
715 state.checked |= self.component(p).and_then(|c| c.checked_state()).unwrap_or(ps.checked);
716 break;
717 }
718 up = self.parent(p);
719 }
720 }
721 if state.focused && !component.accepts_text() && self.focus_from_pointer(self.root_of(id)) {
724 state.focused = false;
725 }
726
727 classes.clear();
728 component.class_chain(classes);
729 let inherited = match cb.theme_name() {
731 "" => inherited,
732 name => self.theme_named(name).unwrap_or(inherited),
733 };
734 let mixed = self.mixed_theme(inherited, classes);
735 let colors = cb.colors;
738 let recolored = colors.recolors_theme().then(|| {
739 let key = (mixed.name.clone(), colors);
740 self.recolored.borrow_mut().entry(key).or_insert_with(|| std::rc::Rc::new(colors.apply_theme(mixed))).clone()
741 });
742 let (target, reach) = {
743 let theme: &Theme = recolored.as_deref().unwrap_or(mixed);
744 (theme.resolve(classes, cb.style(), state), theme.reach(classes, cb.style()).max(cb.shadow().map_or(0.0, |s| s.reach())))
745 };
746 let (mut style, transitioning) = if self.design_mode {
748 (target, false)
749 } else if peek {
750 visual.borrow().clone().update(state, target, self.time)
751 } else {
752 visual.borrow_mut().update(state, target, self.time)
753 };
754 let font = if cb.font.is_empty() { parent_font.clone() } else { cb.font.over(parent_font) };
756 if !font.is_empty() {
757 font.apply(&mut style.font);
758 }
759 if cb.text_scale() != 1.0 {
761 style.font.size *= cb.text_scale();
762 }
763 if !self.font_names().is_empty() {
765 style.font.family = self.resolve_font(&style.font.family);
766 }
767 let paint_fill = colors.fill.is_some() && component.transparent_background();
770 if let Some(fill) = colors.fill {
771 let toward = if crate::component::luminance(fill) < 0.5 { crate::Color::WHITE } else { crate::Color::BLACK };
774 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 };
775 style.fill = fill.lerp(toward.with_opacity(fill.a as f32 / 255.0), amount);
776 }
777 if let Some(border) = colors.border {
778 style.border_color = border;
779 style.border_width = style.border_width.max(1.0);
780 }
781 if let Some(text) = colors.text {
782 style.text = text;
783 }
784 Look { enabled, state, inherited, mixed, recolored, colors, style, transitioning, paint_fill, font, reach }
785 }
786
787 pub(crate) fn drawing_unchanged(&self, id: ComponentId) -> bool {
792 let Some(entry) = self.entry(id) else { return false };
793 let Some(component) = entry.component.as_deref() else { return false };
794 let Some(cb) = component.control() else { return false };
795 let Some(before) = entry.visual.borrow().drawing else { return false };
796 if !component.paint_is_pure() || entry.paint_hook.is_some() || self.paint_failed(id) || self.flips_content(id) || cb.rotation() != 0.0 {
797 return false;
798 }
799 let mut chain = Vec::new();
801 let mut current = self.parent(id);
802 while let Some(p) = current {
803 chain.push(p);
804 current = self.parent(p);
805 }
806 let (mut enabled, mut inherited, mut font) = (true, &*self.theme, crate::component::FontOverride::default());
807 for &a in chain.iter().rev() {
808 let Some(acb) = self.control(a) else { continue };
809 enabled &= acb.enabled();
810 if !acb.theme_name().is_empty() {
811 inherited = self.theme_named(acb.theme_name()).unwrap_or(inherited);
812 }
813 if !acb.font.is_empty() {
814 font = acb.font.over(&font);
815 }
816 }
817 let mut classes = Vec::new();
818 let look = self.look(id, component, cb, &entry.visual, enabled, &mut classes, inherited, &font, true);
819 if look.transitioning {
821 return false;
822 }
823 let (requested, wake) = (Cell::new(false), Cell::new(None));
824 let ctx = PaintCtx {
825 ui: self,
826 id,
827 rect: RectF::from_size(cb.bounds().size()),
828 state: look.state,
829 style: &look.style,
830 theme: look.theme(),
831 time: self.time,
832 design: self.design_mode,
833 colors: look.colors,
834 frame_request: &requested,
835 wake_at: &wake,
836 resources: self.services().resources.as_deref(),
837 };
838 let ghost = if self.design_mode && cb.design_hidden { 0.35 } else { 1.0 };
839 let opacity = cb.opacity() * look.style.opacity * ghost;
840 if opacity <= 0.0 {
841 return false;
842 }
843 let mut hasher = std::hash::DefaultHasher::new();
844 std::hash::Hash::hash(&opacity.to_bits(), &mut hasher);
845 std::hash::Hash::hash(&cb.blend_mode(), &mut hasher);
846 let text = self.services().text.as_deref();
847 let mut trace = crate::trace::TraceCanvas::new(None, text, &mut hasher);
848 let painted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
849 self.paint_own(&mut trace, component, &ctx, look.paint_fill, cb.shadow().as_ref());
850 component.paint_after(&mut trace, &ctx);
851 }));
852 let volatile = trace.volatile;
853 painted.is_ok() && !volatile && !requested.get() && std::hash::Hasher::finish(&hasher) == before
854 }
855
856 fn paint_own(&self, canvas: &mut dyn Canvas, component: &dyn crate::Component, ctx: &PaintCtx<'_>, paint_fill: bool, shadow: Option<&crate::Shadow>) {
859 let style = ctx.style;
860 let shape = component.clip_shape();
862 let radius = shape.as_ref().map_or(style.radius, |s| s.radius(ctx.rect));
863 if let Some(shadow) = shadow.or(style.shadow.as_ref()) {
864 canvas.draw_shadow(ctx.rect, radius, shadow);
865 }
866 if let Some(fill) = ctx.colors.fill.filter(|_| paint_fill) {
867 match shape {
868 Some(s) => s.fill(canvas, ctx.rect, &crate::Brush::Solid(fill)),
869 None => canvas.fill_rect(ctx.rect, radius, &crate::Brush::Solid(fill)),
870 }
871 }
872 if style.material != crate::theme::Material::None {
874 canvas.backdrop_blur(ctx.rect, radius, style.material.blur());
875 }
876 component.paint(canvas, ctx);
877 if style.material == crate::theme::Material::Glass {
878 paint_glass_light(canvas, ctx.rect, radius, ctx.theme.dark);
879 }
880 }
881
882 fn paint_reveal(&self, canvas: &mut dyn Canvas, ctx: &PaintCtx<'_>, shape: Option<crate::ClipShape>) {
887 let reveal = ctx.style.reveal;
888 let id = ctx.id;
889 if !reveal.on() {
890 if !self.reveal_ids.borrow().is_empty() {
891 self.reveal_ids.borrow_mut().remove(&id);
892 }
893 return;
894 }
895 self.reveal_ids.borrow_mut().insert(id, reveal.radius);
896 let Some(at) = self.pointer_position(self.root_of(id)) else { return };
897 let p = self.local_point(id, at);
898 let rect = ctx.rect;
899 let dx = (rect.x - p.x).max(p.x - rect.right()).max(0.0);
900 let dy = (rect.y - p.y).max(p.y - rect.bottom()).max(0.0);
901 if dx.hypot(dy) >= reveal.radius {
902 return;
903 }
904 let light = |color: crate::Color| crate::Brush::Radial {
905 center: p,
906 radius: reveal.radius,
907 stops: vec![crate::canvas::GradientStop::new(0.0, color), crate::canvas::GradientStop::new(1.0, color.with_opacity(0.0))],
908 };
909 let radius = shape.as_ref().map_or(ctx.style.radius, |s| s.radius(rect));
910 if reveal.background && rect.contains(p) {
911 let brush = light(reveal.color.with_opacity(0.55));
912 match &shape {
913 Some(s) => s.fill(canvas, rect, &brush),
914 None => canvas.fill_rect(rect, radius, &brush),
915 }
916 }
917 if reveal.border {
918 let width = ctx.style.border_width.max(1.0);
919 let half = width / 2.0;
920 let inner = crate::RectF::new(rect.x + half, rect.y + half, (rect.width - width).max(0.0), (rect.height - width).max(0.0));
921 let stroke = crate::canvas::Stroke::new(light(reveal.color), width);
922 match &shape {
923 Some(s) => canvas.stroke_path(&s.outline(inner), &stroke),
924 None => canvas.stroke_rect(inner, (radius - half).max(0.0), &stroke),
925 }
926 }
927 }
928
929 #[allow(clippy::too_many_arguments)]
932 fn paint_own_with_hook(
933 &self,
934 canvas: &mut dyn Canvas,
935 id: ComponentId,
936 entry: &crate::ui::Entry,
937 component: &dyn crate::Component,
938 ctx: &PaintCtx<'_>,
939 paint_fill: bool,
940 shadow: Option<&crate::Shadow>,
941 flip: bool,
942 ) {
943 let style = ctx.style;
944 let shape = component.clip_shape();
946 let radius = shape.as_ref().map_or(style.radius, |s| s.radius(ctx.rect));
947 if let Some(shadow) = shadow.or(style.shadow.as_ref()) {
948 canvas.draw_shadow(ctx.rect, radius, shadow);
949 }
950 if let Some(fill) = ctx.colors.fill.filter(|_| paint_fill) {
951 match shape {
952 Some(s) => s.fill(canvas, ctx.rect, &crate::Brush::Solid(fill)),
953 None => canvas.fill_rect(ctx.rect, radius, &crate::Brush::Solid(fill)),
954 }
955 }
956 if style.material != crate::theme::Material::None {
958 canvas.backdrop_blur(ctx.rect, radius, style.material.blur());
959 }
960 if flip {
961 canvas.save();
962 canvas.translate(ctx.rect.width, 0.0);
963 }
964 {
965 let mut mirror;
966 let target: &mut dyn Canvas = if flip {
967 mirror = Mirror { inner: &mut *canvas };
968 &mut mirror
969 } else {
970 &mut *canvas
971 };
972 if self.paint_failed(id) {
975 paint_failure(target, ctx.rect);
976 } else {
977 let painted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match &entry.paint_hook {
978 Some(hook) => hook(target, ctx, &|c: &mut dyn Canvas, x: &PaintCtx<'_>| component.paint(c, x)),
979 None => component.paint(target, ctx),
980 }));
981 if let Err(payload) = painted {
982 self.note_paint_failure(id, payload.as_ref());
983 }
984 }
985 }
986 if flip {
987 canvas.restore();
988 }
989 if style.material == crate::theme::Material::Glass {
990 paint_glass_light(canvas, ctx.rect, radius, ctx.theme.dark);
991 }
992 }
993
994 fn paint_node(
995 &self,
996 id: ComponentId,
997 canvas: &mut dyn Canvas,
998 parent_enabled: bool,
999 classes: &mut Vec<&'static str>,
1000 inherited: &Theme,
1001 parent_font: &crate::component::FontOverride,
1002 visible: Option<&[RectF]>,
1003 ) {
1004 let behind_mover = self.backdrop_next.replace(false);
1007 let Some(entry) = self.entry(id) else { return };
1008 let Some(component) = entry.component.as_deref() else { return };
1009 let Some(cb) = component.control() else { return };
1010 if !cb.visible() || (cb.design_only && !self.design_mode) {
1011 return;
1012 }
1013 let place = {
1018 let b = cb.bounds();
1019 let t = cb.translate();
1020 RectF::new(b.x + t.x, b.y + t.y, b.width, b.height)
1021 };
1022 let contained = cb.clip_children() || entry.children.is_empty();
1023 let away = cb.rotation() == 0.0
1027 && visible.is_some_and(|v| !v.iter().any(|r| place.inflate(CULL_MARGIN).intersects(*r)))
1028 && !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)));
1029 if away && (contained || !self.descendants_reach(id, place, visible.unwrap_or(&[]))) {
1030 return;
1031 }
1032 self.paint_count.set(self.paint_count.get() + 1);
1033 let look = self.look(id, component, cb, &entry.visual, parent_enabled, classes, inherited, parent_font, false);
1034 entry.visual.borrow_mut().reach = Some(look.reach);
1035 let (enabled, state, inherited, colors, paint_fill) = (look.enabled, look.state, look.inherited, look.colors, look.paint_fill);
1036 let (theme, style, font) = (look.theme(), &look.style, &look.font);
1037 if look.transitioning {
1038 self.style_animating.set(true);
1039 self.frame_ids.borrow_mut().push(id);
1040 }
1041 let ghost = if self.design_mode && cb.design_hidden { 0.35 } else { 1.0 };
1043 let opacity = cb.opacity() * style.opacity * ghost;
1044 if opacity <= 0.0 {
1045 entry.visual.borrow_mut().drawing = None;
1046 return;
1047 }
1048 let outer_ink = self.ink.borrow_mut().take();
1051 let outer_plain = self.plain.replace(crate::ink::Plain::Nothing);
1052 let bounds = cb.bounds();
1053 {
1056 let mut timed = self.timed_frames.borrow_mut();
1057 if !timed.is_empty() {
1058 timed.remove(&id);
1059 }
1060 }
1061 let scale = cb.scale();
1064 let ctx = PaintCtx {
1065 ui: self,
1066 id,
1067 rect: RectF::from_size(cb.inner_size()),
1068 state,
1069 style: &style,
1070 theme,
1071 time: self.time,
1072 design: self.design_mode,
1073 colors,
1074 frame_request: &self.style_animating,
1075 wake_at: &self.wake_at,
1076 resources: self.services().resources.as_deref(),
1077 };
1078
1079 let flip = self.flips_content(id);
1081 let automatic = self.auto_layers.get()
1091 && !entry.children.is_empty()
1092 && ((cb.clip_children() && (self.animates_placement(id) || (behind_mover && self.backdrop_worth(id, entry.visual.borrow().version)))) || self.in_transition(id));
1093 let blend = cb.blend_mode();
1095 let pulled = self.overscroll_pull(id).and_then(|p| self.overscroll_of(id).map(|s| (p, s)));
1098 let shifts = pulled.is_some_and(|(_, s)| matches!(s, crate::Overscroll::Stretch | crate::Overscroll::Bounce));
1099 let cached = !flip && !shifts && blend == crate::BlendMode::Normal && (cb.cache_layer() || automatic);
1100 let skip_own = away && !cached && !flip;
1105
1106 canvas.save();
1107 let shift = cb.translate();
1108 let drawn = if cached && shift != PointF::ZERO {
1112 let s = canvas.device_scale().max(f32::EPSILON);
1113 PointF::new((shift.x * s).round() / s, (shift.y * s).round() / s)
1114 } else {
1115 shift
1116 };
1117 canvas.translate(bounds.x + drawn.x, bounds.y + drawn.y);
1118 let rotation = cb.rotation();
1119 if rotation != 0.0 {
1120 canvas.translate(bounds.width / 2.0, bounds.height / 2.0);
1121 canvas.rotate(rotation);
1122 canvas.translate(-bounds.width / 2.0, -bounds.height / 2.0);
1123 }
1124 if scale != 1.0 {
1125 canvas.scale(scale, scale);
1126 }
1127 if let Some((p, style)) = pulled.filter(|_| shifts) {
1128 canvas.save();
1129 canvas.clip_rect(ctx.rect);
1130 overscroll_shift(canvas, ctx.rect, p, style);
1131 }
1132 let layer = opacity < 1.0 || blend != crate::BlendMode::Normal;
1133 if blend != crate::BlendMode::Normal {
1134 canvas.save_layer_blend(opacity, blend, ctx.rect.inflate(look.reach + 1.0));
1135 } else if layer {
1136 canvas.save_layer(opacity);
1137 }
1138
1139 let traced = component.paint_is_pure() && entry.paint_hook.is_none() && !flip && rotation == 0.0 && !self.paint_failed(id);
1142 let mut hasher = std::hash::DefaultHasher::new();
1143 std::hash::Hash::hash(&opacity.to_bits(), &mut hasher);
1144 std::hash::Hash::hash(&blend, &mut hasher);
1145 let mut volatile = false;
1146 let layer_key = cached.then(|| {
1147 let mut key = std::hash::DefaultHasher::new();
1148 let version = entry.visual.borrow().version;
1149 std::hash::Hash::hash(&(id, version, self.layer_epoch.get(), self.design_mode), &mut key);
1150 std::hash::Hasher::finish(&key)
1151 });
1152 let old_key = std::mem::replace(&mut entry.visual.borrow_mut().layer_key, layer_key);
1155 if let Some(old) = old_key.filter(|old| Some(*old) != layer_key) {
1156 canvas.forget_cached(old);
1157 }
1158 let cache_hit = layer_key.is_some_and(|key| canvas.begin_cached(key, ctx.rect.inflate(look.reach + 1.0)));
1159 if !cache_hit {
1160 if skip_own {
1161 } else if traced {
1162 let mut trace = crate::trace::TraceCanvas::new(Some(&mut *canvas), None, &mut hasher);
1163 let painted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.paint_own(&mut trace, component, &ctx, paint_fill, cb.shadow().as_ref())));
1164 volatile |= trace.volatile;
1165 if let Err(payload) = painted {
1166 self.note_paint_failure(id, payload.as_ref());
1167 }
1168 } else {
1169 self.paint_own_with_hook(canvas, id, entry, component, &ctx, paint_fill, cb.shadow().as_ref(), flip);
1170 }
1171 if !skip_own {
1172 self.paint_reveal(canvas, &ctx, component.painted_shape());
1173 }
1174
1175 let scrolled_form = cb.scroll_offset().y > 0.0 && self.parent(id).is_none();
1177 let shape = component.clip_shape();
1179 let clip = cb.clip_children() || scrolled_form || shape.is_some();
1180 if clip {
1181 canvas.save();
1182 let r = if scrolled_form {
1183 let s = cb.safe_area;
1184 crate::RectF::new(ctx.rect.x, ctx.rect.y + s.top, ctx.rect.width, (ctx.rect.height - s.top - s.bottom).max(0.0))
1185 } else {
1186 ctx.rect
1187 };
1188 canvas.clip_rect(r);
1189 if let Some(s) = shape {
1190 s.clip(canvas, ctx.rect);
1191 }
1192 }
1193 let inner: Option<Vec<RectF>> = match visible.filter(|_| rotation == 0.0 && !cached) {
1197 Some(v) => Some(
1198 v.iter()
1199 .map(|r| r.offset(-place.x, -place.y))
1200 .map(|r| if scale == 1.0 { r } else { RectF::new(r.x / scale, r.y / scale, r.width / scale, r.height / scale) })
1202 .map(|local| if clip { intersection(local, ctx.rect) } else { local })
1203 .filter(|r| r.width > 0.0 && r.height > 0.0)
1204 .collect(),
1205 ),
1206 None if clip && rotation == 0.0 => Some(vec![ctx.rect]),
1207 None => None,
1208 };
1209 let hidden = self.covered_children(&entry.children, inner.as_deref());
1210 let mover_at = if self.auto_layers.get() {
1212 self.movers.borrow().iter().filter(|&&(p, _)| p == id).filter_map(|&(_, m)| entry.children.iter().position(|&c| c == m)).max()
1213 } else {
1214 None
1215 };
1216 for (k, &child) in entry.children.iter().enumerate() {
1217 if hidden.get(k).copied().unwrap_or(false) {
1218 continue;
1219 }
1220 self.backdrop_next.set(mover_at.is_some_and(|m| k < m));
1221 self.paint_node(child, canvas, enabled, classes, inherited, &font, inner.as_deref());
1222 }
1223 if clip {
1224 canvas.restore();
1225 }
1226 if self.paint_failed(id) || skip_own {
1227 } else if flip {
1229 canvas.save();
1230 canvas.translate(ctx.rect.width, 0.0);
1231 let after = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| component.paint_after(&mut Mirror { inner: &mut *canvas }, &ctx)));
1232 canvas.restore();
1233 if let Err(payload) = after {
1234 self.note_paint_failure(id, payload.as_ref());
1235 }
1236 } else if traced {
1237 let mut trace = crate::trace::TraceCanvas::new(Some(&mut *canvas), None, &mut hasher);
1238 let after = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| component.paint_after(&mut trace, &ctx)));
1239 volatile |= trace.volatile;
1240 if let Err(payload) = after {
1241 self.note_paint_failure(id, payload.as_ref());
1242 }
1243 } else if let Err(payload) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| component.paint_after(canvas, &ctx))) {
1244 self.note_paint_failure(id, payload.as_ref());
1245 }
1246 if cached {
1247 canvas.end_cached();
1248 }
1249 }
1250
1251 if layer {
1252 canvas.restore();
1253 }
1254 if shifts {
1255 canvas.restore();
1256 }
1257 if let Some((p, crate::Overscroll::Glow)) = pulled {
1258 overscroll_glow(canvas, ctx.rect, p, self.theme.color("primary"));
1259 }
1260 canvas.restore();
1261 let ink = std::mem::replace(&mut *self.ink.borrow_mut(), outer_ink);
1262 let plain = self.plain.replace(outer_plain);
1263 let mut visual = entry.visual.borrow_mut();
1264 if skip_own {
1265 visual.shift = shift;
1267 drop(visual);
1268 return;
1269 }
1270 if let (Some(new), Some(area)) = (ink, self.paint_area.get()) {
1271 let seen = self.paint_form.get().map_or(new, |form| intersection(new, form));
1277 let outside = seen.width > 0.0 && seen.height > 0.0 && !area.inflate(SPILL_SLACK).contains_rect(seen);
1278 if outside && !visual.ink.is_some_and(|old| old.inflate(SPILL_SLACK).contains_rect(seen)) {
1279 self.spilled.set(true);
1280 }
1281 }
1282 visual.ink = ink;
1283 visual.plain = plain.after(visual.plain);
1284 visual.shift = shift;
1285 visual.drawing = (traced && !cache_hit && !volatile && !self.paint_failed(id)).then(|| std::hash::Hasher::finish(&hasher));
1286 let whole = opacity >= 1.0 && rotation == 0.0 && !flip && !self.paint_failed(id) && component.clip_shape().is_none();
1289 drop(visual);
1290 let own = component.opaque(&style) || paint_fill && colors.fill.is_some_and(|f| f.a == 255) && style.radius <= 0.0;
1291 let by_child = || {
1292 entry.children.iter().any(|&c| {
1293 self.entry(c).is_some_and(|e| {
1294 e.visual.borrow().covers
1295 && e.component.as_deref().and_then(|c| c.control()).is_some_and(|ccb| ccb.visible() && place_of(ccb).contains_rect(ctx.rect))
1296 })
1297 })
1298 };
1299 let covers = whole && (own || by_child());
1300 let was = std::mem::replace(&mut entry.visual.borrow_mut().covers, covers);
1301 if was && !covers {
1302 self.style_animating.set(true);
1305 self.frame_ids.borrow_mut().push(id);
1306 }
1307 }
1308
1309 fn backdrop_worth(&self, id: ComponentId, version: u64) -> bool {
1313 let parent = self.parent(id);
1314 let mut backdrops = self.backdrops.borrow_mut();
1315 let b = backdrops.entry(id).or_insert(Backdrop { parent, version, builds: 1 });
1316 if b.version != version {
1317 b.version = version;
1318 b.builds += 1;
1319 }
1320 b.builds <= BACKDROP_BUILDS
1321 }
1322
1323 fn covered_children(&self, children: &[ComponentId], inner: Option<&[RectF]>) -> Vec<bool> {
1328 let mut hidden = Vec::new();
1329 let mut covers: Vec<RectF> = Vec::new();
1332 for (k, &child) in children.iter().enumerate().rev() {
1333 let Some(entry) = self.entry(child) else { continue };
1334 let Some(cb) = entry.component.as_deref().and_then(|c| c.control()) else { continue };
1335 if !cb.visible() {
1336 continue;
1337 }
1338 let place = place_of(cb);
1339 if !covers.is_empty() {
1340 let reach = entry.visual.borrow().reach.unwrap_or(CULL_MARGIN);
1341 let own = place.inflate(reach);
1342 let contained = !entry.children.is_empty() && !cb.clip_children();
1343 let gone = covers.iter().any(|c| {
1344 c.contains_rect(own) && (!contained || inner.is_some_and(|areas| !areas.is_empty() && areas.iter().all(|a| c.contains_rect(*a))))
1345 });
1346 if gone {
1347 if hidden.is_empty() {
1348 hidden = vec![false; children.len()];
1349 }
1350 hidden[k] = true;
1351 continue;
1352 }
1353 }
1354 if entry.visual.borrow().covers {
1355 covers.push(place);
1356 if covers.len() > 4 {
1357 covers.sort_by(|a, b| (b.width * b.height).total_cmp(&(a.width * a.height)));
1358 covers.truncate(4);
1359 }
1360 }
1361 }
1362 hidden
1363 }
1364}
1365
1366fn overscroll_shift(canvas: &mut dyn Canvas, rect: RectF, p: PointF, style: crate::Overscroll) {
1370 if style == crate::Overscroll::Bounce {
1371 canvas.translate(p.x, p.y);
1372 return;
1373 }
1374 let sx = 1.0 + p.x.abs() / rect.width.max(1.0);
1375 let sy = 1.0 + p.y.abs() / rect.height.max(1.0);
1376 let ax = if p.x > 0.0 { rect.x } else { rect.right() };
1378 let ay = if p.y > 0.0 { rect.y } else { rect.bottom() };
1379 canvas.translate(ax, ay);
1380 canvas.scale(sx, sy);
1381 canvas.translate(-ax, -ay);
1382}
1383
1384fn overscroll_glow(canvas: &mut dyn Canvas, rect: RectF, p: PointF, color: crate::Color) {
1386 canvas.save();
1387 canvas.clip_rect(rect);
1388 let tint = |k: f32| crate::Color::rgba(color.r, color.g, color.b, (40.0 + 90.0 * k).min(255.0) as u8);
1389 if p.y != 0.0 {
1390 let k = (p.y.abs() / (rect.height * 0.2).max(1.0)).min(1.0);
1391 let depth = (rect.width * 0.25).min(rect.height * 0.5) * (0.3 + 0.7 * k);
1392 let y = if p.y > 0.0 { rect.y - depth } else { rect.bottom() - depth };
1393 canvas.fill_ellipse(RectF::new(rect.x - rect.width * 0.25, y, rect.width * 1.5, depth * 2.0), &crate::Brush::Solid(tint(k)));
1394 }
1395 if p.x != 0.0 {
1396 let k = (p.x.abs() / (rect.width * 0.2).max(1.0)).min(1.0);
1397 let depth = (rect.height * 0.25).min(rect.width * 0.5) * (0.3 + 0.7 * k);
1398 let x = if p.x > 0.0 { rect.x - depth } else { rect.right() - depth };
1399 canvas.fill_ellipse(RectF::new(x, rect.y - rect.height * 0.25, depth * 2.0, rect.height * 1.5), &crate::Brush::Solid(tint(k)));
1400 }
1401 canvas.restore();
1402}
1403
1404fn place_of(cb: &crate::component::ControlBase) -> RectF {
1405 let b = cb.bounds();
1406 let t = cb.translate();
1407 RectF::new(b.x + t.x, b.y + t.y, b.width, b.height)
1408}
1409
1410fn paint_failure(canvas: &mut dyn Canvas, rect: RectF) {
1414 let red = crate::color::Color::rgb(220, 38, 38);
1415 canvas.fill_rect(rect, 0.0, &crate::canvas::Brush::Solid(red.with_opacity(0.12)));
1416 let stroke = crate::canvas::Stroke::new(red, 2.0);
1417 canvas.stroke_rect(rect.inflate(-1.0), 0.0, &stroke);
1418 canvas.draw_line(rect.origin(), PointF::new(rect.right(), rect.bottom()), &stroke);
1419 canvas.draw_line(PointF::new(rect.right(), rect.y), PointF::new(rect.x, rect.bottom()), &stroke);
1420}
1421
1422pub fn paint_glass_light(canvas: &mut dyn Canvas, rect: crate::RectF, radius: f32, dark: bool) {
1423 use crate::canvas::{Brush, GradientStop, Stroke};
1424 use crate::{Color, PointF};
1425 if rect.width <= 2.0 || rect.height <= 2.0 {
1426 return;
1427 }
1428 let shine = if dark { 0.16 } else { 0.42 };
1429 canvas.fill_rect(
1430 rect,
1431 radius,
1432 &Brush::Linear {
1433 start: PointF::new(0.0, rect.y),
1434 end: PointF::new(0.0, rect.y + rect.height * 0.6),
1435 stops: vec![GradientStop::new(0.0, Color::WHITE.with_opacity(shine)), GradientStop::new(1.0, Color::WHITE.with_opacity(0.0))],
1436 },
1437 );
1438 let edge = Brush::Linear {
1439 start: PointF::new(rect.x, rect.y),
1440 end: PointF::new(rect.x + rect.width * 0.35, rect.bottom()),
1441 stops: vec![
1442 GradientStop::new(0.0, Color::WHITE.with_opacity(if dark { 0.45 } else { 0.95 })),
1443 GradientStop::new(0.55, Color::WHITE.with_opacity(if dark { 0.10 } else { 0.35 })),
1444 GradientStop::new(1.0, if dark { Color::WHITE.with_opacity(0.18) } else { Color::BLACK.with_opacity(0.10) }),
1445 ],
1446 };
1447 let r = (radius - 0.5).max(0.0);
1448 canvas.stroke_rect(rect.inflate(-0.5), r, &Stroke::new(edge, 1.0));
1449}
1450
1451pub(crate) struct Mirror<'a> {
1455 pub(crate) inner: &'a mut dyn Canvas,
1456}
1457
1458impl Mirror<'_> {
1459 fn x(x: f32) -> f32 {
1460 -x
1461 }
1462
1463 fn point(p: crate::PointF) -> crate::PointF {
1464 crate::PointF::new(-p.x, p.y)
1465 }
1466
1467 fn rect(r: crate::RectF) -> crate::RectF {
1468 crate::RectF::new(-r.right(), r.y, r.width, r.height)
1469 }
1470
1471 fn path(p: &crate::Path) -> crate::Path {
1472 p.map_points(Self::point)
1473 }
1474
1475 fn brush(b: &crate::Brush) -> crate::Brush {
1476 use crate::Brush;
1477 match b {
1478 Brush::Solid(c) => Brush::Solid(*c),
1479 Brush::Linear { start, end, stops } => Brush::Linear { start: Self::point(*start), end: Self::point(*end), stops: stops.clone() },
1480 Brush::Radial { center, radius, stops } => Brush::Radial { center: Self::point(*center), radius: *radius, stops: stops.clone() },
1481 Brush::Sweep { center, start_angle, stops } => Brush::Sweep {
1483 center: Self::point(*center),
1484 start_angle: 180.0 - start_angle,
1485 stops: stops.iter().rev().map(|s| crate::GradientStop::new(1.0 - s.offset, s.color)).collect(),
1486 },
1487 }
1488 }
1489
1490 fn stroke(s: &crate::Stroke) -> crate::Stroke {
1491 crate::Stroke { brush: Self::brush(&s.brush), ..s.clone() }
1492 }
1493}
1494
1495impl Canvas for Mirror<'_> {
1496 fn save(&mut self) {
1497 self.inner.save();
1498 }
1499 fn restore(&mut self) {
1500 self.inner.restore();
1501 }
1502 fn translate(&mut self, dx: f32, dy: f32) {
1503 self.inner.translate(Self::x(dx), dy);
1504 }
1505 fn scale(&mut self, sx: f32, sy: f32) {
1506 self.inner.scale(sx, sy);
1507 }
1508 fn rotate(&mut self, degrees: f32) {
1509 self.inner.rotate(-degrees);
1510 }
1511 fn clip_rect(&mut self, rect: crate::RectF) {
1512 self.inner.clip_rect(Self::rect(rect));
1513 }
1514 fn save_layer(&mut self, opacity: f32) {
1515 self.inner.save_layer(opacity);
1516 }
1517 fn save_layer_blend(&mut self, opacity: f32, mode: crate::BlendMode, bounds: crate::RectF) {
1518 self.inner.save_layer_blend(opacity, mode, Self::rect(bounds));
1519 }
1520 fn fill_rect(&mut self, rect: crate::RectF, radius: f32, brush: &crate::Brush) {
1521 self.inner.fill_rect(Self::rect(rect), radius, &Self::brush(brush));
1522 }
1523 fn stroke_rect(&mut self, rect: crate::RectF, radius: f32, stroke: &crate::Stroke) {
1524 self.inner.stroke_rect(Self::rect(rect), radius, &Self::stroke(stroke));
1525 }
1526 fn fill_ellipse(&mut self, rect: crate::RectF, brush: &crate::Brush) {
1527 self.inner.fill_ellipse(Self::rect(rect), &Self::brush(brush));
1528 }
1529 fn stroke_ellipse(&mut self, rect: crate::RectF, stroke: &crate::Stroke) {
1530 self.inner.stroke_ellipse(Self::rect(rect), &Self::stroke(stroke));
1531 }
1532 fn draw_line(&mut self, from: crate::PointF, to: crate::PointF, stroke: &crate::Stroke) {
1533 self.inner.draw_line(Self::point(from), Self::point(to), &Self::stroke(stroke));
1534 }
1535 fn draw_text(&mut self, text: &str, rect: crate::RectF, style: &TextStyle) {
1536 use crate::TextAlign;
1537 let mut style = style.clone();
1538 style.h_align = match style.h_align {
1539 TextAlign::Leading => TextAlign::Trailing,
1540 TextAlign::Trailing => TextAlign::Leading,
1541 other => other,
1542 };
1543 self.inner.draw_text(text, Self::rect(rect), &style);
1544 }
1545 fn measure_text(&mut self, text: &str, style: &TextStyle) -> crate::SizeF {
1546 self.inner.measure_text(text, style)
1547 }
1548 fn measure_text_wrapped(&mut self, text: &str, style: &TextStyle, max_width: f32) -> crate::SizeF {
1549 self.inner.measure_text_wrapped(text, style, max_width)
1550 }
1551 fn draw_image(&mut self, image: &crate::Image, src: crate::RectF, dest: crate::RectF, opacity: f32) {
1552 self.inner.draw_image(image, src, Self::rect(dest), opacity);
1553 }
1554 fn image_size(&mut self, image: &crate::Image) -> Option<crate::SizeF> {
1555 self.inner.image_size(image)
1556 }
1557 fn clip_round_rect(&mut self, rect: crate::RectF, radius: f32) {
1558 self.inner.clip_round_rect(Self::rect(rect), radius);
1559 }
1560 fn fill_path(&mut self, path: &crate::Path, brush: &crate::Brush) {
1561 self.inner.fill_path(&Self::path(path), &Self::brush(brush));
1562 }
1563 fn clip_path(&mut self, path: &crate::Path, inverse: bool) {
1564 self.inner.clip_path(&Self::path(path), inverse);
1565 }
1566 fn backdrop_blur(&mut self, rect: crate::RectF, radius: f32, blur: f32) -> bool {
1567 self.inner.backdrop_blur(Self::rect(rect), radius, blur)
1568 }
1569 fn begin_masked(&mut self, inverse: bool) -> bool {
1570 self.inner.begin_masked(inverse)
1571 }
1572 fn begin_mask(&mut self) {
1573 self.inner.begin_mask();
1574 }
1575 fn begin_luminance_mask(&mut self) {
1576 self.inner.begin_luminance_mask();
1577 }
1578 fn end_mask(&mut self) {
1579 self.inner.end_mask();
1580 }
1581 fn stroke_path(&mut self, path: &crate::Path, stroke: &crate::Stroke) {
1582 self.inner.stroke_path(&Self::path(path), &Self::stroke(stroke));
1583 }
1584 fn draw_shadow(&mut self, rect: crate::RectF, radius: f32, shadow: &crate::Shadow) {
1585 let mut shadow = shadow.clone();
1586 shadow.offset.x = -shadow.offset.x;
1587 self.inner.draw_shadow(Self::rect(rect), radius, &shadow);
1588 }
1589 fn device_scale(&self) -> f32 {
1590 self.inner.device_scale()
1591 }
1592 fn gpu_device(&self) -> Option<crate::GpuDevice> {
1593 self.inner.gpu_device()
1594 }
1595 fn draw_gpu_surface(&mut self, dest: crate::RectF, surface: &crate::GpuSurface) -> bool {
1596 self.inner.draw_gpu_surface(Self::rect(dest), surface)
1597 }
1598}
1599
1600impl Ui {
1601 fn descendants_reach(&self, id: ComponentId, place: RectF, visible: &[RectF]) -> bool {
1608 let Some(abs) = self.absolute_rect(id) else { return true };
1610 let (ox, oy) = (place.x - abs.x, place.y - abs.y);
1611 let hits = |r: RectF| visible.iter().any(|a| r.intersects(*a));
1612 let mut stack: Vec<(ComponentId, PointF)> = self.children(id).iter().map(|&c| (c, place.origin())).collect();
1613 while let Some((c, origin)) = stack.pop() {
1614 let Some(entry) = self.entry(c) else { continue };
1615 let Some(cb) = entry.component.as_deref().and_then(|c| c.control()) else { continue };
1616 if !cb.visible() || (cb.design_only && !self.design_mode) {
1617 continue;
1618 }
1619 if cb.rotation() != 0.0 || cb.scale() != 1.0 || cb.translate() != PointF::ZERO {
1620 return true;
1621 }
1622 let r = cb.bounds().offset(origin.x, origin.y);
1623 let visual = entry.visual.borrow();
1624 if hits(r.inflate(CULL_MARGIN)) || visual.ink.is_some_and(|ink| hits(ink.offset(ox, oy))) {
1625 return true;
1626 }
1627 if !cb.clip_children() {
1629 stack.extend(entry.children.iter().map(|&k| (k, r.origin())));
1630 }
1631 }
1632 false
1633 }
1634}
1635
1636const CULL_MARGIN: f32 = 48.0;
1639
1640fn intersection(a: RectF, b: RectF) -> RectF {
1642 let x = a.x.max(b.x);
1643 let y = a.y.max(b.y);
1644 RectF::new(x, y, (a.right().min(b.right()) - x).max(0.0), (a.bottom().min(b.bottom()) - y).max(0.0))
1645}
1646
1647fn warn_missing_icon(ui: &crate::Ui, name: &str, design: bool) {
1652 if design || !cfg!(debug_assertions) {
1653 return;
1654 }
1655 let Some((pack, _)) = name.split_once(':') else { return };
1658 thread_local! {
1659 static WARNED: std::cell::RefCell<std::collections::HashSet<String>> = Default::default();
1660 }
1661 if WARNED.with(|w| w.borrow().contains(name)) || !ui.has_icon_pack(pack) {
1662 return;
1663 }
1664 if WARNED.with(|w| w.borrow_mut().insert(name.to_string())) {
1665 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)");
1666 }
1667}