rust_widgets 2.7.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! AutoCompleteEdit widget — a text input with an auto-completion dropdown.
//!
//! The AutoCompleteEdit widget provides a text entry field that filters and
//! displays a dropdown list of suggestions as the user types. The user can
//! select a suggestion with the keyboard (Enter) or by clicking.

use crate::core::{Color, Font, HorizontalAlignment, Point, Rect};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::Signal1;
use crate::undo::{TextSnapshotCommand, UndoStack};
use crate::widget::capability::coercion::{expect_string, 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};
use std::cell::RefCell;
use std::rc::Rc;

/// A text input field with auto-completion dropdown support.
///
/// As the user types, the widget filters its suggestions list and shows
/// matching entries in a dropdown below the text field. The user can select
/// a highlighted suggestion via Enter key or by clicking.
pub struct AutoCompleteEdit {
    base: BaseWidget,
    text: String,
    suggestions: Vec<String>,
    filtered_suggestions: Vec<String>,
    show_dropdown: bool,
    selected_suggestion: Option<usize>,
    max_visible: usize,
    /// Emitted when the text content changes.
    pub text_changed: Signal1<String>,
    /// Emitted when a suggestion is selected from the dropdown.
    pub suggestion_selected: Signal1<String>,
    undo_stack: UndoStack,
    history_target: Rc<RefCell<String>>,
    restoring_history: bool,
}

