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
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! PieMenu (radial menu) widget.
//!
//! A circular popup menu that displays items as radial slices.
//! Users hover to highlight and click to select an item.
use std::f32::consts::TAU;
use crate::core::{Color, Font, HorizontalAlignment, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::{GenericSignal, Signal1};
use crate::widget::capability::coercion::{expect_f32, expect_usize};
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};
/// A single item in a `PieMenu`.
#[derive(Debug, Clone)]
pub struct PieMenuItem {
text: String,
icon_text: String,
enabled: bool,
angle_start: f32,
angle_end: f32,
}
impl PieMenuItem {
/// Creates an enabled item with the given label, no icon text, and its
/// angles unset (`0.0` for both).
///
/// The angles are placeholders until the item is inserted into a
/// [`PieMenu`], which recomputes them to divide the circle evenly among all
/// items.
pub fn new(text: impl Into<String>) -> Self {
Self {
text: text.into(),
icon_text: String::new(),
enabled: true,
angle_start: 0.0,
angle_end: 0.0,
}
}
/// Returns the item's label.
pub fn text(&self) -> &str {
&self.text
}
/// Replaces the item's label. The slice angle is not affected, and no
/// redraw is requested.
pub fn set_text(&mut self, text: impl Into<String>) {
self.text = text.into();
}
/// Returns the icon text, or an empty string when the item has no icon.
///
/// This is a text stand-in for an icon, not image data.
pub fn icon_text(&self) -> &str {
&self.icon_text
}
/// Replaces the icon text. An empty string means "no icon".
pub fn set_icon_text(&mut self, icon: impl Into<String>) {
self.icon_text = icon.into();
}
/// Returns whether the item can be clicked. Defaults to `true`.
pub fn is_enabled(&self) -> bool {
self.enabled
}
/// Enables or disables the item. A disabled item is still drawn but is
/// skipped by hit testing, so hovering it clears the hover highlight rather
/// than selecting it.
pub fn set_enabled(&mut self, enabled: bool) {
self.enabled = enabled;
}
/// Returns the slice's start angle, in radians measured clockwise from the
/// positive x axis (see the module drawing code), with `0.0` at the right
/// of the menu centre.
///
/// Managed by [`PieMenu`]; setting it directly is only meaningful for a
/// standalone item.
pub fn angle_start(&self) -> f32 {
self.angle_start
}
/// Sets the slice's start angle in radians. Not validated, and the menu
/// overwrites it whenever the item list changes.
pub fn set_angle_start(&mut self, angle: f32) {
self.angle_start = angle;
}
/// Returns the slice's exclusive end angle, in radians. The slice spans
/// `angle_start .. angle_end`.
pub fn angle_end(&self) -> f32 {
self.angle_end
}
/// Sets the slice's exclusive end angle in radians. Not validated.
pub fn set_angle_end(&mut self, angle: f32) {
self.angle_end = angle;
}
}
/// PieMenu (radial/circular menu) widget.
///
/// Displays items arranged radially around a center point. The menu
/// appears as a donut-like ring with labelled slices. Supports hover
/// highlighting, click selection, and keyboard dismissal.
pub struct PieMenu {
base: BaseWidget,
items: Vec<PieMenuItem>,
radius: f32,
inner_radius: f32,
hovered_index: Option<usize>,
current_index: usize,
center: Point,
animation_progress: f32,
hover_color: Color,
text_color: Color,
/// Emitted with the index whose selection was applied. Fires from user
/// clicks and from [`PieMenu::set_current_index`] — so programmatic
/// selection is indistinguishable from a click, and a slot that reacts by
/// calling `set_current_index` again will recurse. A
/// [`PieMenu::set_current_index`] call with an out-of-range index emits
/// nothing.
pub triggered: Signal1<usize>,
/// Emitted with the selected item's label, alongside `triggered`. Empty
/// labels produce an empty payload; duplicate labels are indistinguishable.
pub triggered_text: Signal1<String>,
/// Emitted by [`PieMenu::show_at`], just before the menu becomes visible.
pub about_to_show: GenericSignal,
/// Emitted by [`PieMenu::hide`], after the menu is hidden and the hover
/// highlight cleared.
pub about_to_hide: GenericSignal,
}
impl PieMenu {
/// The smallest outer radius [`PieMenu::new`] and [`PieMenu::set_radius`] accept.
///
/// Exposed because the two are the *only* writers of `radius`, and both floor at this
/// value, which is what makes the `2.0` floor of [`PieMenu::set_inner_radius`] and the
/// `0.95 * radius` ceiling mutually satisfiable. `new` used to accept any value — including
/// zero, which produced a zero-sized geometry no item can be hit-tested against.
pub const MIN_RADIUS: f32 = 10.0;
/// Creates a new `PieMenu` centered at `center` with the given outer `radius`.
///
/// `radius` is floored at [`PieMenu::MIN_RADIUS`], the same floor [`PieMenu::set_radius`]
/// applies, so a menu never starts outside the range its own setters maintain. The inner
/// radius starts at 35% of the **effective** radius, keeping it inside the
/// `2.0 ..= 0.95 * radius` band [`PieMenu::set_inner_radius`] documents.
pub fn new(center: Point, radius: f32) -> Self {
let radius =
if radius.is_finite() { radius.max(Self::MIN_RADIUS) } else { Self::MIN_RADIUS };
let size = (radius * 2.0) as u32;
let geometry = Rect::new(center.x - radius as i32, center.y - radius as i32, size, size);
let inner_radius = radius * 0.35;
Self {
base: BaseWidget::new(WidgetKind::PieMenu, geometry, "PieMenu"),
items: Vec::new(),
radius,
inner_radius,
hovered_index: None,
current_index: 0,
center,
animation_progress: 1.0,
hover_color: Color::rgb(0, 120, 215),
text_color: Color::rgb(30, 30, 30),
triggered: Signal1::new(),
triggered_text: Signal1::new(),
about_to_show: GenericSignal::new(),
about_to_hide: GenericSignal::new(),
}
}
/// Returns the current (last selected) index.
pub fn current_index(&self) -> usize {
self.current_index
}
/// Sets the current index with bounds checking.
///
/// An out-of-range index is silently ignored. On success this emits
/// `triggered` and `triggered_text` and requests a redraw; the current
/// index is **not** updated for an item that is disabled.
pub fn set_current_index(&mut self, idx: usize) {
if idx < self.items.len() {
// Mirror the click/hit-test paths: a disabled item is not selectable,
// so the index is left untouched and no signal fires.
if !self.items[idx].is_enabled() {
return;
}
self.current_index = idx;
self.triggered.emit(idx);
if let Some(text) = self.items.get(idx).map(|item| item.text().to_string()) {
self.triggered_text.emit(text);
}
self.base.request_redraw();
}
}
/// Adds a menu item and returns its index.
pub fn add_item(&mut self, text: impl Into<String>) -> usize {
self.add_item_with_icon(text, "")
}
/// Adds an item with a text icon and returns its index.
///
/// Angles are recomputed so all items share the circle equally, which means
/// adding an item moves every existing slice.
pub fn add_item_with_icon(
&mut self,
text: impl Into<String>,
icon: impl Into<String>,
) -> usize {
let idx = self.items.len();
let mut item = PieMenuItem::new(text);
item.set_icon_text(icon);
self.items.push(item);
self.recalculate_angles();
idx
}
/// Inserts an item at `index`, or appends when `index` is past the end.
///
/// The new item has no icon text. Angles are recomputed for every item, and
/// [`PieMenu::current_index`] is not adjusted, so it can end up naming a
/// different item than before.
pub fn insert_item(&mut self, index: usize, text: impl Into<String>) {
let idx = index.min(self.items.len());
self.items.insert(idx, PieMenuItem::new(text));
self.recalculate_angles();
}
/// Removes the item at `index`; out-of-range indices are ignored.
///
/// Angles are recomputed for the remaining items. [`PieMenu::current_index`]
/// and [`PieMenu::hovered_index`] are not adjusted, so they can be left
/// pointing past the end of the list.
pub fn remove_item(&mut self, index: usize) {
if index < self.items.len() {
self.items.remove(index);
self.recalculate_angles();
}
}
/// Removes all menu items and clears the hover highlight.
///
/// [`PieMenu::current_index`] is left as-is even though it now names no
/// item.
pub fn clear(&mut self) {
self.items.clear();
self.hovered_index = None;
}
/// Returns the number of items in the menu.
pub fn item_count(&self) -> usize {
self.items.len()
}
/// Returns a slice of all menu items.
pub fn items(&self) -> &[PieMenuItem] {
&self.items
}
/// Enables or disables the item at `index`, ignoring out-of-range indices.
/// Disabling does not clear an existing hover highlight or redraw.
pub fn set_item_enabled(&mut self, index: usize, enabled: bool) {
if let Some(item) = self.items.get_mut(index) {
item.set_enabled(enabled);
}
}
/// Returns the outer radius of the menu.
pub fn radius(&self) -> f32 {
self.radius
}
/// Sets the outer radius of the menu.
///
/// Values below `10.0` are raised to `10.0` ([`PieMenu::MIN_RADIUS`]); a non-finite value
/// falls back to that floor. The inner radius is pulled down if it would otherwise reach
/// past 90% of the new outer radius, and the widget geometry is recomputed to the
/// enclosing square.
pub fn set_radius(&mut self, radius: f32) {
self.radius =
if radius.is_finite() { radius.max(Self::MIN_RADIUS) } else { Self::MIN_RADIUS };
self.inner_radius = self.inner_radius.min(self.radius * 0.9);
self.update_geometry();
}
/// Returns the inner (donut hole) radius.
pub fn inner_radius(&self) -> f32 {
self.inner_radius
}
/// Sets the inner (donut hole) radius.
///
/// Clamped into `2.0 ..= 0.95 * radius`; the widget geometry is recomputed.
///
/// # Why the clamp order matters
///
/// This was `inner_radius.max(2.0).min(self.radius * 0.95)`: raising the floor first and
/// only then applying the ceiling means the ceiling wins, so the documented lower bound is
/// not actually guaranteed when `0.95 * radius < 2.0`. That required `radius < ~2.11`,
/// which [`PieMenu::set_radius`] could not produce (it floors at 10.0) but
/// [`PieMenu::new`] **could**, because it accepted any radius: `new(center, 2.0)` followed
/// by `set_inner_radius(1.0)` stored `1.9`, below the documented floor. `min` then `max`
/// makes the band's own definition authoritative, and with both writers now flooring the
/// radius the two bounds cannot cross.
///
/// A non-finite input is refused (the previous value is kept) rather than propagated:
/// `f32::max`/`f32::min` return the non-NaN operand, so a NaN input silently produced
/// whatever the other operand was, which is not a value the caller asked for either.
pub fn set_inner_radius(&mut self, inner_radius: f32) {
if !inner_radius.is_finite() {
return;
}
self.inner_radius = inner_radius.min(self.radius * 0.95).max(2.0);
self.update_geometry();
}
/// Returns the center point of the menu.
pub fn center(&self) -> Point {
self.center
}
/// Sets the center point of the menu, in parent-relative logical pixels,
/// and recomputes the widget geometry so it is the square of side
/// `2 * radius` centred on that point.
pub fn set_center(&mut self, center: Point) {
self.center = center;
self.update_geometry();
}
/// Returns the animation progress (0.0 to 1.0).
pub fn animation_progress(&self) -> f32 {
self.animation_progress
}
/// Sets the animation progress, clamped to `0.0 ..= 1.0`.
///
/// The value is a plain stored number: the widget never advances it itself
/// and does not request a redraw, so an animating caller must step it and
/// repaint. `1.0` (fully shown) is the initial value.
pub fn set_animation_progress(&mut self, progress: f32) {
self.animation_progress = progress.clamp(0.0, 1.0);
}
/// Returns the hover highlight color.
pub fn hover_color(&self) -> Color {
self.hover_color
}
/// Sets the hover highlight color. Does not request a redraw.
pub fn set_hover_color(&mut self, color: Color) {
self.hover_color = color;
}
/// Returns the text color for labels.
pub fn text_color(&self) -> Color {
self.text_color
}
/// Sets the text color for labels. Does not request a redraw.
pub fn set_text_color(&mut self, color: Color) {
self.text_color = color;
}
/// Returns the currently hovered item index, if any.
pub fn hovered_index(&self) -> Option<usize> {
self.hovered_index
}
/// Shows the menu centred on `center` (parent-relative logical pixels).
///
/// Clears the hover highlight, emits `about_to_show`, then makes the widget
/// visible. The radius and item list are unchanged.
pub fn show_at(&mut self, center: Point) {
self.center = center;
self.update_geometry();
self.hovered_index = None;
self.about_to_show.emit();
self.base.show();
}
/// Hides the menu, clears the hover highlight, then emits `about_to_hide`.
///
/// Note the ordering is the reverse of [`PieMenu::show_at`], which emits
/// before showing. Emits unconditionally, even when already hidden.
pub fn hide(&mut self) {
self.base.hide();
self.hovered_index = None;
self.about_to_hide.emit();
}
// ── Private helpers ──────────────────────────────────────────
/// Recalculates the start/end angles for every item based on equal division.
fn recalculate_angles(&mut self) {
let count = self.items.len();
if count == 0 {
return;
}
let slice = TAU / count as f32;
for (i, item) in self.items.iter_mut().enumerate() {
item.set_angle_start(i as f32 * slice);
item.set_angle_end((i as f32 + 1.0) * slice);
}
}
/// Updates the widget geometry to match the current center and radius.
fn update_geometry(&mut self) {
let size = (self.radius * 2.0) as u32;
self.base.set_geometry(Rect::new(
self.center.x - self.radius as i32,
self.center.y - self.radius as i32,
size,
size,
));
}
/// Returns the index of the slice at the given position, or `None`.
fn hit_test(&self, pos: Point) -> Option<usize> {
let dx = (pos.x - self.center.x) as f32;
let dy = (pos.y - self.center.y) as f32;
let dist = (dx * dx + dy * dy).sqrt();
if dist < self.inner_radius || dist > self.radius {
return None;
}
let mut angle = dy.atan2(dx);
if angle < 0.0 {
angle += TAU;
}
for (i, item) in self.items.iter().enumerate() {
if angle >= item.angle_start() && angle < item.angle_end() {
if item.is_enabled() {
return Some(i);
}
return None;
}
}
None
}
/// Fills the whole donut track — the ring the slices are cut from.
///
/// Painted before any slice, so an open menu with no items is still a visible ring rather
/// than nothing at all. Built the same way as [`Self::fill_slice`] — dense arcs at a range of
/// radii — so the track and the wedges it carries are drawn by one technique.
fn fill_ring(
&self,
context: &mut RenderContext,
center: Point,
outer_r: f32,
inner_r: f32,
color: Color,
) {
let cx = center.x as f32;
let cy = center.y as f32;
let strips = ((outer_r - inner_r) * 0.5).clamp(4.0, 30.0) as u32;
let strip_count = strips.max(4);
let full_circle = core::f32::consts::TAU;
for i in 0..strip_count {
let frac = i as f32 / strip_count as f32;
let r = inner_r + frac * (outer_r - inner_r);
let sub_segments = ((r * full_circle * 0.25) as u32).clamp(8, 96);
let step_a = full_circle / sub_segments as f32;
for j in 0..sub_segments {
let a1 = j as f32 * step_a;
let a2 = a1 + step_a;
context.draw_line_stroke(
Point::from_f32(cx + r * a1.cos(), cy + r * a1.sin()),
Point::from_f32(cx + r * a2.cos(), cy + r * a2.sin()),
color,
1,
);
}
}
}
/// Fills a pie slice wedge by drawing dense radial lines.
#[allow(clippy::too_many_arguments)]
fn fill_slice(
&self,
context: &mut RenderContext,
center: Point,
outer_r: f32,
inner_r: f32,
angle_start: f32,
angle_end: f32,
color: Color,
) {
let cx = center.x as f32;
let cy = center.y as f32;
let delta_angle = angle_end - angle_start;
// Number of radial strips to approximate the fill
let strips = ((outer_r - inner_r) * 0.5).clamp(4.0, 30.0) as u32;
let strip_count = strips.max(4);
for i in 0..strip_count {
let frac = i as f32 / strip_count as f32;
let r = inner_r + frac * (outer_r - inner_r);
let sub_segments = (r * delta_angle * 0.25).clamp(4.0, 20.0) as u32;
let sub_segments = sub_segments.clamp(3, 20);
let step_a = delta_angle / sub_segments as f32;
for j in 0..sub_segments {
let a1 = angle_start + j as f32 * step_a;
let a2 = angle_start + (j + 1) as f32 * step_a;
context.draw_line_stroke(
Point::from_f32(cx + r * a1.cos(), cy + r * a1.sin()),
Point::from_f32(cx + r * a2.cos(), cy + r * a2.sin()),
color,
1,
);
}
}
// Side edges
let inner_start =
Point::from_f32(cx + inner_r * angle_start.cos(), cy + inner_r * angle_start.sin());
let outer_start =
Point::from_f32(cx + outer_r * angle_start.cos(), cy + outer_r * angle_start.sin());
let inner_end =
Point::from_f32(cx + inner_r * angle_end.cos(), cy + inner_r * angle_end.sin());
let outer_end =
Point::from_f32(cx + outer_r * angle_end.cos(), cy + outer_r * angle_end.sin());
context.draw_line_stroke(inner_start, outer_start, color, 1);
context.draw_line_stroke(inner_end, outer_end, color, 1);
}
/// Returns a colour for the slice at index `i`, cycling through a pleasant palette.
fn slice_color(&self, i: usize) -> Color {
const PALETTE: &[Color] = &[
Color::rgb(173, 216, 230), // light blue
Color::rgb(255, 182, 193), // light pink
Color::rgb(152, 251, 152), // pale green
Color::rgb(255, 218, 185), // peach
Color::rgb(216, 191, 216), // thistle
Color::rgb(255, 228, 181), // moccasin
Color::rgb(175, 238, 238), // turquoise
Color::rgb(255, 239, 213), // papaya whip
Color::rgb(221, 160, 221), // plum
Color::rgb(176, 224, 230), // powder blue
Color::rgb(240, 230, 140), // khaki
Color::rgb(255, 192, 203), // pink
];
PALETTE[i % PALETTE.len()]
}
}
impl Widget for PieMenu {
fn base(&self) -> &BaseWidget {
&self.base
}
fn base_mut(&mut self) -> &mut BaseWidget {
&mut self.base
}
fn size_hint(&self) -> Size {
crate::core::Size::new(200, 200)
}
fn show(&mut self) {
self.about_to_show.emit();
self.base.show();
}
fn hide(&mut self) {
self.base.hide();
self.hovered_index = None;
self.about_to_hide.emit();
}
impl_draw_bridge!();
impl_widget_property_hooks!();
}
/// `PieMenu`'s property contract.
///
/// All four properties are read-only projections of the menu's geometry and
/// selection state — none of them has a setter that would not fight the layout
/// that produced the radii — so there is no write arm for them and the schema
/// marks each one non-writable.
impl WidgetProperties for PieMenu {
fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
match name {
"item_count" => Ok(CapabilityValue::UInt(self.item_count() as u64)),
"radius" => Ok(CapabilityValue::Float(self.radius() as f64)),
"inner_radius" => Ok(CapabilityValue::Float(self.inner_radius() as f64)),
"current_index" => Ok(CapabilityValue::UInt(self.current_index() as u64)),
_ => base_property_get(self, name),
}
}
fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
match name {
"radius" => {
self.set_radius(expect_f32(value)?);
Ok(())
}
"inner_radius" => {
self.set_inner_radius(expect_f32(value)?);
Ok(())
}
"current_index" => {
self.set_current_index(expect_usize(value)?);
Ok(())
}
// Derived from the item vector, so there is nothing to assign.
"item_count" => Err(CapabilityAccessError::ReadOnlyProperty),
_ => base_property_set(self, name, value),
}
}
fn property_names(&self) -> &'static [&'static str] {
property_names_of![
"item_count",
"radius",
"inner_radius",
"current_index",
BASE_PROPERTY_NAMES
]
}
/// Runs one of the commands `pie_menu` publishes.
///
/// `add_item` takes the label string and `remove_item` the index, so those
/// are answered as needing a payload rather than being called unknown.
/// `set_radius` is wired to the widget's real `set_radius`, which recomputes
/// the geometry, but the value is what the caller actually wants to change,
/// so a bare invocation is reported as needing it too. `set_current_index`
/// selects the item at that index, which likewise cannot be guessed.
fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
match name {
"add_item" | "remove_item" | "set_radius" | "set_current_index" => {
Err(CapabilityAccessError::OutOfRange)
}
_ => Err(CapabilityAccessError::UnknownCommand),
}
}
}
impl EventHandler for PieMenu {
fn handle_event(&mut self, event: &Event) {
self.base.handle_event(event);
if !self.base.is_enabled() || !self.base.is_visible() {
return;
}
match event {
Event::MouseMove { pos } => {
self.hovered_index = self.hit_test(*pos);
}
Event::MousePress { pos, button: 1 } => {
if let Some(idx) = self.hit_test(*pos) {
if let Some(item) = self.items.get(idx) {
if item.is_enabled() {
let text = item.text().to_string();
self.triggered.emit(idx);
self.triggered_text.emit(text);
self.hide();
}
}
}
}
Event::KeyPress { key, .. } if *key == 27 => {
// Escape
self.hide();
}
_ => { /* Other events are not relevant */ }
}
}
}
impl Draw for PieMenu {
fn draw(&mut self, context: &mut RenderContext) {
if !self.is_visible() {
return;
}
// Chrome colours resolve the explicit style first, then the theme's resolved style for
// this control, and only then a literal. The ring, its separators and the hub hole all
// used to be literals, so a light/dark switch left the control's chrome unchanged — the
// rendering census reported it as theme-blind.
//
// 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("pie_menu");
// Read as its own lock acquisition and copied out as values, so the guard is dropped
// before anything else touches the theme.
let (window_fill, foreground, secondary) = {
let manager = crate::style::theme_manager();
match manager.current_theme() {
Some(active) => {
(active.colors.background, active.colors.foreground, active.colors.secondary)
}
None => (Color::rgb(240, 240, 240), Color::BLACK, Color::rgb(158, 158, 158)),
}
};
let ink = style
.text_color
.or_else(|| theme.as_ref().and_then(|t| t.text_color))
.unwrap_or(foreground);
// `pie_menu` is absent from `WidgetRole::for_kind_name`'s table, so it classifies as
// `Surface` and the active theme writes the window fill into `style.background_color`.
// A ring painted in that colour would be byte-identical to the frame behind it, so a
// resolved surface equal to the window fill is re-derived a visible step away from it,
// while a colour the caller set still wins.
let ring = match style.background_color {
Some(resolved) if resolved != window_fill => resolved,
_ => window_fill.blend(&ink, 0.12),
};
let border = style
.border_color
.or_else(|| theme.as_ref().and_then(|t| t.border_color))
.filter(|resolved| *resolved != ring)
.unwrap_or_else(|| ring.blend(&secondary, 0.45));
let center = self.center;
let outer_r = self.radius;
let inner_r = self.inner_radius;
let cx = center.x as f32;
let cy = center.y as f32;
// The ring track and its hub are drawn before the early return on an empty item list, so a
// freshly constructed menu is visible rather than reporting `ink = 0`; an empty ring reads
// as a menu that has been opened with nothing to offer.
self.fill_ring(context, center, outer_r, inner_r, ring);
// Draw each slice
for (i, item) in self.items.iter().enumerate() {
let is_hovered = self.hovered_index == Some(i);
// A disabled slice takes the themed track rather than a fixed light grey, so it reads
// as a muted wedge on either appearance.
let base_color = if !item.is_enabled() {
ring
} else if is_hovered {
self.hover_color
} else {
self.slice_color(i)
};
self.fill_slice(
context,
center,
outer_r,
inner_r,
item.angle_start(),
item.angle_end(),
base_color,
);
}
// Draw separator lines between slices (radial lines)
for item in self.items.iter() {
context.draw_line_stroke(
Point::from_f32(
cx + inner_r * item.angle_start().cos(),
cy + inner_r * item.angle_start().sin(),
),
Point::from_f32(
cx + outer_r * item.angle_start().cos(),
cy + outer_r * item.angle_start().sin(),
),
border,
1,
);
}
// Draw the outer ring border
context.draw_circle_stroke(center, outer_r as u32, border, 1);
// Draw the inner donut hole circle
let hub = ring.blend(&ink, 0.10);
context.fill_circle(center, inner_r as u32, hub);
context.draw_circle_stroke(center, inner_r as u32, border, 1);
// Draw text labels centered in each slice
let font = Font::default();
for (i, item) in self.items.iter().enumerate() {
if !item.is_enabled() {
continue;
}
let mid_angle = (item.angle_start() + item.angle_end()) * 0.5;
let label_r = (outer_r + inner_r) * 0.5;
let lx = cx + label_r * mid_angle.cos();
let ly = cy + label_r * mid_angle.sin();
let label_text =
if item.icon_text().is_empty() { item.text() } else { item.icon_text() };
// A highlighted label takes the contrast colour of the accent it sits on, so it is not
// a fixed white that may vanish on a light accent.
let text_color = if self.hovered_index == Some(i) {
self.hover_color.contrast_color()
} else {
self.text_color
};
context.draw_text(
Point::from_f32(lx, ly),
label_text,
&font,
text_color,
HorizontalAlignment::Left,
);
}
// Draw a small center dot
context.fill_circle(center, 3, border);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::Color;
use crate::event::Event;
use crate::widget::svg::render_to_svg;
use std::sync::{Arc, Mutex};
/// 1. Creating default PieMenu (verify kind, geometry, default state)
#[test]
fn test_default_creation() {
let center = Point::new(200, 200);
let radius = 100.0;
let menu = PieMenu::new(center, radius);
assert_eq!(menu.kind(), WidgetKind::PieMenu);
assert_eq!(menu.center(), center);
assert_eq!(menu.radius(), radius);
assert!(menu.inner_radius() < radius);
assert_eq!(menu.inner_radius(), radius * 0.35);
assert_eq!(menu.current_index(), 0);
assert_eq!(menu.hovered_index(), None);
assert_eq!(menu.animation_progress(), 1.0);
assert_eq!(menu.item_count(), 0);
assert!(menu.is_visible());
assert!(menu.is_enabled());
assert!(menu.items().is_empty());
// Default colors
assert_eq!(menu.hover_color(), Color::rgb(0, 120, 215));
assert_eq!(menu.text_color(), Color::rgb(30, 30, 30));
// Geometry: centered at (200,200) with radius 100 => rect (100, 100, 200, 200)
let geom = menu.geometry();
assert_eq!(geom.x, 100);
assert_eq!(geom.y, 100);
assert_eq!(geom.width, 200);
assert_eq!(geom.height, 200);
}
/// 2. Adding items
#[test]
fn test_add_item() {
let mut menu = PieMenu::new(Point::new(100, 100), 80.0);
let idx0 = menu.add_item("Cut");
assert_eq!(idx0, 0);
assert_eq!(menu.item_count(), 1);
let idx1 = menu.add_item("Copy");
assert_eq!(idx1, 1);
assert_eq!(menu.item_count(), 2);
let idx2 = menu.add_item_with_icon("Paste", "📋");
assert_eq!(idx2, 2);
assert_eq!(menu.item_count(), 3);
// Verify items
let items = menu.items();
assert_eq!(items[0].text(), "Cut");
assert_eq!(items[1].text(), "Copy");
assert_eq!(items[2].text(), "Paste");
assert_eq!(items[2].icon_text(), "📋");
}
/// 3. Inserting items at specific index
#[test]
fn test_insert_item_at_index() {
let mut menu = PieMenu::new(Point::new(100, 100), 80.0);
menu.add_item("First");
menu.add_item("Third");
assert_eq!(menu.item_count(), 2);
// Insert at middle
menu.insert_item(1, "Second");
assert_eq!(menu.item_count(), 3);
assert_eq!(menu.items()[0].text(), "First");
assert_eq!(menu.items()[1].text(), "Second");
assert_eq!(menu.items()[2].text(), "Third");
// Insert at beginning
menu.insert_item(0, "Zero");
assert_eq!(menu.items()[0].text(), "Zero");
assert_eq!(menu.items()[1].text(), "First");
// Insert beyond end => appends
menu.insert_item(99, "Last");
assert_eq!(menu.items().last().unwrap().text(), "Last");
// Verify angles are recalculated (all items get equal slices)
let count = menu.item_count();
let slice = std::f32::consts::TAU / count as f32;
for (i, item) in menu.items().iter().enumerate() {
let expected_start = i as f32 * slice;
let expected_end = (i as f32 + 1.0) * slice;
assert!((item.angle_start() - expected_start).abs() < 0.001);
assert!((item.angle_end() - expected_end).abs() < 0.001);
}
}
/// 4. Removing items
#[test]
fn test_remove_item() {
let mut menu = PieMenu::new(Point::new(100, 100), 80.0);
menu.add_item("A");
menu.add_item("B");
menu.add_item("C");
assert_eq!(menu.item_count(), 3);
// Remove middle
menu.remove_item(1);
assert_eq!(menu.item_count(), 2);
assert_eq!(menu.items()[0].text(), "A");
assert_eq!(menu.items()[1].text(), "C");
// Remove out of bounds => no-op
menu.remove_item(99);
assert_eq!(menu.item_count(), 2);
// Remove all
menu.remove_item(1);
menu.remove_item(0);
assert_eq!(menu.item_count(), 0);
}
/// 5. Setting/getting current index
#[test]
fn test_current_index() {
let mut menu = PieMenu::new(Point::new(100, 100), 80.0);
menu.add_item("Red");
menu.add_item("Green");
menu.add_item("Blue");
// Default is 0
assert_eq!(menu.current_index(), 0);
menu.set_current_index(1);
assert_eq!(menu.current_index(), 1);
menu.set_current_index(2);
assert_eq!(menu.current_index(), 2);
// Out of bounds => no-op
menu.set_current_index(99);
assert_eq!(menu.current_index(), 2);
}
/// 6. Item count
#[test]
fn test_item_count() {
let mut menu = PieMenu::new(Point::new(100, 100), 80.0);
assert_eq!(menu.item_count(), 0);
menu.add_item("One");
assert_eq!(menu.item_count(), 1);
menu.add_item("Two");
menu.add_item("Three");
assert_eq!(menu.item_count(), 3);
menu.clear();
assert_eq!(menu.item_count(), 0);
}
/// 7. Setting item text and icon
#[test]
fn test_item_text_and_icon() {
let mut menu = PieMenu::new(Point::new(100, 100), 80.0);
menu.add_item("Initial");
// Mutable access via items() slice is not directly mutable,
// but we can use the item API through the menu.
// Create a new item and check PieMenuItem's setters
let mut item = PieMenuItem::new("Test");
assert_eq!(item.text(), "Test");
assert_eq!(item.icon_text(), "");
item.set_text("Updated");
assert_eq!(item.text(), "Updated");
item.set_icon_text("🚀");
assert_eq!(item.icon_text(), "🚀");
// Also verify that add_item_with_icon sets icon correctly
let mut menu2 = PieMenu::new(Point::new(50, 50), 60.0);
menu2.add_item_with_icon("Save", "💾");
assert_eq!(menu2.items()[0].text(), "Save");
assert_eq!(menu2.items()[0].icon_text(), "💾");
}
/// 8. Enabling/disabling items
#[test]
fn test_enable_disable_items() {
let mut menu = PieMenu::new(Point::new(100, 100), 80.0);
menu.add_item("Alpha");
menu.add_item("Beta");
menu.add_item("Gamma");
// All start enabled
assert!(menu.items()[0].is_enabled());
assert!(menu.items()[1].is_enabled());
assert!(menu.items()[2].is_enabled());
menu.set_item_enabled(1, false);
assert!(menu.items()[0].is_enabled());
assert!(!menu.items()[1].is_enabled());
assert!(menu.items()[2].is_enabled());
// Re-enable
menu.set_item_enabled(1, true);
assert!(menu.items()[1].is_enabled());
// Out of bounds => no-op
menu.set_item_enabled(99, false);
assert_eq!(menu.item_count(), 3);
}
/// 9. Setting radius and center
#[test]
fn test_radius_and_center() {
let mut menu = PieMenu::new(Point::new(100, 100), 80.0);
assert_eq!(menu.radius(), 80.0);
assert_eq!(menu.center(), Point::new(100, 100));
// Set radius
menu.set_radius(120.0);
assert_eq!(menu.radius(), 120.0);
// Clamped minimum
menu.set_radius(5.0);
assert_eq!(menu.radius(), 10.0);
// Set center
menu.set_center(Point::new(300, 400));
assert_eq!(menu.center(), Point::new(300, 400));
// Geometry updates with new center/radius
let geom = menu.geometry();
assert_eq!(geom.x, 290); // center.x(300) - radius(10) = 290
assert_eq!(geom.width, 20);
assert_eq!(geom.height, 20);
}
/// 10. Item visibility (via base widget delegation)
#[test]
fn test_item_visibility() {
let mut menu = PieMenu::new(Point::new(100, 100), 80.0);
assert!(menu.is_visible());
menu.hide();
assert!(!menu.is_visible());
assert_eq!(menu.hovered_index(), None);
menu.show();
assert!(menu.is_visible());
// show_at also makes it visible
menu.hide();
menu.show_at(Point::new(200, 200));
assert!(menu.is_visible());
}
/// 11. Signal accessors (triggered, triggered_text, about_to_show, about_to_hide)
#[test]
fn test_signal_accessors() {
let mut menu = PieMenu::new(Point::new(100, 100), 80.0);
menu.add_item("Open");
menu.add_item("Save");
menu.add_item("Exit");
// Test triggered signal via set_current_index
let triggered = Arc::new(Mutex::new(None));
menu.triggered.connect({
let triggered = Arc::clone(&triggered);
move |val: Arc<usize>| {
*triggered.lock().unwrap() = Some(*val);
}
});
menu.set_current_index(1);
assert_eq!(*triggered.lock().unwrap(), Some(1));
// Test triggered_text signal
let triggered_text = Arc::new(Mutex::new(None::<String>));
menu.triggered_text.connect({
let triggered_text = Arc::clone(&triggered_text);
move |val: Arc<String>| {
*triggered_text.lock().unwrap() = Some(val.to_string());
}
});
menu.set_current_index(2);
assert_eq!(triggered_text.lock().unwrap().as_deref(), Some("Exit"));
// Test about_to_show signal
let show_fired = Arc::new(Mutex::new(false));
menu.about_to_show.connect({
let show_fired = Arc::clone(&show_fired);
move || {
*show_fired.lock().unwrap() = true;
}
});
menu.hide();
menu.show_at(Point::new(150, 150));
assert!(*show_fired.lock().unwrap());
// Test about_to_hide signal
let hide_fired = Arc::new(Mutex::new(false));
menu.about_to_hide.connect({
let hide_fired = Arc::clone(&hide_fired);
move || {
*hide_fired.lock().unwrap() = true;
}
});
menu.hide();
assert!(*hide_fired.lock().unwrap());
}
/// 12. Geometry delegation
#[test]
fn test_geometry_delegation() {
let mut menu = PieMenu::new(Point::new(50, 60), 40.0);
// Geometry via Widget trait
let geom = menu.geometry();
assert_eq!(geom.x, 10); // 50 - 40
assert_eq!(geom.y, 20); // 60 - 40
assert_eq!(geom.width, 80);
assert_eq!(geom.height, 80);
// set_geometry through Widget trait
menu.set_geometry(Rect::new(0, 0, 100, 100));
assert_eq!(menu.geometry(), Rect::new(0, 0, 100, 100));
// rect() alias
assert_eq!(menu.geometry(), Rect::new(0, 0, 100, 100));
// position / size
assert_eq!(menu.position(), Point::new(0, 0));
assert_eq!(menu.size(), crate::core::Size::new(100, 100));
}
/// 13. Widget ID and kind
#[test]
fn test_widget_id_and_kind() {
let menu = PieMenu::new(Point::new(0, 0), 50.0);
// Kind
assert_eq!(menu.kind(), WidgetKind::PieMenu);
// ID should be non-zero (Object generates unique IDs)
assert_ne!(menu.id(), 0);
// Two menus should have different IDs
let menu2 = PieMenu::new(Point::new(10, 10), 30.0);
assert_ne!(menu.id(), menu2.id());
}
/// 14. SVG output verification
#[test]
fn test_svg_output() {
let mut menu = PieMenu::new(Point::new(50, 50), 50.0);
menu.add_item("Cut");
menu.add_item("Copy");
menu.add_item("Paste");
let svg = render_to_svg(&mut menu);
// Should be a valid SVG string
assert!(svg.starts_with("<svg"));
assert!(svg.contains("xmlns=\"http://www.w3.org/2000/svg\""));
// Geometry-derived viewBox/viewport
assert!(svg.contains("width=\"100\""));
assert!(svg.contains("height=\"100\""));
// Should draw circle borders and center dot
assert!(svg.contains("circle"));
assert!(svg.contains("line"));
// Empty menu also produces SVG with just circles
let mut empty = PieMenu::new(Point::new(10, 10), 10.0);
let empty_svg = render_to_svg(&mut empty);
assert!(empty_svg.starts_with("<svg"));
}
/// 15. Disabled state blocks events
#[test]
fn test_disabled_state_blocks_events() {
let mut menu = PieMenu::new(Point::new(100, 100), 80.0);
menu.add_item("Test");
// Disable the widget
menu.set_enabled(false);
assert!(!menu.is_enabled());
// Hover events should not update hovered_index when disabled
menu.handle_event(&Event::MouseMove { pos: Point::new(100, 100) });
assert_eq!(menu.hovered_index(), None);
// Mouse press should not trigger
let triggered = Arc::new(Mutex::new(false));
menu.triggered.connect({
let triggered = Arc::clone(&triggered);
move |_: Arc<usize>| {
*triggered.lock().unwrap() = true;
}
});
menu.handle_event(&Event::MousePress { pos: Point::new(100, 100), button: 1 });
assert!(!*triggered.lock().unwrap());
// Re-enable and verify events flow again
// Use a point within the pie slice (dist >= inner_radius and <= radius)
menu.set_enabled(true);
menu.handle_event(&Event::MouseMove { pos: Point::new(150, 100) });
assert_eq!(menu.hovered_index(), Some(0));
}
/// 16. Clear all items
#[test]
fn test_clear_items() {
let mut menu = PieMenu::new(Point::new(100, 100), 80.0);
menu.add_item("A");
menu.add_item("B");
menu.add_item("C");
menu.set_current_index(1);
menu.clear();
assert_eq!(menu.item_count(), 0);
assert!(menu.items().is_empty());
assert_eq!(menu.hovered_index(), None);
}
/// 17. Inner radius get/set
#[test]
fn test_inner_radius() {
let mut menu = PieMenu::new(Point::new(100, 100), 100.0);
// Default
assert!((menu.inner_radius() - 35.0).abs() < 0.001);
// Set inner radius
menu.set_inner_radius(50.0);
assert!((menu.inner_radius() - 50.0).abs() < 0.001);
// Clamped to min 2.0
menu.set_inner_radius(1.0);
assert!((menu.inner_radius() - 2.0).abs() < 0.001);
// Clamped to max radius * 0.95
menu.set_inner_radius(200.0);
assert!((menu.inner_radius() - 95.0).abs() < 0.001);
}
/// 18. show_at and hide
#[test]
fn test_show_at_and_hide() {
let mut menu = PieMenu::new(Point::new(0, 0), 50.0);
// Initially visible
assert!(menu.is_visible());
// show_at updates center and makes visible
menu.show_at(Point::new(200, 300));
assert_eq!(menu.center(), Point::new(200, 300));
assert!(menu.is_visible());
assert_eq!(menu.hovered_index(), None);
// hide
menu.hide();
assert!(!menu.is_visible());
assert_eq!(menu.hovered_index(), None);
// Widget trait show/hide delegation
menu.show();
assert!(menu.is_visible());
menu.hide();
assert!(!menu.is_visible());
}
/// 19. Hover color and text color
#[test]
fn test_hover_and_text_colors() {
let mut menu = PieMenu::new(Point::new(100, 100), 80.0);
// Default hover color
assert_eq!(menu.hover_color(), Color::rgb(0, 120, 215));
// Change hover color
menu.set_hover_color(Color::rgb(255, 0, 0));
assert_eq!(menu.hover_color(), Color::rgb(255, 0, 0));
// Default text color
assert_eq!(menu.text_color(), Color::rgb(30, 30, 30));
// Change text color
menu.set_text_color(Color::rgb(255, 255, 255));
assert_eq!(menu.text_color(), Color::rgb(255, 255, 255));
}
/// 20. Animation progress
#[test]
fn test_animation_progress() {
let mut menu = PieMenu::new(Point::new(100, 100), 80.0);
// Default
assert!((menu.animation_progress() - 1.0).abs() < 0.001);
// Set value
menu.set_animation_progress(0.5);
assert!((menu.animation_progress() - 0.5).abs() < 0.001);
// Clamped to [0.0, 1.0]
menu.set_animation_progress(-0.5);
assert!((menu.animation_progress() - 0.0).abs() < 0.001);
menu.set_animation_progress(1.5);
assert!((menu.animation_progress() - 1.0).abs() < 0.001);
}
/// The documented inner-radius band holds for every constructor input.
///
/// `set_inner_radius` was `inner_radius.max(2.0).min(self.radius * 0.95)`: the floor was
/// raised first and the ceiling applied second, so the ceiling won and the documented
/// `2.0` lower bound was not actually guaranteed once `0.95 * radius < 2.0`.
/// `set_radius` could not produce such a radius (it floors at 10.0) but `new` could,
/// because it accepted any value — `new(center, 2.0)` then `set_inner_radius(1.0)` stored
/// `1.9`. Both writers now floor the radius, and the clamp runs ceiling-then-floor.
#[test]
fn pie_menu_inner_radius_stays_inside_the_documented_band() {
for radius in [100.0f32, 10.0, 5.0, 2.1, 2.0, 1.0, 0.0, -5.0] {
let mut menu = PieMenu::new(Point::new(0, 0), radius);
let outer = menu.radius();
assert!(
outer >= PieMenu::MIN_RADIUS,
"new({radius}) produced radius {outer}, below the floor"
);
menu.set_inner_radius(1.0);
assert!(
menu.inner_radius() >= 2.0,
"new({radius}): inner {} is below the documented floor 2.0",
menu.inner_radius()
);
menu.set_inner_radius(f32::MAX);
assert!(
menu.inner_radius() <= 0.95 * outer,
"new({radius}): inner {} exceeds 0.95 * radius ({})",
menu.inner_radius(),
0.95 * outer
);
}
}
/// `new` floors the radius, exactly as `set_radius` does.
///
/// A zero radius produced a zero-sized geometry, which makes every item unreachable: the
/// hit test compares a distance against `inner_radius`/`radius`, and there is no point in a
/// zero-radius menu that is inside it.
#[test]
fn pie_menu_new_floors_the_radius() {
for radius in [0.0f32, -1.0, 0.5, 9.9] {
let menu = PieMenu::new(Point::new(10, 10), radius);
assert_eq!(menu.radius(), PieMenu::MIN_RADIUS, "new({radius}) must floor");
assert_eq!(menu.geometry().width, (PieMenu::MIN_RADIUS * 2.0) as u32);
}
assert_eq!(PieMenu::new(Point::new(0, 0), 42.0).radius(), 42.0, "above the floor is kept");
}
/// A non-finite radius falls back to the floor rather than propagating.
#[test]
fn pie_menu_non_finite_radius_falls_back_to_the_floor() {
let menu = PieMenu::new(Point::new(0, 0), f32::NAN);
assert_eq!(menu.radius(), PieMenu::MIN_RADIUS);
let mut menu = PieMenu::new(Point::new(0, 0), 50.0);
menu.set_radius(f32::INFINITY);
assert_eq!(menu.radius(), PieMenu::MIN_RADIUS);
}
/// A non-finite inner radius is refused, leaving the previous value in place.
///
/// `f32::max`/`min` return the non-NaN operand, so a NaN input used to silently become
/// whichever bound the arithmetic happened to keep — a value the caller never asked for.
#[test]
fn pie_menu_non_finite_inner_radius_is_refused() {
let mut menu = PieMenu::new(Point::new(0, 0), 100.0);
menu.set_inner_radius(30.0);
menu.set_inner_radius(f32::NAN);
assert_eq!(menu.inner_radius(), 30.0, "NaN must not change the value");
menu.set_inner_radius(f32::INFINITY);
assert_eq!(menu.inner_radius(), 30.0, "infinity must not change the value");
}
/// Exhaustive proof that the `2.0 ..= 0.95 * radius` band
/// [`PieMenu::set_inner_radius`] documents is actually unbreakable.
///
/// The earlier order (`max(2.0)` then `min(0.95 * radius)`) made the ceiling win,
/// so the floor was not really guaranteed whenever the band was unsatisfiable —
/// which needed `radius < ~2.11`. `new` was the only way in, and it now floors the
/// radius at [`PieMenu::MIN_RADIUS`]. This test pins the property rather than
/// restating the reasoning: for every radius that can reach either writer,
/// including the absurd ones, both bounds hold after either extreme inner radius.
#[test]
fn pie_menu_inner_radius_band_is_unbreakable() {
for &radius in &[
-1e9_f32,
0.0,
1.0,
2.0,
2.105,
5.0,
PieMenu::MIN_RADIUS,
1e6,
f32::INFINITY,
f32::NAN,
] {
let mut menu = PieMenu::new(Point::new(100, 100), radius);
assert!(
menu.radius() >= PieMenu::MIN_RADIUS,
"new({radius}) left radius below MIN_RADIUS: {}",
menu.radius()
);
menu.set_inner_radius(-5.0);
let low = menu.inner_radius();
menu.set_inner_radius(1e9);
let high = menu.inner_radius();
let ceiling = menu.radius() * 0.95;
assert!(low >= 2.0 - 1e-4, "inner radius {low} fell below the 2.0 floor");
assert!(
high <= ceiling + 1e-4,
"inner radius {high} rose above 0.95 * radius ({ceiling})"
);
assert!(low <= high, "the setters must be monotonic in the requested value");
}
}
/// `set_radius` is the other writer of `radius`; shrinking it must pull the
/// inner radius down with it rather than leaving it outside the band.
#[test]
fn pie_menu_shrinking_radius_pulls_inner_radius_down() {
let mut menu = PieMenu::new(Point::new(0, 0), 200.0);
menu.set_inner_radius(180.0);
assert!(menu.inner_radius() <= menu.radius() * 0.95 + 1e-4);
menu.set_radius(PieMenu::MIN_RADIUS);
assert!(
menu.inner_radius() <= menu.radius() * 0.95 + 1e-4,
"inner radius {} escaped the band after shrinking to {}",
menu.inner_radius(),
menu.radius()
);
assert!(menu.inner_radius() >= 2.0 - 1e-4);
}
}