1use std::any::Any;
10use std::sync::{Arc, Mutex};
11use std::time::Duration;
12
13use iced::Task;
14use iced_runtime::core::widget::Id;
15
16use iced_core::event::Event;
17use iced_core::widget::Operation;
18use iced_core::widget::tree::{self, Tree};
19use iced_core::{
20 Background, Border, Clipboard, Color, Layout, Length, Padding, Point, Rectangle, Shadow, Shell,
21 Vector, Widget, layout, mouse, overlay, renderer, touch,
22};
23use iced_runtime::platform_specific::wayland::CornerRadius;
24
25use crate::surface::action::LiveSettings;
26use crate::theme::THEME;
27
28pub use super::{Catalog, Style};
29
30#[allow(missing_debug_implementations)]
32#[must_use]
33pub struct Tooltip<'a, Message, TopLevelMessage> {
34 id: Id,
35 #[cfg(feature = "a11y")]
36 name: Option<std::borrow::Cow<'a, str>>,
37 #[cfg(feature = "a11y")]
38 description: Option<iced_accessibility::Description<'a>>,
39 #[cfg(feature = "a11y")]
40 label: Option<Vec<iced_accessibility::accesskit::NodeId>>,
41 content: crate::Element<'a, Message>,
42 on_leave: Message,
43 on_surface_action: Box<dyn Fn(crate::surface::Action<TopLevelMessage>) -> Message>,
44 width: Length,
45 height: Length,
46 padding: Padding,
47 selected: bool,
48 style: crate::theme::Tooltip,
49 delay: Option<Duration>,
50 settings: Option<
51 Arc<
52 dyn Fn(Rectangle) -> iced_runtime::platform_specific::wayland::popup::SctkPopupSettings
53 + Send
54 + Sync
55 + 'static,
56 >,
57 >,
58 view: Arc<
59 dyn Fn() -> crate::Element<'static, crate::Action<TopLevelMessage>> + Send + Sync + 'static,
60 >,
61}
62
63impl<'a, Message, TopLevelMessage> Tooltip<'a, Message, TopLevelMessage> {
64 pub fn new(
66 content: impl Into<crate::Element<'a, Message>>,
67 settings: Option<
68 impl Fn(Rectangle) -> iced_runtime::platform_specific::wayland::popup::SctkPopupSettings
69 + Send
70 + Sync
71 + 'static,
72 >,
73 view: impl Fn() -> crate::Element<'static, crate::Action<TopLevelMessage>>
74 + Send
75 + Sync
76 + 'static,
77 on_leave: Message,
78 on_surface_action: impl Fn(crate::surface::Action<TopLevelMessage>) -> Message + 'static,
79 ) -> Self {
80 Self {
81 id: Id::unique(),
82 #[cfg(feature = "a11y")]
83 name: None,
84 #[cfg(feature = "a11y")]
85 description: None,
86 #[cfg(feature = "a11y")]
87 label: None,
88 content: content.into(),
89 width: Length::Shrink,
90 height: Length::Shrink,
91 padding: Padding::new(0.0),
92 selected: false,
93 style: crate::theme::Tooltip::default(),
94 on_leave,
95 on_surface_action: Box::new(on_surface_action),
96 delay: None,
97 settings: if let Some(s) = settings {
98 Some(Arc::new(s))
99 } else {
100 None
101 },
102 view: Arc::new(view),
103 }
104 }
105
106 pub fn delay(mut self, dur: Duration) -> Self {
107 self.delay = Some(dur);
108 self
109 }
110
111 pub fn id(mut self, id: Id) -> Self {
113 self.id = id;
114 self
115 }
116
117 pub fn width(mut self, width: impl Into<Length>) -> Self {
119 self.width = width.into();
120 self
121 }
122
123 pub fn height(mut self, height: impl Into<Length>) -> Self {
125 self.height = height.into();
126 self
127 }
128
129 pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self {
131 self.padding = padding.into();
132 self
133 }
134
135 pub fn selected(mut self, selected: bool) -> Self {
139 self.selected = selected;
140
141 self
142 }
143
144 pub fn class(mut self, style: crate::theme::Tooltip) -> Self {
146 self.style = style;
147 self
148 }
149
150 #[cfg(feature = "a11y")]
151 pub fn name(mut self, name: impl Into<std::borrow::Cow<'a, str>>) -> Self {
153 self.name = Some(name.into());
154 self
155 }
156
157 #[cfg(feature = "a11y")]
158 pub fn description_widget<T: iced_accessibility::Describes>(mut self, description: &T) -> Self {
160 self.description = Some(iced_accessibility::Description::Id(
161 description.description(),
162 ));
163 self
164 }
165
166 #[cfg(feature = "a11y")]
167 pub fn description(mut self, description: impl Into<std::borrow::Cow<'a, str>>) -> Self {
169 self.description = Some(iced_accessibility::Description::Text(description.into()));
170 self
171 }
172
173 #[cfg(feature = "a11y")]
174 pub fn label(mut self, label: &dyn iced_accessibility::Labels) -> Self {
176 self.label = Some(label.label().into_iter().map(|l| l.into()).collect());
177 self
178 }
179}
180
181impl<'a, Message: 'static + Clone, TopLevelMessage: 'static + Clone>
182 Widget<Message, crate::Theme, crate::Renderer> for Tooltip<'a, Message, TopLevelMessage>
183{
184 fn tag(&self) -> tree::Tag {
185 tree::Tag::of::<State>()
186 }
187
188 fn state(&self) -> tree::State {
189 tree::State::new(State::default())
190 }
191
192 fn children(&self) -> Vec<Tree> {
193 vec![Tree::new(&self.content)]
194 }
195
196 fn diff(&mut self, tree: &mut Tree) {
197 tree.diff_children(std::slice::from_mut(&mut self.content));
198 }
199
200 fn size(&self) -> iced_core::Size<Length> {
201 iced_core::Size::new(self.width, self.height)
202 }
203
204 fn layout(
205 &mut self,
206 tree: &mut Tree,
207 renderer: &crate::Renderer,
208 limits: &layout::Limits,
209 ) -> layout::Node {
210 layout(
211 renderer,
212 limits,
213 self.width,
214 self.height,
215 self.padding,
216 |renderer, limits| {
217 self.content
218 .as_widget_mut()
219 .layout(&mut tree.children[0], renderer, limits)
220 },
221 )
222 }
223
224 fn operate(
225 &mut self,
226 tree: &mut Tree,
227 layout: Layout<'_>,
228 renderer: &crate::Renderer,
229 operation: &mut dyn Operation<()>,
230 ) {
231 operation.container(Some(&self.id), layout.bounds());
232 operation.traverse(&mut |operation| {
233 self.content.as_widget_mut().operate(
234 &mut tree.children[0],
235 layout
236 .children()
237 .next()
238 .unwrap()
239 .with_virtual_offset(layout.virtual_offset()),
240 renderer,
241 operation,
242 );
243 });
244 }
245
246 fn update(
247 &mut self,
248 tree: &mut Tree,
249 event: &Event,
250 layout: Layout<'_>,
251 cursor: mouse::Cursor,
252 renderer: &crate::Renderer,
253 clipboard: &mut dyn Clipboard,
254 shell: &mut Shell<'_, Message>,
255 viewport: &Rectangle,
256 ) {
257 update(
258 self.id.clone(),
259 event.clone(),
260 layout,
261 cursor,
262 shell,
263 self.settings.as_ref(),
264 &self.view,
265 self.delay,
266 &self.on_leave,
267 &self.on_surface_action,
268 || tree.state.downcast_mut::<State>(),
269 );
270
271 self.content.as_widget_mut().update(
272 &mut tree.children[0],
273 event,
274 layout
275 .children()
276 .next()
277 .unwrap()
278 .with_virtual_offset(layout.virtual_offset()),
279 cursor,
280 renderer,
281 clipboard,
282 shell,
283 viewport,
284 );
285 }
286
287 #[allow(clippy::too_many_lines)]
288 fn draw(
289 &self,
290 tree: &Tree,
291 renderer: &mut crate::Renderer,
292 theme: &crate::Theme,
293 renderer_style: &renderer::Style,
294 layout: Layout<'_>,
295 cursor: mouse::Cursor,
296 viewport: &Rectangle,
297 ) {
298 let bounds = layout.bounds();
299 if !viewport.intersects(&bounds) {
300 return;
301 }
302 let content_layout = layout.children().next().unwrap();
303
304 let styling = theme.style(&self.style);
305
306 let icon_color = styling.icon_color.unwrap_or(renderer_style.icon_color);
307
308 draw::<_, crate::Theme>(
309 renderer,
310 bounds,
311 *viewport,
312 &styling,
313 |renderer, _styling| {
314 self.content.as_widget().draw(
315 &tree.children[0],
316 renderer,
317 theme,
318 &renderer::Style {
319 icon_color,
320 text_color: styling.text_color,
321 scale_factor: renderer_style.scale_factor,
322 },
323 content_layout.with_virtual_offset(layout.virtual_offset()),
324 cursor,
325 &viewport.intersection(&bounds).unwrap_or_default(),
326 );
327 },
328 );
329 }
330
331 fn mouse_interaction(
332 &self,
333 tree: &Tree,
334 layout: Layout<'_>,
335 cursor: mouse::Cursor,
336 viewport: &Rectangle,
337 renderer: &crate::Renderer,
338 ) -> mouse::Interaction {
339 self.content.as_widget().mouse_interaction(
340 &tree.children[0],
341 layout.children().next().unwrap(),
342 cursor,
343 viewport,
344 renderer,
345 )
346 }
347
348 fn overlay<'b>(
349 &'b mut self,
350 tree: &'b mut Tree,
351 layout: Layout<'b>,
352 renderer: &crate::Renderer,
353 viewport: &Rectangle,
354 mut translation: Vector,
355 ) -> Option<overlay::Element<'b, Message, crate::Theme, crate::Renderer>> {
356 let position = layout.bounds().position();
357 translation.x += position.x;
358 translation.y += position.y;
359 self.content.as_widget_mut().overlay(
360 &mut tree.children[0],
361 layout
362 .children()
363 .next()
364 .unwrap()
365 .with_virtual_offset(layout.virtual_offset()),
366 renderer,
367 viewport,
368 translation,
369 )
370 }
371
372 #[cfg(feature = "a11y")]
373 fn a11y_nodes(
375 &self,
376 layout: Layout<'_>,
377 state: &Tree,
378 p: mouse::Cursor,
379 ) -> iced_accessibility::A11yTree {
380 let c_layout = layout.children().next().unwrap();
381
382 self.content.as_widget().a11y_nodes(
383 c_layout.with_virtual_offset(layout.virtual_offset()),
384 state,
385 p,
386 )
387 }
388
389 fn id(&self) -> Option<Id> {
390 Some(self.id.clone())
391 }
392
393 fn set_id(&mut self, id: Id) {
394 self.id = id;
395 }
396}
397
398impl<'a, Message: Clone + 'static, TopLevelMessage: Clone + 'static>
399 From<Tooltip<'a, Message, TopLevelMessage>> for crate::Element<'a, Message>
400{
401 fn from(button: Tooltip<'a, Message, TopLevelMessage>) -> Self {
402 Self::new(button)
403 }
404}
405
406#[derive(Debug, Clone, Default)]
408#[allow(clippy::struct_field_names)]
409pub struct State {
410 is_hovered: Arc<Mutex<bool>>,
411}
412
413impl State {
414 pub fn is_hovered(self) -> bool {
416 let guard = self.is_hovered.lock().unwrap();
417 *guard
418 }
419}
420
421#[allow(clippy::needless_pass_by_value)]
424pub fn update<'a, Message: Clone + 'static, TopLevelMessage: Clone + 'static>(
425 _id: Id,
426 event: Event,
427 layout: Layout<'_>,
428 cursor: mouse::Cursor,
429 shell: &mut Shell<'_, Message>,
430 settings: Option<
431 &Arc<
432 dyn Fn(Rectangle) -> iced_runtime::platform_specific::wayland::popup::SctkPopupSettings
433 + Send
434 + Sync
435 + 'static,
436 >,
437 >,
438 view: &Arc<
439 dyn Fn() -> crate::Element<'static, crate::Action<TopLevelMessage>> + Send + Sync + 'static,
440 >,
441 delay: Option<Duration>,
442 on_leave: &Message,
443 on_surface_action: &dyn Fn(crate::surface::Action<TopLevelMessage>) -> Message,
444 state: impl FnOnce() -> &'a mut State,
445) {
446 match event {
447 Event::Touch(touch::Event::FingerLifted { .. }) => {
448 let state = state();
449 let mut guard = state.is_hovered.lock().unwrap();
450 if *guard {
451 *guard = false;
452
453 shell.publish(on_leave.clone());
454
455 shell.capture_event();
456 }
457 }
458
459 Event::Touch(touch::Event::FingerLost { .. }) | Event::Mouse(mouse::Event::CursorLeft) => {
460 let state = state();
461 let mut guard = state.is_hovered.lock().unwrap();
462
463 if *guard {
464 *guard = false;
465
466 shell.publish(on_leave.clone());
467 }
468 }
469
470 Event::Mouse(mouse::Event::CursorMoved { .. }) => {
471 let state = state();
472 let bounds = layout.bounds();
473 let is_hovered = state.is_hovered.clone();
474 let mut guard = state.is_hovered.lock().unwrap();
475
476 if *guard {
477 *guard = cursor.is_over(bounds);
478 if !*guard {
479 shell.publish(on_leave.clone());
480 }
481 } else {
482 *guard = cursor.is_over(bounds);
483 if *guard && let Some(settings) = settings {
484 if let Some(delay) = delay {
485 let s = settings.clone();
486 let view = view.clone();
487 let bounds = layout.bounds();
488
489 let sm = crate::surface::Action::Task(Arc::new(move || {
490 let s = s.clone();
491 let view = view.clone();
492 let is_hovered = is_hovered.clone();
493 Task::future(async move {
494 #[cfg(feature = "tokio")]
495 {
496 _ = tokio::time::sleep(delay).await;
497 }
498 #[cfg(feature = "smol")]
499 {
500 _ = smol::Timer::after(delay).await;
501 }
502 let is_hovered = is_hovered.clone();
503 let g = is_hovered.lock().unwrap();
504 if !*g {
505 return crate::surface::Action::Ignore;
506 }
507 let boxed: Box<
508 dyn Fn() -> iced_runtime::platform_specific::wayland::popup::SctkPopupSettings
509 + Send
510 + Sync
511 + 'static,
512 > = Box::new(move || s(bounds));
513 let boxed: Box<dyn Any + Send + Sync + 'static> = Box::new(boxed);
514
515 let theme = THEME.lock().unwrap();
516
517 let corners = theme.cosmic().corner_radii.radius_s;
518 let boxed_live: Box<
519 dyn Fn() -> LiveSettings + Send + Sync + 'static,
520 > = Box::new(move || LiveSettings {
521 corners: Some(CornerRadius {
522 top_left: corners[0] as u32,
523 top_right: corners[1] as u32,
524 bottom_left: corners[3] as u32,
525 bottom_right: corners[2] as u32,
526 }),
527 ..Default::default()
528 });
529 let boxed_live: Box<dyn Any + Send + Sync + 'static> =
530 Box::new(boxed_live);
531 crate::surface::Action::Popup(
532 Arc::new(boxed),
533 Arc::new(boxed_live),
534 Some(Arc::new(move || view())
535 as crate::surface::View<TopLevelMessage>),
536 )
537 })
538 }));
539
540 shell.publish((on_surface_action)(sm));
541 } else {
542 let s = settings.clone();
543 let view = view.clone();
544 let bounds = layout.bounds();
545
546 let boxed: Box<
547 dyn Fn() -> iced_runtime::platform_specific::wayland::popup::SctkPopupSettings
548 + Send
549 + Sync
550 + 'static,
551 > = Box::new(move || s(bounds));
552 let boxed: Box<dyn Any + Send + Sync + 'static> = Box::new(boxed);
553 let theme = THEME.lock().unwrap();
554
555 let corners = theme.cosmic().corner_radii.radius_s;
556 let boxed_live: Box<dyn Fn() -> LiveSettings + Send + Sync + 'static> =
557 Box::new(move || LiveSettings {
558 corners: Some(CornerRadius {
559 top_left: corners[0] as u32,
560 top_right: corners[1] as u32,
561 bottom_left: corners[3] as u32,
562 bottom_right: corners[2] as u32,
563 }),
564 ..Default::default()
565 });
566 let boxed_live: Box<dyn Any + Send + Sync + 'static> = Box::new(boxed_live);
567
568 let sm = crate::surface::Action::Popup(
569 Arc::new(boxed),
570 Arc::new(boxed_live),
571 Some(Arc::new(move || view()) as crate::surface::View<TopLevelMessage>),
572 );
573 shell.publish((on_surface_action)(sm));
574 }
575 }
576 }
577 }
578 _ => {}
579 }
580}
581
582#[allow(clippy::too_many_arguments)]
583pub fn draw<Renderer: iced_core::Renderer, Theme>(
584 renderer: &mut Renderer,
585 bounds: Rectangle,
586 viewport_bounds: Rectangle,
587 styling: &super::Style,
588 draw_contents: impl FnOnce(&mut Renderer, &Style),
589) where
590 Theme: super::Catalog,
591{
592 let doubled_border_width = styling.border_width * 2.0;
593 let doubled_outline_width = styling.outline_width * 2.0;
594
595 if styling.outline_width > 0.0 {
596 renderer.fill_quad(
597 renderer::Quad {
598 bounds: Rectangle {
599 x: bounds.x - styling.border_width - styling.outline_width,
600 y: bounds.y - styling.border_width - styling.outline_width,
601 width: bounds.width + doubled_border_width + doubled_outline_width,
602 height: bounds.height + doubled_border_width + doubled_outline_width,
603 },
604 border: Border {
605 width: styling.outline_width,
606 color: styling.outline_color,
607 radius: styling.border_radius,
608 },
609 shadow: Shadow::default(),
610 snap: true,
611 },
612 Color::TRANSPARENT,
613 );
614 }
615
616 if styling.background.is_some() || styling.border_width > 0.0 {
617 if styling.shadow_offset != Vector::default() {
618 renderer.fill_quad(
620 renderer::Quad {
621 bounds: Rectangle {
622 x: bounds.x + styling.shadow_offset.x,
623 y: bounds.y + styling.shadow_offset.y,
624 width: bounds.width,
625 height: bounds.height,
626 },
627 border: Border {
628 radius: styling.border_radius,
629 ..Default::default()
630 },
631 shadow: Shadow::default(),
632 snap: true,
633 },
634 Background::Color([0.0, 0.0, 0.0, 0.5].into()),
635 );
636 }
637
638 if let Some(background) = styling.background {
640 renderer.fill_quad(
641 renderer::Quad {
642 bounds,
643 border: Border {
644 radius: styling.border_radius,
645 ..Default::default()
646 },
647 shadow: Shadow::default(),
648 snap: true,
649 },
650 background,
651 );
652 }
653
654 draw_contents(renderer, styling);
656
657 let mut clipped_bounds = viewport_bounds.intersection(&bounds).unwrap_or_default();
658 clipped_bounds.height += styling.border_width;
659
660 renderer.with_layer(clipped_bounds, |renderer| {
661 renderer.fill_quad(
663 renderer::Quad {
664 bounds,
665 border: Border {
666 width: styling.border_width,
667 color: styling.border_color,
668 radius: styling.border_radius,
669 },
670 shadow: Shadow::default(),
671 snap: true,
672 },
673 Color::TRANSPARENT,
674 );
675 });
676 } else {
677 draw_contents(renderer, styling);
678 }
679}
680
681pub fn layout<Renderer>(
683 renderer: &Renderer,
684 limits: &layout::Limits,
685 width: Length,
686 height: Length,
687 padding: Padding,
688 layout_content: impl FnOnce(&Renderer, &layout::Limits) -> layout::Node,
689) -> layout::Node {
690 let limits = limits.width(width).height(height);
691
692 let mut content = layout_content(renderer, &limits.shrink(padding));
693 let padding = padding.fit(content.size(), limits.max());
694 let size = limits
695 .shrink(padding)
696 .resolve(width, height, content.size())
697 .expand(padding);
698
699 content = content.move_to(Point::new(padding.left, padding.top));
700
701 layout::Node::with_children(size, vec![content])
702}