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) layer_key: Option<u64>,
161}
162
163const SPILL_SLACK: f32 = 0.01;
166
167const RGBA_MARGIN: u32 = 16;
169
170#[derive(Clone, Copy, Debug)]
172pub(crate) struct Backdrop {
173 parent: Option<ComponentId>,
175 version: u64,
177 builds: u32,
179}
180
181const BACKDROP_BUILDS: u32 = 2;
185
186struct Look<'t> {
188 enabled: bool,
189 state: ControlState,
190 inherited: &'t Theme,
192 mixed: &'t Theme,
193 recolored: Option<std::rc::Rc<Theme>>,
194 colors: crate::component::ColorOverride,
195 style: ResolvedStyle,
196 transitioning: bool,
197 paint_fill: bool,
198 font: crate::component::FontOverride,
199 reach: f32,
200}
201
202impl Look<'_> {
203 fn theme(&self) -> &Theme {
205 self.recolored.as_deref().unwrap_or(self.mixed)
206 }
207}
208
209impl Visual {
210 fn update(&mut self, state: ControlState, target: ResolvedStyle, now: f64) -> (ResolvedStyle, bool) {
213 let duration = target.transition_ms as f64 / 1000.0;
214 if self.state.is_some_and(|s| s != state) && duration > 0.0 && self.shown.as_ref().is_some_and(|s| *s != target) {
217 if let Some(shown) = self.shown.take() {
218 self.from = Some(shown);
219 self.start = now;
220 }
221 }
222 self.state = Some(state);
223 let (style, running) = match &self.from {
224 Some(from) if duration > 0.0 => {
225 let t = ((now - self.start) / duration) as f32;
226 if t >= 1.0 {
227 (target, false)
228 } else {
229 (from.lerp(&target, Easing::OutQuad.apply(t)), true)
230 }
231 }
232 _ => (target, false),
233 };
234 if !running {
235 self.from = None;
236 }
237 self.shown = Some(style.clone());
238 (style, running)
239 }
240}
241
242impl Ui {
243 pub fn render_png(&mut self, id: ComponentId, width: f32, height: f32, scale: f32) -> Option<Vec<u8>> {
253 let service = self.services_mut().offscreen.take()?;
254 if let Some(cb) = self.control_mut(id) {
255 cb.set_position(0.0, 0.0).set_size(width, height);
256 }
257 self.layout();
258 for _ in 0..4 {
261 if !self.needs_layout() {
262 break;
263 }
264 self.layout();
265 }
266 let background = self.theme().color("background");
267 let png = service.render_png(width.ceil() as u32, height.ceil() as u32, scale, background, &mut |canvas| self.paint(id, canvas));
268 self.services_mut().offscreen = Some(service);
269 png
270 }
271
272 pub fn snapshot(&self, id: ComponentId, scale: f32) -> Option<crate::Image> {
277 let service = self.services().offscreen.as_ref()?;
278 let cb = self.cb(id)?;
279 let (place, size) = {
280 let b = cb.bounds();
281 let t = cb.translate();
282 (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))
283 };
284 let enabled = self.ancestors_enabled(id);
285 let png = service.render_png(size.0, size.1, scale, crate::Color::TRANSPARENT, &mut |canvas| {
286 canvas.translate(-place.x, -place.y);
288 let mut classes = Vec::new();
289 self.paint_node(id, canvas, enabled, &mut classes, &self.theme, &Default::default(), None);
290 })?;
291 Some(crate::Image::encoded(png))
292 }
293
294 pub fn render_rgba(&mut self, id: ComponentId, rect: RectF, scale: f32) -> Option<(u32, u32, Vec<u8>)> {
308 if !(scale > 0.0 && rect.width > 0.0 && rect.height > 0.0) {
309 return None;
310 }
311 let (w, h) = ((rect.width * scale).ceil() as u32, (rect.height * scale).ceil() as u32);
312 crate::image::checked_size(w, h).ok()?;
313 self.cb(id)?;
314 let (mw, mh) = (w + 2 * RGBA_MARGIN, h + 2 * RGBA_MARGIN);
318 crate::image::checked_size(mw, mh).ok()?;
319 let margin = RGBA_MARGIN as f32 / scale;
320 let service = self.services_mut().offscreen.take()?;
321 self.update_layout();
322 let rgba = if self.parent(id).is_none() {
323 let origin = self.cb(id).map(|cb| cb.bounds().origin()).unwrap_or_default();
324 let area = rect.offset(origin.x, origin.y);
325 let painted = RectF::new(area.x - margin, area.y - margin, area.width + 2.0 * margin, area.height + 2.0 * margin);
326 let background = self.theme().color("background");
327 let pending = self.repaint_requested;
329 let out = service.render_rgba(mw, mh, scale, background, &mut |canvas| {
330 canvas.translate(-painted.x, -painted.y);
331 self.paint_regions_in(id, canvas, &[painted], true);
332 });
333 self.repaint_requested |= pending;
334 out
335 } else {
336 let place = {
337 let cb = self.cb(id)?;
338 let (b, t) = (cb.bounds(), cb.translate());
339 PointF::new(b.x + t.x + rect.x - margin, b.y + t.y + rect.y - margin)
340 };
341 let enabled = self.ancestors_enabled(id);
342 service.render_rgba(mw, mh, scale, crate::Color::TRANSPARENT, &mut |canvas| {
343 canvas.translate(-place.x, -place.y);
344 let mut classes = Vec::new();
345 self.paint_node(id, canvas, enabled, &mut classes, &self.theme, &Default::default(), None);
346 })
347 };
348 self.services_mut().offscreen = Some(service);
349 let rgba = rgba?;
350 let (row, stride, m) = (w as usize * 4, mw as usize * 4, RGBA_MARGIN as usize);
351 let pixels = (0..h as usize).flat_map(|y| {
352 let start = (y + m) * stride + m * 4;
353 rgba[start..start + row].iter().copied()
354 });
355 Some((w, h, pixels.collect()))
356 }
357
358 pub(crate) fn invoke_render_rgba(&mut self, id: ComponentId, args: &[crate::PropValue]) -> std::result::Result<crate::PropValue, String> {
362 let number = |i: usize| args.get(i).and_then(|v| v.to_f64().ok()).map(|v| v as f32);
363 let (Some(x), Some(y), Some(width), Some(height)) = (number(0), number(1), number(2), number(3)) else {
364 return Err("render_rgba pede x, y, width, height e, se quiser, scale".into());
365 };
366 let scale = number(4).unwrap_or(1.0);
367 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")?;
368 Ok(crate::PropValue::String(crate::image::encode_base64(&rgba)))
369 }
370
371 fn ancestors_enabled(&self, id: ComponentId) -> bool {
373 let mut cur = self.parent(id);
374 while let Some(c) = cur {
375 if self.cb(c).is_some_and(|cb| !cb.enabled()) {
376 return false;
377 }
378 cur = self.parent(c);
379 }
380 true
381 }
382
383 pub fn paint(&mut self, root: ComponentId, canvas: &mut dyn Canvas) {
384 self.paint_region(root, canvas, None);
385 }
386
387 pub fn paint_region(&mut self, root: ComponentId, canvas: &mut dyn Canvas, area: Option<RectF>) {
391 match area {
392 Some(a) => self.paint_regions(root, canvas, &[a]),
393 None => self.paint_regions(root, canvas, &[]),
394 }
395 }
396
397 pub fn paint_regions(&mut self, root: ComponentId, canvas: &mut dyn Canvas, areas: &[RectF]) {
402 self.paint_regions_in(root, canvas, areas, areas.is_empty());
403 }
404
405 pub(crate) fn paint_regions_in(&mut self, root: ComponentId, canvas: &mut dyn Canvas, areas: &[RectF], whole: bool) {
408 let area = areas.iter().copied().reduce(|a, b| a.union(b));
409 let _profile = crate::profile::scope(crate::profile::Lane::Paint, || format!("pintura {}", self.path_of(root)));
410 self.update_layout();
411 self.style_animating.set(false);
412 self.wake_at.set(None);
413 let mut classes = Vec::new();
414 self.overlays.borrow_mut().clear();
415 if whole {
416 self.overlay_users.borrow_mut().clear();
417 self.layer_epoch.set(self.layer_epoch.get() + 1);
419 }
420 for key in self.dead_layers.borrow_mut().drain(..) {
423 canvas.forget_cached(key);
424 }
425 {
428 let mut movers = self.movers.borrow_mut();
429 movers.clear();
430 movers.extend(self.placement_movers().filter_map(|m| self.parent(m).map(|p| (p, m))));
431 if !self.backdrops.borrow().is_empty() {
432 self.backdrops.borrow_mut().retain(|&id, b| {
433 let keep = movers.iter().any(|&(p, _)| Some(p) == b.parent);
434 if !keep {
435 let own = self.control(id).is_some_and(|cb| cb.cache_layer()) || self.in_transition(id);
436 if let Some(key) = self.entry(id).filter(|_| !own).and_then(|e| e.visual.borrow_mut().layer_key.take()) {
437 canvas.forget_cached(key);
438 }
439 }
440 keep
441 });
442 }
443 }
444 self.backdrop_next.set(false);
445 let caching = match self.get_prop(root, "layer_cache") {
448 Ok(crate::PropValue::Enum(name)) => <crate::LayerCaching as crate::prop::PropEnum>::from_name(&name).unwrap_or_default(),
449 _ => crate::LayerCaching::Project,
450 };
451 self.auto_layers.set(caching.enabled());
452 let visible: Option<Vec<RectF>> = self.control(root).map(|cb| match area {
454 Some(_) => areas.iter().map(|a| intersection(cb.bounds(), *a)).filter(|r| r.width > 0.0 && r.height > 0.0).collect(),
455 None => vec![cb.bounds()],
456 });
457 let visible = visible.as_deref();
458 self.spilled.set(false);
459 self.paint_area.set(area);
460 self.paint_form.set(self.control(root).map(|cb| cb.bounds()));
461 self.paint_count.set(0);
462 let mut ink = crate::ink::InkCanvas::new(&mut *canvas, &self.ink);
463 if self.text_mode == crate::textcore::TextMode::Native {
465 self.paint_node(root, &mut ink, true, &mut classes, &self.theme, &Default::default(), visible);
466 } else {
467 let mut text = crate::textcore::TextCanvas { inner: &mut ink, mode: self.text_mode };
468 self.paint_node(root, &mut text, true, &mut classes, &self.theme, &Default::default(), visible);
469 }
470 self.flush_paint_failures();
471 let origin = self.absolute_rect(root).map_or(PointF::default(), |r| r.origin());
473 for (at, page) in self.overlays.borrow_mut().drain(..) {
474 canvas.save();
475 canvas.translate(at.x - origin.x, at.y - origin.y);
476 page.replay(canvas);
477 canvas.restore();
478 }
479 if let Some((strip, color)) = self.status_strip(root) {
480 canvas.fill_rect(strip, 0.0, &crate::Brush::Solid(color));
481 }
482 self.paint_drag(root, canvas);
483 self.paint_hint(root, canvas);
484 self.paint_busy(root, canvas);
485 self.frame_requests.borrow_mut().insert(root, (self.style_animating.get(), self.wake_at.get()));
486 crate::profile::sample("controles pintados", self.paint_count.get() as f64);
488 self.repaint_requested = false;
489 if area.is_some() && self.spilled.get() {
492 self.request_repaint();
493 }
494 }
495
496 pub fn last_paint_count(&self) -> usize {
499 self.paint_count.get()
500 }
501
502 pub fn paint_overflow(&mut self, root: ComponentId, canvas: &mut dyn Canvas) {
505 self.update_layout();
506 let Some(cb) = self.cb(root) else { return };
507 let inherited = match cb.theme_name() {
508 "" => &self.theme,
509 name => self.theme_named(name).unwrap_or(&self.theme),
510 };
511 let enabled = cb.enabled();
512 let size = self.form_area(root);
513 let mut classes = Vec::new();
514 let children: Vec<ComponentId> = self.children(root).iter().copied().filter(|&c| self.sticks_out(c, size)).collect();
517 for child in children {
518 self.paint_node(child, canvas, enabled, &mut classes, inherited, &cb.font, None);
519 }
520 }
521
522 pub fn overflows(&self, root: ComponentId) -> bool {
525 let area = self.form_area(root);
526 self.children(root).iter().any(|&c| self.sticks_out(c, area))
527 }
528
529 fn form_area(&self, root: ComponentId) -> RectF {
531 let origin = self.absolute_rect(root).unwrap_or_default();
532 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()))
533 }
534
535 fn sticks_out(&self, id: ComponentId, area: RectF) -> bool {
537 let Some(cb) = self.cb(id) else { return false };
538 if !cb.visible() {
539 return false;
540 }
541 let Some(r) = self.absolute_rect(id) else { return false };
542 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;
544 outside || (!cb.clip_children() && self.children(id).iter().any(|&c| self.sticks_out(c, area)))
545 }
546
547 fn paint_drag(&self, root: ComponentId, canvas: &mut dyn Canvas) {
550 let Some((label, at, target)) = self.drag_view(root) else { return };
551 let origin = self.absolute_rect(root).map_or(PointF::default(), |r| r.origin());
552 let data = self.drag_data(root).unwrap_or_default();
555 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)));
556 if let Some(r) = target.and_then(|t| self.absolute_rect(t)) {
557 let r = RectF::new(r.x - origin.x, r.y - origin.y, r.width, r.height);
558 canvas.stroke_rect(r.inflate(1.0), 6.0, &crate::canvas::Stroke::new(self.theme.color("primary"), 2.0));
559 }
560 let visual = self.drag_visual(root).map(|(v, _)| v);
562 let mut label_at = PointF::new(at.x + 14.0, at.y + 14.0);
563 if let Some(v) = visual {
564 let r = RectF::new(at.x - v.hotspot.x, at.y - v.hotspot.y, v.size.width, v.size.height);
565 if !self.native_drag_image {
566 if let Some(size) = canvas.image_size(&v.image) {
567 canvas.save();
568 canvas.clip_round_rect(r, 6.0);
569 let (src, dest) = crate::ImageFit::Cover.place(size, r);
570 canvas.draw_image(&v.image, src, dest, v.opacity);
571 canvas.restore();
572 }
573 }
574 label_at = PointF::new(r.x, r.bottom() + 4.0);
576 }
577 if label.is_empty() {
578 return;
579 }
580 let style = self.theme.resolve(&["Hint"], "", ControlState::default());
581 let mut ts = crate::canvas::TextStyle { font: style.font.clone(), color: style.text, ..Default::default() };
582 ts.trimming = crate::text::Trimming::Character;
583 let pad = style.padding;
584 let w = canvas.measure_text(&label, &ts).width.min(320.0) + pad.left + pad.right + 1.0;
585 let h = (ts.font.size * 1.4).round() + pad.top + pad.bottom;
586 let rect = RectF::new(label_at.x, label_at.y, w, h);
587 if let Some(shadow) = &style.shadow {
588 canvas.draw_shadow(rect, style.radius, shadow);
589 }
590 canvas.fill_rect(rect, style.radius, &crate::canvas::Brush::Solid(style.fill.with_opacity(0.92)));
591 canvas.draw_text(&label, RectF::new(rect.x + pad.left, rect.y + pad.top, w - pad.left - pad.right, h - pad.top - pad.bottom), &ts);
592 }
593
594 fn paint_hint(&self, root: ComponentId, canvas: &mut dyn Canvas) {
596 let Some((text, at)) = self.visible_hint(root) else { return };
597 let Some(form) = self.control(root).map(|cb| cb.bounds()) else { return };
598 let style = self.theme.resolve(&["Hint"], "", ControlState::default());
599 let mut ts = crate::canvas::TextStyle { font: style.font.clone(), color: style.text, ..Default::default() };
600 ts.v_align = crate::canvas::TextAlign::Leading;
601 let max = 280.0f32.min(form.width - 16.0).max(40.0);
602 let mut measure = |s: &str| canvas.measure_text(s, &ts).width;
603 let lines = crate::text::layout_lines(&text, max, 12, true, crate::text::Trimming::Word, &mut measure);
604 let width = lines.iter().map(|l| measure(l)).fold(0.0f32, f32::max);
605 let lh = (ts.font.size * 1.4).round();
606 let pad = style.padding;
607 let w = width + pad.left + pad.right + 1.0;
608 let h = lines.len() as f32 * lh + pad.top + pad.bottom;
609 let mut x = at.x + 4.0;
610 let mut y = at.y + 22.0;
611 if x + w > form.width - 4.0 {
612 x = (form.width - 4.0 - w).max(4.0);
613 }
614 if y + h > form.height - 4.0 {
615 y = (at.y - h - 8.0).max(4.0);
616 }
617 let rect = RectF::new(x, y, w, h);
618 if let Some(shadow) = &style.shadow {
619 canvas.draw_shadow(rect, style.radius, shadow);
620 }
621 canvas.fill_rect(rect, style.radius, &crate::canvas::Brush::Solid(style.fill));
622 if style.border_width > 0.0 && !style.border_color.is_transparent() {
624 canvas.stroke_rect(rect, style.radius, &style.border_stroke(style.border_color, style.border_width));
625 }
626 let mut ly = y + pad.top;
627 for line in &lines {
628 canvas.draw_text(line, RectF::new(x + pad.left, ly, width + 1.0, lh), &ts);
629 ly += lh;
630 }
631 }
632
633 #[allow(clippy::too_many_arguments)]
637 fn look<'t>(
638 &'t self,
639 id: ComponentId,
640 component: &dyn crate::Component,
641 cb: &crate::ControlBase,
642 visual: &std::cell::RefCell<Visual>,
643 parent_enabled: bool,
644 classes: &mut Vec<&'static str>,
645 inherited: &'t Theme,
646 parent_font: &crate::component::FontOverride,
647 peek: bool,
648 ) -> Look<'t> {
649 let enabled = parent_enabled && cb.enabled();
650 let mut state = cb.state();
651 state.disabled = !enabled;
652 if let Some(checked) = component.checked_state() {
653 state.checked = checked;
654 }
655 if self.still_picture {
656 state.hover = false;
657 state.pressed = false;
658 state.focused = false;
659 }
660 if cb.inherit_state() {
662 let mut up = self.parent(id);
663 while let Some(p) = up {
664 let Some(pcb) = self.cb(p) else { break };
665 if !pcb.inherit_state() {
666 let ps = pcb.state();
667 state.hover |= ps.hover;
668 state.pressed |= ps.pressed;
669 state.checked |= self.component(p).and_then(|c| c.checked_state()).unwrap_or(ps.checked);
670 break;
671 }
672 up = self.parent(p);
673 }
674 }
675 if state.focused && !component.accepts_text() && self.focus_from_pointer(self.root_of(id)) {
678 state.focused = false;
679 }
680
681 classes.clear();
682 component.class_chain(classes);
683 let inherited = match cb.theme_name() {
685 "" => inherited,
686 name => self.theme_named(name).unwrap_or(inherited),
687 };
688 let mixed = self.mixed_theme(inherited, classes);
689 let colors = cb.colors;
692 let recolored = colors.recolors_theme().then(|| {
693 let key = (mixed.name.clone(), colors);
694 self.recolored.borrow_mut().entry(key).or_insert_with(|| std::rc::Rc::new(colors.apply_theme(mixed))).clone()
695 });
696 let (target, reach) = {
697 let theme: &Theme = recolored.as_deref().unwrap_or(mixed);
698 (theme.resolve(classes, cb.style(), state), theme.reach(classes, cb.style()).max(cb.shadow().map_or(0.0, |s| s.reach())))
699 };
700 let (mut style, transitioning) = if self.design_mode {
702 (target, false)
703 } else if peek {
704 visual.borrow().clone().update(state, target, self.time)
705 } else {
706 visual.borrow_mut().update(state, target, self.time)
707 };
708 let font = if cb.font.is_empty() { parent_font.clone() } else { cb.font.over(parent_font) };
710 if !font.is_empty() {
711 font.apply(&mut style.font);
712 }
713 if cb.text_scale() != 1.0 {
715 style.font.size *= cb.text_scale();
716 }
717 if !self.font_names().is_empty() {
719 style.font.family = self.resolve_font(&style.font.family);
720 }
721 let paint_fill = colors.fill.is_some() && component.transparent_background();
724 if let Some(fill) = colors.fill {
725 let toward = if crate::component::luminance(fill) < 0.5 { crate::Color::WHITE } else { crate::Color::BLACK };
728 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 };
729 style.fill = fill.lerp(toward.with_opacity(fill.a as f32 / 255.0), amount);
730 }
731 if let Some(border) = colors.border {
732 style.border_color = border;
733 style.border_width = style.border_width.max(1.0);
734 }
735 if let Some(text) = colors.text {
736 style.text = text;
737 }
738 Look { enabled, state, inherited, mixed, recolored, colors, style, transitioning, paint_fill, font, reach }
739 }
740
741 pub(crate) fn drawing_unchanged(&self, id: ComponentId) -> bool {
746 let Some(entry) = self.entry(id) else { return false };
747 let Some(component) = entry.component.as_deref() else { return false };
748 let Some(cb) = component.control() else { return false };
749 let Some(before) = entry.visual.borrow().drawing else { return false };
750 if !component.paint_is_pure() || entry.paint_hook.is_some() || self.paint_failed(id) || self.flips_content(id) || cb.rotation() != 0.0 {
751 return false;
752 }
753 let mut chain = Vec::new();
755 let mut current = self.parent(id);
756 while let Some(p) = current {
757 chain.push(p);
758 current = self.parent(p);
759 }
760 let (mut enabled, mut inherited, mut font) = (true, &*self.theme, crate::component::FontOverride::default());
761 for &a in chain.iter().rev() {
762 let Some(acb) = self.control(a) else { continue };
763 enabled &= acb.enabled();
764 if !acb.theme_name().is_empty() {
765 inherited = self.theme_named(acb.theme_name()).unwrap_or(inherited);
766 }
767 if !acb.font.is_empty() {
768 font = acb.font.over(&font);
769 }
770 }
771 let mut classes = Vec::new();
772 let look = self.look(id, component, cb, &entry.visual, enabled, &mut classes, inherited, &font, true);
773 if look.transitioning {
775 return false;
776 }
777 let (requested, wake) = (Cell::new(false), Cell::new(None));
778 let ctx = PaintCtx {
779 ui: self,
780 id,
781 rect: RectF::from_size(cb.bounds().size()),
782 state: look.state,
783 style: &look.style,
784 theme: look.theme(),
785 time: self.time,
786 design: self.design_mode,
787 colors: look.colors,
788 frame_request: &requested,
789 wake_at: &wake,
790 resources: self.services().resources.as_deref(),
791 };
792 let ghost = if self.design_mode && cb.design_hidden { 0.35 } else { 1.0 };
793 let opacity = cb.opacity() * look.style.opacity * ghost;
794 if opacity <= 0.0 {
795 return false;
796 }
797 let mut hasher = std::hash::DefaultHasher::new();
798 std::hash::Hash::hash(&opacity.to_bits(), &mut hasher);
799 std::hash::Hash::hash(&cb.blend_mode(), &mut hasher);
800 let text = self.services().text.as_deref();
801 let mut trace = crate::trace::TraceCanvas::new(None, text, &mut hasher);
802 let painted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
803 self.paint_own(&mut trace, component, &ctx, look.paint_fill, cb.shadow().as_ref());
804 component.paint_after(&mut trace, &ctx);
805 }));
806 let volatile = trace.volatile;
807 painted.is_ok() && !volatile && !requested.get() && std::hash::Hasher::finish(&hasher) == before
808 }
809
810 fn paint_own(&self, canvas: &mut dyn Canvas, component: &dyn crate::Component, ctx: &PaintCtx<'_>, paint_fill: bool, shadow: Option<&crate::Shadow>) {
813 let style = ctx.style;
814 let shape = component.clip_shape();
816 let radius = shape.as_ref().map_or(style.radius, |s| s.radius(ctx.rect));
817 if let Some(shadow) = shadow.or(style.shadow.as_ref()) {
818 canvas.draw_shadow(ctx.rect, radius, shadow);
819 }
820 if let Some(fill) = ctx.colors.fill.filter(|_| paint_fill) {
821 match shape {
822 Some(s) => s.fill(canvas, ctx.rect, &crate::Brush::Solid(fill)),
823 None => canvas.fill_rect(ctx.rect, radius, &crate::Brush::Solid(fill)),
824 }
825 }
826 if style.material != crate::theme::Material::None {
828 canvas.backdrop_blur(ctx.rect, radius, style.material.blur());
829 }
830 component.paint(canvas, ctx);
831 if style.material == crate::theme::Material::Glass {
832 paint_glass_light(canvas, ctx.rect, radius, ctx.theme.dark);
833 }
834 }
835
836 fn paint_reveal(&self, canvas: &mut dyn Canvas, ctx: &PaintCtx<'_>, shape: Option<crate::ClipShape>) {
841 let reveal = ctx.style.reveal;
842 let id = ctx.id;
843 if !reveal.on() {
844 if !self.reveal_ids.borrow().is_empty() {
845 self.reveal_ids.borrow_mut().remove(&id);
846 }
847 return;
848 }
849 self.reveal_ids.borrow_mut().insert(id, reveal.radius);
850 let Some(at) = self.pointer_position(self.root_of(id)) else { return };
851 let p = self.local_point(id, at);
852 let rect = ctx.rect;
853 let dx = (rect.x - p.x).max(p.x - rect.right()).max(0.0);
854 let dy = (rect.y - p.y).max(p.y - rect.bottom()).max(0.0);
855 if dx.hypot(dy) >= reveal.radius {
856 return;
857 }
858 let light = |color: crate::Color| crate::Brush::Radial {
859 center: p,
860 radius: reveal.radius,
861 stops: vec![crate::canvas::GradientStop::new(0.0, color), crate::canvas::GradientStop::new(1.0, color.with_opacity(0.0))],
862 };
863 let radius = shape.as_ref().map_or(ctx.style.radius, |s| s.radius(rect));
864 if reveal.background && rect.contains(p) {
865 let brush = light(reveal.color.with_opacity(0.55));
866 match &shape {
867 Some(s) => s.fill(canvas, rect, &brush),
868 None => canvas.fill_rect(rect, radius, &brush),
869 }
870 }
871 if reveal.border {
872 let width = ctx.style.border_width.max(1.0);
873 let half = width / 2.0;
874 let inner = crate::RectF::new(rect.x + half, rect.y + half, (rect.width - width).max(0.0), (rect.height - width).max(0.0));
875 let stroke = crate::canvas::Stroke::new(light(reveal.color), width);
876 match &shape {
877 Some(s) => canvas.stroke_path(&s.outline(inner), &stroke),
878 None => canvas.stroke_rect(inner, (radius - half).max(0.0), &stroke),
879 }
880 }
881 }
882
883 #[allow(clippy::too_many_arguments)]
886 fn paint_own_with_hook(
887 &self,
888 canvas: &mut dyn Canvas,
889 id: ComponentId,
890 entry: &crate::ui::Entry,
891 component: &dyn crate::Component,
892 ctx: &PaintCtx<'_>,
893 paint_fill: bool,
894 shadow: Option<&crate::Shadow>,
895 flip: bool,
896 ) {
897 let style = ctx.style;
898 let shape = component.clip_shape();
900 let radius = shape.as_ref().map_or(style.radius, |s| s.radius(ctx.rect));
901 if let Some(shadow) = shadow.or(style.shadow.as_ref()) {
902 canvas.draw_shadow(ctx.rect, radius, shadow);
903 }
904 if let Some(fill) = ctx.colors.fill.filter(|_| paint_fill) {
905 match shape {
906 Some(s) => s.fill(canvas, ctx.rect, &crate::Brush::Solid(fill)),
907 None => canvas.fill_rect(ctx.rect, radius, &crate::Brush::Solid(fill)),
908 }
909 }
910 if style.material != crate::theme::Material::None {
912 canvas.backdrop_blur(ctx.rect, radius, style.material.blur());
913 }
914 if flip {
915 canvas.save();
916 canvas.translate(ctx.rect.width, 0.0);
917 }
918 {
919 let mut mirror;
920 let target: &mut dyn Canvas = if flip {
921 mirror = Mirror { inner: &mut *canvas };
922 &mut mirror
923 } else {
924 &mut *canvas
925 };
926 if self.paint_failed(id) {
929 paint_failure(target, ctx.rect);
930 } else {
931 let painted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match &entry.paint_hook {
932 Some(hook) => hook(target, ctx, &|c: &mut dyn Canvas, x: &PaintCtx<'_>| component.paint(c, x)),
933 None => component.paint(target, ctx),
934 }));
935 if let Err(payload) = painted {
936 self.note_paint_failure(id, payload.as_ref());
937 }
938 }
939 }
940 if flip {
941 canvas.restore();
942 }
943 if style.material == crate::theme::Material::Glass {
944 paint_glass_light(canvas, ctx.rect, radius, ctx.theme.dark);
945 }
946 }
947
948 fn paint_node(
949 &self,
950 id: ComponentId,
951 canvas: &mut dyn Canvas,
952 parent_enabled: bool,
953 classes: &mut Vec<&'static str>,
954 inherited: &Theme,
955 parent_font: &crate::component::FontOverride,
956 visible: Option<&[RectF]>,
957 ) {
958 let behind_mover = self.backdrop_next.replace(false);
961 let Some(entry) = self.entry(id) else { return };
962 let Some(component) = entry.component.as_deref() else { return };
963 let Some(cb) = component.control() else { return };
964 if !cb.visible() || (cb.design_only && !self.design_mode) {
965 return;
966 }
967 let place = {
972 let b = cb.bounds();
973 let t = cb.translate();
974 RectF::new(b.x + t.x, b.y + t.y, b.width, b.height)
975 };
976 let contained = cb.clip_children() || entry.children.is_empty();
977 if contained && cb.rotation() == 0.0 && visible.is_some_and(|v| !v.iter().any(|r| place.inflate(CULL_MARGIN).intersects(*r))) {
978 let ink = entry.visual.borrow().ink;
981 let reaches = 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)));
982 if !reaches {
983 return;
984 }
985 }
986 self.paint_count.set(self.paint_count.get() + 1);
987 let look = self.look(id, component, cb, &entry.visual, parent_enabled, classes, inherited, parent_font, false);
988 entry.visual.borrow_mut().reach = Some(look.reach);
989 let (enabled, state, inherited, colors, paint_fill) = (look.enabled, look.state, look.inherited, look.colors, look.paint_fill);
990 let (theme, style, font) = (look.theme(), &look.style, &look.font);
991 if look.transitioning {
992 self.style_animating.set(true);
993 self.frame_ids.borrow_mut().push(id);
994 }
995 let ghost = if self.design_mode && cb.design_hidden { 0.35 } else { 1.0 };
997 let opacity = cb.opacity() * style.opacity * ghost;
998 if opacity <= 0.0 {
999 entry.visual.borrow_mut().drawing = None;
1000 return;
1001 }
1002 let outer_ink = self.ink.borrow_mut().take();
1005 let bounds = cb.bounds();
1006 {
1009 let mut timed = self.timed_frames.borrow_mut();
1010 if !timed.is_empty() {
1011 timed.remove(&id);
1012 }
1013 }
1014 let scale = cb.scale();
1017 let ctx = PaintCtx {
1018 ui: self,
1019 id,
1020 rect: RectF::from_size(cb.inner_size()),
1021 state,
1022 style: &style,
1023 theme,
1024 time: self.time,
1025 design: self.design_mode,
1026 colors,
1027 frame_request: &self.style_animating,
1028 wake_at: &self.wake_at,
1029 resources: self.services().resources.as_deref(),
1030 };
1031
1032 let flip = self.flips_content(id);
1034 let automatic = self.auto_layers.get()
1044 && !entry.children.is_empty()
1045 && ((cb.clip_children() && (self.animates_placement(id) || (behind_mover && self.backdrop_worth(id, entry.visual.borrow().version)))) || self.in_transition(id));
1046 let blend = cb.blend_mode();
1048 let pulled = self.overscroll_pull(id).and_then(|p| self.overscroll_of(id).map(|s| (p, s)));
1051 let shifts = pulled.is_some_and(|(_, s)| matches!(s, crate::Overscroll::Stretch | crate::Overscroll::Bounce));
1052 let cached = !flip && !shifts && blend == crate::BlendMode::Normal && (cb.cache_layer() || automatic);
1053
1054 canvas.save();
1055 let shift = cb.translate();
1056 let drawn = if cached && shift != PointF::ZERO {
1060 let s = canvas.device_scale().max(f32::EPSILON);
1061 PointF::new((shift.x * s).round() / s, (shift.y * s).round() / s)
1062 } else {
1063 shift
1064 };
1065 canvas.translate(bounds.x + drawn.x, bounds.y + drawn.y);
1066 let rotation = cb.rotation();
1067 if rotation != 0.0 {
1068 canvas.translate(bounds.width / 2.0, bounds.height / 2.0);
1069 canvas.rotate(rotation);
1070 canvas.translate(-bounds.width / 2.0, -bounds.height / 2.0);
1071 }
1072 if scale != 1.0 {
1073 canvas.scale(scale, scale);
1074 }
1075 if let Some((p, style)) = pulled.filter(|_| shifts) {
1076 canvas.save();
1077 canvas.clip_rect(ctx.rect);
1078 overscroll_shift(canvas, ctx.rect, p, style);
1079 }
1080 let layer = opacity < 1.0 || blend != crate::BlendMode::Normal;
1081 if blend != crate::BlendMode::Normal {
1082 canvas.save_layer_blend(opacity, blend, ctx.rect.inflate(look.reach + 1.0));
1083 } else if layer {
1084 canvas.save_layer(opacity);
1085 }
1086
1087 let traced = component.paint_is_pure() && entry.paint_hook.is_none() && !flip && rotation == 0.0 && !self.paint_failed(id);
1090 let mut hasher = std::hash::DefaultHasher::new();
1091 std::hash::Hash::hash(&opacity.to_bits(), &mut hasher);
1092 std::hash::Hash::hash(&blend, &mut hasher);
1093 let mut volatile = false;
1094 let layer_key = cached.then(|| {
1095 let mut key = std::hash::DefaultHasher::new();
1096 let version = entry.visual.borrow().version;
1097 std::hash::Hash::hash(&(id, version, self.layer_epoch.get(), self.design_mode), &mut key);
1098 std::hash::Hasher::finish(&key)
1099 });
1100 let old_key = std::mem::replace(&mut entry.visual.borrow_mut().layer_key, layer_key);
1103 if let Some(old) = old_key.filter(|old| Some(*old) != layer_key) {
1104 canvas.forget_cached(old);
1105 }
1106 let cache_hit = layer_key.is_some_and(|key| canvas.begin_cached(key, ctx.rect.inflate(look.reach + 1.0)));
1107 if !cache_hit {
1108 if traced {
1109 let mut trace = crate::trace::TraceCanvas::new(Some(&mut *canvas), None, &mut hasher);
1110 let painted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.paint_own(&mut trace, component, &ctx, paint_fill, cb.shadow().as_ref())));
1111 volatile |= trace.volatile;
1112 if let Err(payload) = painted {
1113 self.note_paint_failure(id, payload.as_ref());
1114 }
1115 } else {
1116 self.paint_own_with_hook(canvas, id, entry, component, &ctx, paint_fill, cb.shadow().as_ref(), flip);
1117 }
1118 self.paint_reveal(canvas, &ctx, component.clip_shape());
1119
1120 let scrolled_form = cb.scroll_offset().y > 0.0 && self.parent(id).is_none();
1122 let shape = component.clip_shape();
1124 let clip = cb.clip_children() || scrolled_form || shape.is_some();
1125 if clip {
1126 canvas.save();
1127 let r = if scrolled_form {
1128 let s = cb.safe_area;
1129 crate::RectF::new(ctx.rect.x, ctx.rect.y + s.top, ctx.rect.width, (ctx.rect.height - s.top - s.bottom).max(0.0))
1130 } else {
1131 ctx.rect
1132 };
1133 canvas.clip_rect(r);
1134 if let Some(s) = shape {
1135 s.clip(canvas, ctx.rect);
1136 }
1137 }
1138 let inner: Option<Vec<RectF>> = match visible.filter(|_| rotation == 0.0 && !cached) {
1142 Some(v) => Some(
1143 v.iter()
1144 .map(|r| r.offset(-place.x, -place.y))
1145 .map(|r| if scale == 1.0 { r } else { RectF::new(r.x / scale, r.y / scale, r.width / scale, r.height / scale) })
1147 .map(|local| if clip { intersection(local, ctx.rect) } else { local })
1148 .filter(|r| r.width > 0.0 && r.height > 0.0)
1149 .collect(),
1150 ),
1151 None if clip && rotation == 0.0 => Some(vec![ctx.rect]),
1152 None => None,
1153 };
1154 let hidden = self.covered_children(&entry.children, inner.as_deref());
1155 let mover_at = if self.auto_layers.get() {
1157 self.movers.borrow().iter().filter(|&&(p, _)| p == id).filter_map(|&(_, m)| entry.children.iter().position(|&c| c == m)).max()
1158 } else {
1159 None
1160 };
1161 for (k, &child) in entry.children.iter().enumerate() {
1162 if hidden.get(k).copied().unwrap_or(false) {
1163 continue;
1164 }
1165 self.backdrop_next.set(mover_at.is_some_and(|m| k < m));
1166 self.paint_node(child, canvas, enabled, classes, inherited, &font, inner.as_deref());
1167 }
1168 if clip {
1169 canvas.restore();
1170 }
1171 if self.paint_failed(id) {
1172 } else if flip {
1174 canvas.save();
1175 canvas.translate(ctx.rect.width, 0.0);
1176 let after = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| component.paint_after(&mut Mirror { inner: &mut *canvas }, &ctx)));
1177 canvas.restore();
1178 if let Err(payload) = after {
1179 self.note_paint_failure(id, payload.as_ref());
1180 }
1181 } else if traced {
1182 let mut trace = crate::trace::TraceCanvas::new(Some(&mut *canvas), None, &mut hasher);
1183 let after = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| component.paint_after(&mut trace, &ctx)));
1184 volatile |= trace.volatile;
1185 if let Err(payload) = after {
1186 self.note_paint_failure(id, payload.as_ref());
1187 }
1188 } else if let Err(payload) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| component.paint_after(canvas, &ctx))) {
1189 self.note_paint_failure(id, payload.as_ref());
1190 }
1191 if cached {
1192 canvas.end_cached();
1193 }
1194 }
1195
1196 if layer {
1197 canvas.restore();
1198 }
1199 if shifts {
1200 canvas.restore();
1201 }
1202 if let Some((p, crate::Overscroll::Glow)) = pulled {
1203 overscroll_glow(canvas, ctx.rect, p, self.theme.color("primary"));
1204 }
1205 canvas.restore();
1206 let ink = std::mem::replace(&mut *self.ink.borrow_mut(), outer_ink);
1207 let mut visual = entry.visual.borrow_mut();
1208 if let (Some(new), Some(area)) = (ink, self.paint_area.get()) {
1209 let seen = self.paint_form.get().map_or(new, |form| intersection(new, form));
1215 let outside = seen.width > 0.0 && seen.height > 0.0 && !area.inflate(SPILL_SLACK).contains_rect(seen);
1216 if outside && !visual.ink.is_some_and(|old| old.inflate(SPILL_SLACK).contains_rect(seen)) {
1217 self.spilled.set(true);
1218 }
1219 }
1220 visual.ink = ink;
1221 visual.shift = shift;
1222 visual.drawing = (traced && !cache_hit && !volatile && !self.paint_failed(id)).then(|| std::hash::Hasher::finish(&hasher));
1223 let whole = opacity >= 1.0 && rotation == 0.0 && !flip && !self.paint_failed(id) && component.clip_shape().is_none();
1226 drop(visual);
1227 let own = component.opaque(&style) || paint_fill && colors.fill.is_some_and(|f| f.a == 255) && style.radius <= 0.0;
1228 let by_child = || {
1229 entry.children.iter().any(|&c| {
1230 self.entry(c).is_some_and(|e| {
1231 e.visual.borrow().covers
1232 && e.component.as_deref().and_then(|c| c.control()).is_some_and(|ccb| ccb.visible() && place_of(ccb).contains_rect(ctx.rect))
1233 })
1234 })
1235 };
1236 let covers = whole && (own || by_child());
1237 let was = std::mem::replace(&mut entry.visual.borrow_mut().covers, covers);
1238 if was && !covers {
1239 self.style_animating.set(true);
1242 self.frame_ids.borrow_mut().push(id);
1243 }
1244 }
1245
1246 fn backdrop_worth(&self, id: ComponentId, version: u64) -> bool {
1250 let parent = self.parent(id);
1251 let mut backdrops = self.backdrops.borrow_mut();
1252 let b = backdrops.entry(id).or_insert(Backdrop { parent, version, builds: 1 });
1253 if b.version != version {
1254 b.version = version;
1255 b.builds += 1;
1256 }
1257 b.builds <= BACKDROP_BUILDS
1258 }
1259
1260 fn covered_children(&self, children: &[ComponentId], inner: Option<&[RectF]>) -> Vec<bool> {
1265 let mut hidden = Vec::new();
1266 let mut covers: Vec<RectF> = Vec::new();
1269 for (k, &child) in children.iter().enumerate().rev() {
1270 let Some(entry) = self.entry(child) else { continue };
1271 let Some(cb) = entry.component.as_deref().and_then(|c| c.control()) else { continue };
1272 if !cb.visible() {
1273 continue;
1274 }
1275 let place = place_of(cb);
1276 if !covers.is_empty() {
1277 let reach = entry.visual.borrow().reach.unwrap_or(CULL_MARGIN);
1278 let own = place.inflate(reach);
1279 let contained = !entry.children.is_empty() && !cb.clip_children();
1280 let gone = covers.iter().any(|c| {
1281 c.contains_rect(own) && (!contained || inner.is_some_and(|areas| !areas.is_empty() && areas.iter().all(|a| c.contains_rect(*a))))
1282 });
1283 if gone {
1284 if hidden.is_empty() {
1285 hidden = vec![false; children.len()];
1286 }
1287 hidden[k] = true;
1288 continue;
1289 }
1290 }
1291 if entry.visual.borrow().covers {
1292 covers.push(place);
1293 if covers.len() > 4 {
1294 covers.sort_by(|a, b| (b.width * b.height).total_cmp(&(a.width * a.height)));
1295 covers.truncate(4);
1296 }
1297 }
1298 }
1299 hidden
1300 }
1301}
1302
1303fn overscroll_shift(canvas: &mut dyn Canvas, rect: RectF, p: PointF, style: crate::Overscroll) {
1307 if style == crate::Overscroll::Bounce {
1308 canvas.translate(p.x, p.y);
1309 return;
1310 }
1311 let sx = 1.0 + p.x.abs() / rect.width.max(1.0);
1312 let sy = 1.0 + p.y.abs() / rect.height.max(1.0);
1313 let ax = if p.x > 0.0 { rect.x } else { rect.right() };
1315 let ay = if p.y > 0.0 { rect.y } else { rect.bottom() };
1316 canvas.translate(ax, ay);
1317 canvas.scale(sx, sy);
1318 canvas.translate(-ax, -ay);
1319}
1320
1321fn overscroll_glow(canvas: &mut dyn Canvas, rect: RectF, p: PointF, color: crate::Color) {
1323 canvas.save();
1324 canvas.clip_rect(rect);
1325 let tint = |k: f32| crate::Color::rgba(color.r, color.g, color.b, (40.0 + 90.0 * k).min(255.0) as u8);
1326 if p.y != 0.0 {
1327 let k = (p.y.abs() / (rect.height * 0.2).max(1.0)).min(1.0);
1328 let depth = (rect.width * 0.25).min(rect.height * 0.5) * (0.3 + 0.7 * k);
1329 let y = if p.y > 0.0 { rect.y - depth } else { rect.bottom() - depth };
1330 canvas.fill_ellipse(RectF::new(rect.x - rect.width * 0.25, y, rect.width * 1.5, depth * 2.0), &crate::Brush::Solid(tint(k)));
1331 }
1332 if p.x != 0.0 {
1333 let k = (p.x.abs() / (rect.width * 0.2).max(1.0)).min(1.0);
1334 let depth = (rect.height * 0.25).min(rect.width * 0.5) * (0.3 + 0.7 * k);
1335 let x = if p.x > 0.0 { rect.x - depth } else { rect.right() - depth };
1336 canvas.fill_ellipse(RectF::new(x, rect.y - rect.height * 0.25, depth * 2.0, rect.height * 1.5), &crate::Brush::Solid(tint(k)));
1337 }
1338 canvas.restore();
1339}
1340
1341fn place_of(cb: &crate::component::ControlBase) -> RectF {
1342 let b = cb.bounds();
1343 let t = cb.translate();
1344 RectF::new(b.x + t.x, b.y + t.y, b.width, b.height)
1345}
1346
1347fn paint_failure(canvas: &mut dyn Canvas, rect: RectF) {
1351 let red = crate::color::Color::rgb(220, 38, 38);
1352 canvas.fill_rect(rect, 0.0, &crate::canvas::Brush::Solid(red.with_opacity(0.12)));
1353 let stroke = crate::canvas::Stroke::new(red, 2.0);
1354 canvas.stroke_rect(rect.inflate(-1.0), 0.0, &stroke);
1355 canvas.draw_line(rect.origin(), PointF::new(rect.right(), rect.bottom()), &stroke);
1356 canvas.draw_line(PointF::new(rect.right(), rect.y), PointF::new(rect.x, rect.bottom()), &stroke);
1357}
1358
1359pub fn paint_glass_light(canvas: &mut dyn Canvas, rect: crate::RectF, radius: f32, dark: bool) {
1360 use crate::canvas::{Brush, GradientStop, Stroke};
1361 use crate::{Color, PointF};
1362 if rect.width <= 2.0 || rect.height <= 2.0 {
1363 return;
1364 }
1365 let shine = if dark { 0.16 } else { 0.42 };
1366 canvas.fill_rect(
1367 rect,
1368 radius,
1369 &Brush::Linear {
1370 start: PointF::new(0.0, rect.y),
1371 end: PointF::new(0.0, rect.y + rect.height * 0.6),
1372 stops: vec![GradientStop::new(0.0, Color::WHITE.with_opacity(shine)), GradientStop::new(1.0, Color::WHITE.with_opacity(0.0))],
1373 },
1374 );
1375 let edge = Brush::Linear {
1376 start: PointF::new(rect.x, rect.y),
1377 end: PointF::new(rect.x + rect.width * 0.35, rect.bottom()),
1378 stops: vec![
1379 GradientStop::new(0.0, Color::WHITE.with_opacity(if dark { 0.45 } else { 0.95 })),
1380 GradientStop::new(0.55, Color::WHITE.with_opacity(if dark { 0.10 } else { 0.35 })),
1381 GradientStop::new(1.0, if dark { Color::WHITE.with_opacity(0.18) } else { Color::BLACK.with_opacity(0.10) }),
1382 ],
1383 };
1384 let r = (radius - 0.5).max(0.0);
1385 canvas.stroke_rect(rect.inflate(-0.5), r, &Stroke::new(edge, 1.0));
1386}
1387
1388pub(crate) struct Mirror<'a> {
1392 pub(crate) inner: &'a mut dyn Canvas,
1393}
1394
1395impl Mirror<'_> {
1396 fn x(x: f32) -> f32 {
1397 -x
1398 }
1399
1400 fn point(p: crate::PointF) -> crate::PointF {
1401 crate::PointF::new(-p.x, p.y)
1402 }
1403
1404 fn rect(r: crate::RectF) -> crate::RectF {
1405 crate::RectF::new(-r.right(), r.y, r.width, r.height)
1406 }
1407
1408 fn path(p: &crate::Path) -> crate::Path {
1409 p.map_points(Self::point)
1410 }
1411
1412 fn brush(b: &crate::Brush) -> crate::Brush {
1413 use crate::Brush;
1414 match b {
1415 Brush::Solid(c) => Brush::Solid(*c),
1416 Brush::Linear { start, end, stops } => Brush::Linear { start: Self::point(*start), end: Self::point(*end), stops: stops.clone() },
1417 Brush::Radial { center, radius, stops } => Brush::Radial { center: Self::point(*center), radius: *radius, stops: stops.clone() },
1418 Brush::Sweep { center, start_angle, stops } => Brush::Sweep {
1420 center: Self::point(*center),
1421 start_angle: 180.0 - start_angle,
1422 stops: stops.iter().rev().map(|s| crate::GradientStop::new(1.0 - s.offset, s.color)).collect(),
1423 },
1424 }
1425 }
1426
1427 fn stroke(s: &crate::Stroke) -> crate::Stroke {
1428 crate::Stroke { brush: Self::brush(&s.brush), ..s.clone() }
1429 }
1430}
1431
1432impl Canvas for Mirror<'_> {
1433 fn save(&mut self) {
1434 self.inner.save();
1435 }
1436 fn restore(&mut self) {
1437 self.inner.restore();
1438 }
1439 fn translate(&mut self, dx: f32, dy: f32) {
1440 self.inner.translate(Self::x(dx), dy);
1441 }
1442 fn scale(&mut self, sx: f32, sy: f32) {
1443 self.inner.scale(sx, sy);
1444 }
1445 fn rotate(&mut self, degrees: f32) {
1446 self.inner.rotate(-degrees);
1447 }
1448 fn clip_rect(&mut self, rect: crate::RectF) {
1449 self.inner.clip_rect(Self::rect(rect));
1450 }
1451 fn save_layer(&mut self, opacity: f32) {
1452 self.inner.save_layer(opacity);
1453 }
1454 fn save_layer_blend(&mut self, opacity: f32, mode: crate::BlendMode, bounds: crate::RectF) {
1455 self.inner.save_layer_blend(opacity, mode, Self::rect(bounds));
1456 }
1457 fn fill_rect(&mut self, rect: crate::RectF, radius: f32, brush: &crate::Brush) {
1458 self.inner.fill_rect(Self::rect(rect), radius, &Self::brush(brush));
1459 }
1460 fn stroke_rect(&mut self, rect: crate::RectF, radius: f32, stroke: &crate::Stroke) {
1461 self.inner.stroke_rect(Self::rect(rect), radius, &Self::stroke(stroke));
1462 }
1463 fn fill_ellipse(&mut self, rect: crate::RectF, brush: &crate::Brush) {
1464 self.inner.fill_ellipse(Self::rect(rect), &Self::brush(brush));
1465 }
1466 fn stroke_ellipse(&mut self, rect: crate::RectF, stroke: &crate::Stroke) {
1467 self.inner.stroke_ellipse(Self::rect(rect), &Self::stroke(stroke));
1468 }
1469 fn draw_line(&mut self, from: crate::PointF, to: crate::PointF, stroke: &crate::Stroke) {
1470 self.inner.draw_line(Self::point(from), Self::point(to), &Self::stroke(stroke));
1471 }
1472 fn draw_text(&mut self, text: &str, rect: crate::RectF, style: &TextStyle) {
1473 use crate::TextAlign;
1474 let mut style = style.clone();
1475 style.h_align = match style.h_align {
1476 TextAlign::Leading => TextAlign::Trailing,
1477 TextAlign::Trailing => TextAlign::Leading,
1478 other => other,
1479 };
1480 self.inner.draw_text(text, Self::rect(rect), &style);
1481 }
1482 fn measure_text(&mut self, text: &str, style: &TextStyle) -> crate::SizeF {
1483 self.inner.measure_text(text, style)
1484 }
1485 fn draw_image(&mut self, image: &crate::Image, src: crate::RectF, dest: crate::RectF, opacity: f32) {
1486 self.inner.draw_image(image, src, Self::rect(dest), opacity);
1487 }
1488 fn image_size(&mut self, image: &crate::Image) -> Option<crate::SizeF> {
1489 self.inner.image_size(image)
1490 }
1491 fn clip_round_rect(&mut self, rect: crate::RectF, radius: f32) {
1492 self.inner.clip_round_rect(Self::rect(rect), radius);
1493 }
1494 fn fill_path(&mut self, path: &crate::Path, brush: &crate::Brush) {
1495 self.inner.fill_path(&Self::path(path), &Self::brush(brush));
1496 }
1497 fn clip_path(&mut self, path: &crate::Path, inverse: bool) {
1498 self.inner.clip_path(&Self::path(path), inverse);
1499 }
1500 fn backdrop_blur(&mut self, rect: crate::RectF, radius: f32, blur: f32) -> bool {
1501 self.inner.backdrop_blur(Self::rect(rect), radius, blur)
1502 }
1503 fn begin_masked(&mut self, inverse: bool) -> bool {
1504 self.inner.begin_masked(inverse)
1505 }
1506 fn begin_mask(&mut self) {
1507 self.inner.begin_mask();
1508 }
1509 fn end_mask(&mut self) {
1510 self.inner.end_mask();
1511 }
1512 fn stroke_path(&mut self, path: &crate::Path, stroke: &crate::Stroke) {
1513 self.inner.stroke_path(&Self::path(path), &Self::stroke(stroke));
1514 }
1515 fn draw_shadow(&mut self, rect: crate::RectF, radius: f32, shadow: &crate::Shadow) {
1516 let mut shadow = shadow.clone();
1517 shadow.offset.x = -shadow.offset.x;
1518 self.inner.draw_shadow(Self::rect(rect), radius, &shadow);
1519 }
1520 fn device_scale(&self) -> f32 {
1521 self.inner.device_scale()
1522 }
1523 fn gpu_device(&self) -> Option<crate::GpuDevice> {
1524 self.inner.gpu_device()
1525 }
1526 fn draw_gpu_surface(&mut self, dest: crate::RectF, surface: &crate::GpuSurface) -> bool {
1527 self.inner.draw_gpu_surface(Self::rect(dest), surface)
1528 }
1529}
1530
1531const CULL_MARGIN: f32 = 48.0;
1534
1535fn intersection(a: RectF, b: RectF) -> RectF {
1537 let x = a.x.max(b.x);
1538 let y = a.y.max(b.y);
1539 RectF::new(x, y, (a.right().min(b.right()) - x).max(0.0), (a.bottom().min(b.bottom()) - y).max(0.0))
1540}
1541
1542fn warn_missing_icon(ui: &crate::Ui, name: &str, design: bool) {
1547 if design || !cfg!(debug_assertions) {
1548 return;
1549 }
1550 let Some((pack, _)) = name.split_once(':') else { return };
1553 thread_local! {
1554 static WARNED: std::cell::RefCell<std::collections::HashSet<String>> = Default::default();
1555 }
1556 if WARNED.with(|w| w.borrow().contains(name)) || !ui.has_icon_pack(pack) {
1557 return;
1558 }
1559 if WARNED.with(|w| w.borrow_mut().insert(name.to_string())) {
1560 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)");
1561 }
1562}