impl AutoCompleteEdit {
    /// Creates a new AutoCompleteEdit widget with the given geometry.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::AutoCompleteEdit, geometry, "AutoCompleteEdit"),
            text: String::new(),
            suggestions: Vec::new(),
            filtered_suggestions: Vec::new(),
            show_dropdown: false,
            selected_suggestion: None,
            max_visible: 5,
            text_changed: Signal1::new(),
            suggestion_selected: Signal1::new(),
            undo_stack: UndoStack::new(),
            history_target: Rc::new(RefCell::new(String::new())),
            restoring_history: false,
        }
    }

    /// Returns the current text content.
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Sets the text content, updates the filtered suggestions list,
    /// and emits the `text_changed` signal.
    pub fn set_text(&mut self, text: String) {
        let cloned = text.clone();
        let before = self.text.clone();
        self.text = text;
        if !self.restoring_history {
            *self.history_target.borrow_mut() = self.text.clone();
            self.undo_stack.push(Box::new(TextSnapshotCommand::new(
                self.history_target.clone(),
                before,
                self.text.clone(),
                "auto_complete_text",
            )));
        }
        self.filter_suggestions();
        self.text_changed.emit(cloned);
        self.base.request_redraw();
    }

    /// Adds a single suggestion to the suggestion list.
    pub fn add_suggestion(&mut self, suggestion: String) {
        self.suggestions.push(suggestion);
        self.base.request_redraw();
    }

    /// Removes a suggestion by value. Returns true if the suggestion was found and removed.
    pub fn remove_suggestion(&mut self, suggestion: &str) -> bool {
        let idx = self.suggestions.iter().position(|s| s == suggestion);
        if let Some(pos) = idx {
            self.suggestions.remove(pos);
            self.filter_suggestions();
            self.base.request_redraw();
            true
        } else {
            false
        }
    }

    /// Replaces the entire suggestion list with the given vector.
    pub fn set_suggestions(&mut self, suggestions: Vec<String>) {
        self.suggestions = suggestions;
        self.filter_suggestions();
        self.base.request_redraw();
    }

    /// Returns a reference to the full suggestion list.
    pub fn suggestions(&self) -> &[String] {
        &self.suggestions
    }

    /// Removes all suggestions and hides the dropdown.
    pub fn clear_suggestions(&mut self) {
        self.suggestions.clear();
        self.filtered_suggestions.clear();
        self.show_dropdown = false;
        self.selected_suggestion = None;
        self.base.request_redraw();
    }

    /// Steps back one text edit and returns `true`, or `false` when there is
    /// nothing to undo.
    ///
    /// Replaying history emits `text_changed` but deliberately does not push a
    /// new undo entry. The undo stack is **not** cleared, so a redo of the
    /// undone change remains available.
    pub fn undo(&mut self) -> bool {
        if self.undo_stack.undo().is_err() {
            return false;
        }
        self.restore_history_text();
        true
    }

    /// Steps forward one undone edit and returns `true`, or `false` when there is
    /// nothing to redo. Signal behaviour matches
    /// [`AutoCompleteEdit::undo`].
    pub fn redo(&mut self) -> bool {
        if self.undo_stack.redo().is_err() {
            return false;
        }
        self.restore_history_text();
        true
    }

    /// Returns `true` if [`AutoCompleteEdit::undo`] would change the text.
    pub fn can_undo(&self) -> bool {
        self.undo_stack.can_undo()
    }
    /// Returns `true` if [`AutoCompleteEdit::redo`] would change the text.
    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.filter_suggestions();
        self.text_changed.emit(self.text.clone());
        self.base.request_redraw();
    }

    /// Returns whether the dropdown is currently visible.
    pub fn is_showing_dropdown(&self) -> bool {
        self.show_dropdown
    }

    /// Returns the number of suggestions currently offered for the typed text.
    ///
    /// Counts the filtered list the dropdown draws, not the full suggestion set,
    /// so the number matches what the user can actually pick right now.
    pub fn suggestion_count(&self) -> usize {
        self.filtered_suggestions.len()
    }

    /// Shows the dropdown (if there are filtered suggestions).
    pub fn show_dropdown(&mut self) {
        if !self.filtered_suggestions.is_empty() {
            self.show_dropdown = true;
            self.selected_suggestion = Some(0);
            self.base.request_redraw();
        }
    }

    /// Hides the dropdown.
    pub fn hide_dropdown(&mut self) {
        self.show_dropdown = false;
        self.selected_suggestion = None;
        self.base.request_redraw();
    }

    /// Toggles the dropdown visibility.
    pub fn toggle_dropdown(&mut self) {
        if self.show_dropdown {
            self.hide_dropdown();
        } else {
            self.show_dropdown();
        }
    }

    /// Filters the suggestion list based on the current text.
    fn filter_suggestions(&mut self) {
        if self.text.is_empty() {
            self.filtered_suggestions.clear();
            self.show_dropdown = false;
            self.selected_suggestion = None;
            return;
        }
        let lower = self.text.to_lowercase();
        self.filtered_suggestions = self
            .suggestions
            .iter()
            .filter(|s| s.to_lowercase().contains(&lower))
            .cloned()
            .collect();
        if self.filtered_suggestions.is_empty() {
            self.show_dropdown = false;
            self.selected_suggestion = None;
        } else {
            self.show_dropdown = true;
            self.selected_suggestion = Some(0);
        }
    }

    /// Selects the highlighted suggestion and commits it as the current text.
    fn select_highlighted(&mut self) {
        if let Some(idx) = self.selected_suggestion {
            if let Some(suggestion) = self.filtered_suggestions.get(idx) {
                let selected = suggestion.clone();
                self.set_text(selected.clone());
                self.suggestion_selected.emit(selected);
                self.hide_dropdown();
                self.base.request_redraw();
            }
        }
    }

    /// Moves the selection highlight up (towards the first item).
    fn select_previous(&mut self) {
        if let Some(idx) = self.selected_suggestion {
            if idx > 0 {
                self.selected_suggestion = Some(idx - 1);
                self.base.request_redraw();
            }
        }
    }

    /// Moves the selection highlight down (towards the last item).
    fn select_next(&mut self) {
        if let Some(idx) = self.selected_suggestion {
            if idx + 1 < self.filtered_suggestions.len() {
                self.selected_suggestion = Some(idx + 1);
                self.base.request_redraw();
            }
        }
    }

    /// Returns the index of the highlighted suggestion, or `None` when none is.
    ///
    /// # Why this exists as a public accessor
    ///
    /// The dropdown draws a highlight and the arrow keys move it, but nothing outside the control could
    /// ask *where* it was — so the property contract could only publish `suggestion_count`. A driver
    /// that cannot read the highlight cannot confirm its own navigation worked.
    pub fn selected_suggestion(&self) -> Option<usize> {
        self.selected_suggestion
    }

    /// Highlights the suggestion at `index`, or clears the highlight if it is out of range.
    ///
    /// Out of range clears rather than being ignored: the caller asked for a highlight that cannot be
    /// shown, and leaving the previous one up would silently select a different suggestion than the one
    /// requested.
    pub fn set_selected_suggestion(&mut self, index: usize) {
        let next = if index < self.filtered_suggestions.len() { Some(index) } else { None };
        if self.selected_suggestion != next {
            self.selected_suggestion = next;
            self.base.request_redraw();
        }
    }

    /// Clears the highlight, leaving the dropdown open.
    ///
    /// Distinct from `hide_dropdown`, which also closes the list — the two are different facts and the
    /// property contract publishes them separately.
    pub fn clear_selected_suggestion(&mut self) {
        if self.selected_suggestion.is_some() {
            self.selected_suggestion = None;
            self.base.request_redraw();
        }
    }

    /// Returns how many rows the dropdown will show at once.
    pub fn max_visible(&self) -> usize {
        self.max_visible
    }

    /// Sets how many rows the dropdown shows at once, floored at one.
    ///
    /// A zero would draw an open dropdown with no rows in it, which reads as a glitch rather than as a
    /// setting, so the floor is applied here rather than left to the caller.
    pub fn set_max_visible(&mut self, max_visible: usize) {
        let next = max_visible.max(1);
        if self.max_visible != next {
            self.max_visible = next;
            self.base.request_redraw();
        }
    }
}

