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
1486
1487
1488
1489
1490
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! SearchBox widget — a text input with search icon, placeholder, and clear button.
//!
//! The SearchBox presents a text field with a magnifying glass icon on the left,
//! placeholder text when empty, and a clear (X) button on the right when the
//! text is non-empty. It emits `text_changed` with the current text value on
//! every edit.
use crate::core::{Color, HorizontalAlignment, Point, Rect};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::shortcut::Key;
use crate::signal::Signal1;
use crate::undo::{UndoStack, ValueCommand};
use crate::widget::capability::coercion::{
expect_horizontal_alignment, expect_string, horizontal_alignment_to_str,
};
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::input_widgets::shortcut_editor::primary_shortcut_pressed;
use crate::widget::metrics::{dimensions, effective_font, estimate_text_width, ControlMetrics};
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};
use std::cell::RefCell;
use std::rc::Rc;
/// Width of the magnifier glyph drawn in the field's leading slot.
const SEARCH_BOX_ICON_SIZE: u32 = 14;
/// Inset between the field's leading edge and the magnifier.
const SEARCH_BOX_ICON_MARGIN: u32 = 10;
/// Gap between the magnifier and the value's box.
const SEARCH_BOX_ICON_GAP: u32 = 6;
/// Diameter of the clear button's hit circle.
const SEARCH_BOX_CLEAR_BUTTON: u32 = 16;
/// Inset between the clear button and the field's trailing edge.
const SEARCH_BOX_CLEAR_MARGIN: u32 = 8;
/// Narrowest a search field may be, so an empty one is still a field.
const SEARCH_BOX_MIN_WIDTH: u32 = 120;
/// The leading space the magnifier takes out of the field.
///
/// The paint path, the text box and the size hint all read this one sum, so a wider glyph
/// cannot be sized for and painted over the value.
fn leading_slot() -> u32 {
SEARCH_BOX_ICON_MARGIN + SEARCH_BOX_ICON_SIZE + SEARCH_BOX_ICON_GAP
}
/// The trailing space the value may need when the clear button is present.
///
/// The hint reserves the whole slot even for an empty value, so sizing does not change when
/// the first character is typed and the button appears. The paint path reserves it only while
/// there is text to clear, because there is no button to paint otherwise.
fn trailing_slot() -> u32 {
SEARCH_BOX_CLEAR_MARGIN + SEARCH_BOX_CLEAR_BUTTON + SEARCH_BOX_CLEAR_MARGIN
}
/// SearchBox widget with search icon, placeholder, and clear button.
pub struct SearchBox {
base: BaseWidget,
text: String,
placeholder: String,
focused: bool,
/// How the typed value is aligned within its own box.
///
/// Horizontal only: the value is centred vertically in the field band as a matter of the
/// field's own layout, so a `top`/`bottom` value would be one this control could never honour —
/// [`crate::widget::capability::coercion::expect_horizontal_alignment`] refuses those rather
/// than accepting a write that does nothing. Defaults to left, so a caller that never asks
/// behaves exactly as it did.
alignment: crate::core::Alignment,
/// Emitted when the text changes, providing the new text value.
pub text_changed: Signal1<String>,
/// Emitted with the query when Enter is pressed.
///
/// This is the box's *submission*, as distinct from `text_changed`'s every-keystroke
/// notification: a search host wants to run the query once per Enter, not once per
/// character. The same name [`crate::widget::SearchBar`] publishes, so a host can treat the
/// two controls the same way.
pub search_submitted: Signal1<String>,
undo_stack: UndoStack,
history_target: Rc<RefCell<String>>,
restoring_history: bool,
/// The insertion point, in bytes from the start of the value.
cursor: usize,
/// The other end of a selection, in bytes. `None` means there is no selection.
selection_anchor: Option<usize>,
/// The caret's blink state. Shared with every other caret in the crate so the tempo is one
/// implementation rather than a per-control constant.
cursor_blink: crate::style::CursorBlink,
/// Whether a pointer drag is extending a selection (I-110).
dragging_selection: bool,
}
impl SearchBox {
/// Creates a new SearchBox widget with the given geometry.
/// Uses "Search…" as the default placeholder text.
pub fn new(geometry: Rect) -> Self {
Self {
base: BaseWidget::new(WidgetKind::SearchBox, geometry, "SearchBox"),
text: String::new(),
placeholder: "Search\u{2026}".to_string(),
focused: false,
alignment: crate::core::Alignment::Left,
text_changed: Signal1::new(),
search_submitted: Signal1::new(),
undo_stack: UndoStack::new(),
history_target: Rc::new(RefCell::new(String::new())),
restoring_history: false,
cursor: 0,
selection_anchor: None,
cursor_blink: crate::style::CursorBlink::new(),
dragging_selection: false,
}
}
/// Returns the current text content.
pub fn text(&self) -> &str {
&self.text
}
/// How the typed value is aligned within its own box.
pub fn alignment(&self) -> crate::core::Alignment {
self.alignment
}
/// Sets how the typed value is aligned within its own box.
///
/// Horizontal only. A `top`/`bottom` alignment is **ignored**, because the value is centred
/// vertically in the field band by the field's own layout — the property route refuses it
/// through [`crate::widget::capability::coercion::expect_horizontal_alignment`], and this setter
/// matching that keeps the two entry points from disagreeing.
pub fn set_alignment(&mut self, alignment: crate::core::Alignment) {
if alignment.to_horizontal().is_none() || self.alignment == alignment {
return;
}
self.alignment = alignment;
self.base.request_redraw();
}
/// Returns the current text content (alias for `text()`).
pub fn get_text(&self) -> &str {
&self.text
}
/// Sets the text content. Emits `text_changed` if the text actually changes.
pub fn set_text(&mut self, text: impl Into<String>) {
let text = text.into();
if self.text != text {
let before = self.text.clone();
self.text = text.clone();
if !self.restoring_history {
*self.history_target.borrow_mut() = self.text.clone();
self.undo_stack.push(Box::new(ValueCommand::new(
self.history_target.clone(),
before,
self.text.clone(),
"Edit text",
"search_box_text",
)));
}
// A programmatic write replaces the value, so the caret belongs at its end and any
// selection is meaningless.
self.cursor = self.text.len();
self.selection_anchor = None;
self.text_changed.emit(text);
self.base.request_redraw();
}
}
/// Returns the current placeholder text.
pub fn placeholder(&self) -> &str {
&self.placeholder
}
/// Sets the placeholder text shown when the search box is empty.
pub fn set_placeholder(&mut self, placeholder: &str) {
if self.placeholder == placeholder {
return;
}
self.placeholder = placeholder.to_string();
self.base.request_redraw();
}
/// Returns whether this search box currently has keyboard focus.
pub fn is_focused(&self) -> bool {
self.focused
}
/// Sets the focused state.
pub fn set_focused(&mut self, focused: bool) {
if self.focused != focused {
self.focused = focused;
if focused {
self.cursor_blink.start();
} else {
self.cursor_blink.stop();
self.selection_anchor = None;
}
self.base.request_redraw();
if focused {
self.base.focus_gained.emit();
} else {
self.base.focus_lost.emit();
}
}
}
/// The caret's byte offset in the value.
pub fn cursor_position(&self) -> usize {
self.cursor
}
/// Moves the caret, clearing the selection unless `extend` is set.
///
/// The offset is clamped to the value and snapped to a character boundary, so slicing the
/// value at the caret is always valid.
pub fn set_cursor_position(&mut self, position: usize) {
let position = crate::widget::text_utils::floor_char_boundary(
&self.text,
position.min(self.text.len()),
);
if self.cursor == position && self.selection_anchor.is_none() {
return;
}
self.cursor = position;
self.selection_anchor = None;
self.base.request_redraw();
}
/// The selected byte range, or `None` when nothing is selected.
pub fn selection_range(&self) -> Option<(usize, usize)> {
let anchor = self.selection_anchor?;
let (start, end) =
if anchor <= self.cursor { (anchor, self.cursor) } else { (self.cursor, anchor) };
(start != end).then_some((start, end))
}
/// The selected text, or an empty string when nothing is selected.
pub fn selected_text(&self) -> String {
self.selection_range()
.map_or_else(String::new, |(start, end)| self.text[start..end].to_string())
}
/// Selects the whole value.
pub fn select_all(&mut self) {
if self.text.is_empty() {
return;
}
self.selection_anchor = Some(0);
self.cursor = self.text.len();
self.base.request_redraw();
}
/// Clears the selection without moving the caret.
pub fn clear_selection(&mut self) {
if self.selection_anchor.take().is_some() {
self.base.request_redraw();
}
}
/// Advances the caret blink. Returns whether it owes another frame.
pub fn tick(&mut self, delta_ms: u32) -> bool {
if !self.focused {
return false;
}
let running = self.cursor_blink.tick(delta_ms);
if running {
self.base.request_redraw();
}
running
}
/// Moves the caret by `delta` characters, extending the selection when `extend` is set.
fn move_caret(&mut self, delta: i32, extend: bool) {
let mut target = self.cursor;
if delta < 0 {
for _ in 0..delta.unsigned_abs() {
target = crate::widget::text_utils::previous_char_boundary(&self.text, target);
}
} else {
for _ in 0..delta.unsigned_abs() {
target = crate::widget::text_utils::next_char_boundary(&self.text, target);
}
}
self.move_caret_to(target, extend);
}
/// Moves the caret to `position`, extending the selection when `extend` is set.
fn move_caret_to(&mut self, position: usize, extend: bool) {
let position = crate::widget::text_utils::floor_char_boundary(
&self.text,
position.min(self.text.len()),
);
if extend {
if self.selection_anchor.is_none() {
self.selection_anchor = Some(self.cursor);
}
} else {
self.selection_anchor = None;
}
if self.cursor != position {
self.cursor = position;
self.base.request_redraw();
}
}
/// Removes the selection, or the character before the caret when there is none.
fn backspace(&mut self) {
let (start, end) = self.selection_range().unwrap_or_else(|| {
let start = crate::widget::text_utils::previous_char_boundary(&self.text, self.cursor);
(start, self.cursor)
});
if start == end {
return;
}
self.text.replace_range(start..end, "");
self.cursor = start;
self.selection_anchor = None;
*self.history_target.borrow_mut() = self.text.clone();
self.text_changed.emit(self.text.clone());
self.base.request_redraw();
}
/// Removes the selection, or the character after the caret when there is none.
fn delete_forward(&mut self) {
let (start, end) = self.selection_range().unwrap_or_else(|| {
let end = crate::widget::text_utils::next_char_boundary(&self.text, self.cursor);
(self.cursor, end)
});
if start == end {
return;
}
self.text.replace_range(start..end, "");
self.cursor = start;
self.selection_anchor = None;
*self.history_target.borrow_mut() = self.text.clone();
self.text_changed.emit(self.text.clone());
self.base.request_redraw();
}
/// Clears the text content. Emits `text_changed` if the text was non-empty.
pub fn clear(&mut self) {
if !self.text.is_empty() {
self.set_text(String::new());
}
}
/// Reverts the most recent edit in this search box.
///
/// Returns `false` and changes nothing when there is nothing to undo;
/// otherwise emits `text_changed` with the restored text.
pub fn undo(&mut self) -> bool {
if self.undo_stack.undo().is_err() {
return false;
}
self.restore_history_text();
true
}
/// Reapplies the most recently undone edit.
///
/// Returns `false` and changes nothing when there is nothing to redo;
/// otherwise emits `text_changed` with the restored text.
pub fn redo(&mut self) -> bool {
if self.undo_stack.redo().is_err() {
return false;
}
self.restore_history_text();
true
}
/// Returns whether there is an edit to undo.
pub fn can_undo(&self) -> bool {
self.undo_stack.can_undo()
}
/// Returns whether there is an undone edit to reapply.
pub fn can_redo(&self) -> bool {
self.undo_stack.can_redo()
}
fn restore_history_text(&mut self) {
self.restoring_history = true;
self.text = self.history_target.borrow().clone();
self.restoring_history = false;
self.text_changed.emit(self.text.clone());
self.base.request_redraw();
}
/// Appends platform-committed text to the query (D09-INPUT-01).
///
/// The desktop backends deliver a printable character or an IME commit as
/// `Event::TextInput`/`Event::ImeCommit`, not as a `KeyPress`. Both that variant and the
/// `KeyPress` printable arm funnel through here so the append — and the `changed` signal it
/// emits through `set_text` — has a single implementation. Control characters are dropped so a
/// stray one cannot replace the query with a non-printing value.
fn append_committed_text(&mut self, text: &str) {
let filtered: String = text.chars().filter(|c| !c.is_control()).collect();
if filtered.is_empty() {
return;
}
// Insert at the caret, replacing any selected range. Insertion used to be
// end-anchored, so there was no way to correct a typo in the middle of a query.
let (start, end) = self.selection_range().unwrap_or((self.cursor, self.cursor));
let before = self.text.clone();
self.text.replace_range(start..end, &filtered);
self.cursor = start + filtered.len();
self.selection_anchor = None;
// I-110: this entry point now pushes the same undo step `set_text` does, so a query typed
// through `TextInput` can be undone like one typed through the programmatic route.
self.record_edit(before);
self.base.request_redraw();
}
/// Files `before` as one undo step and emits `text_changed`.
fn record_edit(&mut self, before: String) {
if self.restoring_history {
return;
}
*self.history_target.borrow_mut() = self.text.clone();
self.undo_stack.push(Box::new(ValueCommand::new(
self.history_target.clone(),
before,
self.text.clone(),
"Edit text",
"search_box_text",
)));
self.text_changed.emit(self.text.clone());
}
/// Copies the selected text to the platform clipboard (I-110).
#[cfg(not(alloc_frugal))]
fn copy_selection_to_clipboard(&self) -> Option<String> {
let selected = self.selected_text();
if selected.is_empty() {
return None;
}
crate::set_clipboard_text(&selected);
Some(selected)
}
#[cfg(alloc_frugal)]
fn copy_selection_to_clipboard(&self) -> Option<String> {
None
}
/// Inserts the platform clipboard's text at the caret (I-110).
#[cfg(not(alloc_frugal))]
fn paste_from_clipboard(&mut self) {
let text = crate::get_clipboard_text();
if !text.is_empty() {
self.append_committed_text(&text);
}
}
#[cfg(alloc_frugal)]
fn paste_from_clipboard(&mut self) {}
/// The byte offset a horizontal pixel points at, using the same fitted origin the paint uses.
fn byte_index_at_x(&self, x: i32) -> usize {
if self.text.is_empty() {
return 0;
}
let font = effective_font(self.style());
let mut measurement =
crate::render::SoftwarePaintBackend::new(crate::core::Size::new(0, 0), 1.0);
let context = RenderContext::new(&mut measurement);
let rect = self.field_rect();
let icon_margin = 10;
let icon_size = 14;
let clear_btn_size = 16;
let clear_margin = 8;
let text_x = rect.x + icon_margin + icon_size + 6;
let text_width = rect.width as i32
- (icon_margin + icon_size + 6 + clear_margin + clear_btn_size + clear_margin);
let value_box = Rect::new(text_x, rect.y, text_width.max(1) as u32, rect.height);
let advance = context.measure_text(&self.text, font).width as i32;
let origin = crate::render::fitted_origin(
value_box,
advance,
self.alignment.to_horizontal().unwrap_or(HorizontalAlignment::Left),
);
let dx = (x - origin.x).max(0);
// Accumulated real advances instead of a proportional mapping (I-P63).
let mut best = 0usize;
let mut prefix = 0i32;
let mut glyph = [0u8; 4];
for (index, ch) in self.text.char_indices() {
let advance = context.measure_text(ch.encode_utf8(&mut glyph), font).width as i32;
if dx < prefix + advance / 2 {
break;
}
prefix += advance;
best = index + ch.len_utf8();
}
best
}
}
impl Widget for SearchBox {
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 {
// A search box is a text field with a magnifier in it, so it reports the field's
// own minimum height — the same 48 a `lineedit` reports, which is what stops the
// two entry controls in one form being different sizes.
//
// The width is measured rather than fixed at 200: a hint that ignored the placeholder
// clipped a localised "Search…" longer than the default, and one that ignored the
// current value made a query wider than the field the layout had already chosen. Both
// strings are measured and the wider one wins, so the hint cannot shrink when the
// caller types a longer query than the placeholder it replaced.
let font = effective_font(self.style());
let placeholder_width = estimate_text_width(&self.placeholder, font, 1.0);
let text_width = estimate_text_width(&self.text, font, 1.0);
let content = placeholder_width.max(text_width);
let width = (leading_slot() + content + trailing_slot()).max(SEARCH_BOX_MIN_WIDTH);
crate::core::Size::new(width, dimensions::SEARCH_BOX_FIELD_HEIGHT)
}
/// A focused field owes frames for as long as its caret blinks.
fn is_animating(&self) -> bool {
self.focused && self.cursor_blink.is_running()
}
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 {
"text_changed" => {
Some(EventSignalRef::mapped("text_changed", &self.text_changed, |v| {
CapabilityValue::String(v.clone())
}))
}
"search_submitted" => {
Some(EventSignalRef::mapped("search_submitted", &self.search_submitted, |v| {
CapabilityValue::String(v.clone())
}))
}
_ => None,
}
}
}
/// `SearchBox`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_input.in.rs` / `access_write_input.in.rs` dispatch, so callers see
/// the same coercions and the same errors as before.
impl WidgetProperties for SearchBox {
fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
match name {
"text" => Ok(CapabilityValue::String(self.text().to_string())),
"placeholder" => Ok(CapabilityValue::String(self.placeholder().to_string())),
"alignment" => Ok(CapabilityValue::String(
horizontal_alignment_to_str(self.alignment()).to_string(),
)),
_ => base_property_get(self, name),
}
}
fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
match name {
"text" => {
self.set_text(expect_string(value)?);
Ok(())
}
"placeholder" => {
self.set_placeholder(&expect_string(value)?);
Ok(())
}
"alignment" => {
self.set_alignment(expect_horizontal_alignment(value)?);
Ok(())
}
_ => base_property_set(self, name, value),
}
}
fn property_names(&self) -> &'static [&'static str] {
property_names_of!["text", "placeholder", "alignment", BASE_PROPERTY_NAMES]
}
/// Runs one of the commands `search_box` publishes.
///
/// `clear` is the zero-argument action and goes through the control's own method, so
/// the `text_changed` signal and the empty-text short circuit stay in one place.
/// `set_text` and `set_placeholder` assign state and need a payload, so they are
/// answered through the property route.
fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
match name {
"clear" => {
self.clear();
Ok(())
}
"set_text" | "set_placeholder" => Err(CapabilityAccessError::OutOfRange),
_ => Err(CapabilityAccessError::UnknownCommand),
}
}
}
impl SearchBox {
/// The field the control actually paints.
///
/// # Why the field is not the control's rectangle
///
/// A search box is a text field, and every other field in this crate
/// ([`crate::widget::LineEdit`]) is [`dimensions::TEXT_FIELD_MIN_HEIGHT`] tall, full
/// width, centred in the area it is given. This control painted a **240x120**
/// stadium (`rx=6`) in the census cell — a pill four times the height of the input it
/// shares a form with — so a search box and a text field side by side did not even
/// look like the same kind of control. [`ControlMetrics::full_width_band`] is the
/// shared derivation: full width, the field's own height, centred. Everything the
/// control paints — the fill, the border, the magnifier, the value and the clear
/// button — and everything it hit-tests is placed from this one box, so the ink and
/// the clickable area cannot drift apart.
fn field_rect(&self) -> Rect {
ControlMetrics::full_width_band(self.geometry(), dimensions::SEARCH_BOX_FIELD_HEIGHT)
}
}
impl Draw for SearchBox {
fn draw(&mut self, context: &mut RenderContext) {
let is_enabled = self.base.is_enabled();
// The field's own box: every child measurement below is taken from it rather
// than from the control's rectangle, so the magnifier, the value and the clear
// button stay on the field's middle line in any layout.
let rect = self.field_rect();
// A field with no height left to paint is not a field: the guard keeps the
// magnifier and the clear button from being emitted as zero-extent elements, and
// it is why the geometry queries below can assume a non-empty box.
if rect.width == 0 || rect.height == 0 {
return;
}
let icon_size = SEARCH_BOX_ICON_SIZE as i32;
let icon_margin = SEARCH_BOX_ICON_MARGIN as i32;
let clear_btn_size = SEARCH_BOX_CLEAR_BUTTON as i32;
let clear_margin = SEARCH_BOX_CLEAR_MARGIN as i32;
let text_x = rect.x + leading_slot() as i32;
// The clear button only paints when there is text, but its margin is reserved either
// way so the value's box does not jump when the first character arrives.
let trailing = if self.text.is_empty() {
SEARCH_BOX_CLEAR_MARGIN as i32
} else {
clear_margin + clear_btn_size + clear_margin
};
let text_width = rect.width as i32 - leading_slot() as i32 - trailing;
let text_rect = Rect::new(text_x, rect.y, text_width.max(1) as u32, rect.height);
let center_y = rect.y + rect.height as i32 / 2;
// — Background —
//
// A stadium on the field's own box, so the radius is half the field's height
// rather than a literal 6 written for a 28 px field: at 48 the two disagree, and
// the border below must follow the same curve or the two edges cross.
let field_radius = rect.height / 2;
// From the style, not a literal. This painted a fixed light grey in every state and
// so stayed light in a dark theme: the theme resolved a search box's colour, handed
// it to the widget, and the widget ignored it. The three-state ladder is kept, but
// it is now *derived* from the resolved colour — a focused box is the resolved
// colour blended toward the accent, a disabled one is faded — so the states stay
// distinguishable *and* follow the theme.
let style = self.style();
// Resolved once, because the three branches below all need it and re-resolving would
// take the theme lock three times inside one draw.
let themed = crate::style::resolved_theme_style_shared("search_box");
let themed_bg = themed.as_ref().and_then(|resolved| resolved.background_color);
let themed_border = themed.as_ref().and_then(|resolved| resolved.border_color);
// Precedence: an explicit style wins, then the theme, then the original literal as a
// last resort so an inactive theme still gives the widget a defined appearance.
let accent = style.border_color.or(themed_border);
let base_bg =
style.background_color.or(themed_bg).unwrap_or(Color::rgba(235, 235, 235, 200));
// The page this field sits in, read once: a disabled fill recedes toward it.
let window_fill = crate::style::theme_manager()
.current_theme()
.map(|active| active.colors.background)
.unwrap_or(Color::WHITE);
let bg_color = if !is_enabled {
// A disabled field recedes toward the page it sits in. The comment here claimed that
// "blending toward white expresses energy taken out", but white is not a direction: on
// a dark field the disabled fill moves *away* from the window, and the disabled state
// ends up the more prominent of the two.
self.base.disabled_surface_near(base_bg, window_fill)
} else if self.focused {
base_bg.blend(&accent.unwrap_or(Color::rgba(60, 140, 255, 200)), 0.18)
} else if self.base.is_hovered() || self.base.is_pressed() {
// # Why hover comes last
//
// Focus is a stronger claim than hover — a focused field is the one keystrokes go
// to — so a field that is both keeps the focus tint. This arm is what a *pointer*
// over an unfocused field gets, and without it the one state a user most often
// produces (pointing at the box before clicking it) painted the resting fill.
// The weight is `StateOverlay::fill_blend`, so it matches the theme's own
// `"<kind>:hover"` key rather than a private constant.
let overlay = crate::style::StateOverlay::from_base(
self.base.is_hovered(),
self.base.is_pressed(),
false,
);
base_bg.blend(&base_bg.contrast_color(), overlay.fill_blend())
} else {
base_bg
};
context.fill_rounded_rect(rect, field_radius, bg_color);
// — Focus border —
if self.focused && is_enabled {
context.draw_rounded_rect_stroke(
rect,
field_radius,
accent.unwrap_or(Color::rgba(60, 140, 255, 200)),
2,
);
} else {
context.draw_rounded_rect_stroke(
rect,
field_radius,
style.border_color.unwrap_or(Color::rgba(200, 200, 200, 160)),
1,
);
}
// — Search icon (magnifying glass) —
let icon_cx = rect.x + icon_margin + icon_size / 2;
let icon_cy = center_y;
let icon_color = if is_enabled {
Color::rgba(140, 140, 140, 220)
} else {
Color::rgba(180, 180, 180, 120)
};
// Draw circle part of magnifying glass
let circle_radius = icon_size as u32 * 5 / 14; // ~5 pixel radius
context.draw_circle(Point::new(icon_cx - 1, icon_cy - 1), circle_radius, icon_color);
// Draw handle (angled line)
let handle_start_x = icon_cx - 1 + circle_radius as i32;
let handle_start_y = icon_cy - 1 + circle_radius as i32;
let handle_end_x = handle_start_x + 4;
let handle_end_y = handle_start_y + 4;
context.draw_line(
Point::new(handle_start_x, handle_start_y),
Point::new(handle_end_x, handle_end_y),
icon_color,
);
// — Text / Placeholder —
// The **effective font** — the resolved theme/caller font, via the shared accessor — so the
// value/placeholder honours the theme body font and the user's text scale (D09-STYLE-01).
let font = effective_font(self.style());
// The typed text is the control's ink, so it follows the theme; the previous literal
// `30,30,30` was written for a light field and rendered at 1.7:1 once the field's own
// background resolved to a dark surface. The placeholder stays dimmer than the ink on
// purpose (it is a hint, not a value), but it is derived from the ink now rather than
// being a second fixed grey that could not match either appearance.
let ink = crate::style::theme_manager()
.current_theme()
.map(|active| active.colors.foreground)
.unwrap_or(Color::rgba(30, 30, 30, 230));
let text_color = if !is_enabled {
// Derived from the field the text sits on, not blended toward a fixed white: a text
// colour moved toward `Color::WHITE` goes *up* in contrast on the dark appearance
// (where the field is dark) and *down* on the light one, so one appearance got a
// "disabled" label that was more prominent than the enabled one.
self.base.disabled_ink_on(ink, bg_color)
} else if !self.text.is_empty() {
ink
} else {
ink.blend(&Color::WHITE, 0.55)
};
let display_text = if self.text.is_empty() { &self.placeholder } else { &self.text };
let value_align = self.alignment.to_horizontal().unwrap_or(HorizontalAlignment::Left);
// The origin the value is laid out from. Both the selection band and the caret use it,
// so a centred or right-aligned query keeps its decorations on the glyphs instead of at
// the field's leading edge.
let value_advance = context.measure_text(display_text, font).width as i32;
let value_origin = crate::render::fitted_origin(text_rect, value_advance, value_align);
let text_line = context.text_line(text_rect, font);
// — Selection band —
if !self.text.is_empty() {
if let Some((start, end)) = self.selection_range() {
let start_x =
value_origin.x + context.measure_text(&self.text[..start], font).width as i32;
let end_x =
value_origin.x + context.measure_text(&self.text[..end], font).width as i32;
let right =
(value_origin.x + value_advance).min(text_rect.x + text_rect.width as i32);
let left = start_x.min(right);
let right = end_x.min(right).max(left);
context.fill_rect(
Rect::new(
left,
text_line.y,
(right - left).max(0) as u32,
text_line.height.max(1),
),
accent.unwrap_or(Color::rgba(60, 140, 255, 200)).with_alpha(90),
);
}
}
// The field's own line box. A glyph origin is the box's top-left edge, so the old
// `text_rect.y + text_rect.height / 2 + 4` put that edge on the field's middle line and
// drew the text half a line low. The value is drawn only when there is one: the
// placeholder is *text the caller supplied*, so an empty placeholder with no value is
// nothing to paint rather than a blank row.
if !display_text.is_empty() {
// The value (and the placeholder, which shares this run) is fitted into the field's
// text box so a centred or right-aligned value is positioned against the box it is
// aligned within rather than against a fixed inset.
context.draw_text_fitted_cow(
Rect::new(text_rect.x, text_line.y, text_rect.width, text_line.height),
display_text,
font,
text_color,
value_align,
);
}
// — Caret —
// Drawn from the same origin and prefix measurement as the band, and clipped to the
// field's text box. A focused field used to show no insertion point at all, so after a
// click or a Tab there was nothing saying where typing would land.
if self.focused && is_enabled && self.cursor_blink.is_visible() {
let caret_byte =
crate::widget::text_utils::floor_char_boundary(&self.text, self.cursor);
let caret_x =
value_origin.x + context.measure_text(&self.text[..caret_byte], font).width as i32;
let caret_x = caret_x.min(text_rect.x + text_rect.width as i32 - 1).max(text_rect.x);
context.draw_line(
Point::new(caret_x, text_line.y),
Point::new(caret_x, text_line.y + text_line.height as i32),
text_color,
);
}
// — Clear button (X circle) —
if !self.text.is_empty() && is_enabled {
let clear_cx = rect.x + rect.width as i32 - clear_margin - clear_btn_size / 2;
let clear_cy = center_y;
let clear_radius = clear_btn_size as u32 / 2;
// Circle background
context.fill_circle(
Point::new(clear_cx, clear_cy),
clear_radius,
Color::rgba(180, 180, 180, 200),
);
// X mark (two diagonal lines)
let offset = 3;
context.draw_line(
Point::new(clear_cx - offset, clear_cy - offset),
Point::new(clear_cx + offset, clear_cy + offset),
Color::WHITE,
);
context.draw_line(
Point::new(clear_cx + offset, clear_cy - offset),
Point::new(clear_cx - offset, clear_cy + offset),
Color::WHITE,
);
}
}
}
impl EventHandler for SearchBox {
fn handle_event(&mut self, event: &Event) {
if !self.base.is_enabled() {
return;
}
match event {
Event::MousePress { pos, button, .. } if *button == 1 => {
// Check if clear button was clicked. The circle is placed from the **drawn
// field**, not from the control's rectangle: the two used to be the same
// box, so the hit test silently agreed with the ink by accident, and once
// the field became a centred band they would have diverged — the X would
// have been painted in the field but clickable where the rectangle was.
if !self.text.is_empty() {
let rect = self.field_rect();
let clear_margin = SEARCH_BOX_CLEAR_MARGIN as i32;
let clear_btn_size = SEARCH_BOX_CLEAR_BUTTON as i32;
let center_y = rect.y + rect.height as i32 / 2;
let clear_cx = rect.x + rect.width as i32 - clear_margin - clear_btn_size / 2;
let clear_cy = center_y;
let dx = pos.x - clear_cx;
let dy = pos.y - clear_cy;
let clear_radius = clear_btn_size as u32 / 2;
// Hit-test within the clear button circle
if dx * dx + dy * dy <= (clear_radius as i32 * clear_radius as i32) {
self.clear();
return;
}
}
// Click on the search box → gain focus and place the caret where it landed.
self.set_focused(true);
let position = self.byte_index_at_x(pos.x);
self.cursor = position;
// I-110: a press anchors a selection a drag can extend.
self.selection_anchor = Some(position);
self.dragging_selection = true;
self.base.request_redraw();
}
Event::MouseMove { pos } => {
// I-110: a pointer drag extends the selection the press began.
if self.dragging_selection {
self.cursor = self.byte_index_at_x(pos.x);
self.base.request_redraw();
}
}
Event::MouseRelease { pos: _, button } if *button == 1 => {
self.dragging_selection = false;
}
Event::FocusGained { .. } => {
self.set_focused(true);
}
Event::FocusLost => {
self.set_focused(false);
}
Event::KeyPress { key, modifiers } => {
if !self.focused {
return;
}
// Undo and redo are the platform primary chord: Control+Z/Y on
// Windows and Linux, Command+Z/Y on macOS. A shifted chord is a
// different binding and stays unbound here.
if primary_shortcut_pressed(*key, *modifiers, Key::Z) {
let _ = self.undo();
return;
}
if primary_shortcut_pressed(*key, *modifiers, Key::Y) {
let _ = self.redo();
return;
}
let mods = crate::shortcut::Modifiers::from_event_bits(*modifiers);
let shift = mods.contains(crate::shortcut::Modifiers::SHIFT);
// Primary+A selects the whole query, matching the text fields around it.
if mods.contains(crate::shortcut::Modifiers::CTRL) && (*key == 65 || *key == 97) {
self.select_all();
return;
}
// I-110: the clipboard chords the other text fields publish.
if primary_shortcut_pressed(*key, *modifiers, Key::C) {
let _ = self.copy_selection_to_clipboard();
return;
}
if primary_shortcut_pressed(*key, *modifiers, Key::X) {
let _ = self.copy_selection_to_clipboard();
if let Some((start, end)) = self.selection_range() {
let before = self.text.clone();
self.text.replace_range(start..end, "");
self.cursor = start;
self.selection_anchor = None;
self.record_edit(before);
self.base.request_redraw();
}
return;
}
if primary_shortcut_pressed(*key, *modifiers, Key::V) {
self.paste_from_clipboard();
return;
}
match *key {
8 => self.backspace(),
127 => self.delete_forward(),
37 => self.move_caret(-1, shift),
39 => self.move_caret(1, shift),
36 => self.move_caret_to(0, shift),
35 => self.move_caret_to(self.text.len(), shift),
13 => {
// Enter submits the query, then the field gives up focus. Escape only
// gives up focus: abandoning a search is not submitting it.
self.search_submitted.emit(self.text.clone());
self.set_focused(false);
}
27 => {
self.set_focused(false);
}
_ => {
// Character input
if let Some(ch) = char::from_u32(*key) {
if ch.is_ascii_graphic() || ch == ' ' {
self.append_committed_text(&ch.to_string());
}
}
}
}
}
// Platform-committed text (D09-INPUT-01). This is where a printable character or an
// IME commit actually arrives from the desktop backends, so without this branch the
// search box received `TextInput` and dropped it — typing only worked because the
// `KeyPress` path happened to be fed by the same producers. An unfocused box ignores it,
// matching the key path above.
Event::TextInput { text } | Event::ImeCommit { text } => {
if self.focused {
self.append_committed_text(text);
}
}
_ => {
self.base.handle_event(event);
}
}
}
}
#[cfg(all(test, full_widgets))]
mod tests {
use super::*;
use std::sync::{Arc, Mutex};
#[test]
fn search_box_default_creation() {
let sb = SearchBox::new(Rect::new(0, 0, 200, 32));
assert_eq!(sb.text(), "");
assert_eq!(sb.get_text(), "");
assert_eq!(sb.placeholder(), "Search\u{2026}");
assert!(!sb.is_focused());
assert_eq!(sb.kind(), WidgetKind::SearchBox);
assert!(sb.is_enabled());
}
#[test]
fn search_box_set_text_get_text() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
sb.set_text("hello");
assert_eq!(sb.text(), "hello");
assert_eq!(sb.get_text(), "hello");
}
#[test]
fn search_box_set_text_emits_signal() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
let captured = Arc::new(Mutex::new(None::<String>));
sb.text_changed.connect({
let captured = Arc::clone(&captured);
move |val: Arc<String>| {
*captured.lock().unwrap() = Some(val.to_string());
}
});
sb.set_text("world");
assert_eq!(*captured.lock().unwrap(), Some("world".to_string()));
}
// ─── D09-INPUT-01: platform-committed text reaches the query ───
/// A `TextInput` from the platform must be appended to the query.
///
/// # The defect this pins (D09-INPUT-01)
///
/// The desktop backends deliver a printable character or an IME commit as `Event::TextInput`,
/// not as a `KeyPress`; the handler only matched `KeyPress`, so committed text was dropped. The
/// test feeds `TextInput` to prove that path itself is wired.
#[test]
fn text_input_is_appended_to_the_query() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
sb.set_focused(true);
sb.handle_event(&Event::TextInput { text: "hé".to_string() });
assert_eq!(sb.text(), "hé");
}
/// An IME commit is appended the same way.
#[test]
fn ime_commit_is_appended_to_the_query() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
sb.set_focused(true);
sb.handle_event(&Event::ime_commit("ä½ å¥½"));
assert_eq!(sb.text(), "ä½ å¥½");
}
/// Committed text emits `text_changed` once with the new value.
#[test]
fn text_input_emits_text_changed() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
sb.set_focused(true);
let last = Arc::new(Mutex::new(String::new()));
sb.text_changed.connect({
let last = Arc::clone(&last);
move |val: Arc<String>| *last.lock().unwrap() = val.to_string()
});
sb.handle_event(&Event::TextInput { text: "abc".to_string() });
assert_eq!(sb.text(), "abc");
assert_eq!(*last.lock().unwrap(), "abc");
}
/// An unfocused box ignores committed text, matching the key gate.
#[test]
fn unfocused_ignores_text_input() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
sb.handle_event(&Event::TextInput { text: "X".to_string() });
assert_eq!(sb.text(), "");
}
/// A disabled box ignores committed text.
#[test]
fn disabled_ignores_text_input() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
sb.set_enabled(false);
sb.set_focused(true);
sb.handle_event(&Event::TextInput { text: "X".to_string() });
assert_eq!(sb.text(), "");
}
#[test]
fn search_box_text_changed_signal_on_type() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
let last = Arc::new(Mutex::new(String::new()));
sb.text_changed.connect({
let last = Arc::clone(&last);
move |val: Arc<String>| {
*last.lock().unwrap() = val.to_string();
}
});
// Simulate typing 'a', 'b', 'c'
sb.set_focused(true);
sb.handle_event(&Event::KeyPress { key: 97, modifiers: 0 }); // 'a'
sb.handle_event(&Event::KeyPress { key: 98, modifiers: 0 }); // 'b'
sb.handle_event(&Event::KeyPress { key: 99, modifiers: 0 }); // 'c'
assert_eq!(sb.text(), "abc");
assert_eq!(*last.lock().unwrap(), "abc");
}
#[test]
fn search_box_placeholder_display() {
let sb = SearchBox::new(Rect::new(0, 0, 200, 32));
// Default placeholder
assert_eq!(sb.placeholder(), "Search\u{2026}");
// Custom placeholder
let mut sb_custom = SearchBox::new(Rect::new(0, 0, 200, 32));
sb_custom.set_placeholder("Find...");
assert_eq!(sb_custom.placeholder(), "Find...");
}
#[test]
fn search_box_clear_button_click() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
sb.set_text("test text");
assert_eq!(sb.text(), "test text");
// Calculate clear button center position
let clear_margin = 8;
let clear_btn_size = 16;
let rect = sb.geometry();
let center_y = rect.y + rect.height as i32 / 2;
let clear_cx = rect.x + rect.width as i32 - clear_margin - clear_btn_size / 2;
let clear_cy = center_y;
// Click the clear button
sb.handle_event(&Event::MousePress {
pos: Point::new(clear_cx, clear_cy),
button: 1,
modifiers: 0,
});
assert_eq!(sb.text(), "");
}
#[test]
fn search_box_clear_button_emits_signal() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
let captured = Arc::new(Mutex::new(None::<String>));
sb.text_changed.connect({
let captured = Arc::clone(&captured);
move |val: Arc<String>| {
*captured.lock().unwrap() = Some(val.to_string());
}
});
sb.set_text("hello");
// Clear via method
sb.clear();
assert_eq!(sb.text(), "");
assert_eq!(*captured.lock().unwrap(), Some("".to_string()));
}
#[test]
fn search_box_backspace() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
sb.set_text("hello");
sb.set_focused(true);
sb.handle_event(&Event::KeyPress { key: 8, modifiers: 0 }); // Backspace
assert_eq!(sb.text(), "hell");
sb.handle_event(&Event::KeyPress { key: 8, modifiers: 0 }); // Backspace
assert_eq!(sb.text(), "hel");
}
/// Delete removes the character after the caret, and does nothing at the end of the value.
#[test]
fn search_box_delete_removes_forward_from_the_caret() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
sb.set_text("hello");
sb.set_focused(true);
// A click or an arrow can put the caret inside the value, and Delete then removes the
// character in front of it rather than being a no-op everywhere.
sb.set_cursor_position(2);
sb.handle_event(&Event::KeyPress { key: 127, modifiers: 0 }); // Delete
assert_eq!(sb.text(), "helo");
// At the end there is nothing forward to remove.
sb.set_cursor_position(sb.text().len());
sb.handle_event(&Event::KeyPress { key: 127, modifiers: 0 }); // Delete
assert_eq!(sb.text(), "helo");
// Backspace still edits.
sb.handle_event(&Event::KeyPress { key: 8, modifiers: 0 }); // Backspace
assert_eq!(sb.text(), "hel");
}
#[test]
fn search_box_set_placeholder_text() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
sb.set_placeholder("Type to search...");
assert_eq!(sb.placeholder(), "Type to search...");
}
#[test]
fn search_box_focus_on_click() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
assert!(!sb.is_focused());
sb.handle_event(&Event::MousePress { pos: Point::new(50, 16), button: 1, modifiers: 0 });
assert!(sb.is_focused());
}
#[test]
fn search_box_focus_lost_on_escape() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
sb.set_focused(true);
assert!(sb.is_focused());
sb.handle_event(&Event::KeyPress { key: 27, modifiers: 0 }); // Escape
assert!(!sb.is_focused());
}
#[test]
fn search_box_disabled_blocks_events() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
sb.set_enabled(false);
sb.handle_event(&Event::MousePress { pos: Point::new(50, 16), button: 1, modifiers: 0 });
assert!(!sb.is_focused());
assert_eq!(sb.text(), "");
}
#[test]
fn search_box_disabled_blocks_keyboard() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
sb.set_enabled(false);
sb.set_focused(true);
sb.handle_event(&Event::KeyPress { key: 97, modifiers: 0 }); // 'a'
assert_eq!(sb.text(), "");
}
#[test]
fn search_box_svg_output() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
let svg = crate::widget::svg::render_to_svg(&mut sb);
assert!(svg.starts_with("<svg"));
assert!(svg.contains("width=\"200\""));
assert!(svg.contains("height=\"32\""));
}
#[test]
fn search_box_svg_with_text() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
sb.set_text("testing");
let svg = crate::widget::svg::render_to_svg(&mut sb);
assert!(svg.starts_with("<svg"));
}
#[test]
fn search_box_clear_non_empty_only() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
let captured = Arc::new(Mutex::new(0));
let c = captured.clone();
sb.text_changed.connect(move |_: Arc<String>| {
*c.lock().unwrap() += 1;
});
// Clear when already empty — should not emit
sb.clear();
assert_eq!(*captured.lock().unwrap(), 0);
// Set text and clear
sb.set_text("data");
assert_eq!(*captured.lock().unwrap(), 1);
sb.clear();
assert_eq!(*captured.lock().unwrap(), 2);
assert_eq!(sb.text(), "");
}
#[test]
fn search_box_no_duplicate_emit_on_set_same_text() {
let mut sb = SearchBox::new(Rect::new(0, 0, 200, 32));
let count = Arc::new(Mutex::new(0));
let c = count.clone();
sb.text_changed.connect(move |_: Arc<String>| {
*c.lock().unwrap() += 1;
});
sb.set_text("hello");
sb.set_text("hello"); // same text — should not emit
assert_eq!(*count.lock().unwrap(), 1);
}
/// A search box is a text field, so it is the same height as one in any rectangle.
///
/// This pins the defect the fix removes: the field was painted across the control's
/// whole `rect`, so the 240x120 census cell drew a **240x120 stadium** (`rx=6`) while
/// `lineedit` drew a 48 px band — two entry controls in one form that did not even
/// look like the same kind of control. The field is now
/// [`dimensions::TEXT_FIELD_MIN_HEIGHT`] tall, full width, centred, exactly as
/// `lineedit` is.
#[test]
fn the_field_is_a_text_field_height_in_any_rectangle() {
for height in [48u32, 120, 300] {
let sb = SearchBox::new(Rect::new(0, 0, 240, height));
let field = sb.field_rect();
assert_eq!(
field.height,
dimensions::TEXT_FIELD_MIN_HEIGHT,
"at control height {height}"
);
assert_eq!(field.width, 240, "the field spans the control's width");
assert_eq!(field.y, (height - field.height) as i32 / 2, "at control height {height}");
}
// A control shorter than a field clamps it rather than painting outside.
let short = SearchBox::new(Rect::new(0, 0, 240, 20));
assert_eq!(short.field_rect().height, 20);
}
/// The emitted stadium is the field's own box, and its radius follows that box.
///
/// The fill used to be `fill_rounded_rect(rect, 6, ..)` over a 240x120 rectangle, so
/// the snapshot carried a near-rectangular slab; the radius is now half the field's
/// height, which is what makes the two-entry-control shapes match.
#[test]
fn the_search_box_paints_a_field_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 sb = SearchBox::new(crate::widget::census::CENSUS_RECT);
let svg = crate::widget::svg::render_to_svg(&mut sb);
let field = sb.field_rect();
assert_eq!(field.height, dimensions::TEXT_FIELD_MIN_HEIGHT);
assert_eq!(field.y, 36, "a 48 px field centred in the 120 px cell");
let radius = field.height / 2;
assert!(
svg.contains(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" rx=\"{}\" ry=\"{}\"",
field.x, field.y, field.width, field.height, radius, radius
)),
"the field's own box is what is painted: {svg}"
);
// The defect's signature: a fill the control's own height.
assert!(
!svg.contains(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"120\"",
field.x, field.y, field.width
)),
"the control's own height would mean a panel fill: {svg}"
);
}
/// An empty value with an empty placeholder paints no text at all.
///
/// The value line is emitted only when there is something to draw, so a caller that
/// cleared the placeholder gets a bare field rather than a blank text element.
#[test]
fn an_empty_value_and_placeholder_paint_no_text() {
let mut sb = SearchBox::new(Rect::new(0, 0, 240, 48));
sb.clear();
sb.set_placeholder("");
let svg = crate::widget::svg::render_to_svg(&mut sb);
assert!(!svg.contains("<text"), "nothing to write means nothing drawn: {svg}");
}
/// The clear button's hit circle is the one that was painted.
///
/// The hit test used to read the control's rectangle, which happened to be the same
/// box the X was drawn in; once the field became a centred band the two would have
/// diverged, so this pins that a click lands on the X and a click on the field's
/// empty row does not clear.
#[test]
fn the_clear_button_hit_circle_follows_the_drawn_field() {
let mut sb = SearchBox::new(Rect::new(0, 0, 240, 120));
sb.set_text("query");
let field = sb.field_rect();
let clear_cx = field.x + field.width as i32 - 8 - 16 / 2;
let clear_cy = field.y + field.height as i32 / 2;
// A press on the X clears the value.
sb.handle_event(&Event::MousePress {
pos: Point::new(clear_cx, clear_cy),
button: 1,
modifiers: 0,
});
assert_eq!(sb.text(), "", "a press on the drawn X clears");
// A press above the field, inside the control's rectangle, does not clear.
sb.set_text("query");
sb.handle_event(&Event::MousePress {
pos: Point::new(clear_cx, field.y - 10),
button: 1,
modifiers: 0,
});
assert_eq!(sb.text(), "query", "a press outside the field must not clear");
}
/// Typing lands at the caret, and the editing keys act around it.
///
/// The field used to be append-only, so a typo in the middle of a query could only be
/// fixed by clearing everything after it.
#[test]
fn the_caret_drives_insertion_and_deletion() {
let mut sb = SearchBox::new(Rect::new(0, 0, 300, 40));
sb.set_text("helo");
sb.handle_event(&Event::FocusGained { reason: crate::event::FocusReason::Tab });
// Move the caret before the `o` and insert the missing letter.
sb.handle_event(&Event::KeyPress { key: 37, modifiers: 0 });
sb.handle_event(&Event::KeyPress { key: 108, modifiers: 0 }); // 'l'
assert_eq!(sb.text(), "hello");
assert_eq!(sb.cursor_position(), 4);
// Delete removes the character after the caret.
sb.handle_event(&Event::KeyPress { key: 36, modifiers: 0 }); // Home
sb.handle_event(&Event::KeyPress { key: 127, modifiers: 0 }); // Delete
assert_eq!(sb.text(), "ello");
assert_eq!(sb.cursor_position(), 0);
// Backspace with no selection at the start is a no-op.
sb.handle_event(&Event::KeyPress { key: 8, modifiers: 0 });
assert_eq!(sb.text(), "ello");
// End returns the caret to the end.
sb.handle_event(&Event::KeyPress { key: 35, modifiers: 0 });
assert_eq!(sb.cursor_position(), 4);
}
/// Shift+arrows select a range and typing replaces it; the selection is painted.
#[test]
fn shift_selects_and_the_selection_is_painted() {
let mut sb = SearchBox::new(Rect::new(0, 0, 300, 40));
sb.set_text("alpha");
sb.handle_event(&Event::FocusGained { reason: crate::event::FocusReason::Tab });
let before = crate::widget::svg::render_to_svg(&mut sb);
sb.handle_event(&Event::KeyPress { key: 37, modifiers: 1 });
sb.handle_event(&Event::KeyPress { key: 37, modifiers: 1 });
assert_eq!(sb.selection_range(), Some((3, 5)));
assert_eq!(sb.selected_text(), "ha");
let selected = crate::widget::svg::render_to_svg(&mut sb);
assert_ne!(selected, before, "a selection must be visible");
sb.handle_event(&Event::text_input("ha!"));
assert_eq!(sb.text(), "alpha!");
assert_eq!(sb.selection_range(), None);
sb.select_all();
assert_eq!(sb.selected_text(), "alpha!");
sb.clear_selection();
assert_eq!(sb.selection_range(), None);
}
}