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