1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
use crate::core::{Color, Font, HorizontalAlignment, Point, Rect};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::{GenericSignal, Signal1};
use crate::widget::capability::coercion::{expect_bool, expect_string};
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};
/// Command link widget for command link buttons.
///
/// A two-line button: a title line plus a secondary description, typically used
/// to present a small set of mutually exclusive options (for example in a
/// wizard). The widget renders both strings but does not draw the usual arrow
/// glyph itself.
///
pub struct CommandLink {
base: BaseWidget,
text: String,
description: String,
/// Emitted when command link is clicked.
///
/// Fires from [`CommandLink::click`] and from a completed primary-button
/// click, but only while enabled. Carries no payload.
pub clicked: GenericSignal,
/// Emitted with the new hover flag when the pointer enters or leaves the
/// widget. Not emitted when the pointer moves within the widget.
pub hovered: Signal1<bool>,
}
impl CommandLink {
/// Creates an enabled command link whose title is `"Command"` and whose
/// description is empty, with no hover state.
///
/// `geometry` is in parent-relative logical pixels.
pub fn new(geometry: Rect) -> Self {
Self {
base: BaseWidget::new(WidgetKind::CommandLink, geometry, "CommandLink"),
text: "Command".to_string(),
description: "".to_string(),
clicked: GenericSignal::new(),
hovered: Signal1::new(),
}
}
/// Returns the title line.
pub fn text(&self) -> &str {
&self.text
}
/// Returns the secondary description line; empty when none was set.
pub fn description(&self) -> &str {
&self.description
}
/// Returns whether this widget accepts input.
///
/// Shadows the inherited [`Widget::is_enabled`] with an identical result;
/// both read the same base flag.
pub fn is_enabled(&self) -> bool {
self.base.is_enabled()
}
/// Replaces the title line and requests a redraw. The description is
/// unaffected.
pub fn set_text(&mut self, text: String) {
self.text = text;
self.base.request_redraw();
}
/// Replaces the description line and requests a redraw. An empty string
/// removes the second line.
pub fn set_description(&mut self, description: String) {
self.description = description;
self.base.request_redraw();
}
/// Enables or disables the widget and requests a redraw. A disabled link is
/// still drawn but ignores clicks and does not report hover.
pub fn set_enabled(&mut self, enabled: bool) {
self.base.set_enabled(enabled);
self.base.request_redraw();
}
/// Emits `clicked` if the widget is enabled; a no-op otherwise.
///
/// Takes `&self` because the click carries no state: unlike a button, there
/// is no pressed state to update.
pub fn click(&self) {
if self.base.is_enabled() {
self.clicked.emit();
}
}
}
impl Widget for CommandLink {
fn base(&self) -> &BaseWidget {
&self.base
}
fn base_mut(&mut self) -> &mut BaseWidget {
&mut self.base
}
fn size_hint(&self) -> crate::core::Size {
crate::core::Size::new(300, 40)
}
fn is_enabled(&self) -> bool {
self.base.is_enabled()
}
impl_draw_bridge!();
impl_widget_property_hooks!();
}
/// `CommandLink`'s property contract.
///
/// `enabled` is listed here because `COMMAND_LINK_PROPERTIES` publishes it as a
/// property of this control; it is answered by the control's own accessor and
/// writer, which is the same pair the old arm called.
impl WidgetProperties for CommandLink {
fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
match name {
"text" => Ok(CapabilityValue::String(self.text().to_string())),
"description" => Ok(CapabilityValue::String(self.description().to_string())),
"enabled" => Ok(CapabilityValue::Bool(self.is_enabled())),
_ => base_property_get(self, name),
}
}
fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
match name {
"text" => {
self.set_text(expect_string(value)?);
Ok(())
}
"description" => {
self.set_description(expect_string(value)?);
Ok(())
}
"enabled" => {
self.set_enabled(expect_bool(value)?);
Ok(())
}
_ => base_property_set(self, name, value),
}
}
fn property_names(&self) -> &'static [&'static str] {
// Mirrors `COMMAND_LINK_PROPERTIES`.
property_names_of!["text", "description", "enabled", BASE_PROPERTY_NAMES]
}
/// Runs one of the commands `command_link` publishes.
///
/// `click` is the zero-argument action: it emits `clicked` when the link is
/// enabled and does nothing when it is not, which is exactly what a pointer
/// activation does — so a programmatic click cannot fire a disabled link. It needs
/// no `&mut self`, but the trait's signature supplies one and the borrow does not
/// change the effect. The other three assign state and need a payload, so they are
/// answered through the property route.
fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
match name {
"click" => {
self.click();
Ok(())
}
"set_text" | "set_description" | "set_enabled" => {
Err(CapabilityAccessError::OutOfRange)
}
_ => Err(CapabilityAccessError::UnknownCommand),
}
}
}
impl EventHandler for CommandLink {
fn handle_event(&mut self, event: &Event) {
self.base.handle_event(event);
match event {
Event::MousePress { button: 1, .. } if self.base.is_enabled() => {
self.clicked.emit();
}
Event::MouseEnter { .. } => {
self.hovered.emit(true);
}
Event::MouseLeave { .. } => {
self.hovered.emit(false);
}
_ => { /* Other events are not relevant */ }
}
}
}
impl Draw for CommandLink {
fn draw(&mut self, context: &mut RenderContext) {
let rect = self.geometry();
let style = self.style();
let bg_color = style.background_color.unwrap_or(Color::TRANSPARENT);
let text_color = style.text_color.unwrap_or(Color::rgb(0, 102, 204));
// The hover ink is the theme's `primary`, the hue a theme is expected to vary most.
//
// It used to be a literal `rgb(0, 0, 255)`, applied unconditionally on hover — so the
// themed `text_color` above was thrown away the moment the pointer arrived, and a
// command link was the one control in its group that ignored the appearance in exactly
// the state a user is most likely to be looking at. Deriving it means light and dark
// differ on hover rather than both snapping to the same blue.
let hover_color = crate::style::theme_manager()
.current_theme()
.map(|active| active.colors.primary)
.unwrap_or(text_color);
let disabled_color = Color::GRAY;
let is_hovered = self.base.is_hovered();
let is_enabled = self.base.is_enabled();
// Draw background (transparent by default)
if bg_color != Color::TRANSPARENT {
context.fill_rect(rect, bg_color);
}
// Determine text color based on state
let current_text_color = if !is_enabled {
disabled_color
} else if is_hovered {
hover_color
} else {
text_color
};
// Draw main text
let padding = &style.padding;
let text_font = Font::new("Arial", 12.0, false, true);
let text_x = rect.x + padding.left as i32;
// The two lines are stacked from their **measured** line boxes rather than from the
// literals `+ 12` and `+ 16`. Those constants pinned the layout to one particular font
// size: the label's offset had no relation to its own line height, so a theme or a
// caller passing a larger font moved the description into the label. The label sits in
// the top half of the content box and the description directly below it, each in its own
// measured line, which is the same reading a stacked link has in every toolkit.
let content_top = rect.y + padding.top as i32;
let text_band = Rect {
x: text_x,
y: content_top,
width: rect.width.saturating_sub(padding.left + padding.right),
height: rect.height.saturating_sub(padding.top + padding.bottom),
};
let line = context.text_line(text_band, &text_font);
let text_y = line.y;
context.draw_text_fitted(
line,
&self.text,
&text_font,
current_text_color,
HorizontalAlignment::Left,
);
// Draw description if present
if !self.description.is_empty() {
let desc_font = Font::new("Arial", 10.0, false, false);
// `Color::GRAY` was a literal that never moved with the appearance; the disabled
// ink already follows it, so an enabled description is the same ink damped toward
// whatever the control was actually given to paint on.
let desc_color = if !is_enabled {
disabled_color
} else {
current_text_color.blend(&bg_color, 0.35)
};
let desc_line =
context.text_line(Rect { y: text_y + line.height as i32, ..text_band }, &desc_font);
context.draw_text_fitted(
desc_line,
&self.description,
&desc_font,
desc_color,
HorizontalAlignment::Left,
);
}
// Draw underline for hover state
if is_hovered && is_enabled {
let text_metrics = context.measure_text(&self.text, &text_font);
// The rule sits on the label's own line-box bottom edge, so it tracks the glyphs it
// underlines instead of a second hand-tuned offset.
let underline_y = text_y + line.height as i32;
context.draw_line(
Point::new(text_x, underline_y),
Point::new(text_x + text_metrics.width as i32, underline_y),
current_text_color,
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::{Color, Rect};
use crate::style::WidgetStyle;
#[test]
fn commandlink_creation_defaults() {
let cl = CommandLink::new(Rect::new(0, 0, 300, 60));
assert_eq!(cl.text(), "Command");
assert!(cl.description().is_empty());
assert!(cl.is_enabled());
}
#[test]
fn commandlink_set_text() {
let mut cl = CommandLink::new(Rect::new(0, 0, 300, 60));
cl.set_text("Save".to_string());
assert_eq!(cl.text(), "Save");
}
#[test]
fn commandlink_set_description() {
let mut cl = CommandLink::new(Rect::new(0, 0, 300, 60));
cl.set_description("Save the current document".to_string());
assert_eq!(cl.description(), "Save the current document");
cl.set_description(String::new());
assert!(cl.description().is_empty());
}
#[test]
fn commandlink_set_enabled() {
let mut cl = CommandLink::new(Rect::new(0, 0, 300, 60));
assert!(cl.is_enabled());
cl.set_enabled(false);
assert!(!cl.is_enabled());
cl.set_enabled(true);
assert!(cl.is_enabled());
}
#[test]
fn commandlink_set_enabled_updates_base_state() {
let mut cl = CommandLink::new(Rect::new(0, 0, 300, 60));
assert!(cl.base().is_enabled());
cl.set_enabled(false);
assert!(!cl.base().is_enabled());
cl.set_enabled(true);
assert!(cl.base().is_enabled());
}
#[test]
fn commandlink_click() {
let cl = CommandLink::new(Rect::new(0, 0, 300, 60));
cl.click(); // Should not panic
}
#[test]
fn commandlink_geometry_delegation() {
let mut cl = CommandLink::new(Rect::new(0, 0, 300, 60));
cl.set_geometry(Rect::new(10, 10, 400, 80));
assert_eq!(cl.geometry(), Rect::new(10, 10, 400, 80));
}
#[test]
fn commandlink_visibility() {
let mut cl = CommandLink::new(Rect::new(0, 0, 300, 60));
assert!(cl.is_visible());
cl.hide();
assert!(!cl.is_visible());
cl.show();
assert!(cl.is_visible());
}
#[test]
fn commandlink_tooltip_roundtrip() {
let mut cl = CommandLink::new(Rect::new(0, 0, 300, 60));
assert!(cl.tooltip().is_empty());
cl.set_tooltip("Click here".to_string());
assert_eq!(cl.tooltip(), "Click here");
cl.set_tooltip(String::new());
assert!(cl.tooltip().is_empty());
}
#[test]
fn commandlink_style_roundtrip() {
let mut cl = CommandLink::new(Rect::new(0, 0, 300, 60));
assert_eq!(*cl.style(), WidgetStyle::default());
let custom = WidgetStyle::default().with_background(Color::rgb(240, 240, 240));
cl.set_style(custom.clone());
assert_eq!(*cl.style(), custom);
}
#[test]
fn commandlink_id_kind() {
let cl_a = CommandLink::new(Rect::new(0, 0, 100, 50));
let cl_b = CommandLink::new(Rect::new(0, 0, 100, 50));
assert_ne!(cl_a.id(), cl_b.id());
assert_eq!(cl_a.kind(), WidgetKind::CommandLink);
assert_eq!(cl_b.kind(), WidgetKind::CommandLink);
}
#[test]
fn commandlink_signal_accessors() {
let cl = CommandLink::new(Rect::new(0, 0, 100, 50));
let _clicked = &cl.clicked;
let _hovered = &cl.hovered;
}
/// The hover underline follows the appearance rather than a fixed blue.
///
/// # The defect this pins
///
/// On hover the ink was a literal `rgb(0, 0, 255)`, applied unconditionally to the label
/// **and** to the underline. The themed `text_color` the control had just resolved was
/// therefore discarded in the one state a user is most likely to be looking at, so a light
/// and a dark build drew the same blue under a link whose resting ink differed.
///
/// # Why the underline, and not the whole document
///
/// A first instinct is to compare the two documents wholesale, but a document-wide
/// comparison is satisfied by any colour that differs — including ones this test is not
/// about. The hover underline is emitted as a single `<line ... stroke="rgba(...)" />`,
/// which names the exact element the fix moved, so that is what the assertion reads.
#[test]
#[cfg(feature = "desktop")]
fn the_hover_ink_follows_the_appearance() {
let _guard = crate::style::theme_test_guard();
crate::widget::census::install_preset_appearances();
let rect = Rect::new(0, 0, 300, 60);
let hover_stroke = |appearance| -> String {
crate::theme::global_theme_manager().set_appearance(appearance);
let mut cl = CommandLink::new(rect);
cl.set_text("Open".to_string());
// The `MouseEnter` the base records is what puts the control in its hover state, so
// the underline is drawn at all.
cl.handle_event(&Event::MouseEnter { pos: Point::new(1, 1) });
crate::theme::apply_theme_to_widget(&mut cl);
let svg = crate::widget::svg::render_widget_to_svg(&mut cl, rect);
underline_stroke(&svg).unwrap_or_else(|| {
panic!("a hovered command link must underline itself; svg was {svg}")
})
};
let dark = hover_stroke(crate::theme::AppearanceMode::Dark);
let light = hover_stroke(crate::theme::AppearanceMode::Light);
assert_ne!(dark, light, "the hover ink must follow the appearance; both were {dark}");
assert_ne!(
dark, "rgba(0,0,255,255)",
"the hover ink must not be the fixed blue the defect used"
);
}
/// The `stroke` of the SVG `<line>` element, if the document has one.
#[cfg(feature = "desktop")]
fn underline_stroke(svg: &str) -> Option<String> {
let at = svg.find("<line ")?;
let rest = &svg[at..];
let end = rest.find("/>")? + 2;
let element = &rest[..end];
let key = "stroke=\"";
let from = element.find(key)? + key.len();
let to = element[from..].find('"')? + from;
Some(element[from..to].to_string())
}
}