impl Widget for AutoCompleteEdit {
    fn base(&self) -> &BaseWidget {
        &self.base
    }

    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> crate::core::Size {
        crate::core::Size::new(200, 28)
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

/// `AutoCompleteEdit`'s property contract.
///
/// # The defect this replaces
///
/// The control published `suggestion_count` and nothing else — a *derived* number. A consumer driving
/// it could count the suggestions but could not read which one was highlighted, could not ask whether
/// the dropdown was actually open, and could not ask whether an undo was available, even though the
/// control answers all three (`selected_suggestion`, `show_dropdown`, `can_undo`). Those are the
/// facts a driver or a test needs; a count alone describes the list but not the control's *state*.
///
/// 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. `suggestion_count` is derived
/// from the filtered list, so it is refused as read-only rather than reported as a
/// name this control does not know.
impl WidgetProperties for AutoCompleteEdit {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "text" => Ok(CapabilityValue::String(self.text().to_string())),
            "suggestion_count" => Ok(CapabilityValue::UInt(self.suggestion_count() as u64)),
            // `Null` for "nothing highlighted", the same encoding `hovered_index`-style properties
            // use elsewhere in the crate: index 0 is a real selection and must not stand in for
            // "none".
            "selected_index" => match self.selected_suggestion() {
                Some(index) => Ok(CapabilityValue::UInt(index as u64)),
                None => Ok(CapabilityValue::Null),
            },
            "selected_suggestion" => Ok(match self.selected_suggestion() {
                Some(index) => match self.filtered_suggestions.get(index) {
                    Some(text) => CapabilityValue::String(text.clone()),
                    None => CapabilityValue::Null,
                },
                None => CapabilityValue::Null,
            }),
            // `dropdown_visible` is the *state*; `suggestion_count` is the size of what it would show.
            // A consumer that only reads `suggestion_count > 0` is guessing.
            "dropdown_visible" => Ok(CapabilityValue::Bool(self.is_showing_dropdown())),
            "max_visible" => Ok(CapabilityValue::UInt(self.max_visible as u64)),
            // Publishing undo/redo availability is what lets a toolbar button bind to it; the
            // commands exist regardless, so a driver that cannot ask ends up issuing a no-op.
            "can_undo" => Ok(CapabilityValue::Bool(self.can_undo())),
            "can_redo" => Ok(CapabilityValue::Bool(self.can_redo())),
            _ => 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(())
            }
            // Selecting an index is a real write the control already supported through
            // `set_selected_suggestion`; publishing it makes keyboard-style navigation drivable.
            "selected_index" => match value {
                CapabilityValue::Null => {
                    self.clear_selected_suggestion();
                    Ok(())
                }
                other => {
                    self.set_selected_suggestion(expect_usize(other)?);
                    Ok(())
                }
            },
            "max_visible" => {
                self.set_max_visible(expect_usize(value)?);
                Ok(())
            }
            // Derived or read-only: the two counts describe the list, and the two booleans describe
            // what the control has already done.
            "suggestion_count"
            | "selected_suggestion"
            | "dropdown_visible"
            | "can_undo"
            | "can_redo" => Err(CapabilityAccessError::ReadOnlyProperty),
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of![
            "text",
            "suggestion_count",
            "selected_index",
            "selected_suggestion",
            "dropdown_visible",
            "max_visible",
            "can_undo",
            "can_redo",
            BASE_PROPERTY_NAMES
        ]
    }

