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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! Rating widget — a star rating control (like 1-5 stars).
//!
//! The Rating widget displays a horizontal row of stars that the user can click
//! to set a rating value. Stars are the `Star` **icon outline** (Material Symbols), not the
//! `★`/`☆` text glyphs: those codepoints are covered by no bundled face, so drawing them through
//! the text pipeline fell back to 8x8 bitmap blocks. The rated portion is the accent colour and
//! the unrated remainder is a muted tint of the same solid star, which is how Material 3 draws a
//! rating rather than with a separate hollow glyph.
use crate::core::{Color, Point, Rect};
use crate::event::{key_codes, Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::Signal1;
use crate::widget::capability::coercion::{expect_bool, expect_f64, expect_u32};
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::metrics::{dimensions, ControlMetrics};
use crate::widget::{BaseWidget, Draw, IconName, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};
/// Star rating widget for selecting a rating from 1 to N stars.
pub struct Rating {
base: BaseWidget,
/// The rating, as a fraction so half-stars are representable.
///
/// # Why this is `f32` while `rating()` is `u32`
///
/// Real ratings are routinely fractional — "4.5 of 5" is the most common review score
/// there is — and the published contract has always declared `value` as `Float`. Storing
/// `u32` meant a caller writing `3.7` silently got `4`: the schema promised a float and the
/// control dropped the fraction, which is the "reported success for something that did not
/// happen" shape principle #1 rejects. The integral accessors stay as the projection for
/// callers that only ever deal in whole stars, so nothing that used the old API changes
/// behaviour; the exact accessors are what carry the fraction, and `draw` fills the star
/// the value lands in partially. (BLUE21 A.4.5d, this plan's A.4 `rating` row.)
rating: f32,
max_rating: u32,
star_size: u32,
/// The number of stars under the pointer, or `None` when it is outside the row.
///
/// A preview is **paint state, not data**: moving the pointer never writes `rating`, so a
/// host reading the control still sees the committed value. The preview is what the row
/// illustrates the pointer would commit, and `MouseLeave` clears it.
hover_preview: Option<u32>,
/// The exact value the pointer would commit, including a half step.
///
/// [`Self::hover_preview`] is the whole-star projection the painter and the published signal
/// use; this field keeps the fraction so a half-step rating commits what the pointer actually
/// points at.
hover_preview_exact: Option<f32>,
/// Whether pointer and keyboard input commit half-star steps.
///
/// Off by default, which is the historical whole-star behaviour. When on, the horizontal
/// position inside a star maps to `n + 0.5` or `n + 1.0`.
allow_half_step: bool,
/// Whether mouse and keyboard input are ignored entirely.
///
/// A read-only rating is a display of someone else's score rather than an input: it keeps
/// its value and takes part in layout, but a click or an arrow key cannot change it.
read_only: bool,
/// Emitted when the whole-star value changes.
///
/// Kept as `u32` so an existing subscriber's handler signature is unchanged; the exact
/// value is available from [`Rating::rating_exact`] inside the handler.
pub rating_changed: Signal1<u32>,
/// Emitted whenever the hover preview changes.
///
/// The payload has the same meaning as [`Rating::hover_preview`]: the number of whole stars
/// under the pointer, or `None` when the pointer leaves the row. A host that shows a hover
/// hint no longer has to poll the control.
pub hover_preview_changed: Signal1<Option<u32>>,
}
impl Rating {
/// Creates a new Rating widget with the given geometry.
/// Defaults to 5 stars with a rating of 0 (no stars selected).
pub fn new(geometry: Rect) -> Self {
Self {
base: BaseWidget::new(WidgetKind::Rating, geometry, "Rating"),
rating: 0.0,
max_rating: 5,
star_size: dimensions::RATING_STAR_SIZE,
hover_preview: None,
hover_preview_exact: None,
allow_half_step: false,
read_only: false,
rating_changed: Signal1::new(),
hover_preview_changed: Signal1::new(),
}
}
/// Returns the current rating, rounded to whole stars.
///
/// The projection, not the whole story: a rating of 3.7 is *four* whole stars and reads as
/// "4 of 5" here, while [`Rating::rating_exact`] reports `3.7` and the drawn row fills the
/// fourth star 70% of the way.
pub fn rating(&self) -> u32 {
self.rating.round() as u32
}
/// Returns the current rating as a fraction of a star.
pub fn rating_exact(&self) -> f32 {
self.rating
}
/// Sets the rating value, clamped to `[0, max_rating]`, to whole stars.
/// Emits `rating_changed` if the whole-star value changes.
pub fn set_rating(&mut self, rating: u32) {
self.set_rating_exact(rating as f32);
}
/// Sets the rating value, clamped to `[0, max_rating]`, keeping the fraction.
///
/// This is the setter the `value` property uses, so `set("value", 3.5)` draws three and a
/// half stars rather than silently four. Emits `rating_changed` only when the *whole-star*
/// projection changes, so a subscriber counting stars is not woken by a half-step.
pub fn set_rating_exact(&mut self, rating: f32) {
// A non-finite write is rejected rather than clamped: `NaN.clamp` is `NaN`, and a NaN
// rating would make every subsequent comparison false and the row draw nothing.
if !rating.is_finite() {
return;
}
let clamped = rating.clamp(0.0, self.max_rating as f32);
let whole_before = self.rating();
if self.rating != clamped {
self.rating = clamped;
let whole_after = self.rating();
if whole_before != whole_after {
self.rating_changed.emit(whole_after);
}
self.base.request_redraw();
}
}
/// Returns the maximum rating value.
pub fn max_rating(&self) -> u32 {
self.max_rating
}
/// Submits a hover-frame repaint bounded by the painted box plus the damage margin.
///
/// A hover preview changes only the star row, so a mounted control submits the rectangle it
/// actually painted rather than asking for a whole-control redraw. An unmounted control
/// falls back to [`BaseWidget::request_redraw`], keeping the redraw signal contract for
/// host-owned controls; a frame in [`crate::widget::runtime::RepaintMode::Full`] keeps that
/// fallback too, exactly as `switch` does for its interaction frames.
fn request_frame_repaint(&self, bounds: Option<Rect>) {
let _ = bounds;
#[cfg(not(alloc_frugal))]
{
if let Some(id) = crate::widget::runtime::registry_id_of(self.id()) {
let narrow = crate::widget::runtime::repaint_mode(id)
!= crate::widget::runtime::RepaintMode::Full;
if narrow || bounds.is_none() {
let damage = bounds
.or_else(|| crate::widget::runtime::painted_box_with_damage_margin(id))
.unwrap_or_else(|| self.damage_bounds());
crate::widget::runtime::request_repaint_rect(id, damage);
// The replaced `request_redraw` emitted this signal; keep it.
self.base.redraw_requested.emit();
return;
}
}
}
self.base.request_redraw();
}
/// This control's own rectangle grown by the shared damage margin.
#[cfg(not(alloc_frugal))]
fn damage_bounds(&self) -> Rect {
let rect = self.geometry();
let margin = crate::widget::metrics::DAMAGE_MARGIN;
let offset = margin as i32;
Rect::new(
rect.x.saturating_sub(offset),
rect.y.saturating_sub(offset),
rect.width.saturating_add(margin).saturating_add(margin),
rect.height.saturating_add(margin).saturating_add(margin),
)
}
/// Sets the maximum rating value.
/// The current rating is clamped to the new maximum.
pub fn set_max_rating(&mut self, max_rating: u32) {
let max = max_rating.max(1);
self.max_rating = max;
if self.rating > max as f32 {
let whole_before = self.rating();
self.rating = max as f32;
if whole_before != max {
self.rating_changed.emit(max);
}
}
self.base.request_redraw();
}
/// Returns the size of each star in pixels.
pub fn star_size(&self) -> u32 {
self.star_size
}
/// Sets the size of each star in pixels.
pub fn set_star_size(&mut self, size: u32) {
let size = size.max(8);
if self.star_size == size {
return;
}
self.star_size = size;
self.base.request_redraw();
}
/// Returns whether the control ignores mouse and keyboard input.
pub fn is_read_only(&self) -> bool {
self.read_only
}
/// Enables or disables read-only behaviour.
///
/// A read-only rating keeps its current value and paints normally, but a pointer press,
/// hover preview, or arrow/space key cannot change it. Turning read-only on also clears
/// any hover preview, so no stale highlight survives the switch.
pub fn set_read_only(&mut self, read_only: bool) {
if self.read_only == read_only {
return;
}
self.read_only = read_only;
if read_only {
self.clear_hover_preview();
}
self.base.request_redraw();
}
/// Whether pointer and keyboard input commit half-star steps.
pub fn allow_half_step(&self) -> bool {
self.allow_half_step
}
/// Enables or disables half-star commits.
///
/// The default is `false`, which keeps every existing interaction path at whole stars. When
/// enabled, a click at the left half of a star commits `n + 0.5` and the right half `n + 1.0`;
/// the arrow keys move by `0.5`.
pub fn set_allow_half_step(&mut self, allow: bool) {
if self.allow_half_step == allow {
return;
}
self.allow_half_step = allow;
self.base.request_redraw();
}
/// Clears both the projected and the exact hover preview, reporting the change once.
fn clear_hover_preview(&mut self) {
let had_preview = self.hover_preview.is_some();
self.hover_preview = None;
self.hover_preview_exact = None;
if had_preview {
self.hover_preview_changed.emit(None);
}
}
/// Records a pointer preview at `pos`, emitting only when the whole-star projection changes.
fn update_hover_preview(&mut self, pos: Point) {
let Some(index) = self.star_index_at(pos) else {
self.clear_hover_preview();
return;
};
let exact = if self.allow_half_step {
self.star_cell(index)
.map(|cell| {
let fraction =
((pos.x - cell.x) as f32 / cell.width.max(1) as f32).clamp(0.0, 1.0);
if fraction < 0.5 {
index as f32 + 0.5
} else {
index as f32 + 1.0
}
})
.unwrap_or(index as f32 + 1.0)
} else {
index as f32 + 1.0
};
self.hover_preview_exact = Some(exact);
let preview = index + 1;
if self.hover_preview != Some(preview) {
self.hover_preview = Some(preview);
self.hover_preview_changed.emit(Some(preview));
// Only the star row changed; the preview is a narrow, region-sized frame.
self.request_frame_repaint(None);
}
}
/// The number of stars under the pointer, or `None` when the pointer is elsewhere.
///
/// Exposed for tests and for a host that wants to describe the preview to an assistive
/// technology without re-deriving the hit test from the geometry.
pub fn hover_preview(&self) -> Option<u32> {
self.hover_preview
}
/// The fraction of the row that is filled, in `0.0..=1.0`.
///
/// # Why this is derived here and not in each consumer
///
/// A rating appears as a number, as a row of stars, and as a bar in a summary card. All three are
/// the same statement — "this much of the range" — and computing it in each place is how they come
/// to disagree about whether three of five stars is 60% or 50%. Reads `max_rating().max(1)`, so a
/// control whose ceiling was somehow zero reports `0.0` rather than dividing by zero.
pub fn fill_fraction(&self) -> f32 {
(self.rating / self.max_rating.max(1) as f32).clamp(0.0, 1.0)
}
/// The fraction of star `index` that is filled, in `0.0..=1.0`.
///
/// Split out because a half-star is a *per-star* statement, not a row-level one: a 3.5 of 5
/// rating fills three stars completely, one half, and none of the fifth. Deriving it from
/// `fill_fraction` would fill 70% of the whole row instead, which is a progress bar wearing
/// stars. The same function answers both the draw and any test asserting the half.\
pub fn star_fill(&self, index: u32) -> f32 {
// The stars before `index` are whole; the star `index` holds the remainder.
(self.rating - index as f32).clamp(0.0, 1.0)
}
/// The rating as it should be spoken or shown: `"3 of 5"`, or `"no rating"` when unset.
///
/// # Why "no rating" rather than "0 of 5"
///
/// Zero stars means the user has not rated yet, which is a different statement from having rated
/// it the lowest possible. A screen reader announcing "0 of 5" makes an unrated control sound like
/// a one-star verdict; the same distinction [`crate::platform::accessibility::A11yState::checked`]
/// documents for `Option<bool>`.
pub fn display_text(&self) -> String {
if self.rating <= 0.0 {
return "no rating".to_string();
}
// A whole-star rating reads "3 of 5"; a fractional one keeps its fraction, because
// rounding it here would reintroduce on the announcement path exactly the silent
// truncation this control no longer has on the value path.
if (self.rating - self.rating.round()).abs() < 0.05 {
format!("{} of {}", self.rating(), self.max_rating)
} else {
format!(
"{} of {}",
crate::widget::display_widgets::rating::trim_trailing_zero(self.rating),
self.max_rating
)
}
}
/// The single column the whole star row is measured from.
///
/// # Why the row is not the control's rectangle
///
/// A rating is a **row of fixed-size glyphs**: one 24 px star, five of them, and a
/// 4 px gap between neighbours. The control used to derive its pitch from the
/// rectangle it was handed (`(rect.width - total_width) / 2` as a start, plus a
/// background fill across the whole of `rect`), so the 240x120 census cell drew a
/// full-canvas panel with five glyphs floating at y 53 and the star positions moved
/// whenever the caller changed the control's width. Deriving the row's x from the
/// stars themselves means the control draws the same object in any rectangle, which
/// is what [`dimensions::RATING_ROW_HEIGHT`] does for the vertical axis.
///
/// The horizontal origin is the first star's left edge, so the row is centred by
/// definition rather than by a second, independent arithmetic on `rect.width`.
fn star_row(&self) -> Rect {
let count = self.max_rating.max(1);
let width = count * self.star_size + count.saturating_sub(1) * dimensions::RATING_STAR_GAP;
// The full-width band is what makes the row's height fixed and centred; its own
// width is then replaced by the measured star row, centred inside it. `center_in`
// would clamp an over-wide row rather than letting it overflow the control, which
// is the same "never paint outside the rectangle" rule every piece of chrome
// follows.
let band = ControlMetrics::full_width_band(self.geometry(), dimensions::RATING_ROW_HEIGHT);
ControlMetrics::center_in(band, crate::core::Size::new(width, band.height))
}
/// The cell one star occupies, or `None` when it would not fit inside the row.
///
/// Nothing here reads `rect.width`, so a star is at the same distance from its
/// neighbour whatever the caller's layout did. A control too narrow for five stars
/// drops the ones that do not fit rather than painting them over the edge: nothing
/// clips a widget at this layer, so an overflowing cell would be a drawing
/// instruction that leaves the control's own rectangle.
fn star_cell(&self, index: u32) -> Option<Rect> {
let row = self.star_row();
let step = self.star_size + dimensions::RATING_STAR_GAP;
let x = row.x + (index * step) as i32;
// A partial cell is not a star, so the guard is on the cell's own extent rather
// than on its left edge alone: a slice of a star reads as a rendering fault.
if x < row.x || x + self.star_size as i32 > row.x + row.width as i32 {
return None;
}
Some(Rect::new(x, row.y, self.star_size, row.height))
}
/// The star cell under `pos`, or `None` when the pointer is outside the drawn row.
///
/// The press handler and the hover preview share this hit test, so the star the pointer
/// highlights and the star a click commits can never disagree.
fn star_index_at(&self, pos: Point) -> Option<u32> {
let row = self.star_row();
if pos.y < row.y || pos.y >= row.y + row.height as i32 {
return None;
}
let rel_x = pos.x - row.x;
if rel_x < 0 {
return None;
}
let step = (self.star_size + dimensions::RATING_STAR_GAP) as i32;
let index = (rel_x / step) as u32;
// A star the row dropped is not hovered or clickable either: the hit test and the ink
// are the same set of cells.
if index < self.max_rating && self.star_cell(index).is_some() {
Some(index)
} else {
None
}
}
}
impl Widget for Rating {
fn base(&self) -> &BaseWidget {
&self.base
}
fn set_state_theme_hook(&mut self) {
crate::style::reapply_active_theme_state(self);
}
fn base_mut(&mut self) -> &mut BaseWidget {
&mut self.base
}
fn size_hint(&self) -> crate::core::Size {
// The row's own height, so a layout that honours the hint hands the control
// exactly the band the stars are painted in. The width is the row's fixed extent.
crate::core::Size::new(
self.max_rating.max(1) * (self.star_size + dimensions::RATING_STAR_GAP),
dimensions::RATING_ROW_HEIGHT,
)
}
impl_draw_bridge!();
impl_widget_property_hooks!();
/// Resolves a published event name to the control's own signal.
///
/// # Why this is explicit per control
///
/// `connect_event` validates a name against the capability table and registers a hub slot; only
/// `event_signal_dyn` joins that name to the signal the control actually emits. Without it a name
/// is valid and inert, which is the silent failure `tools/check_event_signal_dyn.sh` exists to
/// make impossible. The arm set is checked against the capability's published names, so this
/// list cannot drift from what the control advertises.
fn event_signal_dyn(&self, name: &str) -> Option<crate::signal::EventSignalRef> {
use crate::signal::EventSignalRef;
#[allow(unused_imports)]
use crate::widget::capability::CapabilityValue;
match name {
"rating_changed" => {
Some(EventSignalRef::mapped("rating_changed", &self.rating_changed, |v| {
CapabilityValue::UInt(*v as u64)
}))
}
"hover_preview_changed" => Some(EventSignalRef::mapped(
"hover_preview_changed",
&self.hover_preview_changed,
|preview: &Option<u32>| match preview {
Some(count) => CapabilityValue::UInt(u64::from(*count)),
None => CapabilityValue::Null,
},
)),
_ => None,
}
}
}
/// `Rating`'s property contract.
///
/// # The defect this replaces
///
/// `value` and `max` describe the *number*, and nothing described the control. `star_size` had a
/// setter and no way to be read or written through the contract, and the little text a rating can
/// legitimately show ("3 of 5") was not published at all — so a consumer had to re-derive it from
/// `value` and `max`, which is exactly the second derivation the property contract exists to remove.
///
/// 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. `value` is published as
/// `Float` and is stored as the same fraction, so a caller writing `3.5` gets
/// three and a half stars rather than the `4` the old rounding produced; `max`
/// stays `UInt`.
impl WidgetProperties for Rating {
fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
match name {
"value" => Ok(CapabilityValue::Float(f64::from(self.rating_exact()))),
"max" => Ok(CapabilityValue::UInt(u64::from(self.max_rating()))),
"star_size" => Ok(CapabilityValue::UInt(u64::from(self.star_size()))),
"allow_half_step" => Ok(CapabilityValue::Bool(self.allow_half_step())),
// The proportional fill, in `0.0..=1.0`. `value` alone is not enough for a consumer that
// wants a bar or a percentage: it would have to know `max`, and dividing in the consumer is
// the second derivation this contract removes.
"fill" => Ok(CapabilityValue::Float(f64::from(self.fill_fraction()))),
// "3 of 5" — the announcement text, derived once here so a screen reader, a tooltip and a
// snapshot all say the same thing.
"display_text" => Ok(CapabilityValue::String(self.display_text())),
_ => base_property_get(self, name),
}
}
fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
match name {
"value" => {
let value = expect_f64(value)?;
if !value.is_finite() {
return Err(CapabilityAccessError::TypeMismatch);
}
self.set_rating_exact(value as f32);
Ok(())
}
"max" => {
self.set_max_rating(expect_u32(value)?);
Ok(())
}
"star_size" => {
self.set_star_size(expect_u32(value)?);
Ok(())
}
"allow_half_step" => {
self.set_allow_half_step(expect_bool(value)?);
Ok(())
}
// Derived from `value` and `max`, so writing either would be a second way to say the same
// thing — and one of the two would be able to disagree.
"fill" | "display_text" => Err(CapabilityAccessError::ReadOnlyProperty),
_ => base_property_set(self, name, value),
}
}
fn property_names(&self) -> &'static [&'static str] {
property_names_of![
"value",
"max",
"star_size",
"allow_half_step",
"fill",
"display_text",
BASE_PROPERTY_NAMES
]
}
/// Runs one of the commands `rating` publishes.
///
/// `set_value` assigns the star count and `set_max` the ceiling; both need an
/// argument a command carries none of, so both are refused as
/// [`CapabilityAccessError::OutOfRange`] — use `set("value", ..)` / `set("max", ..)`
/// — rather than reported unknown.
fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
match name {
"set_value" | "set_max" => Err(CapabilityAccessError::OutOfRange),
_ => Err(CapabilityAccessError::UnknownCommand),
}
}
}
impl Draw for Rating {
fn draw(&mut self, context: &mut RenderContext) {
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 a literal. The theme step is what
// makes an appearance switch visible; previously the plate below and the
// empty-star grey were hardcoded literals, so light and dark rendered
// identically.
//
// `resolved_theme_style` takes and releases the global manager's lock
// internally, so no guard is held across the draw (the mutex is not
// re-entrant).
let style = self.base.style();
let theme = crate::style::resolved_theme_style_shared("rating");
let background = style
.background_color
.or_else(|| theme.as_ref().and_then(|t| t.background_color))
.unwrap_or(Color::WHITE);
let text_color = style
.text_color
.or_else(|| theme.as_ref().and_then(|t| t.text_color))
.unwrap_or(Color::BLACK);
// ── The row actually painted ──
//
// A rating paints a **row of stars**, not a panel: the fill is the row's own
// band, `RATING_ROW_HEIGHT` tall and centred in the control. This used to be
// `fill_rect(rect, ..)`, which made the 240x120 census cell a full-bleed plate
// behind five glyphs — a rectangle the user reads as "a panel that happens to
// contain stars" rather than as the rating control itself.
let row = self.star_row();
context.fill_rect(row, background);
if self.max_rating == 0 {
// Nothing to rate: the row band above is the whole control, so there is no
// per-star chrome to emit rather than a loop that would divide by zero stars.
return;
}
// A star is an **icon**, not a glyph: `★`/`☆` (U+2605/U+2606) are absent from every
// bundled face, so `draw_text("★")` fell back to an 8x8 bitmap block. The cell is the
// star's own square box centred in the row, and the outline is drawn through the shared
// `draw_icon_at` primitive so a star here and an `Icon::new(.., IconName::Star)` widget
// are the same shape.
let star_side = self.star_size.min(row.height) as i32;
// A filled star is the theme's accent — the slot the palette reserves for a
// value indicator — so it moves with the appearance instead of staying a
// fixed gold. The warning token is that slot's public accessor. An empty star
// is the unselected state of the same control: a tint of the resolved
// foreground, muted further when the control is disabled.
let accent = crate::style::semantic_color(crate::style::SemanticColor::Warning)
.map(|token| token.blend(&background, 0.0))
.unwrap_or_else(|| text_color.blend(&background, 0.0));
// An explicit style wins over the palette, so a host that set a star colour
// keeps it; the accent is what an unstyled control uses.
let explicit = self.base.style();
let filled_color = explicit.border_color.or(explicit.background_color).unwrap_or(accent);
// The hover preview is the same accent at lower emphasis: it reads as "this is what a
// press would set" rather than as a committed value. It is only painted while the
// pointer is over a star, so an untouched control's output is unchanged.
let preview_color = filled_color.blend(&background, 0.45);
// Material 3 has no hollow star: the unselected mark is the *same* solid star at lower
// emphasis, which is why there is one `Star` icon rather than a `Star`/`StarBorder` pair.
let empty_color = if is_enabled {
text_color.blend(&background, 0.35)
} else {
text_color.blend(&background, 0.6)
};
for i in 0..self.max_rating {
// The cell comes from the row and the star's own size, so a star's position
// is a function of the rating control and not of the caller's rectangle. A
// star that will not fit is skipped rather than clipped.
let Some(cell) = self.star_cell(i) else {
continue;
};
// A hover preview replaces the row's fills for as long as it is present: stars up to
// the pointer are lit, the rest are empty. That is the same picture a click would
// commit, and it never writes the committed value.
let (fill, mark_color) = match self.hover_preview {
Some(count) if i < count => (1.0, preview_color),
Some(_) => (0.0, filled_color),
None => (self.star_fill(i), filled_color),
};
// The star's square box, centred vertically in the control's band.
let icon_rect = Rect {
x: cell.x,
y: row.y + (row.height as i32 - star_side) / 2,
width: star_side as u32,
height: star_side as u32,
};
// A whole star needs no clip: the filled star exactly covers the outline. When the
// filled colour is fully opaque that also makes the outline layer redundant, so it
// is skipped; a translucent explicit colour still needs the outline underneath to
// keep the same pixels as before. A partial star always keeps the outline, because
// only the outline supplies the unrated remainder of the shape.
let whole_opaque = fill >= 1.0 && mark_color.a == 255;
if !whole_opaque {
crate::widget::draw_icon_at(context, icon_rect, empty_color, IconName::Star);
}
if fill <= 0.0 {
continue;
}
if fill >= 1.0 {
crate::widget::draw_icon_at(context, icon_rect, mark_color, IconName::Star);
continue;
}
// A partial star is the filled star clipped to the rated share of the cell. The
// filled star is drawn in the *whole* cell and the clip cuts it, so the filled
// half is registered with the outline rather than squeezed into half a cell —
// squeezing it would draw a smaller star, not a half-filled one.
let filled_width = (icon_rect.width as f32 * fill).round() as u32;
if filled_width == 0 {
continue;
}
context.push_clip(icon_rect.x, icon_rect.y, filled_width, icon_rect.height);
crate::widget::draw_icon_at(context, icon_rect, mark_color, IconName::Star);
context.pop_clip();
}
}
}
/// Formats a fractional star count without a trailing `.0`.
///
/// A whole star reads `"4"` and a half reads `"4.5"`, so the announcement a screen reader gets
/// matches what the row shows instead of saying "4.0 of 5" for four solid stars.\
fn trim_trailing_zero(value: f32) -> String {
let text = format!("{value:.1}");
match text.strip_suffix(".0") {
Some(whole) => whole.to_string(),
None => text,
}
}
impl EventHandler for Rating {
fn handle_event(&mut self, event: &Event) {
// A disabled or read-only control consumes nothing, so the base state stays
// authoritative and neither the pointer nor the keyboard can change the value.
if !self.base.is_enabled() || self.read_only {
return;
}
self.base.handle_event(event);
match event {
Event::MouseMove { pos } => {
// Previewing is paint-only. `rating` is deliberately not written here, so a
// host reading the control while the pointer moves still sees the committed
// score.
self.update_hover_preview(*pos);
}
Event::MouseLeave { .. } => {
self.clear_hover_preview();
self.request_frame_repaint(None);
}
Event::MouseRelease { pos, button } => {
if *button != 1 {
return;
}
// The hit test is the **drawn geometry**: the star row's own band, so the
// clickable area and the ink are the same object. The same helper drives the
// hover preview, so the star highlighted and the star committed cannot differ.
let Some(index) = self.star_index_at(*pos) else {
return;
};
if self.allow_half_step {
// The horizontal position inside the star decides the half step. This is the
// fraction the painter already uses to fill the star, so what is drawn and
// what is committed are the same quantity.
let fraction = self
.star_cell(index)
.map(|cell| {
((pos.x - cell.x) as f32 / cell.width.max(1) as f32).clamp(0.0, 1.0)
})
.unwrap_or(1.0);
let exact = index as f32 + if fraction < 0.5 { 0.5 } else { 1.0 };
self.set_rating_exact(exact);
return;
}
// Clicking the same star as the current rating toggles between that star and
// clearing; any other star sets that many. Compared against the whole-star
// projection so a 4.5 rating still toggles its fourth star off rather than
// being treated as a fifth.
let new_rating = if self.rating() == index + 1 { index } else { index + 1 };
self.set_rating(new_rating);
}
Event::KeyPress { key, .. } => match *key {
key_codes::LEFT => {
let step = if self.allow_half_step { 0.5 } else { 1.0 };
let next = (self.rating_exact() - step).max(0.0);
self.set_rating_exact(next);
}
key_codes::RIGHT => {
let step = if self.allow_half_step { 0.5 } else { 1.0 };
let next = (self.rating_exact() + step).min(self.max_rating as f32);
self.set_rating_exact(next);
}
key_codes::SPACE => {
// Space commits the preview, if there is one. With no preview it is a
// no-op rather than an implicit "rate zero". The exact preview is used when
// half steps are enabled, so Space and the click agree.
if let Some(exact) = self.hover_preview_exact.take() {
self.hover_preview = None;
self.hover_preview_changed.emit(None);
self.set_rating_exact(exact);
self.request_frame_repaint(None);
} else if let Some(count) = self.hover_preview.take() {
self.hover_preview_changed.emit(None);
self.set_rating(count);
self.request_frame_repaint(None);
}
}
_ => {}
},
_ => {}
}
}
}
#[cfg(all(test, full_widgets))]
mod tests {
use super::*;
use crate::core::Point;
use std::sync::{Arc, Mutex};
#[test]
fn rating_default_values() {
let r = Rating::new(Rect::new(0, 0, 200, 40));
assert_eq!(r.rating(), 0);
assert_eq!(r.max_rating(), 5);
assert_eq!(r.star_size(), dimensions::RATING_STAR_SIZE);
assert_eq!(r.kind(), WidgetKind::Rating);
}
#[test]
fn rating_set_rating_emits_signal() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
let captured = Arc::new(Mutex::new(None));
r.rating_changed.connect({
let captured = Arc::clone(&captured);
move |val: Arc<u32>| {
*captured.lock().unwrap() = Some(*val);
}
});
r.set_rating(3);
assert_eq!(r.rating(), 3);
assert_eq!(*captured.lock().unwrap(), Some(3));
}
#[test]
fn rating_set_rating_clamped() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
r.set_rating(10);
assert_eq!(r.rating(), 5);
}
#[test]
fn rating_set_rating_zero() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
r.set_rating(4);
assert_eq!(r.rating(), 4);
r.set_rating(0);
assert_eq!(r.rating(), 0);
}
#[test]
fn rating_set_max_rating() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
r.set_rating(5);
r.set_max_rating(3);
assert_eq!(r.max_rating(), 3);
assert_eq!(r.rating(), 3);
}
#[test]
fn rating_max_rating_min_one() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
r.set_max_rating(0);
assert_eq!(r.max_rating(), 1);
}
#[test]
fn rating_star_size_get_set() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
assert_eq!(r.star_size(), dimensions::RATING_STAR_SIZE);
r.set_star_size(32);
assert_eq!(r.star_size(), 32);
}
#[test]
fn rating_star_size_min_eight() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
r.set_star_size(2);
assert_eq!(r.star_size(), 8);
}
/// The two derived readings agree with `value`/`max`, and "unrated" is not "zero of five".
///
/// # The defect this pins
///
/// The contract published only `value` and `max`, so every consumer that wanted a proportion or a
/// label recomputed it — and a rating's zero means *unrated*, which "0 of 5" gets wrong.
#[test]
fn the_contract_publishes_the_fill_and_the_display_text() {
use crate::widget::capability::WidgetProperties;
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
assert_eq!(r.get("value").unwrap(), CapabilityValue::Float(0.0));
assert_eq!(r.get("fill").unwrap(), CapabilityValue::Float(0.0));
assert_eq!(
r.get("display_text").unwrap().as_str(),
Some("no rating"),
"zero means unrated, not a zero-star verdict"
);
r.set_rating(3);
assert_eq!(r.fill_fraction(), 0.6, "three of five is 60%");
// The published value is an `f32` widened to `f64` for the contract, so `3/5` arrives as
// `0.6000000238…` rather than exactly `0.6`. Comparing with a tolerance is the honest
// assertion: the contract is a proportion, not a decimal literal.
match r.get("fill").unwrap() {
CapabilityValue::Float(fill) => {
assert!((fill - 0.6).abs() < 1e-5, "three of five published as {fill}");
}
other => panic!("`fill` must be a Float, got {other:?}"),
}
assert_eq!(r.get("display_text").unwrap().as_str(), Some("3 of 5"));
// The ceiling moves the proportion with it, which is the trap a per-consumer division hits.
r.set_max_rating(10);
assert_eq!(r.fill_fraction(), 0.3, "three of ten is 30%");
assert_eq!(r.get("display_text").unwrap().as_str(), Some("3 of 10"));
// The derived two are read-only: a second writer would be a second way to say the same thing.
assert!(r.set("fill", CapabilityValue::Float(1.0)).is_err());
assert!(r.set("display_text", CapabilityValue::String("x".into())).is_err());
}
/// A half-star is representable, and the published contract does not silently round it away.
///
/// Regression (BLUE21 A.4.5d): the schema declared `value` as `Float` while the control stored
/// `u32`, so `set("value", 3.5)` produced four solid stars and a read-back of `4.0`. A review
/// score of "four and a half" — the most common fractional rating there is — could not be
/// expressed at all, and the contract reported success for a value it had changed.
#[test]
fn a_fractional_rating_round_trips_and_fills_one_star_partially() {
use crate::widget::capability::WidgetProperties;
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
r.set("value", CapabilityValue::Float(3.5)).unwrap();
assert_eq!(
r.get("value").unwrap(),
CapabilityValue::Float(3.5),
"the contract must report the value it was given"
);
// The integral projection is still whole stars, so existing callers are unaffected.
assert_eq!(r.rating(), 4, "3.5 rounds to four whole stars");
assert_eq!(r.rating_exact(), 3.5);
// Per-star fills, not a row-level proportion: three solid, one half, one empty.
assert_eq!(r.star_fill(0), 1.0);
assert_eq!(r.star_fill(2), 1.0);
assert!((r.star_fill(3) - 0.5).abs() < 1e-5, "the fourth star is half rated");
assert_eq!(r.star_fill(4), 0.0, "the fifth is untouched");
// And the announcement keeps the fraction rather than reporting the rounded value.
assert_eq!(
r.get("display_text").unwrap().as_str(),
Some("3.5 of 5"),
"rounding on the announcement path would reintroduce the truncation"
);
}
/// A half-rated star paints the filled star clipped to the rated share of its cell.
///
/// The assertion is on the *clip*, because that is what makes a partial star a full outline
/// with a filled part inside it rather than a smaller star: the filled star is drawn in the
/// whole cell and the clip cuts it. A star is an **icon outline**, not a text glyph, so the
/// filled/empty marks are counted in *contours* and halved to stars — the `Star` outline is
/// two contours, so three painted stars is six filled paths, not three.
#[test]
fn a_half_rated_star_is_painted_with_a_clip() {
// Holds the crate-wide theme guard: this test renders, and a concurrent
// test that switches the appearance would otherwise change a later frame.
let _theme_guard = crate::style::theme_test_guard();
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
r.set_rating_exact(2.5);
let svg = crate::widget::svg::render_to_svg(&mut r);
// Exactly one star is partial, so there is exactly one clip — and its width is half of a
// 24 px cell, which is what "half a star" means geometrically.
assert_eq!(svg.matches("<clipPath").count(), 1, "one partial star: {svg}");
let clip_width = svg
.split("<clipPath")
.nth(1)
.and_then(|rest| rest.split("width=\"").nth(1))
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<u32>().ok())
.expect("the clip must carry a width");
assert_eq!(clip_width, 12, "half of a 24 px cell: {svg}");
// The `Star` outline is a two-contour compound shape, so each painted star is one `<path>`
// containing both contours. The two whole, opaque stars contribute one filled path each
// and no empty outline: an opaque fill covers every pixel the outline would have written,
// so painting the outline first was a redundant second pass. The clipped half star and
// the two unrated stars still need the outline (the half because it supplies the unrated
// remainder, the empty ones because that is all they paint).
let filled = svg.matches("rgba(255,193,7,1.00)").count();
let empty = svg.matches("rgba(63,63,63,1.00)").count();
assert_eq!(filled, 3, "two whole stars and one clipped half: {svg}");
assert_eq!(empty, 3, "the half star and the two unrated stars keep their outline: {svg}");
}
/// `star_size` is reachable from the contract, so the setter is no longer unreachable.
#[test]
fn star_size_round_trips_through_the_property_api() {
use crate::widget::capability::WidgetProperties;
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
assert_eq!(r.get("star_size").unwrap().as_u64(), Some(24));
r.set("star_size", CapabilityValue::UInt(32)).unwrap();
assert_eq!(r.star_size(), 32);
assert_eq!(r.get("star_size").unwrap().as_u64(), Some(32));
// The floor still applies through the contract, not only through the setter.
r.set("star_size", CapabilityValue::UInt(1)).unwrap();
assert_eq!(r.star_size(), 8);
}
/// A press on the third star sets three, using the *drawn* row's own arithmetic.
///
/// The star cells are now derived from the rating's own sizes rather than from
/// `rect` and a local `gap = 4`: with `star_size = 24` and `RATING_STAR_GAP = 4`
/// the row is 136 px wide in a 200 px control and starts at x 32, so the cells are
/// the same ones this test always addressed. What it pins is that the hit test and
/// the ink still agree after the row moved to a named derivation.
#[test]
fn rating_mouse_press_sets_rating() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
// The row is centred in the control's own band, so a press must land on the
// middle row line rather than at the control's top edge.
let row = r.star_row();
assert_eq!(row.width, 136, "five 24 px stars and four 4 px gaps");
assert_eq!(row.x, 32, "centred in the 200 px control");
let mid_y = row.y + row.height as i32 / 2;
assert_eq!(mid_y, 20, "the row is centred in the 40 px control");
// Star 0: [32..56), Star 1: [60..84), Star 2: [88..112), Star 3: [116..140)
// Press the 3rd star (index 2 => rating 3)
r.handle_event(&Event::MouseRelease { pos: Point::new(100, mid_y), button: 1 });
assert_eq!(r.rating(), 3);
}
#[test]
fn rating_mouse_press_toggles_current_star() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
r.set_rating(3);
let row = r.star_row();
let mid_y = row.y + row.height as i32 / 2;
// Click on the 3rd star again (index 2 => rating 3) should set rating back to 2
r.handle_event(&Event::MouseRelease { pos: Point::new(100, mid_y), button: 1 });
assert_eq!(r.rating(), 2);
}
#[test]
fn rating_mouse_press_out_of_bounds() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
let mid_y = r.star_row().y + r.star_row().height as i32 / 2;
r.handle_event(&Event::MousePress { pos: Point::new(300, mid_y), button: 1, modifiers: 0 });
assert_eq!(r.rating(), 0);
}
#[test]
fn rating_mouse_press_before_first_star() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
let mid_y = r.star_row().y + r.star_row().height as i32 / 2;
r.handle_event(&Event::MousePress { pos: Point::new(-10, mid_y), button: 1, modifiers: 0 });
assert_eq!(r.rating(), 0);
}
/// A press outside the drawn star row does nothing, even though it is inside the
/// control's rectangle. This is the hit-test/ink agreement the fix established: the
/// old handler tested `rect`, so the empty space above and below the stars was
/// clickable and a press there could set a rating.
#[test]
fn rating_mouse_press_outside_the_drawn_row_changes_nothing() {
let mut r = Rating::new(Rect::new(0, 0, 240, 120));
let row = r.star_row();
assert_eq!(row.height, dimensions::RATING_ROW_HEIGHT);
assert!(row.y > 0, "the row is centred, so it does not touch the control's top edge");
// Above the row, still well inside the control.
r.handle_event(&Event::MouseRelease { pos: Point::new(120, row.y - 1), button: 1 });
assert_eq!(r.rating(), 0, "a press above the stars must not rate");
// Below the row, still well inside the control.
r.handle_event(&Event::MouseRelease {
pos: Point::new(120, row.y + row.height as i32),
button: 1,
});
assert_eq!(r.rating(), 0, "a press below the stars must not rate");
}
/// The star row is a fixed height in any rectangle, and its stars do not move apart
/// when the caller's width changes.
#[test]
fn the_star_row_keeps_its_own_height_and_pitch() {
let mut narrow = Rating::new(Rect::new(0, 0, 240, 40));
narrow.set_max_rating(5);
let mut wide = Rating::new(Rect::new(0, 0, 600, 300));
wide.set_max_rating(5);
assert_eq!(narrow.star_row().height, dimensions::RATING_ROW_HEIGHT);
assert_eq!(wide.star_row().height, dimensions::RATING_ROW_HEIGHT);
assert_eq!(narrow.star_row().width, wide.star_row().width);
// The pitch between consecutive stars is the star and the gap, in both.
for rating in [&narrow, &wide] {
let first = rating.star_cell(0).expect("a row that fits has a first star");
let second = rating.star_cell(1).expect("a row that fits has a second star");
assert_eq!(
second.x - first.x,
(dimensions::RATING_STAR_SIZE + dimensions::RATING_STAR_GAP) as i32
);
assert_eq!(first.width, dimensions::RATING_STAR_SIZE);
}
}
/// A control narrower than five stars drops the ones that do not fit.
#[test]
fn stars_that_do_not_fit_are_dropped_rather_than_painted_over_the_edge() {
let mut r = Rating::new(Rect::new(0, 0, 60, 24));
r.set_max_rating(5);
// A 60 px row holds two 24 px stars and their gap; the rest are not cells at all.
assert!(r.star_cell(0).is_some());
assert!(r.star_cell(1).is_some());
assert!(r.star_cell(2).is_none(), "the third star has no room in a 60 px control");
// The dropped stars are not clickable either, so ink and hit test stay one set.
let row = r.star_row();
let mid_y = row.y + row.height as i32 / 2;
r.handle_event(&Event::MouseRelease { pos: Point::new(56, mid_y), button: 1 });
assert!(r.rating() <= 2, "a dropped star cannot be selected, got {}", r.rating());
}
/// No emitted star cell is zero-extent, and every one stays inside the control.
#[test]
fn every_star_cell_is_drawable_and_inside_the_control() {
// The last three are deliberately narrower than the five-star row, so the row is
// clamped: the control must not paint stars outside the rectangle it was given.
for rect in [Rect::new(0, 0, 240, 120), Rect::new(0, 0, 600, 300), Rect::new(0, 0, 60, 24)]
{
let r = Rating::new(rect);
for index in 0..r.max_rating() {
if let Some(cell) = r.star_cell(index) {
assert!(
cell.width > 0 && cell.height > 0,
"cell {index} at {rect:?} is drawable"
);
assert!(cell.x >= rect.x, "cell {index} at {rect:?} starts inside the control");
assert!(
cell.x + cell.width as i32 <= rect.x + rect.width as i32,
"cell {index} at {rect:?} ends inside the control"
);
}
}
}
}
#[test]
fn rating_disabled_blocks_events() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
r.set_enabled(false);
let mid_y = r.star_row().y + r.star_row().height as i32 / 2;
r.handle_event(&Event::MousePress { pos: Point::new(40, mid_y), button: 1, modifiers: 0 });
assert_eq!(r.rating(), 0);
}
#[test]
fn rating_right_click_ignored() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
let mid_y = r.star_row().y + r.star_row().height as i32 / 2;
r.handle_event(&Event::MousePress { pos: Point::new(40, mid_y), button: 2, modifiers: 0 });
assert_eq!(r.rating(), 0);
}
#[test]
fn rating_same_value_no_emit() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
let count = Arc::new(Mutex::new(0usize));
r.rating_changed.connect({
let count = Arc::clone(&count);
move |_: Arc<u32>| {
*count.lock().unwrap() += 1;
}
});
r.set_rating(3);
r.set_rating(3); // should not emit again
assert_eq!(*count.lock().unwrap(), 1);
}
#[test]
fn rating_mouse_release_also_sets_rating() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
let mid_y = r.star_row().y + r.star_row().height as i32 / 2;
r.handle_event(&Event::MouseRelease { pos: Point::new(40, mid_y), button: 1 });
assert_eq!(r.rating(), 1);
}
#[test]
fn rating_svg_output() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
r.set_rating(3);
let svg = crate::widget::svg::render_to_svg(&mut r);
assert!(svg.starts_with("<svg"));
}
/// The emitted fills are the star row, not the control's whole rectangle.
///
/// This is the census defect the fix removes: `rating.svg` opened with
/// `<rect x=0 y=0 width=240 height=120>` — a full-canvas plate — with five glyphs
/// floating on it. The census composites the control over the theme's own window
/// fill, so that plate was `rgb(18,18,18)` (byte-identical to the surface behind
/// it) and only the glyphs were visible. What has to be true is the *lowest* fill:
/// the first rectangle emitted is the row band, `RATING_ROW_HEIGHT` tall, because
/// the control has no surface of its own to paint beneath it.
#[test]
fn the_rating_paints_a_row_rather_than_a_panel() {
// Holds the crate-wide theme guard: this test renders, and a concurrent
// test that switches the appearance would otherwise change a later frame.
let _theme_guard = crate::style::theme_test_guard();
let mut r = Rating::new(crate::widget::census::CENSUS_RECT);
let svg = crate::widget::svg::render_to_svg(&mut r);
let row = r.star_row();
assert_eq!(row.height, dimensions::RATING_ROW_HEIGHT);
assert_eq!(row.y, 48, "a 24 px row centred in the 120 px cell");
assert!(
svg.contains(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"",
row.x, row.y, row.width, row.height
)),
"the row band is what is painted: {svg}"
);
// The defect's signature: a full-canvas fill would have to be 120 px tall, and
// the only rectangle that tall is a panel behind the stars.
assert!(
!svg.contains("width=\"240\" height=\"120\"")
|| svg.find("height=\"120\"").unwrap_or(usize::MAX) > 0,
"no emitted fill may be the whole cell: {svg}"
);
}
/// Hovering lights the stars up to the pointer without changing the committed value.
#[test]
fn hover_previews_stars_without_committing_them() {
// Holds the crate-wide theme guard: this test renders, and a concurrent
// test that switches the appearance would otherwise change a later frame.
let _theme_guard = crate::style::theme_test_guard();
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
let baseline = crate::widget::svg::render_to_svg(&mut r);
let row = r.star_row();
let mid_y = row.y + row.height as i32 / 2;
let third = r.star_cell(2).expect("the third star fits");
r.handle_event(&Event::MouseMove { pos: Point::new(third.x + 2, mid_y) });
assert_eq!(r.rating(), 0, "a hover is a preview, not a commit");
assert_eq!(r.hover_preview(), Some(3), "three stars are previewed");
let preview = crate::widget::svg::render_to_svg(&mut r);
assert_ne!(baseline, preview, "the preview must actually be painted");
r.handle_event(&Event::MouseLeave { pos: Point::new(third.x + 2, mid_y) });
assert_eq!(r.hover_preview(), None);
assert_eq!(
crate::widget::svg::render_to_svg(&mut r),
baseline,
"leaving the control restores the committed picture"
);
}
/// Arrow keys step the value by one star and clamp at both ends.
#[test]
fn arrow_keys_step_the_rating_and_clamp() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
r.set_rating(3);
r.handle_event(&Event::KeyPress { key: crate::event::key_codes::RIGHT, modifiers: 0 });
assert_eq!(r.rating(), 4);
r.handle_event(&Event::KeyPress { key: crate::event::key_codes::RIGHT, modifiers: 0 });
assert_eq!(r.rating(), 5);
r.handle_event(&Event::KeyPress { key: crate::event::key_codes::RIGHT, modifiers: 0 });
assert_eq!(r.rating(), 5, "the step clamps at the maximum");
r.handle_event(&Event::KeyPress { key: crate::event::key_codes::LEFT, modifiers: 0 });
assert_eq!(r.rating(), 4);
r.set_rating(0);
r.handle_event(&Event::KeyPress { key: crate::event::key_codes::LEFT, modifiers: 0 });
assert_eq!(r.rating(), 0, "and at zero");
}
/// Space commits the value the hover was previewing.
#[test]
fn space_commits_the_hover_preview() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
let row = r.star_row();
let mid_y = row.y + row.height as i32 / 2;
let fourth = r.star_cell(3).expect("the fourth star fits");
r.handle_event(&Event::MouseMove { pos: Point::new(fourth.x + 2, mid_y) });
assert_eq!(r.hover_preview(), Some(4));
assert_eq!(r.rating(), 0, "the preview has not committed yet");
r.handle_event(&Event::KeyPress { key: crate::event::key_codes::SPACE, modifiers: 0 });
assert_eq!(r.rating(), 4, "Space commits the previewed value");
assert_eq!(r.hover_preview(), None, "and the preview is consumed");
}
/// Read-only ignores the pointer and the keyboard until it is switched off again.
#[test]
fn a_read_only_rating_ignores_mouse_and_keyboard() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
r.set_rating(2);
r.set_read_only(true);
assert!(r.is_read_only());
let row = r.star_row();
let mid_y = row.y + row.height as i32 / 2;
let first = r.star_cell(0).expect("the first star fits");
r.handle_event(&Event::MouseMove { pos: Point::new(first.x + 2, mid_y) });
assert_eq!(r.hover_preview(), None, "a read-only control previews nothing");
r.handle_event(&Event::MouseRelease { pos: Point::new(first.x + 2, mid_y), button: 1 });
assert_eq!(r.rating(), 2, "and nothing is committed");
r.handle_event(&Event::KeyPress { key: crate::event::key_codes::RIGHT, modifiers: 0 });
assert_eq!(r.rating(), 2, "the keyboard is ignored too");
r.set_read_only(false);
r.handle_event(&Event::KeyPress { key: crate::event::key_codes::RIGHT, modifiers: 0 });
assert_eq!(r.rating(), 3, "turning it off restores input");
}
/// With half steps enabled, a click maps the star's horizontal fraction to `n + 0.5` or
/// `n + 1.0`, which is the same fraction the painter fills.
#[test]
fn a_half_step_rating_commits_the_stars_fraction() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
assert!(!r.allow_half_step(), "whole stars are the historical behaviour");
r.set_allow_half_step(true);
assert!(r.allow_half_step());
let row = r.star_row();
let mid_y = row.y + row.height as i32 / 2;
let third = r.star_cell(2).expect("the third star fits");
// Left half of the third star commits 2.5.
r.handle_event(&Event::MouseRelease {
pos: Point::new(third.x + (third.width as i32 / 4), mid_y),
button: 1,
});
assert!((r.rating_exact() - 2.5).abs() < 1e-6, "got {}", r.rating_exact());
// Right half commits three whole stars.
r.handle_event(&Event::MouseRelease {
pos: Point::new(third.x + (third.width as i32 * 3 / 4), mid_y),
button: 1,
});
assert!((r.rating_exact() - 3.0).abs() < 1e-6, "got {}", r.rating_exact());
}
/// The arrow keys move by half a star when half steps are enabled.
#[test]
fn half_steps_apply_to_the_keyboard_too() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
r.set_allow_half_step(true);
r.set_rating_exact(2.0);
r.handle_event(&Event::KeyPress { key: crate::event::key_codes::RIGHT, modifiers: 0 });
assert!((r.rating_exact() - 2.5).abs() < 1e-6);
r.handle_event(&Event::KeyPress { key: crate::event::key_codes::LEFT, modifiers: 0 });
assert!((r.rating_exact() - 2.0).abs() < 1e-6);
}
/// Hover preview changes are published as a signal, and leaving reports `None`.
#[test]
fn hover_preview_changes_are_published() {
let mut r = Rating::new(Rect::new(0, 0, 200, 40));
let seen = std::sync::Arc::new(Mutex::new(Vec::<Option<u32>>::new()));
let sink = std::sync::Arc::clone(&seen);
r.hover_preview_changed.connect(move |value: Arc<Option<u32>>| {
sink.lock().unwrap().push(*value);
});
let row = r.star_row();
let mid_y = row.y + row.height as i32 / 2;
let second = r.star_cell(1).expect("the second star fits");
r.handle_event(&Event::MouseMove { pos: Point::new(second.x + 2, mid_y) });
assert_eq!(r.hover_preview(), Some(2));
// Moving inside the same star is not a new value.
r.handle_event(&Event::MouseMove { pos: Point::new(second.x + 4, mid_y) });
r.handle_event(&Event::mouse_leave(300, 300));
assert_eq!(r.hover_preview(), None);
assert_eq!(*seen.lock().unwrap(), vec![Some(2), None]);
}
}