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