    /// Runs one of the commands `auto_complete_edit` publishes.
    ///
    /// `set_text` assigns the edit contents and needs a payload, so it is answered
    /// through the property route — the capability publishes no zero-argument action.
    fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
        match name {
            "set_text" => Err(CapabilityAccessError::OutOfRange),
            _ => Err(CapabilityAccessError::UnknownCommand),
        }
    }
}

impl Draw for AutoCompleteEdit {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.geometry();
        let is_enabled = self.base.is_enabled();

        // Chrome colours resolve explicit style first, then the theme's resolved style
        // for this control, and only then fall back to a literal. Without the theme step
        // a light/dark switch would change nothing on screen, because the field fill and
        // its outline were previously hardcoded.
        //
        // The theme read is a separate manager lock, taken and released inside
        // `resolved_theme_style`, so it is not held across the draw — the global
        // manager's mutex is not re-entrant.
        let style = self.base.style().clone();
        let theme = crate::style::resolved_theme_style("auto_complete_edit");
        let field_background = style
            .background_color
            .or_else(|| theme.as_ref().and_then(|t| t.background_color))
            .unwrap_or(Color::rgba(255, 255, 255, 255));
        let border_color = style
            .border_color
            .or_else(|| theme.as_ref().and_then(|t| t.border_color))
            .unwrap_or(Color::rgba(180, 180, 180, 255));
        let text_color = style
            .text_color
            .or_else(|| theme.as_ref().and_then(|t| t.text_color))
            .unwrap_or(Color::BLACK);
        // The list is chrome of the same family as the field it drops from: its fill
        // and its ink are the resolved field colours, so both move with the appearance.
        let dropdown_background = if style.background_color.is_some() || theme.is_some() {
            field_background
        } else {
            Color::rgba(255, 255, 255, 255)
        };
        let dropdown_text = text_color;

        // Background
        let bg_color = if is_enabled { field_background } else { Color::rgba(240, 240, 240, 255) };
        context.fill_rounded_rect(rect, 4, bg_color);

        // Border
        context.draw_rounded_rect_stroke(rect, 4, border_color, 1);

        // Draw text
        let font = Font::simple("sans-serif", 13.0);
        let padding = 6i32;
        let text_x = rect.x + padding;
        let text_y = rect.y + padding + 13;

        let display_text = if self.text.is_empty() { "Type to search..." } else { &self.text };
        // Empty field = placeholder: the resolved ink damped toward the fill, so the
        // hint stays legible on either appearance.
        let input_text_color = if self.text.is_empty() {
            text_color.blend(&field_background, 0.4)
        } else if is_enabled {
            text_color
        } else {
            Color::rgba(160, 160, 160, 255)
        };
        context.draw_text(
            Point::new(text_x, text_y),
            display_text,
            &font,
            input_text_color,
            HorizontalAlignment::Left,
        );

