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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! EmptyState widget — a placeholder shown when a view has no content.
//!
//! The EmptyState widget displays a large icon (emoji/symbol), title, descriptive
//! message, and an optional action button. It is commonly used in list views,
//! search results, inboxes, and dashboards to communicate "no data" states
//! rather than showing a blank screen.
use crate::core::{Color, Font, HorizontalAlignment, Point, Rect};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::GenericSignal;
use crate::widget::capability::coercion::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};
/// Fallback icon used when no icon has been explicitly set.
const DEFAULT_EMPTY_ICON: &str = "📭";
/// Default empty title text.
const DEFAULT_TITLE: &str = "Nothing here";
/// Default empty message text.
const DEFAULT_MESSAGE: &str = "There are no items to display yet.";
/// Height of bottom action button area.
const ACTION_BUTTON_HEIGHT: u32 = 36;
/// Padding between layout sections.
const SECTION_GAP: i32 = 12;
/// EmptyState widget — a placeholder shown when a view has no content.
///
/// Displays a centered layout consisting of a large icon, a title label,
/// a descriptive message, and an optional action button. The action button
/// is only drawn when `action_text` is non-empty, and emits `action_pressed`
/// when clicked.
pub struct EmptyState {
base: BaseWidget,
icon: String,
title: String,
message: String,
action_text: String,
/// Emitted when the action button is clicked.
pub action_pressed: GenericSignal,
}
impl EmptyState {
/// Creates a new EmptyState widget with the given geometry.
///
/// The widget is initialized with default placeholder values:
/// - Icon: 📭 (empty mailbox)
/// - Title: "Nothing here"
/// - Message: "There are no items to display yet."
/// - Action text: empty (no action button shown)
pub fn new(geometry: Rect) -> Self {
Self {
base: BaseWidget::new(WidgetKind::EmptyState, geometry, "EmptyState"),
icon: DEFAULT_EMPTY_ICON.to_string(),
title: DEFAULT_TITLE.to_string(),
message: DEFAULT_MESSAGE.to_string(),
action_text: String::new(),
action_pressed: GenericSignal::new(),
}
}
/// Sets the icon displayed at the top of the empty state.
///
/// This is typically an emoji or a short symbol string (1–2 characters).
pub fn set_icon(&mut self, icon: &str) {
self.icon = icon.to_string();
self.base.request_redraw();
}
/// Returns the current icon string.
pub fn icon(&self) -> &str {
&self.icon
}
/// Sets the title text displayed below the icon.
pub fn set_title(&mut self, title: &str) {
self.title = title.to_string();
self.base.request_redraw();
}
/// Returns the current title text.
pub fn title(&self) -> &str {
&self.title
}
/// Sets the descriptive message displayed below the title.
pub fn set_message(&mut self, message: &str) {
self.message = message.to_string();
self.base.request_redraw();
}
/// Returns the current message text.
pub fn message(&self) -> &str {
&self.message
}
/// Sets the action button label text.
///
/// When set to a non-empty string, an action button is rendered at the
/// bottom of the empty state. Clicking the button emits `action_pressed`.
/// When set to an empty string, the action button is hidden.
pub fn set_action_text(&mut self, action_text: &str) {
self.action_text = action_text.to_string();
self.base.request_redraw();
}
/// Returns the current action button label text.
pub fn action_text(&self) -> &str {
&self.action_text
}
/// Returns `true` if the action button is visible (non-empty text).
pub fn has_action(&self) -> bool {
!self.action_text.is_empty()
}
/// Returns the descriptive message shown below the title.
///
/// The `description` property reads this rather than [`EmptyState::message`]
/// because the schema publishes `message` as the widget's title line and
/// `description` as the explanatory sentence below it.
pub fn description(&self) -> &str {
&self.message
}
/// Sets the descriptive message shown below the title.
///
/// The `description` property writes through here, mirroring
/// [`EmptyState::set_message`].
pub fn set_description(&mut self, description: &str) {
self.set_message(description);
}
/// Computes the rectangle for the action button, if it is visible.
fn action_button_rect(&self) -> Option<Rect> {
if !self.has_action() {
return None;
}
let rect = self.geometry();
let btn_width = rect.width.clamp(80, 200);
let btn_x = rect.x + (rect.width as i32 - btn_width as i32) / 2;
let btn_y = rect.y + rect.height as i32 - ACTION_BUTTON_HEIGHT as i32 - SECTION_GAP;
Some(Rect::new(btn_x, btn_y, btn_width, ACTION_BUTTON_HEIGHT))
}
}
impl Widget for EmptyState {
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, 200)
}
impl_draw_bridge!();
impl_widget_property_hooks!();
}
/// `EmptyState`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_other.in.rs` / `access_write_other.in.rs` dispatch, so callers see
/// the same coercions and the same errors as before. The legacy dispatch served
/// `message` / `description` for another `WidgetKind` entirely, so neither name was
/// ever routed here; both are now backed by this control's real state, with
/// `message` mapped to the title line and `description` to the sentence beneath it.
impl WidgetProperties for EmptyState {
fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
match name {
"message" => Ok(CapabilityValue::String(self.title().to_string())),
"description" => Ok(CapabilityValue::String(self.description().to_string())),
_ => base_property_get(self, name),
}
}
fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
match name {
"message" => {
self.set_title(&expect_string(value)?);
Ok(())
}
"description" => {
self.set_description(&expect_string(value)?);
Ok(())
}
_ => base_property_set(self, name, value),
}
}
fn property_names(&self) -> &'static [&'static str] {
property_names_of!["message", "description", BASE_PROPERTY_NAMES]
}
}
impl Draw for EmptyState {
fn draw(&mut self, context: &mut RenderContext) {
let rect = self.geometry();
let is_enabled = self.base.is_enabled();
// Chrome colours resolve explicit style first, then the theme's resolved style
// for this control, and only then fall back to a literal. Without the theme step
// a light/dark switch would change nothing on screen, because the surface and
// every piece of text on it were previously hardcoded.
//
// The theme read is a separate manager lock, taken and released inside
// `resolved_theme_style`, so it is not held across the draw — the global
// manager's mutex is not re-entrant.
let style = self.base.style().clone();
let theme = crate::style::resolved_theme_style("empty_state");
let surface = style
.background_color
.or_else(|| theme.as_ref().and_then(|t| t.background_color))
.unwrap_or(Color::rgba(245, 245, 250, 200));
let ink = style
.text_color
.or_else(|| theme.as_ref().and_then(|t| t.text_color))
.unwrap_or(Color::BLACK);
// The call to action is an accented affordance on this surface: derived by
// tinting the resolved ink back toward the surface, so it stays a distinct
// button in either appearance.
let action_fill = ink.blend(&surface, 0.35);
// ── Background ──
context.fill_rect(rect, surface);
let center_x = rect.x + rect.width as i32 / 2;
// Rows are addressed by the **top edge of their glyph box**, which is what the
// renderer's `origin.y` means (see `RenderContext::draw_text`). The original helper
// took a `y` and used it as the box's top while its own doc-comment called it "a given
// Y baseline", and the two conventions were then mixed in the same stack: the icon was
// passed `icon_y + icon_size` while the title was passed `icon_y + icon_size + gap`,
// i.e. 12 px below the icon's *bottom* under one reading and 28 px inside its 48 px box
// under the other. `snapshots/svg/empty_state.svg` showed the \"Sample\" caption painted
// across the mailbox glyph because of it. One convention, stated once, is the fix.
let draw_centered =
|ctx: &mut RenderContext, top_y: i32, text: &str, font: &Font, color: Color| {
let metrics = ctx.measure_text(text, font);
let origin = Point::new(center_x - (metrics.width as i32 / 2), top_y);
ctx.draw_text(origin, text, font, color, HorizontalAlignment::Left);
};
// ── Icon ──
//
// The stack is centred as a whole rather than started from a fixed top gap. The
// fixed gap made the content taller than the control at the sizes a control is
// actually given (48 + 20 + 14 + button against a 120 px box), so the message ran
// past the bottom edge and the action button overlapped it. Centring means a tall
// empty state fills the box and a short one sits in the middle, and it is the
// layout the control's name implies.
let icon_size: i32 = 48;
let title_font_size: i32 = 20;
let message_font_size: i32 = 14;
// One line box, measured through the renderer rather than assumed from the font
// size, is the unit every row below is placed with. A row's *pitch* is that box
// plus the inter-row gap; the header's contribution to the stack is the icon box
// and the title box in sequence, so the message's rows begin below both.
let title_font = Font::with_weight("Sans", title_font_size as f32, 600, false);
let icon_font = Font::with_weight("Sans", icon_size as f32, 400, false);
let message_font = Font::with_weight("Sans", message_font_size as f32, 400, false);
let icon_height = context.measure_text("M", &icon_font).height.max(1) as i32;
let title_height = context.measure_text("M", &title_font).height.max(1) as i32;
let line_height = context.measure_text("M", &message_font).height.max(1) as i32;
let line_step = line_height + 4;
// The message band is what is left of the box after the icon and the title have
// taken their rows and their two gaps — derived from the same three heights the
// draws below use, so the band and the rows cannot disagree.
let message_top_offset = icon_height + SECTION_GAP + title_height + 6;
let message_band = (rect.height as i32 - message_top_offset).max(0);
// `1 + (band - line_height) / step` is the number of whole lines that fit when the
// first one consumes `line_height` and each subsequent one `line_step`.
let message_line_capacity = (1 + (message_band - line_height) / line_step).max(0) as usize;
let action_extra =
if self.action_text.is_empty() { 0 } else { ACTION_BUTTON_HEIGHT as i32 + SECTION_GAP };
// The stack is measured from the band the message may use, so
// `icon_height + gap + title_height + 6 + the centred band` is exactly the control's
// height. A tall box therefore fills it, while a short one starts its first row
// inside the frame via the `max(rect.y)` floor below.
let stack_height = message_top_offset + message_band.max(line_height) + action_extra;
// `(rect.height - stack_height) / 2` is negative for a short box, which pushes the
// stack above the top edge; `max(rect.y)` keeps the first row inside instead.
let icon_y = (rect.y + (rect.height as i32 - stack_height) / 2).max(rect.y);
// The icon is the palest ink on the surface; disabled fades it further.
let icon_color =
if is_enabled { ink.blend(&surface, 0.35) } else { ink.blend(&surface, 0.75) };
draw_centered(context, icon_y, &self.icon, &icon_font, icon_color);
// ── Title ──
// One gap below the icon's *box*, which is `icon_y + icon_height` — the same sum the
// stack height above was built from, so the drawn title and the reserved space agree.
let title_y = icon_y + icon_height + SECTION_GAP;
let title_color = if is_enabled { ink } else { ink.blend(&surface, 0.65) };
let title_metrics = context.measure_text(&self.title, &title_font);
let title_origin = Point::new(center_x - (title_metrics.width as i32 / 2), title_y);
context.draw_text(
title_origin,
&self.title,
&title_font,
title_color,
HorizontalAlignment::Left,
);
// ── Message ──
let message_y = title_y + title_height + 6;
// The message is the title's ink, one step closer to the surface.
let message_color =
if is_enabled { ink.blend(&surface, 0.25) } else { ink.blend(&surface, 0.7) };
// Wrap message text if it's wider than the available width, then draw only the
// lines the band can hold. The wrap itself was never the defect — the message was
// being *drawn* one step past its last measured row — so the fix is the capacity
// above plus this explicit stop, which keeps the block inside the control on a
// short box and leaves the normal case unchanged.
let available_width = rect.width.max(50) - 20;
let wrapped_lines =
wrap_text(context, &self.message, &message_font, available_width as usize);
for (i, line) in wrapped_lines.iter().enumerate() {
if i >= message_line_capacity {
break;
}
let line_y = message_y + i as i32 * line_step;
let line_metrics = context.measure_text(line, &message_font);
let line_origin = Point::new(center_x - (line_metrics.width as i32 / 2), line_y);
context.draw_text(
line_origin,
line,
&message_font,
message_color,
HorizontalAlignment::Left,
);
}
// ── Action Button ──
if let Some(btn_rect) = self.action_button_rect() {
let corner_radius = btn_rect.height / 2;
// Button background
let btn_bg = if !is_enabled { ink.blend(&surface, 0.8) } else { action_fill };
context.fill_rounded_rect(btn_rect, corner_radius, btn_bg);
// Button text
let btn_text_color =
if !is_enabled { ink.blend(&surface, 0.6) } else { btn_bg.contrast_color() };
let btn_font = Font::with_weight("Sans", 14.0, 600, false);
// Horizontal centring is measured; vertical centring comes from the shared line
// box. The previous `btn_rect.y + btn_rect.height / 2` put the glyph box's top edge
// on the button's middle line and drew the label half a line low.
let btn_metrics = context.measure_text(&self.action_text, &btn_font);
let btn_line = context.text_line(btn_rect, &btn_font);
let btn_origin = Point::new(
btn_rect.x + (btn_rect.width as i32 - btn_metrics.width as i32) / 2,
btn_line.y,
);
context.draw_text(
btn_origin,
&self.action_text,
&btn_font,
btn_text_color,
HorizontalAlignment::Left,
);
}
}
}
impl EventHandler for EmptyState {
fn handle_event(&mut self, event: &Event) {
if !self.base.is_enabled() {
return;
}
match event {
Event::MousePress { pos, button } => {
if *button == 1 {
// Check if the click is on the action button
if let Some(btn_rect) = self.action_button_rect() {
if btn_rect.contains_point(*pos) {
self.action_pressed.emit();
return;
}
}
// Click on empty state body (outside action button)
if self.geometry().contains_point(*pos) {
self.base.clicked.emit();
}
}
}
Event::MouseRelease { pos: _, button } => {
if *button == 1 {
// No special handling needed
}
}
_ => {
self.base.handle_event(event);
}
}
}
}
/// Wraps a text string into multiple lines at word boundaries to fit within
/// `max_width` pixels. Returns a vector of wrapped line strings.
fn wrap_text(context: &RenderContext, text: &str, font: &Font, max_width: usize) -> Vec<String> {
if text.is_empty() {
return vec![String::new()];
}
let words: Vec<&str> = text.split(' ').collect();
let mut lines: Vec<String> = Vec::new();
let mut current_line = String::new();
for word in words {
let candidate = if current_line.is_empty() {
word.to_string()
} else {
format!("{current_line} {word}")
};
let metrics = context.measure_text(&candidate, font);
if metrics.width as usize <= max_width || current_line.is_empty() {
current_line = candidate;
} else {
lines.push(current_line);
current_line = word.to_string();
}
}
if !current_line.is_empty() {
lines.push(current_line);
}
if lines.is_empty() {
lines.push(String::new());
}
lines
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::{Font, Size};
use std::sync::{Arc, Mutex};
#[test]
fn empty_state_default_creation() {
let es = EmptyState::new(Rect::new(0, 0, 300, 200));
assert_eq!(es.icon(), "📭");
assert_eq!(es.title(), "Nothing here");
assert_eq!(es.message(), "There are no items to display yet.");
assert_eq!(es.action_text(), "");
assert!(!es.has_action());
assert_eq!(es.kind(), WidgetKind::EmptyState);
}
#[test]
fn empty_state_set_icon() {
let mut es = EmptyState::new(Rect::new(0, 0, 300, 200));
es.set_icon("🔍");
assert_eq!(es.icon(), "🔍");
es.set_icon("📦");
assert_eq!(es.icon(), "📦");
}
#[test]
fn empty_state_set_title() {
let mut es = EmptyState::new(Rect::new(0, 0, 300, 200));
assert_eq!(es.title(), "Nothing here");
es.set_title("No results found");
assert_eq!(es.title(), "No results found");
es.set_title("");
assert_eq!(es.title(), "");
}
#[test]
fn empty_state_set_message() {
let mut es = EmptyState::new(Rect::new(0, 0, 300, 200));
es.set_message("Your search did not match any items.");
assert_eq!(es.message(), "Your search did not match any items.");
}
#[test]
fn empty_state_set_action_text() {
let mut es = EmptyState::new(Rect::new(0, 0, 300, 200));
assert_eq!(es.action_text(), "");
assert!(!es.has_action());
es.set_action_text("Retry");
assert_eq!(es.action_text(), "Retry");
assert!(es.has_action());
es.set_action_text("");
assert_eq!(es.action_text(), "");
assert!(!es.has_action());
}
#[test]
fn empty_state_action_button_rect_none_when_no_action() {
let es = EmptyState::new(Rect::new(0, 0, 300, 200));
assert!(es.action_button_rect().is_none());
}
#[test]
fn empty_state_action_button_rect_some_when_action() {
let mut es = EmptyState::new(Rect::new(0, 0, 300, 200));
es.set_action_text("Refresh");
let btn_rect = es.action_button_rect();
assert!(btn_rect.is_some());
let rect = btn_rect.unwrap();
// Button should be within the widget bounds
assert!(rect.width <= 200);
assert_eq!(rect.height, 36);
}
#[test]
fn empty_state_action_pressed_signal() {
let mut es = EmptyState::new(Rect::new(0, 0, 300, 200));
es.set_action_text("Retry");
let fired = Arc::new(Mutex::new(false));
es.action_pressed.connect({
let fired = Arc::clone(&fired);
move || {
*fired.lock().unwrap() = true;
}
});
// Compute action button rect and click on it
let btn_rect = es.action_button_rect().unwrap();
let click_x = btn_rect.x + btn_rect.width as i32 / 2;
let click_y = btn_rect.y + btn_rect.height as i32 / 2;
es.handle_event(&Event::mouse_press(click_x, click_y, 1));
assert!(*fired.lock().unwrap());
}
#[test]
fn empty_state_action_pressed_not_emitted_when_no_action() {
let mut es = EmptyState::new(Rect::new(0, 0, 300, 200));
// No action text set
let fired = Arc::new(Mutex::new(false));
es.action_pressed.connect({
let fired = Arc::clone(&fired);
move || {
*fired.lock().unwrap() = true;
}
});
// Click somewhere in the middle of the widget
es.handle_event(&Event::mouse_press(150, 100, 1));
assert!(!*fired.lock().unwrap());
}
#[test]
fn empty_state_click_outside_action_emits_base_clicked() {
let mut es = EmptyState::new(Rect::new(0, 0, 300, 200));
es.set_action_text("Go");
let base_clicked = Arc::new(Mutex::new(false));
es.base.clicked.connect({
let base_clicked = Arc::clone(&base_clicked);
move || {
*base_clicked.lock().unwrap() = true;
}
});
let action_fired = Arc::new(Mutex::new(false));
es.action_pressed.connect({
let action_fired = Arc::clone(&action_fired);
move || {
*action_fired.lock().unwrap() = true;
}
});
// Click in the upper icon area (not on action button)
es.handle_event(&Event::mouse_press(150, 30, 1));
assert!(!*action_fired.lock().unwrap());
assert!(*base_clicked.lock().unwrap());
}
#[test]
fn empty_state_disabled_blocks_events() {
let mut es = EmptyState::new(Rect::new(0, 0, 300, 200));
es.set_action_text("Press Me");
es.set_enabled(false);
let action_fired = Arc::new(Mutex::new(false));
es.action_pressed.connect({
let action_fired = Arc::clone(&action_fired);
move || {
*action_fired.lock().unwrap() = true;
}
});
let btn_rect = es.action_button_rect().unwrap();
let click_x = btn_rect.x + btn_rect.width as i32 / 2;
let click_y = btn_rect.y + btn_rect.height as i32 / 2;
es.handle_event(&Event::mouse_press(click_x, click_y, 1));
assert!(!*action_fired.lock().unwrap());
}
#[test]
fn empty_state_svg_output() {
let mut es = EmptyState::new(Rect::new(0, 0, 300, 200));
es.set_icon("📦");
es.set_title("No items");
es.set_message("Your list is empty.");
es.set_action_text("Add Item");
let svg = crate::widget::svg::render_to_svg(&mut es);
assert!(svg.starts_with("<svg"));
assert!(svg.contains("width=\"300\""));
assert!(svg.contains("height=\"200\""));
assert!(svg.ends_with("</svg>"));
}
#[test]
fn empty_state_setters_chain() {
let mut es = EmptyState::new(Rect::new(0, 0, 400, 250));
es.set_icon("⭐");
es.set_title("Not found");
es.set_message("Try adjusting your filters.");
es.set_action_text("Clear Filters");
assert_eq!(es.icon(), "⭐");
assert_eq!(es.title(), "Not found");
assert_eq!(es.message(), "Try adjusting your filters.");
assert_eq!(es.action_text(), "Clear Filters");
}
#[test]
fn empty_state_right_mouse_button_ignored() {
let mut es = EmptyState::new(Rect::new(0, 0, 300, 200));
es.set_action_text("Click");
let action_fired = Arc::new(Mutex::new(false));
es.action_pressed.connect({
let action_fired = Arc::clone(&action_fired);
move || {
*action_fired.lock().unwrap() = true;
}
});
// Right click should be ignored
let btn_rect = es.action_button_rect().unwrap();
es.handle_event(&Event::mouse_press(
btn_rect.x + btn_rect.width as i32 / 2,
btn_rect.y + btn_rect.height as i32 / 2,
2,
));
assert!(!*action_fired.lock().unwrap());
}
#[test]
fn empty_state_kind() {
let es = EmptyState::new(Rect::new(0, 0, 200, 150));
assert_eq!(es.kind(), WidgetKind::EmptyState);
}
/// Parses the **text runs** out of a rendered SVG, one ink box per `<path>`.
///
/// # Why the ink box and not the string
///
/// The backend no longer emits a `<text>` element: a run is the `font8x8` rectangles the
/// software rasteriser fills, one axis-aligned subpath per set bitmap bit, inside a single
/// `<path>` (see `crate::widget::svg::text_ink_box`). The string is therefore absent from
/// the document in every form — `svg.contains("Sample")` can never be true — and a run is
/// located by *where it is* rather than by *what it says*.
///
/// Only text is a `<path>` in this backend; the empty state's other chrome is `<rect>`,
/// so a path's union box is a run. Subpaths are not deduplicated: a glyph box wider than
/// 8 px maps two bitmap columns onto one pixel column and the backend emits that rectangle
/// twice, exactly as the rasteriser fills it twice. The union is unaffected either way.
fn ink_runs(svg: &str) -> Vec<(i32, i32, i32, i32)> {
let mut runs = Vec::new();
for line in svg.lines() {
let Some(path_at) = line.find("<path ") else { continue };
let Some(d_at) = line[path_at..].find("d=\"") else { continue };
let start = path_at + d_at + 3;
let Some(end) = line[start..].find('"') else { continue };
let mut bounds: Option<(i32, i32, i32, i32)> = None;
for subpath in line[start..start + end].split('M').skip(1) {
let numbers: Vec<i32> = subpath
.split(|c: char| !c.is_ascii_digit() && c != '-')
.filter(|part| !part.is_empty())
.filter_map(|part| part.parse().ok())
.collect();
if numbers.len() < 4 {
continue;
}
let (x, y, w, h) = (numbers[0], numbers[1], numbers[2], numbers[3]);
bounds = Some(match bounds {
None => (x, y, x + w, y + h),
Some((left, top, right, bottom)) => {
(left.min(x), top.min(y), right.max(x + w), bottom.max(y + h))
}
});
}
if let Some(bounds) = bounds {
runs.push(bounds);
}
}
runs
}
/// The stack's rows do not overlap: each begins at or below the previous row's bottom edge.
///
/// The icon was passed a `y` that the helper treated as the glyph box's top while every
/// other row was positioned as though the same number were the box's bottom — so the
/// 48 px icon box covered y 48..96 and the title was drawn at y = 60, **28 px inside it**.
/// `snapshots/svg/empty_state.svg` showed the caption painted across the mailbox glyph.
///
/// # What is asserted, and why it is the ink
///
/// Each row is checked against the *drawing* rather than against an element attribute: the
/// run's ink box top is the row's glyph box top (`origin.y`, the top edge of the run's
/// bitmap), which is exactly the quantity the defect moved. A row's height is the font's
/// own `measure_text("M", font).height`, the renderer's measurement contract, and the
/// order of `ink_runs` is document order — the order the rows are drawn in.
#[cfg(not(alloc_frugal))]
#[test]
fn the_stack_rows_do_not_overlap() {
let mut es = EmptyState::new(Rect::new(0, 0, 240, 120));
let svg = crate::widget::svg::render_to_svg(&mut es);
let rendered = ink_runs(&svg);
assert!(rendered.len() >= 3, "the fixture must render the icon, title and message");
// Each row's glyph box is `font.size()` tall — the renderer's measurement contract
// (`measure_text("M", font).height == font.size()`) — and the rows are drawn in a known
// order: the 48 px icon, the 20 px title, then the 14 px message lines. That order is
// what identifies a run, because the string each run spells is no longer in the
// document; a row drawn out of order would fail on the size it was given rather than
// on its content.
let mut backend = crate::render::SvgPaintBackend::new(Size::new(240, 120));
let context = RenderContext::new(&mut backend);
let height_of = |size: f32| -> i32 {
context.measure_text("M", &Font::with_weight("Sans", size, 400, false)).height as i32
};
let sizes: Vec<i32> = [48.0f32, 20.0, 14.0, 14.0].iter().map(|s| height_of(*s)).collect();
for (index, window) in rendered.windows(2).enumerate() {
let (_, top_a, _, _) = &window[0];
let (_, top_b, _, _) = &window[1];
let bottom_a = top_a + sizes[index];
assert!(
*top_b >= bottom_a,
"run {} starts at y={top_b}, inside run {index}'s box ({top_a}..{bottom_a})",
index + 1
);
}
}
/// Every row is centred on the control's own vertical axis.
///
/// The rows are the icon, the title and the message, all drawn through the same centred
/// helper in `draw`, so their — different — string widths all put the same midpoint on
/// `rect.x + rect.width / 2`. Checking the *ink's* midpoint is what makes this a test of
/// the drawing: the helper places the pen at `center - measured_width / 2`, and the glyphs'
/// own blank columns are inside that measured width, so the ink's midpoint lies on the
/// control's axis for every row independently of what any row says.
#[cfg(not(alloc_frugal))]
#[test]
fn every_stack_row_is_centred_horizontally() {
let mut es = EmptyState::new(Rect::new(0, 0, 240, 120));
let svg = crate::widget::svg::render_to_svg(&mut es);
let runs = ink_runs(&svg);
assert!(runs.len() >= 3, "the fixture must render the icon, title and message");
let center = 120;
for (left, _, right, _) in runs {
// Each row was placed from its *measured* width, so the run's own midpoint is on
// the axis; the ink can only fall inside that measured width, which is why the
// bound is one glyph of slack rather than an equality.
assert!(
((left + right) as f32 / 2.0 - center as f32).abs() <= 8.0,
"a row spans {left}..{right}, whose midpoint must be near the control's axis"
);
}
}
}