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
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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! EditableComboBox widget — a combo box that allows typing custom values.
//!
//! The EditableComboBox combines a text field with a dropdown list. Users can
//! either type a custom value directly or select from the provided items.
//! A `text_changed` signal is emitted when the text field content changes,
//! and an `item_selected` signal is emitted when a dropdown item is clicked.
//!
//! # Why the indicator drives the value's right inset
//!
//! The indicator is the control's trailing chrome, and the value's box must *yield* to it:
//! The shared relation writes this as `rightPadding: padding + indicator.width`, and the
//! reason is that a fixed text inset and a fixed indicator inset are two unrelated
//! derivations from the *same* edge. A wider indicator, a theme that swaps the glyph for a
//! larger one, or a bigger font measuring it then overlaps the value instead of pushing it.
//! The previous form could not express the relation at all — the value was written at
//! `rect.x + 6` with no bound and the indicator placed independently at
//! `rect.x + rect.width - 20`.

use crate::core::{Color, Font, HorizontalAlignment, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::Signal1;
use crate::style::EdgeOffsets;
use crate::undo::{TextSnapshotCommand, UndoStack};
use crate::widget::capability::coercion::expect_string;
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::metrics::{dimensions, 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;

/// Space between the indicator's leading edge and the end of the value's box.
///
/// Half the field's own horizontal padding, so the gap between the value and the indicator
/// is tighter than the gap between the value and the field's edge — a relation, not a third
/// independent numeral.
const INDICATOR_LEADING_GAP: u32 = dimensions::TEXT_FIELD_PADDING_H / 2;

/// The indicator's box and the box the value may occupy, derived together.
///
/// # Why one derivation and not two arithmetic expressions
///
/// The value's inset and the indicator's position were two independent computations from the
/// same field width, so neither could be read from a test and neither constrained the other.
/// Making both outputs of one function is what lets the suite assert that the value yields to
/// the indicator rather than merely observing that it usually appears to.
#[derive(Debug, Clone, Copy, PartialEq)]
struct EditGeometry {
    /// The indicator glyph's bounding box.
    box_rect: Rect,
    /// The rectangle the typed value may occupy.
    text_box: Rect,
}

impl EditGeometry {
    /// Derives both boxes from the band the control paints and `line_height`.
    ///
    /// `line_height` is a parameter rather than measured here, for the same reason
    /// `CheckBox::indicator_rect` takes one: both boxes sit on the *value's* line box and only
    /// the caller knows which font that is.
    fn for_band(band: Rect, line_height: u32) -> Self {
        let indicator_width = dimensions::BUTTON_ICON_SIZE.min(band.width);
        let height = line_height.min(band.height);
        let box_rect = Rect::new(
            band.x
                + band.width.saturating_sub(indicator_width + dimensions::TEXT_FIELD_PADDING_H)
                    as i32,
            band.y + (band.height.saturating_sub(height) / 2) as i32,
            indicator_width,
            height,
        );
        // The value's box stops one gap before the indicator. `min` with the leading inset
        // keeps a squeezed field from describing an inverted rectangle: a field with no room
        // for a value draws no value rather than one outside itself.
        let text_right = box_rect.x.saturating_sub(INDICATOR_LEADING_GAP as i32);
        let text_left = (band.x + dimensions::TEXT_FIELD_PADDING_H as i32).min(text_right);
        let text_box =
            Rect::new(text_left, band.y, text_right.saturating_sub(text_left) as u32, band.height);
        Self { box_rect, text_box }
    }
}

/// A combo box that allows both typing custom values and selecting from a list.
///
/// When collapsed, shows the current text in a text field with a dropdown arrow.
/// When expanded, shows a dropdown list of items below the text field.
pub struct EditableComboBox {
    base: BaseWidget,
    text: String,
    items: Vec<String>,
    expanded: bool,
    selected_index: Option<usize>,
    /// Emitted when the text field content changes.
    pub text_changed: Signal1<String>,
    /// Emitted when a dropdown item is selected (by index).
    pub item_selected: Signal1<usize>,
    undo_stack: UndoStack,
    history_target: Rc<RefCell<String>>,
    restoring_history: bool,
}

impl EditableComboBox {
    /// The band the control actually paints: full width, one field tall, centred.
    ///
    /// # Why the control is not its own rectangle
    ///
    /// An editable combo box is a text field, and [`dimensions::TEXT_FIELD_MIN_HEIGHT`] is
    /// what every field in this crate occupies. The 240x120 census cell drew a 240x120
    /// rounded box whose value was then positioned `padding + 13` down from an edge that was
    /// itself not the field's.
    fn field_band(&self) -> Rect {
        ControlMetrics::full_width_band(self.geometry(), dimensions::TEXT_FIELD_MIN_HEIGHT)
    }

    /// The indicator's box and the value's box, derived from the band and one line height.
    fn indicator_geometry(&self, line_height: u32) -> EditGeometry {
        EditGeometry::for_band(self.field_band(), line_height)
    }

    /// Creates a new EditableComboBox widget with the given geometry.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::EditableComboBox, geometry, "EditableComboBox"),
            text: String::new(),
            items: Vec::new(),
            expanded: false,
            selected_index: None,
            text_changed: Signal1::new(),
            item_selected: Signal1::new(),
            undo_stack: UndoStack::new(),
            history_target: Rc::new(RefCell::new(String::new())),
            restoring_history: false,
        }
    }

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

    /// Sets the text in the text field and emits `text_changed`.
    pub fn set_text(&mut self, text: impl Into<String>) {
        let t = text.into();
        if self.text != t {
            let before = self.text.clone();
            self.text = t.clone();
            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(),
                    "editable_combo_text",
                )));
            }
            self.text_changed.emit(self.text.clone());
            self.base.request_redraw();
        }
    }

    /// Adds an item to the dropdown list.
    pub fn add_item(&mut self, item: impl Into<String>) {
        self.items.push(item.into());
        self.base.request_redraw();
    }

    /// Removes an item by index. Returns `true` if the item was removed.
    pub fn remove_item(&mut self, index: usize) -> bool {
        if index < self.items.len() {
            self.items.remove(index);
            if self.selected_index == Some(index) {
                self.selected_index = None;
            } else if let Some(ref mut sel) = self.selected_index {
                if index < *sel {
                    *sel -= 1;
                }
            }
            self.base.request_redraw();
            true
        } else {
            false
        }
    }

    /// Removes all items from the list and closes the dropdown.
    pub fn clear_items(&mut self) {
        self.items.clear();
        self.selected_index = None;
        self.expanded = false;
        self.base.request_redraw();
    }

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

    /// Returns the number of items in the dropdown.
    pub fn item_count(&self) -> usize {
        self.items.len()
    }

    /// Returns whether the dropdown is currently expanded.
    pub fn is_expanded(&self) -> bool {
        self.expanded
    }

    /// Expands the dropdown list.
    pub fn expand(&mut self) {
        if !self.expanded {
            self.expanded = true;
            self.base.request_redraw();
        }
    }

    /// Collapses the dropdown list.
    pub fn collapse(&mut self) {
        if self.expanded {
            self.expanded = false;
            self.base.request_redraw();
        }
    }

    /// Toggles the dropdown between expanded and collapsed.
    pub fn toggle(&mut self) {
        self.expanded = !self.expanded;
        self.base.request_redraw();
    }

    /// Returns the currently selected item index, if any.
    pub fn selected_index(&self) -> Option<usize> {
        self.selected_index
    }

    /// Steps back one text edit and returns `true`, or `false` when there is
    /// nothing to undo.
    ///
    /// The restored text is applied through [`EditableComboBox::set_text`], so
    /// it runs the full validation and signal path. It also clears the selection:
    /// undoing a text change does not restore the previously selected item, and
    /// `selected_index` becomes `None` even though the text may match an item.
    pub fn undo(&mut self) -> bool {
        if self.undo_stack.undo().is_err() {
            return false;
        }
        self.restoring_history = true;
        let text = self.history_target.borrow().clone();
        self.set_text(&text);
        self.restoring_history = false;
        true
    }
    /// Steps forward one undone edit and returns `true`, or `false` when there is
    /// nothing to redo. Selection behaviour matches
    /// [`EditableComboBox::undo`].
    pub fn redo(&mut self) -> bool {
        if self.undo_stack.redo().is_err() {
            return false;
        }
        self.restoring_history = true;
        let text = self.history_target.borrow().clone();
        self.set_text(&text);
        self.restoring_history = false;
        true
    }
    /// Returns `true` if [`EditableComboBox::undo`] would change the text.
    pub fn can_undo(&self) -> bool {
        self.undo_stack.can_undo()
    }
    /// Returns `true` if [`EditableComboBox::redo`] would change the text.
    pub fn can_redo(&self) -> bool {
        self.undo_stack.can_redo()
    }

    /// Selects the item at the given index and sets the text field to its value.
    /// Emits `item_selected`. Returns `true` if the selection changed.
    pub fn select_index(&mut self, index: usize) -> bool {
        if index < self.items.len() && self.selected_index != Some(index) {
            self.selected_index = Some(index);
            self.text = self.items[index].clone();
            self.text_changed.emit(self.text.clone());
            self.item_selected.emit(index);
            self.expanded = false;
            self.base.request_redraw();
            return true;
        }
        false
    }
}

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

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

    fn size_hint(&self) -> crate::core::Size {
        // Derived through the same metric the band is drawn from, so the reported size and the
        // painted box cannot describe two different controls. The width was a bare `200` while
        // `draw` painted the whole given rectangle — neither had a relation to the other.
        let side_air = (dimensions::TEXT_FIELD_MIN_HEIGHT / 2).saturating_sub(8);
        let trailing =
            dimensions::TEXT_FIELD_PADDING_H + dimensions::BUTTON_ICON_SIZE + INDICATOR_LEADING_GAP;
        let padding = EdgeOffsets {
            top: side_air,
            right: trailing,
            bottom: side_air,
            left: dimensions::TEXT_FIELD_PADDING_H,
        };
        // Content width: the text the caller typed, at a nominal advance per character. A
        // hint has no `RenderContext` to measure with, and a hint a few pixels generous is
        // the safe direction — the paint path *fits* the value into the box this produced.
        let content = Size::new(self.text.len() as u32 * 8, 0);
        let floor = Size::new(
            dimensions::TEXT_FIELD_MIN_HEIGHT + trailing,
            dimensions::TEXT_FIELD_MIN_HEIGHT,
        );
        let hint = ControlMetrics::implicit_size(content, padding, floor);
        Size::new(hint.width, self.field_band().height.max(floor.height))
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

/// `EditableComboBox`'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. `item_count` is derived from
/// the dropdown list, so it is refused as read-only rather than reported as a name
/// this control does not know.
impl WidgetProperties for EditableComboBox {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "text" => Ok(CapabilityValue::String(self.text().to_string())),
            "item_count" => Ok(CapabilityValue::UInt(self.item_count() as u64)),
            _ => 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(())
            }
            "item_count" => Err(CapabilityAccessError::ReadOnlyProperty),
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of!["text", "item_count", BASE_PROPERTY_NAMES]
    }

    /// Runs one of the commands `editable_combo_box` 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 EditableComboBox {
    fn draw(&mut self, context: &mut RenderContext) {
        // ── The band actually painted ──
        //
        // `geometry()` is the area the control was *given*; an editable combo box is a text
        // field, and a field is a fixed-height band. The fill, the border, the value and the
        // indicator are all placed from this one box, so none of them can be measured against
        // an edge the field does not have.
        let rect = self.field_band();
        if rect.width == 0 || rect.height == 0 {
            return;
        }
        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. Every colour here used
        // to be a literal, so the control rendered identically in a light and a dark
        // theme — the rendering census reported it as theme-blind.
        //
        // The theme read is a separate manager lock, taken and released inside
        // `resolved_theme_style`, so it is not held across the draw — the global
        // manager's mutex is not re-entrant.
        let style = self.base.style().clone();
        let theme = crate::style::resolved_theme_style("editable_combo_box");
        let themed_ink = theme.as_ref().and_then(|t| t.text_color);
        let themed_border = theme.as_ref().and_then(|t| t.border_color);

        let ink = style.text_color.or(themed_ink).unwrap_or(Color::BLACK);
        let field = style
            .background_color
            .or_else(|| theme.as_ref().and_then(|t| t.background_color))
            .unwrap_or(Color::WHITE);
        let border = style
            .border_color
            .or(themed_border)
            .filter(|resolved| *resolved != field)
            .unwrap_or_else(|| field.blend(&ink, 0.3));

        // A disabled field is the resolved palette, one step toward the surface, rather
        // than a separate literal pair that could only ever suit a light theme.
        let bg_color = if is_enabled { field } else { field.blend(&ink, 0.08) };
        context.fill_rounded_rect(rect, 4, bg_color);

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

        // Draw text content and the dropdown arrow from **one** derivation, so the value
        // yields to the indicator instead of being written at an unconstrained offset.
        let font = Font::simple("sans-serif", 13.0);
        let line = context.text_line(rect, &font);
        let geometry = self.indicator_geometry(line.height);
        let display_text = if self.text.is_empty() && !is_enabled { "" } else { &self.text };
        let text_color = if is_enabled { ink } else { ink.blend(&bg_color, 0.6) };
        // The value is fitted into the box the indicator left, on that box's own line box: a
        // glyph origin is the box's top edge, so the old `padding + 13` put a 13 px font's
        // origin on the field's middle line and drew the value half a line low.
        let value_line = context.text_line(geometry.text_box, &font);
        context.draw_text_fitted(
            Rect::new(
                geometry.text_box.x,
                value_line.y,
                geometry.text_box.width,
                value_line.height,
            ),
            display_text,
            &font,
            text_color,
            HorizontalAlignment::Left,
        );

        // Draw the dropdown indicator inside its own derived box.
        //
        // This glyph *is* the combo box's affordance — it is how a user knows the field opens —
        // so it is held to the text floor rather than dimmed by a fixed fraction. The old
        // `ink.blend(&bg_color, 0.45)` measured 3.45:1 on the dark field and 3.83:1 on the light
        // one, i.e. the control's one signifier was its least legible mark. It is still drawn
        // slightly quieter than the value, which is what keeps it reading as chrome.
        let arrow_text = if self.expanded { "▲" } else { "▼" };
        let arrow_color = if is_enabled {
            ink.legible_on(bg_color, 4.5).blend(&bg_color, 0.15)
        } else {
            ink.blend(&bg_color, 0.7)
        };
        context.draw_text_fitted(
            geometry.box_rect,
            arrow_text,
            &font,
            arrow_color,
            HorizontalAlignment::Center,
        );

        // Draw dropdown if expanded
        if !self.expanded || self.items.is_empty() {
            return;
        }

        let drop_down_y = rect.y + rect.height as i32;
        let item_height = 28u32;
        let drop_down_height = item_height * self.items.len() as u32;
        let drop_rect = Rect::new(rect.x, drop_down_y, rect.width, drop_down_height);

        // Dropdown background. The list floats over whatever is beneath it, so it is the
        // field's own colour rather than the window's: a transparent list would show the
        // content behind it through the popup.
        context.fill_rounded_rect(drop_rect, 2, field);
        context.draw_rounded_rect_stroke(drop_rect, 2, border, 1);

        // The selected-row highlight is the theme's accent, which is the one hue a theme
        // is expected to vary most.
        let highlight = crate::style::theme_manager()
            .current_theme()
            .map(|active| active.colors.primary.with_alpha(40))
            .unwrap_or_else(|| ink.blend(&field, 0.85));

        for (i, item) in self.items.iter().enumerate() {
            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,
            );

            // Highlight selected item
            if self.selected_index == Some(i) {
                context.fill_rounded_rect(item_rect, 2, highlight);
            }

            // Item text
            let item_text_x = item_rect.x + 8;
            let item_text_y = item_rect.y + 18;
            let item_color = if is_enabled { ink } else { ink.blend(&field, 0.6) };
            context.draw_text(
                Point::new(item_text_x, item_text_y),
                item,
                &font,
                item_color,
                HorizontalAlignment::Left,
            );
        }
    }
}