        // Draw dropdown if visible
        if !self.show_dropdown || self.filtered_suggestions.is_empty() {
            return;
        }

        let drop_down_y = rect.y + rect.height as i32;
        let item_height = 24u32;
        let visible_count = self.filtered_suggestions.len().min(self.max_visible);
        let drop_down_height = item_height * visible_count as u32;
        let drop_rect = Rect::new(rect.x, drop_down_y, rect.width, drop_down_height);

        // Dropdown background
        context.fill_rounded_rect(drop_rect, 2, dropdown_background);
        context.draw_rounded_rect_stroke(
            drop_rect,
            2,
            border_color.blend(&dropdown_background, 0.3),
            1,
        );

        for i in 0..visible_count {
            let item_rect = Rect::new(
                rect.x + 1,
                drop_down_y + (i as i32) * (item_height as i32),
                rect.width.saturating_sub(2),
                item_height,
            );

            if Some(i) == self.selected_suggestion {
                context.fill_rounded_rect(
                    item_rect,
                    2,
                    dropdown_text.blend(&dropdown_background, 0.85),
                );
            }

            if let Some(suggestion) = self.filtered_suggestions.get(i) {
                let item_text_x = item_rect.x + 4;
                let item_text_y = item_rect.y + 16;
                context.draw_text(
                    Point::new(item_text_x, item_text_y),
                    suggestion,
                    &font,
                    dropdown_text,
                    HorizontalAlignment::Left,
                );
            }
        }
    }
}

