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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! Common widget contract implemented by all widget models.
use super::{BaseWidget, WidgetKind};
use crate::core::{Color, Font, ObjectId, Point, Rect, Size};
use crate::event::EventHandler;
use crate::platform::accessibility::AccessibleRole;
use crate::signal::{ConnectionScope, GenericSignal, Signal1};
use crate::style::css::CssParser;
use crate::style::{Margin, Padding, WidgetStyle};
use std::any::Any;
/// Common widget contract implemented by all widget models.
pub trait Widget: EventHandler + Any {
/// Returns shared base widget state for default trait delegation.
///
/// Every concrete widget must override this method (all 167 kinds do). The
/// default panics instead of silently returning a fake state, so a widget
/// that forgets the override fails loudly on first use rather than corrupting
/// geometry/visibility bookkeeping.
#[track_caller]
fn base(&self) -> &BaseWidget {
panic!("Widget::base() not implemented — override in {}", std::any::type_name::<Self>());
}
/// Returns mutable base widget state for default trait delegation.
///
/// See [`Widget::base`]; every concrete widget overrides this method.
#[track_caller]
fn base_mut(&mut self) -> &mut BaseWidget {
panic!(
"Widget::base_mut() not implemented — override in {}",
std::any::type_name::<Self>()
);
}
/// Get stable widget id.
fn id(&self) -> ObjectId {
self.base().id()
}
/// Get widget runtime kind.
fn kind(&self) -> WidgetKind {
self.base().kind()
}
fn geometry(&self) -> Rect {
self.base().geometry()
}
fn set_geometry(&mut self, geometry: Rect) {
self.base_mut().set_geometry(geometry);
}
#[deprecated(since = "0.1.0", note = "Use `geometry()` instead.")]
fn rect(&self) -> Rect {
self.geometry()
}
#[deprecated(since = "0.1.0", note = "Use `set_geometry()` instead.")]
fn set_rect(&mut self, rect: Rect) {
self.set_geometry(rect);
}
/// Returns widget position from its geometry origin.
fn position(&self) -> Point {
self.geometry().position()
}
/// Returns widget size from its geometry extent.
fn size(&self) -> Size {
self.geometry().size()
}
/// Updates widget position while preserving size.
fn set_position(&mut self, position: Point) {
self.set_geometry(Rect::from_position_size(position, self.size()));
}
/// Updates widget size while preserving position.
fn set_size(&mut self, size: Size) {
self.set_geometry(Rect::from_position_size(self.position(), size));
}
/// Returns minimum size constraint when configured.
fn min_size(&self) -> Option<Size> {
self.base().min_size()
}
/// Returns maximum size constraint when configured.
fn max_size(&self) -> Option<Size> {
self.base().max_size()
}
/// Sets minimum size constraint.
fn set_min_size(&mut self, min_size: Option<Size>) {
self.base_mut().set_min_size(min_size);
}
/// Sets maximum size constraint.
fn set_max_size(&mut self, max_size: Option<Size>) {
self.base_mut().set_max_size(max_size);
}
fn parent(&self) -> Option<ObjectId> {
self.base().parent()
}
fn set_parent(&mut self, parent: Option<ObjectId>) {
self.base_mut().set_parent(parent);
}
fn add_child(&mut self, child: ObjectId) {
self.base_mut().add_child(child);
}
fn remove_child(&mut self, child: ObjectId) {
self.base_mut().remove_child(child);
}
fn children(&self) -> &[ObjectId] {
self.base().children()
}
/// Show widget.
fn show(&mut self) {
self.base_mut().show();
}
/// Hide widget.
fn hide(&mut self) {
self.base_mut().hide();
}
fn is_visible(&self) -> bool {
self.base().is_visible()
}
fn set_visible(&mut self, visible: bool) {
if visible {
self.show();
} else {
self.hide();
}
}
fn set_enabled(&mut self, enabled: bool) {
self.base_mut().set_enabled(enabled);
}
fn is_enabled(&self) -> bool {
self.base().is_enabled()
}
fn set_tooltip(&mut self, tooltip: String) {
self.base_mut().set_tooltip(crate::compat::mini_string_from(tooltip));
}
fn tooltip(&self) -> &str {
self.base().tooltip()
}
/// Returns a human-readable accessibility name used by assistive technologies.
///
/// Default behavior prefers tooltip text when present, then falls back to the
/// widget kind so every widget has a stable non-empty label.
fn accessible_name(&self) -> String {
let tooltip = self.tooltip().trim();
if tooltip.is_empty() {
format!("{:?}", self.kind())
} else {
tooltip.to_string()
}
}
/// Returns the semantic accessibility role for this widget.
fn accessible_role(&self) -> AccessibleRole {
AccessibleRole::from(self.kind())
}
/// Returns a short accessibility description with current visibility/enabled state.
fn accessible_description(&self) -> String {
let mut state_flags: Vec<&str> = Vec::new();
if !self.is_enabled() {
state_flags.push("disabled");
}
if !self.is_visible() {
state_flags.push("hidden");
}
if state_flags.is_empty() {
format!("{:?}", self.accessible_role())
} else {
format!("{:?} ({})", self.accessible_role(), state_flags.join(", "))
}
}
fn dpi_scale(&self) -> f32 {
self.base().dpi_scale()
}
/// Returns this widget as a [`Draw`] implementor, when it paints itself.
///
/// # Why this exists
///
/// [`Widget`] does not require [`Draw`], because many widgets delegate to a
/// real OS control. But the rendering pipeline holds widgets as
/// `&mut dyn Widget` and still needs to ask "can *you* paint yourself?".
/// Without this bridge the only way to reach `Draw::draw` was a concrete
/// generic bound (`W: Draw + Widget`), which no `Box<dyn Widget>` satisfies —
/// so self-drawn widgets could never be painted generically, and mounting
/// one into a native window produced an empty surface.
///
/// # Contract
///
/// Return `Some(self)` from every widget that implements [`Draw`]. The
/// default returns `None`, which is the honest answer for OS-backed widgets
/// and keeps existing implementors compiling unchanged.
///
/// ```
/// use rust_widgets::core::Rect;
/// use rust_widgets::render::RenderContext;
/// use rust_widgets::widget::special_widgets::code_editor::CodeEditor;
/// use rust_widgets::widget::{Draw, Widget};
///
/// let mut editor = CodeEditor::new(Rect::new(0, 0, 100, 50));
/// assert!(editor.as_draw_mut().is_some());
///
/// let widget: &mut dyn Widget = &mut editor;
/// assert!(widget.as_draw_mut().is_some());
/// ```
fn as_draw_mut(&mut self) -> Option<&mut dyn crate::widget::Draw> {
None
}
fn set_dpi_scale(&mut self, scale: f32) {
self.base_mut().set_dpi_scale(scale);
}
fn set_translated_tooltip(&mut self, key: &str) {
self.base_mut().set_translated_tooltip(key);
}
fn style(&self) -> &WidgetStyle {
self.base().style()
}
fn set_style(&mut self, style: WidgetStyle) {
self.base_mut().set_style(style);
}
/// Returns optional background color shorthand.
fn background_color(&self) -> Option<Color> {
self.style().background_color
}
/// Sets optional background color shorthand.
fn set_background_color(&mut self, color: Option<Color>) {
self.base_mut().style_mut().background_color = color;
}
/// Returns optional foreground (text) color shorthand.
fn foreground_color(&self) -> Option<Color> {
self.style().text_color
}
/// Sets optional foreground (text) color shorthand.
fn set_foreground_color(&mut self, color: Option<Color>) {
self.base_mut().style_mut().text_color = color;
}
/// Returns optional font shorthand.
fn font(&self) -> Option<&Font> {
self.style().font.as_ref()
}
/// Sets optional font shorthand.
fn set_font(&mut self, font: Option<Font>) {
self.base_mut().style_mut().font = font;
}
/// Returns optional border color shorthand.
fn border_color(&self) -> Option<Color> {
self.style().border_color
}
/// Returns border width shorthand.
fn border_width(&self) -> Option<u32> {
self.style().border_width
}
/// Returns border radius shorthand.
fn border_radius(&self) -> Option<u32> {
self.style().border_radius
}
/// Sets optional border color shorthand.
fn set_border_color(&mut self, color: Option<Color>) {
self.base_mut().style_mut().border_color = color;
}
/// Sets border width shorthand.
fn set_border_width(&mut self, width: u32) {
self.base_mut().style_mut().border_width = Some(width);
}
/// Sets border radius shorthand.
fn set_border_radius(&mut self, radius: u32) {
self.base_mut().style_mut().border_radius = Some(radius);
}
/// Sets border shorthand in one call.
fn set_border(&mut self, color: Option<Color>, width: u32, radius: u32) {
let mut style = self.style().clone();
style.border_color = color;
style.border_width = Some(width);
style.border_radius = Some(radius);
self.set_style(style);
}
/// Returns current per-side content padding.
fn padding(&self) -> &Padding {
&self.style().padding
}
/// Returns current per-side outer margin.
fn margin(&self) -> &Margin {
&self.style().margin
}
/// Updates widget content padding while preserving other style properties.
fn set_padding(&mut self, padding: Padding) {
self.base_mut().style_mut().padding = padding;
}
/// Updates widget margin while preserving other style properties.
fn set_margin(&mut self, margin: Margin) {
self.base_mut().style_mut().margin = margin;
}
/// Returns connection scope used to auto-disconnect slots when widget drops.
fn connection_scope(&self) -> &ConnectionScope {
self.base().connection_scope()
}
/// Optional clicked signal (legacy API compatibility).
fn clicked_signal(&self) -> &GenericSignal {
&self.base().clicked
}
/// Optional changed signal (legacy API compatibility).
/// Emitted when a stateful value changes (e.g., slider value, checkbox state,
/// line edit text). Concrete widgets with changeable state should wire their
/// own value-change emission to `self.base_mut().changed.emit()`.
fn changed_signal(&self) -> &GenericSignal {
&self.base().changed
}
/// Emits on hover/move interactions while pointer is over widget.
fn hover_signal(&self) -> &Signal1<Point> {
self.base().hover_signal()
}
/// Emits on mouse/pointer press interactions.
fn mouse_down_signal(&self) -> &Signal1<(Point, u32)> {
self.base().mouse_down_signal()
}
/// Emits on mouse/pointer release interactions.
fn mouse_up_signal(&self) -> &Signal1<(Point, u32)> {
self.base().mouse_up_signal()
}
/// Emits on keyboard press interactions.
fn key_down_signal(&self) -> &Signal1<(u32, u32)> {
self.base().key_down_signal()
}
/// Emits on keyboard release interactions.
fn key_up_signal(&self) -> &Signal1<(u32, u32)> {
self.base().key_up_signal()
}
/// Emits when logical focus is gained.
fn focus_gained_signal(&self) -> &GenericSignal {
self.base().focus_gained_signal()
}
/// Emits when logical focus is lost.
fn focus_lost_signal(&self) -> &GenericSignal {
self.base().focus_lost_signal()
}
/// Emits when redraw is requested.
fn redraw_requested_signal(&self) -> &GenericSignal {
self.base().redraw_requested_signal()
}
/// Emits when layout pass is requested.
fn layout_requested_signal(&self) -> &GenericSignal {
self.base().layout_requested_signal()
}
/// Requests redraw and emits redraw signal.
fn request_redraw(&self) {
self.redraw_requested_signal().emit();
}
/// Requests layout and emits layout signal.
fn request_layout(&self) {
self.layout_requested_signal().emit();
}
/// Returns the preferred size hint for layout calculations.
///
/// The default implementation returns `Size::new(0, 0)` (unknown/unconstrained).
/// Widgets should override this to provide meaningful content-based size hints
/// so that layout containers can properly allocate space.
fn size_hint(&self) -> Size {
Size::new(0, 0)
}
/// Apply CSS styles to this widget. The `css` text is parsed and rules matching
/// the widget's kind and optional class/id are applied to the widget's style.
fn apply_css(&mut self, css: &str, class: Option<&str>) -> Result<(), String> {
let kind_str = format!("{:?}", self.kind());
let mut style = self.style().clone();
CssParser::parse_and_apply(css, &kind_str, class, None, None, &mut style)?;
self.set_style(style);
Ok(())
}
/// Checks whether the given point falls within this widget's interactive area.
///
/// By default, this respects the touch-target expansion set via
/// `WidgetStyle::with_touch_target()`, so that small widgets remain
/// easily tappable on touch devices.
fn contains_point(&self, point: Point) -> bool {
self.base().contains_point_with_touch_expansion(point)
}
}
#[cfg(test)]
mod tests {
use super::Widget;
use crate::core::Rect;
use crate::widget::base_widgets::button::Button;
#[test]
fn widget_accessible_name_uses_tooltip_when_present() {
let mut button = Button::new("Open".to_string(), Rect::new(0, 0, 100, 32));
assert_eq!(button.accessible_name(), "Button");
button.set_tooltip("Open file".to_string());
assert_eq!(button.accessible_name(), "Open file");
}
#[test]
fn widget_accessible_description_reflects_state_flags() {
let mut button = Button::new("Open".to_string(), Rect::new(0, 0, 100, 32));
assert_eq!(button.accessible_description(), "Button");
button.set_enabled(false);
button.hide();
assert_eq!(button.accessible_description(), "Button (disabled, hidden)");
}
#[test]
fn widget_structure_button_exposes_expected_kind_and_geometry() {
let button = Button::new("Run".to_string(), Rect::new(10, 20, 120, 36));
assert_eq!(button.kind(), crate::widget::WidgetKind::Button);
assert_eq!(button.geometry(), Rect::new(10, 20, 120, 36));
}
#[test]
fn widget_structure_button_has_distinct_object_ids() {
let a = Button::new("A".to_string(), Rect::new(0, 0, 80, 24));
let b = Button::new("B".to_string(), Rect::new(0, 0, 80, 24));
assert_ne!(a.id(), b.id());
}
}