impl EventHandler for EditableComboBox {
    fn handle_event(&mut self, event: &Event) {
        if !self.base.is_enabled() {
            return;
        }

        match event {
            Event::KeyPress { key, modifiers } => {
                if *modifiers == 2 && *key == 90 {
                    let _ = self.undo();
                    return;
                }
                if *modifiers == 2 && *key == 89 {
                    let _ = self.redo();
                    return;
                }
                match *key {
                    8 => {
                        // Backspace
                        let mut new_text = self.text.clone();
                        new_text.pop();
                        self.set_text(new_text);
                        return;
                    }
                    13 => {
                        // Enter/Return
                        if self.expanded && !self.items.is_empty() {
                            if let Some(idx) = self.selected_index {
                                self.select_index(idx);
                            } else if let Some(idx) =
                                self.items.iter().position(|item| item == &self.text)
                            {
                                self.select_index(idx);
                            }
                        }
                        self.expanded = false;
                        self.base.request_redraw();
                        return;
                    }
                    27 => {
                        // Escape
                        self.expanded = false;
                        self.base.request_redraw();
                        return;
                    }
                    38 => {
                        // ArrowUp
                        if self.expanded && !self.items.is_empty() {
                            let prev = match self.selected_index {
                                Some(0) | None => 0,
                                Some(idx) => idx - 1,
                            };
                            self.selected_index = Some(prev);
                            self.base.request_redraw();
                        }
                        return;
                    }
                    40 => {
                        // ArrowDown
                        if !self.expanded {
                            self.expanded = true;
                        }
                        if !self.items.is_empty() {
                            let next = match self.selected_index {
                                Some(idx) => (idx + 1).min(self.items.len() - 1),
                                None => 0,
                            };
                            self.selected_index = Some(next);
                            self.base.request_redraw();
                        }
                        return;
                    }
                    _ => {
                        // Character input
                        if let Some(ch) = char::from_u32(*key) {
                            if ch.is_ascii_graphic() || ch == ' ' {
                                let mut new_text = self.text.clone();
                                new_text.push(ch);
                                self.set_text(new_text);
                                return;
                            }
                        }
                    }
                }
                self.base.handle_event(event);
            }
            Event::MousePress { pos, button } if *button == 1 => {
                let rect = self.geometry();

                // Click on the text field (with arrow zone)
                if rect.contains_point(*pos) {
                    // Check if click is on the arrow area (right side)
                    let arrow_zone_x = rect.x + rect.width as i32 - 24;
                    if pos.x >= arrow_zone_x {
                        // Arrow zone - toggle dropdown
                        self.toggle();
                    } else {
                        // Text field - focus and expand if items exist
                        if !self.expanded && !self.items.is_empty() {
                            self.expand();
                        } else {
                            self.toggle();
                        }
                    }
                    return;
                }

                // Click on a dropdown item
                if self.expanded {
                    let item_height = 28i32;
                    let drop_down_y = rect.y + rect.height as i32;
                    let drop_down_height = item_height * self.items.len() 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.items.len() {
                            self.select_index(idx);
                        }
                        return;
                    }

                    // Click outside dropdown - collapse
                    if !rect.contains_point(*pos) {
                        self.collapse();
                    }
                }
            }
            _ => {
                self.base.handle_event(event);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::widget::svg::render_to_svg;

    #[test]
    fn editable_combo_box_default_creation() {
        let cb = EditableComboBox::new(Rect::new(0, 0, 200, 30));
        assert_eq!(cb.kind(), WidgetKind::EditableComboBox);
        assert_eq!(cb.text(), "");
        assert_eq!(cb.item_count(), 0);
        assert!(!cb.is_expanded());
        assert!(cb.selected_index().is_none());
    }

    #[test]
    fn editable_combo_box_add_and_remove_items() {
        let mut cb = EditableComboBox::new(Rect::new(0, 0, 200, 30));
        cb.add_item("Option A");
        cb.add_item("Option B");
        cb.add_item("Option C");
        assert_eq!(cb.item_count(), 3);

        assert!(cb.remove_item(1));
        assert_eq!(cb.item_count(), 2);
        assert_eq!(cb.items()[0], "Option A");
        assert_eq!(cb.items()[1], "Option C");

        assert!(!cb.remove_item(5));
        assert_eq!(cb.item_count(), 2);
    }

    #[test]
    fn editable_combo_box_text_operations() {
        let mut cb = EditableComboBox::new(Rect::new(0, 0, 200, 30));
        assert_eq!(cb.text(), "");

        cb.set_text("Hello");
        assert_eq!(cb.text(), "Hello");

        cb.set_text("World");
        assert_eq!(cb.text(), "World");

        cb.clear_items();
        // Text should be unchanged by clear_items
        assert_eq!(cb.text(), "World");
    }

    #[test]
    fn editable_combo_box_expand_collapse() {
        let mut cb = EditableComboBox::new(Rect::new(0, 0, 200, 30));
        assert!(!cb.is_expanded());

        cb.expand();
        assert!(cb.is_expanded());

        cb.collapse();
        assert!(!cb.is_expanded());

        cb.toggle();
        assert!(cb.is_expanded());

        cb.toggle();
        assert!(!cb.is_expanded());
    }

    #[test]
    fn editable_combo_box_select_index() {
        let mut cb = EditableComboBox::new(Rect::new(0, 0, 200, 30));
        cb.add_item("Alpha");
        cb.add_item("Beta");
        cb.add_item("Gamma");

        assert!(cb.select_index(1));
        assert_eq!(cb.selected_index(), Some(1));
        assert_eq!(cb.text(), "Beta");
        assert!(!cb.is_expanded());

        // Selecting same index again should return false
        assert!(!cb.select_index(1));

        // Selecting out of bounds should be noop
        assert!(!cb.select_index(10));
    }

    #[test]
    fn editable_combo_box_svg_output() {
        let mut cb = EditableComboBox::new(Rect::new(0, 0, 200, 30));
        cb.add_item("Item 1");
        cb.add_item("Item 2");
        cb.set_text("Hello");
        let svg = render_to_svg(&mut cb);
        assert!(svg.starts_with("<svg"));
        assert!(svg.ends_with("</svg>"));
    }

    #[test]
    fn editable_combo_box_text_changed_signal() {
        let mut cb = EditableComboBox::new(Rect::new(0, 0, 200, 30));
        let captured = std::sync::Arc::new(std::sync::Mutex::new(None::<String>));
        let c = captured.clone();
        cb.text_changed.connect(move |val: std::sync::Arc<String>| {
            *c.lock().unwrap() = Some(val.to_string());
        });

        cb.set_text("CustomValue");
        assert_eq!(captured.lock().unwrap().as_deref(), Some("CustomValue"));
    }

    #[test]
    fn editable_combo_box_item_selected_signal() {
        let mut cb = EditableComboBox::new(Rect::new(0, 0, 200, 30));
        cb.add_item("A");
        cb.add_item("B");

        let captured = std::sync::Arc::new(std::sync::Mutex::new(None::<usize>));
        let c = captured.clone();
        cb.item_selected.connect(move |val: std::sync::Arc<usize>| {
            *c.lock().unwrap() = Some(*val);
        });

        cb.select_index(1);
        assert_eq!(*captured.lock().unwrap(), Some(1));
    }

    /// The value's box ends where the indicator's box begins, at every control width.
    ///
    /// # What this pins
    ///
    /// BLUE22 §B.6 rule 4: a sub-part's box is derived from its sibling, so the value *yields*
    /// to the indicator. The value used to be written at `rect.x + 6` with no upper bound
    /// while the indicator sat at `rect.x + rect.width - 20`, so a longer value or a wider
    /// indicator glyph put the two on top of each other.
    /// The value's box ends where the indicator's box begins, at every control width.
    ///
    /// # What this pins
    ///
    /// BLUE22 §B.6 rule 4: a sub-part's box is derived from its sibling, so the value *yields*
    /// to the indicator. The value used to be written at `rect.x + 6` with no upper bound
    /// while the indicator sat at `rect.x + rect.width - 20`, so a longer value or a wider
    /// indicator glyph put the two on top of each other.
    ///
    /// The widths below include two that are narrower than the leading inset plus the
    /// indicator, because that is where a derivation that is only *described* as a relation
    /// comes apart: the value's box must collapse rather than claim room the band does not
    /// have.
    #[test]
    fn the_value_box_ends_where_the_indicator_begins() {
        let trailing =
            dimensions::TEXT_FIELD_PADDING_H + dimensions::BUTTON_ICON_SIZE + INDICATOR_LEADING_GAP;
        for width in [0u32, 20, 64, 240, 400] {
            let cb = EditableComboBox::new(Rect::new(0, 0, width, 120));
            let geometry = cb.indicator_geometry(14);
            let band = cb.field_band();
            assert_eq!(
                geometry.text_box.x + geometry.text_box.width as i32 + INDICATOR_LEADING_GAP as i32,
                geometry.box_rect.x,
                "the value must stop one gap short of the indicator at width {width}"
            );
            assert!(
                geometry.box_rect.x + geometry.box_rect.width as i32 <= band.x + band.width as i32,
                "the indicator must stay inside the band at width {width}"
            );
            if width < trailing {
                assert_eq!(
                    geometry.text_box.width, 0,
                    "a band too narrow for its own chrome holds no value at width {width}"
                );
            } else {
                assert!(
                    geometry.text_box.width > 0,
                    "a band with room must give the value some of it at width {width}"
                );
            }
        }
    }

    /// The reported height is the band that is painted.
    #[test]
    fn the_reported_height_is_the_band_that_is_painted() {
        let cb = EditableComboBox::new(Rect::new(0, 0, 240, 120));
        let band = cb.field_band();
        assert_eq!(band.height, dimensions::TEXT_FIELD_MIN_HEIGHT);
        assert_eq!(cb.size_hint().height, band.height);
        assert_eq!(band.y, (120 - dimensions::TEXT_FIELD_MIN_HEIGHT as i32) / 2);
    }
}