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