impl EventHandler for AutoCompleteEdit {
    fn handle_event(&mut self, event: &Event) {
        if !self.base.is_enabled() {
            return;
        }
        match event {
            Event::MousePress { pos, button } if *button == 1 => {
                let rect = self.geometry();
                // Check if click is inside the text field area
                if rect.contains_point(*pos) {
                    self.show_dropdown();
                }
                // Check if click is on a dropdown item
                if self.show_dropdown {
                    let item_height = 24i32;
                    let drop_down_y = rect.y + rect.height as i32;
                    let visible_count = self.filtered_suggestions.len().min(self.max_visible);
                    let drop_down_height = item_height * visible_count as i32;
                    let drop_rect =
                        Rect::new(rect.x, drop_down_y, rect.width, drop_down_height as u32);

                    if drop_rect.contains_point(*pos) {
                        let rel_y = pos.y - drop_down_y;
                        let idx = (rel_y / item_height) as usize;
                        if idx < self.filtered_suggestions.len() {
                            self.selected_suggestion = Some(idx);
                            self.select_highlighted();
                        }
                    }
                }
            }
            Event::KeyPress { key, modifiers } => {
                if *key == 13 {
                    // Enter
                    if self.show_dropdown {
                        self.select_highlighted();
                    }
                } else if *key == 27 {
                    // Escape
                    if self.show_dropdown {
                        self.hide_dropdown();
                    }
                } else if *key == 38 && *modifiers == 0 && self.show_dropdown {
                    // Up arrow
                    self.select_previous();
                } else if *key == 40 && *modifiers == 0 && self.show_dropdown {
                    // Down arrow
                    self.select_next();
                } else if *modifiers == 2 && *key == 90 {
                    let _ = self.undo();
                } else if *modifiers == 2 && *key == 89 {
                    let _ = self.redo();
                } else if *key >= 32 && *key <= 126 {
                    // Printable ASCII — append to text
                    let c = char::from_u32(*key).unwrap_or(' ');
                    let mut new_text = self.text.clone();
                    new_text.push(c);
                    self.set_text(new_text);
                } else if *key == 8 {
                    // Backspace
                    if !self.text.is_empty() {
                        let mut new_text = self.text.clone();
                        new_text.pop();
                        self.set_text(new_text);
                    }
                }
            }
            _ => {
                self.base.handle_event(event);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::widget::svg::render_to_svg;
    use std::sync::{Arc, Mutex};

    #[test]
    fn auto_complete_edit_default_creation() {
        let edit = AutoCompleteEdit::new(Rect::new(0, 0, 200, 30));
        assert_eq!(edit.kind(), WidgetKind::AutoCompleteEdit);
        assert!(edit.text().is_empty());
        assert!(edit.suggestions().is_empty());
        assert!(!edit.is_showing_dropdown());
        assert_eq!(edit.geometry(), Rect::new(0, 0, 200, 30));
    }

    #[test]
    fn auto_complete_edit_add_and_remove_suggestion() {
        let mut edit = AutoCompleteEdit::new(Rect::new(0, 0, 200, 30));
        edit.add_suggestion("Apple".to_string());
        edit.add_suggestion("Banana".to_string());
        edit.add_suggestion("Cherry".to_string());
        assert_eq!(edit.suggestions().len(), 3);

        assert!(edit.remove_suggestion("Banana"));
        assert_eq!(edit.suggestions().len(), 2);

        assert!(!edit.remove_suggestion("NonExistent"));
        assert_eq!(edit.suggestions().len(), 2);
    }

    #[test]
    fn auto_complete_edit_set_text_filters_suggestions() {
        let mut edit = AutoCompleteEdit::new(Rect::new(0, 0, 200, 30));
        edit.set_suggestions(vec![
            "Apple".to_string(),
            "Banana".to_string(),
            "Apricot".to_string(),
            "Cherry".to_string(),
        ]);
        assert_eq!(edit.suggestions().len(), 4);

        edit.set_text("Ap".to_string());
        assert_eq!(edit.text(), "Ap");
        assert!(edit.is_showing_dropdown());

        edit.set_text("XYZ".to_string());
        assert!(!edit.is_showing_dropdown());
    }

    #[test]
    fn auto_complete_edit_text_changed_signal() {
        let mut edit = AutoCompleteEdit::new(Rect::new(0, 0, 200, 30));
        let captured = Arc::new(Mutex::new(None::<String>));
        edit.text_changed.connect({
            let captured = Arc::clone(&captured);
            move |val: Arc<String>| {
                *captured.lock().unwrap() = Some(val.to_string());
            }
        });

        edit.set_text("Hello".to_string());
        assert_eq!(captured.lock().unwrap().as_deref(), Some("Hello"));
    }

    #[test]
    fn auto_complete_edit_suggestion_selected_signal() {
        let mut edit = AutoCompleteEdit::new(Rect::new(0, 0, 200, 30));
        edit.set_suggestions(vec!["Option 1".to_string(), "Option 2".to_string()]);
        edit.set_text("Opt".to_string());

        let captured = Arc::new(Mutex::new(None::<String>));
        edit.suggestion_selected.connect({
            let captured = Arc::clone(&captured);
            move |val: Arc<String>| {
                *captured.lock().unwrap() = Some(val.to_string());
            }
        });

        // Simulate Enter key to select highlighted suggestion
        edit.handle_event(&Event::KeyPress { key: 13, modifiers: 0 });
        assert_eq!(captured.lock().unwrap().as_deref(), Some("Option 1"));
    }

    #[test]
    fn auto_complete_edit_clear_suggestions() {
        let mut edit = AutoCompleteEdit::new(Rect::new(0, 0, 200, 30));
        edit.add_suggestion("Test".to_string());
        assert_eq!(edit.suggestions().len(), 1);

        edit.clear_suggestions();
        assert!(edit.suggestions().is_empty());
        assert!(!edit.is_showing_dropdown());
    }

    #[test]
    fn auto_complete_edit_toggle_dropdown() {
        let mut edit = AutoCompleteEdit::new(Rect::new(0, 0, 200, 30));
        edit.set_suggestions(vec!["Item".to_string()]);
        edit.set_text("It".to_string());

        assert!(edit.is_showing_dropdown());
        edit.hide_dropdown();
        assert!(!edit.is_showing_dropdown());
        edit.show_dropdown();
        assert!(edit.is_showing_dropdown());
        edit.toggle_dropdown();
        assert!(!edit.is_showing_dropdown());
    }

    #[test]
    fn auto_complete_edit_svg_output() {
        let mut edit = AutoCompleteEdit::new(Rect::new(0, 0, 200, 30));
        edit.add_suggestion("Suggestion".to_string());
        edit.set_text("Sug".to_string());
        let svg = render_to_svg(&mut edit);
        assert!(svg.starts_with("<svg"));
        assert!(svg.ends_with("</svg>"));
    }

    /// The contract describes the control's *state*, not just the size of its list.
    ///
    /// # The defect this pins
    ///
    /// `suggestion_count` was the only property, and it is derived: a consumer could count the rows
    /// but could not ask whether the dropdown was open, which row was highlighted, or whether an undo
    /// was available — all three of which the control already knew.
    #[test]
    fn the_contract_reports_the_dropdown_and_highlight_state() {
        use crate::widget::capability::WidgetProperties;

        let mut edit = AutoCompleteEdit::new(Rect::new(0, 0, 200, 30));
        assert_eq!(edit.get("dropdown_visible").unwrap().as_bool(), Some(false));
        assert_eq!(edit.get("selected_index").unwrap(), CapabilityValue::Null);
        assert_eq!(edit.get("selected_suggestion").unwrap(), CapabilityValue::Null);
        assert_eq!(edit.get("max_visible").unwrap().as_u64(), Some(5));
        assert_eq!(edit.get("can_undo").unwrap().as_bool(), Some(false));

        edit.add_suggestion("Alpha".to_string());
        edit.add_suggestion("Alpine".to_string());
        edit.set_text("Al".to_string());

        // Typing opens the dropdown and highlights the first row, which the contract must now show.
        assert_eq!(edit.get("suggestion_count").unwrap().as_u64(), Some(2));
        assert_eq!(edit.get("dropdown_visible").unwrap().as_bool(), Some(true));
        assert_eq!(edit.get("selected_index").unwrap().as_u64(), Some(0));
        assert_eq!(edit.get("selected_suggestion").unwrap().as_str(), Some("Alpha"));

        // `selected_suggestion` is the *text* of the highlighted row; it follows the index.
        edit.set("selected_index", CapabilityValue::UInt(1)).unwrap();
        assert_eq!(edit.get("selected_suggestion").unwrap().as_str(), Some("Alpine"));

        // And `Null` index clears the highlight without closing the list, which is a different fact.
        edit.set("selected_index", CapabilityValue::Null).unwrap();
        assert_eq!(edit.get("selected_index").unwrap(), CapabilityValue::Null);
        assert_eq!(edit.get("dropdown_visible").unwrap().as_bool(), Some(true));
    }

    /// An index out of range clears the highlight rather than silently selecting a different row.
    #[test]
    fn selecting_an_index_out_of_range_clears_the_highlight() {
        let mut edit = AutoCompleteEdit::new(Rect::new(0, 0, 200, 30));
        edit.add_suggestion("Alpha".to_string());
        edit.set_text("Al".to_string());
        assert_eq!(edit.selected_suggestion(), Some(0));

        edit.set_selected_suggestion(99);
        assert_eq!(
            edit.selected_suggestion(),
            None,
            "an unreachable index must not leave the previous row highlighted"
        );
    }

    /// `max_visible` floors at one, so an open dropdown can never be asked to draw no rows.
    #[test]
    fn max_visible_floors_at_one_row() {
        let mut edit = AutoCompleteEdit::new(Rect::new(0, 0, 200, 30));
        edit.set_max_visible(0);
        assert_eq!(edit.max_visible(), 1);
        edit.set("max_visible", CapabilityValue::UInt(3)).unwrap();
        assert_eq!(edit.max_visible(), 3);
    }
}