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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! Rich text editor widget.
use crate::core::HorizontalAlignment;
use crate::core::Rect;
use crate::impl_widget_property_hooks;
use crate::property_names_of;
use crate::render::RenderContext;
use crate::signal::Signal1;
use crate::undo::{TextSnapshotCommand, UndoStack};
use crate::widget::capability::coercion::{expect_bool, 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::text_utils::floor_char_boundary;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use std::cell::RefCell;
use std::rc::Rc;
/// Rich text/code editor baseline widget contract.
///
/// Holds a plain `String` plus a byte-offset selection and a set of change
/// signals. Despite the name it stores no styling or markup: it is a text
/// buffer with editor signalling, and "rich" refers to the role it fills (the
/// editing surface that richer tooling builds on) rather than to its contents.
///
/// Offsets in the selection and cursor signals are **byte** indices into the
/// UTF-8 text, not character indices, so they are not guaranteed to land on
/// character boundaries unless the writer keeps them there.
///
pub struct RichEdit {
base: BaseWidget,
text: String,
selection: Option<(usize, usize)>,
read_only: bool,
/// Emitted with the full new text on every accepted change. Carries the
/// whole document, not a delta.
pub text_changed: Signal1<String>,
/// Emitted with the new selection as byte offsets `(start, end)`, or `None`
/// when the selection is cleared.
pub selection_changed: Signal1<Option<(usize, usize)>>,
/// Emitted with the new flag from [`RichEdit::set_read_only`].
pub read_only_changed: Signal1<bool>,
/// Emitted with the new cursor byte offset whenever the text is replaced.
/// Note the name does not match the payload: it reports an offset, not a
/// position struct.
pub cursor_position_changed: Signal1<usize>,
undo_stack: UndoStack,
history_target: Rc<RefCell<String>>,
restoring_history: bool,
}
impl RichEdit {
/// Creates an empty rich editor.
pub fn new(geometry: Rect) -> Self {
Self {
base: BaseWidget::new(WidgetKind::RichEdit, geometry, "RichEdit"),
text: String::new(),
selection: None,
read_only: false,
text_changed: Signal1::new(),
selection_changed: Signal1::new(),
read_only_changed: Signal1::new(),
cursor_position_changed: Signal1::new(),
undo_stack: UndoStack::new(),
history_target: Rc::new(RefCell::new(String::new())),
restoring_history: false,
}
}
/// Returns current editor text.
pub fn text(&self) -> &str {
&self.text
}
/// Replaces editor text and resets selection/cursor to end.
///
/// Ignored entirely — no change, no signals — when the editor is read-only
/// or when `text` equals the current content. Otherwise the previous content
/// is pushed onto the undo stack (unless an undo/redo is being replayed),
/// the selection is cleared, and `text_changed` then `cursor_position_changed`
/// fire, followed by a redraw request.
///
/// The cursor is reported as `text.len()`, a byte offset at the end of the
/// document.
pub fn set_text(&mut self, text: String) {
if self.read_only || self.text == text {
return;
}
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(),
"rich_edit_text",
)));
}
self.selection = None;
self.text_changed.emit(self.text.clone());
self.cursor_position_changed.emit(self.text.len());
self.base.request_redraw();
}
/// Steps back one text change and returns `true`, or `false` when there is
/// nothing to undo.
///
/// Replaying history emits `text_changed` but does not consult the read-only
/// flag, so an undo can alter the text of a read-only editor. No undo entry
/// is created for the replay.
pub fn undo(&mut self) -> bool {
if self.undo_stack.undo().is_err() {
return false;
}
self.restore_history_text();
true
}
/// Steps forward one undone change and returns `true`, or `false` when there
/// is nothing to redo. Signal behaviour matches [`RichEdit::undo`], including
/// the ignored read-only flag.
pub fn redo(&mut self) -> bool {
if self.undo_stack.redo().is_err() {
return false;
}
self.restore_history_text();
true
}
/// Returns `true` if [`RichEdit::undo`] would change the text.
pub fn can_undo(&self) -> bool {
self.undo_stack.can_undo()
}
/// Returns `true` if [`RichEdit::redo`] would change the text.
pub fn can_redo(&self) -> bool {
self.undo_stack.can_redo()
}
fn restore_history_text(&mut self) {
let text = self.history_target.borrow().clone();
self.restoring_history = true;
self.text = text;
self.selection = Some((self.text.len(), self.text.len()));
self.restoring_history = false;
self.text_changed.emit(self.text.clone());
self.cursor_position_changed.emit(self.text.len());
self.base.request_redraw();
}
/// Returns current selection range.
pub fn selection(&self) -> Option<(usize, usize)> {
self.selection
}
/// Sets selection range.
pub fn set_selection(&mut self, start: usize, end: usize) {
if self.read_only {
return;
}
let start = start.min(self.text.len());
let end = end.min(self.text.len());
if self.selection == Some((start, end)) {
return;
}
self.selection = Some((start, end));
self.selection_changed.emit(self.selection);
self.base.request_redraw();
}
/// Clears selection.
pub fn clear_selection(&mut self) {
if self.selection.is_none() {
return;
}
self.selection = None;
self.selection_changed.emit(None);
}
/// Returns read-only state.
pub fn is_read_only(&self) -> bool {
self.read_only
}
/// Sets read-only state.
pub fn set_read_only(&mut self, read_only: bool) {
if self.read_only == read_only {
return;
}
self.read_only = read_only;
self.read_only_changed.emit(read_only);
self.base.request_redraw();
}
/// Returns cursor position.
pub fn cursor_position(&self) -> usize {
self.selection.map_or(0, |(start, _)| start)
}
/// Converts a byte offset into (line_index, col_index).
/// Returns `None` when the offset is at end of text.
fn byte_offset_to_line_col(&self, offset: usize) -> Option<(usize, usize)> {
if self.text.is_empty() {
return Some((0, 0));
}
let offset = offset.min(self.text.len());
let mut line = 0usize;
let mut col = 0usize;
for (i, ch) in self.text.char_indices() {
if i >= offset {
break;
}
if ch == '\n' {
line += 1;
col = 0;
} else {
col += 1;
}
}
Some((line, col))
}
/// The byte offset at which `line` starts in `self.text`.
///
/// # Why this is derived and not stored
///
/// Line starts are a pure function of the text, and the text is mutated by every edit. A stored
/// table would have to be rebuilt on each of them, and a missed rebuild would put the selection
/// highlight on the wrong line — a defect that only shows up after an edit, which is the hardest
/// kind to reproduce. Deriving it costs one pass over the prefix, which the draw already pays for
/// the caret's own line lookup.
fn line_start_offset(&self, line: usize) -> usize {
if line == 0 {
return 0;
}
let mut current = 0usize;
for (i, ch) in self.text.char_indices() {
if ch == '\n' {
current += 1;
if current == line {
return i + 1;
}
}
}
self.text.len()
}
/// Converts (line_index, col_index) back to a byte offset.
fn line_col_to_byte_offset(&self, line: usize, col: usize) -> usize {
let mut current_line = 0usize;
let mut current_col = 0usize;
for (i, ch) in self.text.char_indices() {
if current_line == line && current_col == col {
return i;
}
if ch == '\n' {
current_line += 1;
current_col = 0;
} else {
current_col += 1;
}
}
// If we reached the end, return the text length if we're on the right line
if current_line == line {
self.text.len()
} else {
0
}
}
/// Sets cursor position.
pub fn set_cursor_position(&mut self, position: usize) {
if self.read_only {
return;
}
let position = position.min(self.text.len());
self.selection = Some((position, position));
self.cursor_position_changed.emit(position);
self.base.request_redraw();
}
}
impl Widget for RichEdit {
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
}
impl_draw_bridge!();
impl_widget_property_hooks!();
}
/// `RichEdit`'s property contract.
///
/// `WidgetKind::RichEdit` is the kind the capability layer pairs with the
/// [`CodeEditor`](crate::widget::CodeEditor) control
/// (`capability::properties::code_editor_capability`), so the `RichEdit` arm of
/// the old centralised dispatch was answered by `CodeEditor`, not by this widget.
/// The trait impl therefore lives beside `CodeEditor` in its own file; this widget
/// declares that it has no properties of its own rather than claiming another
/// control's, which is the honest answer the property layer asks for.
impl WidgetProperties for RichEdit {
fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
match name {
"text" => Ok(CapabilityValue::String(self.text().to_string())),
"line_count" => Ok(CapabilityValue::UInt(self.text().lines().count() as u64)),
"read_only" => Ok(CapabilityValue::Bool(self.read_only)),
_ => 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(())
}
"read_only" => {
self.read_only = expect_bool(value)?;
self.base.request_redraw();
Ok(())
}
// Derived from the document body.
"line_count" => Err(CapabilityAccessError::ReadOnlyProperty),
_ => base_property_set(self, name, value),
}
}
fn property_names(&self) -> &'static [&'static str] {
property_names_of!["text", "line_count", "read_only", BASE_PROPERTY_NAMES]
}
/// Runs one of the commands `rich_edit` publishes.
///
/// `set_text` assigns the document body 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 RichEdit {
fn draw(&mut self, context: &mut RenderContext) {
let rect = self.base.geometry();
use crate::core::Color;
// Chrome colours resolve the explicit style first, then the theme's resolved style for
// this control, and only then fall back to a literal. Every colour below used to be a
// literal, so a light/dark switch left the page, its border, its text and its cursor
// unchanged — the rendering census reported the control 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();
// The fallback name matters: the role table is keyed on **role** names, so `rich_edit`
// (the factory name) is not in it and would classify as `Surface`, i.e. the window fill.
// `richedit` is, and resolves to the editable interior plus the theme's foreground.
let theme = crate::style::resolved_theme_style("rich_edit")
.or_else(|| crate::style::resolved_theme_style("richedit"));
// The window fill, read as its own lock acquisition and copied out as a value, so the
// guard is dropped before anything else touches the theme.
let window_fill = {
let manager = crate::style::theme_manager();
manager.current_theme().map(|active| active.colors.background).unwrap_or(Color::WHITE)
};
let paper_from_theme =
theme.as_ref().and_then(|t| t.background_color).unwrap_or(Color::rgb(255, 255, 255));
// The filter is on the **resolved** value, not only on the theme's: a control absent from
// the role table resolves its background to the window fill, and `text_edit`/`rich_edit`
// are exactly those controls, so letting that value through would paint the document in
// the window's own colour — invisible on screen. A caller's own colour still wins.
let paper = match style.background_color {
Some(resolved) if resolved != window_fill => resolved,
_ => paper_from_theme,
};
let ink = style
.text_color
.or_else(|| theme.as_ref().and_then(|t| t.text_color))
.unwrap_or(Color::BLACK);
// The border is one step from the page toward the ink, and a read-only document is
// recessed a further step so the two states stay distinguishable on either appearance.
let border = style
.border_color
.or_else(|| theme.as_ref().and_then(|t| t.border_color))
.unwrap_or_else(|| paper.blend(&ink, 0.28));
// The selection band is a step from the page toward the accent — visible on both appearances
// and distinct from the caret, which is the accent at full strength.
let selection_fill = crate::style::semantic_color(crate::style::SemanticColor::Info)
.unwrap_or(ink)
.blend(&paper, 0.65);
// Draw background
context.face(
rect,
paper,
self.style().surface.unwrap_or_default(),
self.style().border_radius.unwrap_or(0),
Color::BLACK,
);
// Draw border
context.draw_rect(rect, if self.read_only { border.blend(&paper, 0.50) } else { border });
// Draw text content — all lines
let font = crate::core::Font::default();
let line_height = 16i32;
let padding = 2i32;
let mut line_y = rect.y + padding + line_height;
let cursor_before = self.selection.map_or(0, |(start, _)| start);
// Compute (line, col) for cursor
let cursor_coord = self.byte_offset_to_line_col(cursor_before);
// The selection highlight is drawn as a background band **before** the ink, so the text
// stays legible on top of it.
//
// # The gap this closes (BLUE24 §12 U-4)
//
// The control has published `selection()` / `set_selection()` / `clear_selection()` since it
// was written, and drew **nothing** for them: a caller could select a range and the only
// visible feedback was a caret at one end. A selection model with no rendering is the
// "mechanism built, port not opened" shape this whole plan is about.
//
// The band's two edges are measured with the same `estimate_text_width` the caret uses, so
// highlighting a range cancels exactly to the caret at either end. Computing them `col * 7`
// apart would have reproduced the caret defect twice more.
let selection = self.selection.filter(|(start, end)| start != end);
for (line_idx, line) in self.text.lines().enumerate() {
if line_y > rect.y + rect.height as i32 {
break;
}
if let Some((start, end)) = selection {
let line_start = self.line_start_offset(line_idx);
let line_end = line_start + line.len();
// Clamp the selection to this line, so a range spanning several lines highlights
// each of them only over its own part.
let from = start.max(line_start).min(line_end) - line_start;
let to = end.max(line_start).min(line_end) - line_start;
if from < to {
let left = rect.x
+ padding
+ crate::widget::metrics::estimate_text_width(&line[..from], &font, 1.0)
as i32;
let width =
crate::widget::metrics::estimate_text_width(&line[from..to], &font, 1.0);
context.fill_rect(
crate::core::Rect::new(
left,
line_y - line_height + 2,
width,
line_height as u32,
),
selection_fill,
);
}
}
// Draw the line text
context.draw_text(
crate::core::Point::new(rect.x + padding, line_y),
line,
&font,
ink,
HorizontalAlignment::Left,
);
// Draw cursor on this line if not read-only
if !self.read_only && Some(line_idx) == cursor_coord.map(|(l, _)| l) {
if let Some((_, col)) = cursor_coord {
// The caret sits where the text **actually** ends, measured with the renderer's
// own advance model, rather than at `col * 7`.
//
// # The defect this replaces (BLUE24 §12 U-4's prerequisite)
//
// The old line was `rect.x + padding + (col as i32) * 7`, with the comment
// "rough char width". Seven logical pixels is an average for a proportional
// Latin face at one size, so the caret drifted off the character it was supposed
// to sit on: on the crate's own `Open Sans` an `i` is ~3.5 px and a `w` ~10.3 px
// (measured in §12.2.4), and on a CJK glyph it is off by roughly a factor of two
// per character. A caret that is not where the text is makes every later
// editing gesture look wrong — which is why this is the prerequisite for
// selection handles, not a cosmetic fix.
//
// `estimate_text_width` is the shared model — the one the gate
// `check_implicit_size_uses_metrics` points at and the one the renderer draws
// with — so the caret and the ink cannot disagree about where a character ends.
let prefix: String = line.chars().take(col).collect();
let advance =
crate::widget::metrics::estimate_text_width(&prefix, &font, 1.0) as i32;
let cursor_x = rect.x + padding + advance;
// The caret is the selection indicator, so it carries the accent rather than
// a fixed black the user could not find on a dark page.
let caret = crate::style::semantic_color(crate::style::SemanticColor::Info)
.unwrap_or(ink);
context.draw_line(
crate::core::Point::new(cursor_x, line_y - line_height + 2),
crate::core::Point::new(cursor_x, line_y + 2),
caret,
);
}
}
line_y += line_height;
}
}
}
impl crate::event::EventHandler for RichEdit {
fn handle_event(&mut self, event: &crate::event::Event) {
self.base.handle_event(event);
if !self.base.is_enabled() {
return;
}
if let crate::event::Event::KeyPress { key: 90, modifiers: 2 } = event {
let _ = self.undo();
return;
}
if let crate::event::Event::KeyPress { key: 89, modifiers: 2 } = event {
let _ = self.redo();
return;
}
if self.read_only {
return;
}
match event {
crate::event::Event::MousePress { pos: _, button } if *button == 1 => {
self.base.set_mouse_pressed(true);
}
crate::event::Event::MouseRelease { pos: _, button } if *button == 1 => {
self.base.set_mouse_pressed(false);
}
crate::event::Event::KeyPress { key, modifiers } => {
let cursor = self.selection.map_or(0, |(start, _)| start);
match *key {
8 if cursor > 0 => {
// Backspace — delete char before cursor
let boundary = floor_char_boundary(&self.text, cursor - 1);
let mut next = self.text.clone();
next.drain(boundary..cursor);
let new_cursor = boundary;
self.set_text(next);
self.selection = Some((new_cursor, new_cursor));
self.cursor_position_changed.emit(new_cursor);
}
127 if cursor < self.text.len() => {
// Delete — delete char after cursor
let end = floor_char_boundary(&self.text, cursor + 1);
// Ensure we advance at least one char
let end = if end == cursor { cursor + 1 } else { end };
let mut next = self.text.clone();
next.drain(cursor..end.min(self.text.len()));
self.set_text(next);
self.selection = Some((cursor, cursor));
self.cursor_position_changed.emit(cursor);
}
13 => {
// Enter — insert newline at cursor
let mut next = self.text.clone();
next.insert(cursor, '\n');
self.set_text(next);
let new_cursor = cursor + 1;
self.selection = Some((new_cursor, new_cursor));
self.text_changed.emit(self.text.clone());
self.cursor_position_changed.emit(new_cursor);
}
37 if *modifiers == 0 && cursor > 0 => {
// Left arrow — move cursor left by one char
let boundary = floor_char_boundary(&self.text, cursor - 1);
self.selection = Some((boundary, boundary));
self.cursor_position_changed.emit(boundary);
}
39 if *modifiers == 0 && cursor < self.text.len() => {
// Right arrow — move cursor right by one char
let next = floor_char_boundary(&self.text, cursor + 1);
self.selection = Some((next, next));
self.cursor_position_changed.emit(next);
}
36 if *modifiers == 0 => {
// Home — move to beginning of current line
let coord = self.byte_offset_to_line_col(cursor);
if let Some((line, _)) = coord {
let new_cursor = self.line_col_to_byte_offset(line, 0);
self.selection = Some((new_cursor, new_cursor));
self.cursor_position_changed.emit(new_cursor);
}
}
35 if *modifiers == 0 => {
// End — move to end of current line
let coord = self.byte_offset_to_line_col(cursor);
if let Some((line, _)) = coord {
// Find the line end
let mut current_line = 0usize;
let mut line_end = self.text.len();
for (i, ch) in self.text.char_indices() {
if current_line == line && ch == '\n' {
line_end = i;
break;
}
if ch == '\n' {
current_line += 1;
}
}
// If we didn't find newline on this line, it's the last line
if current_line == line && line_end == self.text.len() {
// line_end already = text.len()
}
self.selection = Some((line_end, line_end));
self.cursor_position_changed.emit(line_end);
}
}
38 if *modifiers == 0 => {
// Up arrow — move cursor up one line if possible
let coord = self.byte_offset_to_line_col(cursor);
if let Some((line, col)) = coord {
if line > 0 {
let new_cursor = self.line_col_to_byte_offset(line - 1, col);
self.selection = Some((new_cursor, new_cursor));
self.cursor_position_changed.emit(new_cursor);
}
}
}
40 if *modifiers == 0 => {
// Down arrow — move cursor down one line if possible
let coord = self.byte_offset_to_line_col(cursor);
if let Some((line, col)) = coord {
let new_cursor = self.line_col_to_byte_offset(line + 1, col);
if new_cursor != cursor {
self.selection = Some((new_cursor, new_cursor));
self.cursor_position_changed.emit(new_cursor);
}
}
}
_ if *key >= 32 && *key <= 126 => {
// Printable ASCII — insert at cursor position
let c = char::from_u32(*key).unwrap_or(' ');
let c = if *modifiers & 0x02 != 0 { c.to_ascii_uppercase() } else { c };
self.text.insert(cursor, c);
let new_cursor = cursor + c.len_utf8();
self.selection = Some((new_cursor, new_cursor));
self.text_changed.emit(self.text.clone());
self.cursor_position_changed.emit(new_cursor);
}
_ => {}
}
}
_ => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::Rect;
use crate::event::EventHandler;
#[test]
fn richedit_creation_defaults() {
let re = RichEdit::new(Rect::new(0, 0, 400, 300));
assert!(re.text().is_empty());
assert!(re.selection().is_none());
assert!(!re.is_read_only());
assert_eq!(re.cursor_position(), 0);
}
/// The caret sits at the measured end of the prefix, not at `col * 7`.
///
/// # The defect this pins (BLUE24 §12 U-4's prerequisite)
///
/// The caret was drawn at `rect.x + padding + col * 7`, with the comment "rough char width".
/// Seven pixels is an average for one proportional face at one size, so on a real face the caret
/// drifts off the character it should sit on — and on CJK, roughly doubles per character. The
/// test asserts the **vertical line the renderer emits** against the shared measurement, so the
/// caret and the ink cannot disagree.
#[test]
fn the_caret_is_placed_by_measurement_not_by_a_fixed_advance() {
use crate::widget::metrics::estimate_text_width;
use crate::widget::svg::render_widget_to_svg;
let bounds = Rect::new(0, 0, 400, 300);
let font = crate::core::Font::default();
// A line whose characters have very different advances: `ill` is narrow, `www` is wide. A
// fixed 7 px per character cannot be right for both.
let text = "illwww";
let mut re = RichEdit::new(bounds);
re.set_text(text.to_string());
// Put the caret after `ill` (column 3).
re.set_cursor_position(3);
let svg = render_widget_to_svg(&mut re, bounds);
// The caret is a vertical `<line>`: x1 == x2. Take the last one (the caret is drawn after
// the text).
let caret_x = svg
.lines()
.filter_map(|line| {
let rest = line.split("<line ").nth(1)?;
let x1: i32 = rest.split("x1=\"").nth(1)?.split('"').next()?.parse().ok()?;
let x2: i32 = rest.split("x2=\"").nth(1)?.split('"').next()?.parse().ok()?;
(x1 == x2).then_some(x1)
})
.next_back()
.expect("the caret is drawn as a vertical line");
// The crate's padding for this control, and the measured advance of `ill`.
let expected = 2 + estimate_text_width("ill", &font, 1.0) as i32;
assert_eq!(
caret_x, expected,
"the caret must be at the measured end of `ill` ({expected}), not at 3 * 7 = 21"
);
assert_ne!(caret_x, 2 + 3 * 7, "the fixed-advance placement is the defect");
}
/// A selected range is actually painted, and its band ends where the caret would be.
///
/// # The gap this pins (BLUE24 §12 U-4)
///
/// The control published `selection()` / `set_selection()` / `clear_selection()` and drew
/// **nothing** for them — a selection model with no rendering. This asserts a filled rect appears
/// whose left edge is the measured start of the range and whose width is the measured length of
/// it, so highlighting a range cancels to the caret at either end.
#[test]
fn a_selection_range_is_painted_and_measured() {
use crate::widget::metrics::estimate_text_width;
use crate::widget::svg::render_widget_to_svg;
let bounds = Rect::new(0, 0, 400, 300);
let font = crate::core::Font::default();
let mut re = RichEdit::new(bounds);
re.set_text("abcdef".to_string());
re.set_selection(1, 4); // `bcd`
let svg = render_widget_to_svg(&mut re, bounds);
let expected_left = 2 + estimate_text_width("a", &font, 1.0) as i32;
let expected_width = estimate_text_width("bcd", &font, 1.0);
// The band is a filled rect at the selection's x, with the selection's width.
let painted = svg.lines().any(|line| {
if !line.contains("<rect ") || line.contains("fill=\"none\"") {
return false;
}
let attr = |name: &str| -> Option<i32> {
line.split(&format!("{name}=\"")).nth(1)?.split('"').next()?.parse().ok()
};
attr("x") == Some(expected_left) && attr("width") == Some(expected_width as i32)
});
assert!(
painted,
"a selection must be painted as a rect at x={expected_left} width={expected_width} \
(the model existed, the rendering did not)"
);
// And an empty selection paints no band, so the highlight is tied to the range rather than
// to the control always drawing one.
re.clear_selection();
let svg = render_widget_to_svg(&mut re, bounds);
let still_painted = svg.lines().any(|line| {
line.contains("<rect ")
&& !line.contains("fill=\"none\"")
&& line
.split("x=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.and_then(|x| x.parse::<i32>().ok())
== Some(expected_left)
});
assert!(!still_painted, "with no selection there is no band");
}
#[test]
fn richedit_set_text() {
let mut re = RichEdit::new(Rect::new(0, 0, 400, 300));
re.set_text("Hello RichEdit".to_string());
assert_eq!(re.text(), "Hello RichEdit");
}
#[test]
fn richedit_undo_redo_restores_text() {
let mut re = RichEdit::new(Rect::new(0, 0, 400, 300));
re.set_text("one".to_string());
re.set_text("two".to_string());
assert!(re.can_undo());
assert!(re.undo());
assert_eq!(re.text(), "one");
assert!(re.can_redo());
assert!(re.redo());
assert_eq!(re.text(), "two");
}
#[test]
fn richedit_control_z_and_control_y_drive_history() {
let mut re = RichEdit::new(Rect::new(0, 0, 400, 300));
re.set_text("before".to_string());
re.set_text("after".to_string());
re.handle_event(&crate::event::Event::key_press(90, 2));
assert_eq!(re.text(), "before");
re.handle_event(&crate::event::Event::key_press(89, 2));
assert_eq!(re.text(), "after");
}
#[test]
fn richedit_set_text_read_only() {
let mut re = RichEdit::new(Rect::new(0, 0, 400, 300));
re.set_read_only(true);
re.set_text("Should not change".to_string());
assert!(re.text().is_empty());
}
#[test]
fn richedit_read_only() {
let mut re = RichEdit::new(Rect::new(0, 0, 400, 300));
assert!(!re.is_read_only());
re.set_read_only(true);
assert!(re.is_read_only());
re.set_read_only(false);
assert!(!re.is_read_only());
}
#[test]
fn richedit_set_selection() {
let mut re = RichEdit::new(Rect::new(0, 0, 400, 300));
re.set_text("Hello World".to_string());
re.set_selection(0, 5);
assert_eq!(re.selection(), Some((0, 5)));
}
#[test]
fn richedit_clear_selection() {
let mut re = RichEdit::new(Rect::new(0, 0, 400, 300));
re.set_text("Hello World".to_string());
re.set_selection(0, 5);
re.clear_selection();
assert!(re.selection().is_none());
}
#[test]
fn richedit_set_cursor_position() {
let mut re = RichEdit::new(Rect::new(0, 0, 400, 300));
re.set_text("Hello".to_string());
re.set_cursor_position(3);
assert_eq!(re.cursor_position(), 3);
re.set_cursor_position(100); // clamps
assert_eq!(re.cursor_position(), 5);
}
#[test]
fn richedit_geometry_delegation() {
let mut re = RichEdit::new(Rect::new(0, 0, 400, 300));
re.set_geometry(Rect::new(10, 10, 500, 400));
assert_eq!(re.geometry(), Rect::new(10, 10, 500, 400));
}
#[test]
fn richedit_visibility() {
let mut re = RichEdit::new(Rect::new(0, 0, 400, 300));
assert!(re.is_visible());
re.hide();
assert!(!re.is_visible());
re.show();
assert!(re.is_visible());
}
#[test]
fn richedit_enabled() {
let mut re = RichEdit::new(Rect::new(0, 0, 400, 300));
assert!(re.is_enabled());
re.set_enabled(false);
assert!(!re.is_enabled());
re.set_enabled(true);
assert!(re.is_enabled());
}
#[test]
fn richedit_id_kind() {
let re_a = RichEdit::new(Rect::new(0, 0, 100, 100));
let re_b = RichEdit::new(Rect::new(0, 0, 100, 100));
assert_ne!(re_a.id(), re_b.id());
assert_eq!(re_a.kind(), WidgetKind::RichEdit);
assert_eq!(re_b.kind(), WidgetKind::RichEdit);
}
#[test]
fn richedit_signal_accessors() {
let re = RichEdit::new(Rect::new(0, 0, 100, 100));
let _ = &re.text_changed;
let _ = &re.selection_changed;
let _ = &re.read_only_changed;
let _ = &re.cursor_position_changed;
}
}