1use super::*;
2
3pub struct Label {
4 text: String,
5 text_reader: Option<Box<dyn Fn() -> String>>,
6 text_source: Option<Arc<dyn Observable<String>>>,
7 semantic_name: Option<String>,
8 style: TextStyle,
9 style_reader: Option<Box<dyn Fn() -> TextStyle>>,
10 font_size_override: Option<f32>,
11 line_height_override: Option<f32>,
12 color_override: Option<Color>,
13 color_reader: Option<Box<dyn Fn() -> Color>>,
14 measurement: Option<TextMeasurement>,
15 layout: Option<PersistentTextLayout>,
16 selection_scope: Option<SelectionScope>,
17 clipboard_behavior: SelectionClipboardBehavior,
18 selection: TextSelection,
19 dragging_selection: Option<u64>,
20}
21
22impl Label {
23 pub fn new(text: impl Into<String>) -> Self {
24 Self {
25 text: text.into(),
26 text_reader: None,
27 text_source: None,
28 semantic_name: None,
29 style: DefaultTheme::default().body_text_style(),
30 style_reader: None,
31 font_size_override: None,
32 line_height_override: None,
33 color_override: None,
34 color_reader: None,
35 measurement: None,
36 layout: None,
37 selection_scope: None,
38 clipboard_behavior: SelectionClipboardBehavior::AppManaged,
39 selection: TextSelection::new(TextCursor::new(0), TextCursor::new(0)),
40 dragging_selection: None,
41 }
42 }
43
44 pub fn dynamic<F>(fallback: impl Into<String>, reader: F) -> Self
45 where
46 F: Fn() -> String + 'static,
47 {
48 Self::new(fallback).text_when(reader)
49 }
50
51 pub fn text_when<F>(mut self, reader: F) -> Self
52 where
53 F: Fn() -> String + 'static,
54 {
55 self.text_reader = Some(Box::new(reader));
56 self.text_source = None;
57 self
58 }
59
60 pub fn text_from<O>(mut self, source: O) -> Self
65 where
66 O: Observable<String> + 'static,
67 {
68 self.text = source.get();
69 self.text_reader = None;
70 self.text_source = Some(Arc::new(source));
71 self
72 }
73
74 pub fn semantic_name(mut self, name: impl Into<String>) -> Self {
75 self.semantic_name = Some(name.into());
76 self
77 }
78
79 pub fn selectable(mut self, selection_scope: SelectionScope) -> Self {
80 self.selection_scope = Some(selection_scope);
81 self
82 }
83
84 pub fn clipboard_behavior(mut self, behavior: SelectionClipboardBehavior) -> Self {
85 self.clipboard_behavior = behavior;
86 self
87 }
88
89 pub fn copy_to_clipboard(self, enabled: bool) -> Self {
90 self.clipboard_behavior(if enabled {
91 SelectionClipboardBehavior::WidgetManaged
92 } else {
93 SelectionClipboardBehavior::AppManaged
94 })
95 }
96
97 pub fn selection_scope(&self) -> Option<&SelectionScope> {
98 self.selection_scope.as_ref()
99 }
100
101 pub fn theme(mut self, theme: DefaultTheme) -> Self {
102 self.style = theme.body_text_style();
103 self.clear_style_overrides();
104 self
105 }
106
107 pub fn text(&self) -> &str {
108 &self.text
109 }
110
111 pub fn set_text(&mut self, text: impl Into<String>) {
112 self.text = text.into();
113 self.text_reader = None;
114 self.text_source = None;
115 }
116
117 pub fn color(mut self, color: Color) -> Self {
118 self.color_override = Some(color);
119 self.color_reader = None;
120 self
121 }
122
123 pub fn color_when<F>(mut self, color: F) -> Self
124 where
125 F: Fn() -> Color + 'static,
126 {
127 self.color_override = None;
128 self.color_reader = Some(Box::new(color));
129 self
130 }
131
132 pub fn font_size(mut self, font_size: f32) -> Self {
133 self.font_size_override = Some(font_size.max(1.0));
134 self
135 }
136
137 pub fn line_height(mut self, line_height: f32) -> Self {
138 self.line_height_override = Some(line_height.max(1.0));
139 self
140 }
141
142 pub fn style(mut self, style: TextStyle) -> Self {
143 self.style = style;
144 self.clear_style_overrides();
145 self
146 }
147
148 pub fn style_when<F>(mut self, style: F) -> Self
154 where
155 F: Fn() -> TextStyle + 'static,
156 {
157 self.clear_style_overrides();
158 self.style_reader = Some(Box::new(style));
159 self
160 }
161
162 fn current_text(&self) -> String {
163 self.text_source
164 .as_ref()
165 .map(|source| source.get())
166 .or_else(|| self.text_reader.as_ref().map(|reader| reader()))
167 .unwrap_or_else(|| self.text.clone())
168 }
169
170 fn observed_text(&self, ctx: &MeasureCtx) -> String {
171 self.text_source
172 .as_ref()
173 .map(|source| ctx.observe_with(source.as_ref(), InvalidationKind::Text))
174 .unwrap_or_else(|| self.current_text())
175 }
176
177 pub(super) fn resolved_style(&self) -> TextStyle {
178 let mut style = self
179 .style_reader
180 .as_ref()
181 .map(|reader| reader())
182 .unwrap_or_else(|| self.style.clone());
183 if let Some(font_size) = self.font_size_override {
184 style.font_size = font_size;
185 }
186 if let Some(line_height) = self.line_height_override {
187 style.line_height = line_height;
188 }
189 if let Some(color) = self.color_override {
190 style.color = color;
191 }
192 if let Some(color_reader) = &self.color_reader {
193 style.color = color_reader();
194 }
195 style
196 }
197
198 fn clear_style_overrides(&mut self) {
199 self.style_reader = None;
200 self.font_size_override = None;
201 self.line_height_override = None;
202 self.color_override = None;
203 self.color_reader = None;
204 }
205
206 fn has_explicit_line_break(text: &str) -> bool {
207 text.bytes().any(|byte| matches!(byte, b'\n' | b'\r'))
208 }
209
210 fn owner_id(widget_id: WidgetId) -> SelectionOwnerId {
211 SelectionOwnerId::from(widget_id)
212 }
213
214 fn selected_range(&self, text_len: usize) -> std::ops::Range<usize> {
215 selection_range(&self.selection, text_len)
216 }
217
218 fn active_selection_range(
219 &self,
220 widget_id: WidgetId,
221 text_len: usize,
222 ) -> Option<std::ops::Range<usize>> {
223 let owner = Self::owner_id(widget_id);
224 let range = self.selected_range(text_len);
225 self.selection_scope
226 .as_ref()
227 .is_some_and(|scope| scope.has_owner_selection(owner))
228 .then_some(range)
229 .filter(|range| !range.is_empty())
230 }
231
232 fn sync_selection_scope(&self, ctx: &mut EventCtx, text: &str) {
233 let Some(scope) = &self.selection_scope else {
234 return;
235 };
236 let owner = Self::owner_id(ctx.widget_id());
237 let range = self.selected_range(text.len());
238 let selected = text.get(range.clone()).unwrap_or("").to_string();
239 let change = scope.replace_text(owner, owner, range, text.len(), selected);
240 request_selection_change(ctx, change);
241 }
242
243 fn label_layout_origin_for_event(&self, bounds: Rect, layout: &PersistentTextLayout) -> Point {
244 let measurement = layout.measurement();
245 let height = self
246 .resolved_style()
247 .line_height
248 .max(measurement.height)
249 .min(bounds.height());
250 Point::new(
251 bounds.x() - measurement.bounds.x(),
252 bounds.y() + ((bounds.height() - height).max(0.0) * 0.5),
253 )
254 }
255
256 fn hit_test_offset(&self, bounds: Rect, position: Point, text_len: usize) -> usize {
257 self.layout
258 .as_ref()
259 .map(|layout| {
260 let origin = self.label_layout_origin_for_event(bounds, layout);
261 layout
262 .hit_test_point(Point::new(position.x - origin.x, position.y - origin.y))
263 .utf8_offset
264 .min(text_len)
265 })
266 .unwrap_or(text_len)
267 }
268
269 fn set_selection(&mut self, anchor: usize, focus: usize, text_len: usize) {
270 self.selection = TextSelection::new(
271 TextCursor::new(anchor.min(text_len)),
272 TextCursor::new(focus.min(text_len)),
273 );
274 }
275
276 fn handles_implicit_clipboard(&self) -> bool {
277 self.clipboard_behavior.is_widget_managed()
278 }
279
280 fn copy_selection(&self, ctx: &mut EventCtx) -> bool {
281 let text = self.current_text();
282 let range = self.selected_range(text.len());
283 let Some(selected) = text.get(range).filter(|selected| !selected.is_empty()) else {
284 return false;
285 };
286 ctx.set_clipboard_text(selected);
287 true
288 }
289}
290
291impl Widget for Label {
292 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
293 if self.selection_scope.is_none() {
294 return;
295 }
296
297 match event {
298 Event::Pointer(pointer)
299 if pointer.kind == PointerEventKind::Down
300 && pointer.button == Some(PointerButton::Primary)
301 && ctx.phase() != sui_runtime::EventPhase::Capture
302 && ctx.bounds().contains(pointer.position) =>
303 {
304 let text = self.current_text();
305 let offset = self.hit_test_offset(ctx.bounds(), pointer.position, text.len());
306 let anchor = if pointer.modifiers.shift {
307 self.selection.anchor.utf8_offset
308 } else {
309 offset
310 };
311 self.set_selection(anchor, offset, text.len());
312 self.dragging_selection = Some(pointer.pointer_id);
313 self.sync_selection_scope(ctx, &text);
314 ctx.request_focus();
315 ctx.request_pointer_capture(pointer.pointer_id);
316 ctx.request_paint();
317 ctx.request_semantics();
318 ctx.set_handled();
319 }
320 Event::Pointer(pointer)
321 if pointer.kind == PointerEventKind::Move
322 && self.dragging_selection == Some(pointer.pointer_id)
323 && pointer.buttons.contains(PointerButton::Primary) =>
324 {
325 let text = self.current_text();
326 let anchor = self.selection.anchor.utf8_offset;
327 let focus = self.hit_test_offset(ctx.bounds(), pointer.position, text.len());
328 self.set_selection(anchor, focus, text.len());
329 self.sync_selection_scope(ctx, &text);
330 ctx.request_paint();
331 ctx.request_semantics();
332 ctx.set_handled();
333 }
334 Event::Pointer(pointer)
335 if pointer.kind == PointerEventKind::Up
336 && self.dragging_selection == Some(pointer.pointer_id) =>
337 {
338 self.dragging_selection = None;
339 ctx.release_pointer_capture(pointer.pointer_id);
340 ctx.set_handled();
341 }
342 Event::Pointer(pointer)
343 if pointer.kind == PointerEventKind::Cancel
344 && self.dragging_selection == Some(pointer.pointer_id) =>
345 {
346 self.dragging_selection = None;
347 ctx.release_pointer_capture(pointer.pointer_id);
348 ctx.set_handled();
349 }
350 Event::Pointer(pointer)
351 if pointer.kind == PointerEventKind::Down
352 && pointer.button == Some(PointerButton::Secondary)
353 && ctx.phase() != EventPhase::Capture
354 && ctx.bounds().contains(pointer.position) =>
355 {
356 ctx.request_focus();
360 ctx.request_paint();
361 ctx.request_semantics();
362 }
363 Event::Keyboard(key)
364 if key.state == KeyState::Pressed
365 && ctx.is_focused()
366 && (key.modifiers.control || key.modifiers.meta)
367 && matches!(key.key.as_str(), "a" | "A") =>
368 {
369 let text = self.current_text();
370 self.set_selection(0, text.len(), text.len());
371 self.sync_selection_scope(ctx, &text);
372 ctx.request_paint();
373 ctx.request_semantics();
374 ctx.set_handled();
375 }
376 Event::Keyboard(key)
377 if key.state == KeyState::Pressed
378 && ctx.is_focused()
379 && (key.modifiers.control || key.modifiers.meta)
380 && matches!(key.key.as_str(), "c" | "C")
381 && self.handles_implicit_clipboard() =>
382 {
383 if self.copy_selection(ctx) {
384 ctx.set_handled();
385 }
386 }
387 Event::Keyboard(key)
388 if key.state == KeyState::Pressed && ctx.is_focused() && key.key == "Escape" =>
389 {
390 if let Some(scope) = &self.selection_scope {
391 let change = scope.clear_owner(Self::owner_id(ctx.widget_id()));
392 request_selection_change(ctx, change);
393 }
394 self.set_selection(0, 0, 0);
395 ctx.request_paint();
396 ctx.request_semantics();
397 ctx.set_handled();
398 }
399 Event::Semantics(semantics) if semantics.target == ctx.widget_id() => {
400 match &semantics.action {
401 SemanticsActionRequest::SetSelection(selection) => {
402 let text = self.current_text();
403 self.set_selection(selection.start, selection.end, text.len());
404 self.sync_selection_scope(ctx, &text);
405 ctx.request_paint();
406 ctx.request_semantics();
407 ctx.set_handled();
408 }
409 SemanticsActionRequest::Copy
410 if self.handles_implicit_clipboard() && self.copy_selection(ctx) =>
411 {
412 ctx.set_handled();
413 }
414 _ => {}
415 }
416 }
417 _ => {}
418 }
419 }
420
421 fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
422 let Some(command) = TextCommand::from_command(command) else {
423 return;
424 };
425 match command {
426 TextCommand::SelectAll => {
427 let text = self.current_text();
428 self.set_selection(0, text.len(), text.len());
429 self.sync_selection_scope(ctx, &text);
430 ctx.request_paint();
431 ctx.request_semantics();
432 ctx.set_handled();
433 }
434 TextCommand::Copy => {
435 if self.copy_selection(ctx) {
436 ctx.set_handled();
437 }
438 }
439 TextCommand::Cut | TextCommand::Paste => {}
440 }
441 }
442
443 fn intrinsic_size(
444 &mut self,
445 ctx: &mut MeasureCtx,
446 axis: Axis,
447 available_cross: f32,
448 ) -> IntrinsicSize {
449 if axis == Axis::Horizontal {
450 let text = self.observed_text(ctx);
451 let style = self.resolved_style();
452 let natural = measure_text(ctx, &text, &style).width;
453 let minimum = text
454 .split_whitespace()
455 .map(|segment| measure_text(ctx, segment, &style).width)
456 .fold(0.0_f32, f32::max);
457 return IntrinsicSize::new(minimum, natural);
458 }
459
460 let width = if available_cross.is_finite() {
461 available_cross.max(0.0)
462 } else {
463 f32::INFINITY
464 };
465 let size = self.measure(
466 ctx,
467 Constraints::new(Size::ZERO, Size::new(width, f32::INFINITY)),
468 );
469 IntrinsicSize::fixed(size.height)
470 }
471
472 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
473 let text = self.observed_text(ctx);
474 let style = self.resolved_style();
475 let natural_measurement = measure_text(ctx, &text, &style);
476 let max_width = constraints.max.width;
477 let wraps_to_constraint = max_width.is_finite() && natural_measurement.width > max_width;
478 let needs_layout = self.selection_scope.is_some()
479 || wraps_to_constraint
480 || Self::has_explicit_line_break(&text);
481 let mut measured_width = if wraps_to_constraint {
482 max_width.max(0.0)
483 } else {
484 natural_measurement.width
485 };
486 let mut measurement = natural_measurement;
487
488 if needs_layout {
489 let layout_width = if max_width.is_finite() {
490 measured_width.min(max_width).max(1.0)
491 } else {
492 measured_width.max(1.0)
493 };
494 measurement = ctx
495 .layout()
496 .shape_text(
497 text.clone(),
498 Size::new(layout_width, f32::INFINITY),
499 style.clone(),
500 )
501 .map(|layout| layout.measurement())
502 .unwrap_or(measurement);
503 if !wraps_to_constraint {
504 measured_width = if max_width.is_finite() {
505 measurement.width.min(max_width).max(0.0)
506 } else {
507 measurement.width.max(0.0)
508 };
509 }
510 self.layout = ctx
511 .layout()
512 .shape_text_persistent(
513 self.layout.as_ref().map(|layout| layout.handle()),
514 text,
515 Size::new(
516 measured_width.max(1.0),
517 measurement.height.max(style.line_height).max(1.0),
518 ),
519 style.clone(),
520 )
521 .ok();
522 } else {
523 self.layout = None;
524 }
525 self.measurement = Some(measurement);
526 constraints.clamp(Size::new(
527 measured_width,
528 measurement.height.max(style.line_height),
529 ))
530 }
531
532 fn paint(&self, ctx: &mut PaintCtx) {
533 let text = self.current_text();
534 let style = self.resolved_style();
535 if let Some(layout) = &self.layout {
536 let layout_bounds = layout.measurement().bounds;
537 let mut layout_rect = aligned_text_rect_for_layout_with_mode(
538 ctx,
539 ctx.bounds(),
540 layout.layout(),
541 style.line_height,
542 0.0,
543 HorizontalTextAlignmentMode::Optical,
544 );
545 if layout.lines().len() > 1 {
546 let block_height = style
547 .line_height
548 .max(layout.measurement().height)
549 .min(ctx.bounds().height());
550 layout_rect = Rect::new(
551 layout_rect.x(),
552 ctx.bounds().y() + ((ctx.bounds().height() - block_height).max(0.0) * 0.5),
553 layout_rect.width(),
554 block_height,
555 );
556 }
557 let origin = Point::new(layout_rect.x() - layout_bounds.x(), layout_rect.y());
558 if let Some(range) = self.active_selection_range(ctx.widget_id(), text.len()) {
559 let theme = DefaultTheme::default();
560 for rect in layout.selection_rects(range) {
561 ctx.fill_rect(rect.translate(origin.to_vector()), theme.palette.selection);
562 }
563 }
564 ctx.draw_persistent_text_layout(origin, layout);
565 } else {
566 paint_aligned_text(ctx, ctx.bounds(), &text, &style, style.line_height, 0.0);
567 }
568 }
569
570 fn semantics(&self, ctx: &mut SemanticsCtx) {
571 let text = self.current_text();
572 let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
573 node.name = Some(self.semantic_name.clone().unwrap_or_else(|| text.clone()));
574 if self.semantic_name.is_some() {
575 node.value = Some(SemanticsValue::Text(text));
576 }
577 if self.selection_scope.is_some() {
578 node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetSelection];
579 if self.handles_implicit_clipboard() {
580 node.actions.push(SemanticsAction::Copy);
581 }
582 node.state.focused = ctx.is_focused();
583 }
584 ctx.push(node);
585 }
586
587 fn accepts_focus(&self) -> bool {
588 self.selection_scope.is_some()
589 }
590
591 fn focus_changed(&mut self, ctx: &mut EventCtx, _focused: bool) {
592 ctx.request_paint();
593 ctx.request_semantics();
594 }
595}
596
597pub struct Link {
598 theme: Box<DefaultTheme>,
599 theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
600 label: String,
601 label_reader: Option<Box<dyn Fn() -> String>>,
602 url: String,
603 url_reader: Option<Box<dyn Fn() -> String>>,
604 semantic_name: Option<String>,
605 text_style: Option<TextStyle>,
606 enabled: bool,
607 enabled_reader: Option<Box<dyn Fn() -> bool>>,
608 hovered: bool,
609 pressed: bool,
610 measurement: Option<TextMeasurement>,
611 on_open: Option<Box<dyn FnMut(&str)>>,
612 on_open_with_ctx: Option<Box<dyn FnMut(&mut EventCtx, &str)>>,
613}
614
615impl Link {
616 pub fn new(label: impl Into<String>, url: impl Into<String>) -> Self {
617 Self {
618 theme: Box::new(DefaultTheme::default()),
619 theme_reader: None,
620 label: label.into(),
621 label_reader: None,
622 url: url.into(),
623 url_reader: None,
624 semantic_name: None,
625 text_style: None,
626 enabled: true,
627 enabled_reader: None,
628 hovered: false,
629 pressed: false,
630 measurement: None,
631 on_open: None,
632 on_open_with_ctx: None,
633 }
634 }
635
636 pub fn url(url: impl Into<String>) -> Self {
637 let url = url.into();
638 Self::new(url.clone(), url)
639 }
640
641 pub fn label_when<F>(mut self, reader: F) -> Self
642 where
643 F: Fn() -> String + 'static,
644 {
645 self.label_reader = Some(Box::new(reader));
646 self
647 }
648
649 pub fn url_when<F>(mut self, reader: F) -> Self
650 where
651 F: Fn() -> String + 'static,
652 {
653 self.url_reader = Some(Box::new(reader));
654 self
655 }
656
657 pub fn semantic_name(mut self, name: impl Into<String>) -> Self {
658 self.semantic_name = Some(name.into());
659 self
660 }
661
662 pub fn theme(mut self, theme: DefaultTheme) -> Self {
663 self.theme = Box::new(theme);
664 self.theme_reader = None;
665 self
666 }
667
668 pub fn theme_when<F>(mut self, theme: F) -> Self
669 where
670 F: Fn() -> DefaultTheme + 'static,
671 {
672 self.theme_reader = Some(Box::new(theme));
673 self
674 }
675
676 pub fn text_style(mut self, text_style: TextStyle) -> Self {
677 self.text_style = Some(text_style);
678 self
679 }
680
681 pub fn enabled(mut self, enabled: bool) -> Self {
682 self.enabled = enabled;
683 self.enabled_reader = None;
684 self
685 }
686
687 pub fn enabled_when<F>(mut self, enabled: F) -> Self
688 where
689 F: Fn() -> bool + 'static,
690 {
691 self.enabled_reader = Some(Box::new(enabled));
692 self
693 }
694
695 pub fn on_open<F>(mut self, on_open: F) -> Self
696 where
697 F: FnMut(&str) + 'static,
698 {
699 self.on_open = Some(Box::new(on_open));
700 self
701 }
702
703 pub fn on_open_with_ctx<F>(mut self, on_open: F) -> Self
704 where
705 F: FnMut(&mut EventCtx, &str) + 'static,
706 {
707 self.on_open_with_ctx = Some(Box::new(on_open));
708 self
709 }
710
711 fn current_label(&self) -> String {
712 single_line_text(
713 self.label_reader
714 .as_ref()
715 .map(|reader| reader())
716 .unwrap_or_else(|| self.label.clone()),
717 )
718 }
719
720 fn current_url(&self) -> String {
721 single_line_text(
722 self.url_reader
723 .as_ref()
724 .map(|reader| reader())
725 .unwrap_or_else(|| self.url.clone()),
726 )
727 .trim()
728 .to_string()
729 }
730
731 fn is_enabled(&self) -> bool {
732 self.enabled_reader
733 .as_ref()
734 .map(|enabled| enabled())
735 .unwrap_or(self.enabled)
736 }
737
738 fn resolved_theme(&self) -> DefaultTheme {
739 self.theme_reader
740 .as_ref()
741 .map(|theme| theme())
742 .unwrap_or(*self.theme)
743 }
744
745 fn resolved_text_style(&self, color: Color) -> TextStyle {
746 let mut style = self
747 .text_style
748 .clone()
749 .unwrap_or_else(|| self.resolved_theme().body_text_style());
750 style.color = color;
751 style
752 }
753
754 fn resolved_color(&self, theme: &DefaultTheme) -> Color {
755 if !self.is_enabled() {
756 return theme
757 .palette
758 .placeholder
759 .with_alpha(theme.interaction.disabled_content_opacity);
760 }
761 if self.pressed {
762 theme.palette.accent_pressed
763 } else if self.hovered {
764 theme.palette.accent_hover
765 } else {
766 theme.palette.accent
767 }
768 }
769
770 fn is_visible_parts(label: &str, url: &str) -> bool {
771 !label.trim().is_empty() && !url.trim().is_empty()
772 }
773
774 fn is_visible(&self) -> bool {
775 Self::is_visible_parts(&self.current_label(), &self.current_url())
776 }
777
778 fn can_activate_parts(&self, label: &str, url: &str) -> bool {
779 self.is_enabled() && Self::is_visible_parts(label, url)
780 }
781
782 fn activate(&mut self, ctx: &mut EventCtx) {
783 let label = self.current_label();
784 let url = self.current_url();
785 if !self.can_activate_parts(&label, &url) {
786 return;
787 }
788 if let Some(on_open) = &mut self.on_open {
789 on_open(&url);
790 }
791 if let Some(on_open) = &mut self.on_open_with_ctx {
792 on_open(ctx, &url);
793 }
794 }
795
796 fn set_hovered(&mut self, hovered: bool, ctx: &mut EventCtx) {
797 if self.hovered != hovered {
798 self.hovered = hovered;
799 ctx.request_paint();
800 ctx.request_semantics();
801 }
802 }
803
804 fn reset_interaction(&mut self, ctx: &mut EventCtx) {
805 if self.hovered || self.pressed {
806 self.hovered = false;
807 self.pressed = false;
808 ctx.request_paint();
809 ctx.request_semantics();
810 }
811 }
812}
813
814impl Widget for Link {
815 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
816 if !self.is_visible() || !self.is_enabled() {
817 self.reset_interaction(ctx);
818 return;
819 }
820
821 match event {
822 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
823 self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
824 }
825 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Enter => {
826 self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
827 }
828 Event::Pointer(_pointer) if _pointer.kind == PointerEventKind::Leave => {
829 self.set_hovered(false, ctx);
830 }
831 Event::Pointer(pointer)
832 if pointer.kind == PointerEventKind::Down
833 && pointer.button == Some(PointerButton::Primary) =>
834 {
835 self.pressed = true;
836 self.hovered = true;
837 ctx.request_pointer_capture(pointer.pointer_id);
838 ctx.request_focus();
839 ctx.request_paint();
840 ctx.request_semantics();
841 ctx.set_handled();
842 }
843 Event::Pointer(pointer)
844 if pointer.kind == PointerEventKind::Up
845 && pointer.button == Some(PointerButton::Primary) =>
846 {
847 let hovered = ctx.bounds().contains(pointer.position);
848 let activate = self.pressed && hovered;
849 self.pressed = false;
850 self.hovered = hovered;
851 ctx.release_pointer_capture(pointer.pointer_id);
852 if activate {
853 self.activate(ctx);
854 }
855 ctx.request_paint();
856 ctx.request_semantics();
857 ctx.set_handled();
858 }
859 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
860 if self.pressed {
861 self.pressed = false;
862 self.hovered = false;
863 ctx.release_pointer_capture(pointer.pointer_id);
864 ctx.request_paint();
865 ctx.request_semantics();
866 ctx.set_handled();
867 }
868 }
869 Event::Keyboard(key)
870 if key.state == KeyState::Pressed
871 && ctx.is_focused()
872 && matches!(key.key.as_str(), "Enter" | " ") =>
873 {
874 self.activate(ctx);
875 ctx.request_paint();
876 ctx.request_semantics();
877 ctx.set_handled();
878 }
879 _ => {}
880 }
881 }
882
883 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
884 let label = self.current_label();
885 let url = self.current_url();
886 if !Self::is_visible_parts(&label, &url) {
887 self.measurement = None;
888 return constraints.clamp(Size::ZERO);
889 }
890
891 let theme = self.resolved_theme();
892 let style = self.resolved_text_style(self.resolved_color(&theme));
893 let measurement = measure_text(ctx, &label, &style);
894 self.measurement = Some(measurement);
895 constraints.clamp(Size::new(
896 measurement.width,
897 measurement.height.max(style.line_height),
898 ))
899 }
900
901 fn paint(&self, ctx: &mut PaintCtx) {
902 let label = self.current_label();
903 let url = self.current_url();
904 if !Self::is_visible_parts(&label, &url) {
905 return;
906 }
907
908 let theme = self.resolved_theme();
909 let color = self.resolved_color(&theme);
910 let style = self.resolved_text_style(color);
911 let bounds = ctx.bounds();
912 ctx.push_clip_rect(bounds);
913 paint_single_line_aligned_text(ctx, bounds, &label, &style, style.line_height, 0.0);
914 ctx.pop_clip();
915
916 let measured_width = self
917 .measurement
918 .map(|measurement| measurement.width)
919 .unwrap_or(bounds.width())
920 .min(bounds.width())
921 .max(0.0);
922 if measured_width > 0.0 {
923 let underline_y = bounds.y() + bounds.height() - physical_pixels(ctx, 2.0);
924 let mut underline = PathBuilder::new();
925 underline
926 .move_to(Point::new(bounds.x(), underline_y))
927 .line_to(Point::new(bounds.x() + measured_width, underline_y));
928 ctx.stroke(
929 underline.build(),
930 color,
931 StrokeStyle::new(physical_pixels(ctx, 1.0)),
932 );
933 }
934
935 if ctx.is_focused() && self.is_enabled() {
936 ctx.stroke_rect(
937 bounds.inflate(physical_pixels(ctx, 2.0), physical_pixels(ctx, 1.0)),
938 theme.palette.focus_ring,
939 StrokeStyle::new(physical_pixels(ctx, 1.0)),
940 );
941 }
942 }
943
944 fn semantics(&self, ctx: &mut SemanticsCtx) {
945 let label = self.current_label();
946 let url = self.current_url();
947 if !Self::is_visible_parts(&label, &url) {
948 return;
949 }
950
951 let enabled = self.is_enabled();
952 let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Link, ctx.bounds());
953 node.name = Some(self.semantic_name.clone().unwrap_or(label));
954 node.value = Some(SemanticsValue::Text(url));
955 node.state.focused = ctx.is_focused();
956 node.state.hovered = self.hovered && enabled;
957 node.state.disabled = !enabled;
958 node.actions = if enabled {
959 vec![SemanticsAction::Focus, SemanticsAction::Activate]
960 } else {
961 Vec::new()
962 };
963 ctx.push(node);
964 }
965
966 fn accepts_focus(&self) -> bool {
967 self.is_enabled() && self.is_visible()
968 }
969
970 fn focus_changed(&mut self, ctx: &mut EventCtx, _focused: bool) {
971 ctx.request_paint();
972 ctx.request_semantics();
973 }
974}