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
//! Keyboard and mouse handling for [`RichTextEdit`], split out of `editor.rs`
//! to keep it under the 800-line cap.
//!
//! Mirrors `TextArea`'s semantics — click positions the caret, drag selects,
//! Shift extends, the usual navigation and clipboard chords — but drives the
//! shared [`RichEditCore`](super::core::RichEditCore) and the rich document's
//! structural edits instead of a flat string. Every handled event is
//! `Consumed` so the auto-invalidation convention schedules the redraw.
use web_time::Instant;
use crate::cursor::{set_cursor_icon, CursorIcon};
use crate::event::{Event, EventResult, Key, MouseButton};
use crate::widgets::multi_click::SelectGranularity;
use crate::widgets::text_field_core::{next_char_boundary, prev_char_boundary};
use super::super::commands::RichCommand;
use super::super::model::DocPos;
use super::scroll::ScrollMove;
use super::RichTextEdit;
impl RichTextEdit {
/// Central event dispatch (called from `Widget::on_event`).
pub(super) fn handle_event(&mut self, event: &Event) -> EventResult {
// While the right-click menu is open it captures events (see
// `has_active_modal`); route them through it first.
if let Some(result) = self.route_context_menu(event) {
return result;
}
match event {
Event::MouseMove { pos } => {
let bar_hover_changed = match self.scrollbar_on_mouse_move(*pos) {
ScrollMove::Dragging(moved) => {
if moved {
crate::animation::request_draw();
}
return EventResult::Consumed;
}
ScrollMove::Hover(changed) => changed,
};
let was = self.hovered;
self.hovered = self.hit_test_local(*pos);
if self.hovered {
set_cursor_icon(CursorIcon::Text);
}
if self.selecting_drag {
let target = self.hit_test_pos(*pos);
self.extend_selection_drag(target);
crate::animation::request_draw();
return EventResult::Consumed;
}
if was != self.hovered || bar_hover_changed {
crate::animation::request_draw();
return EventResult::Consumed;
}
EventResult::Ignored
}
Event::MouseDown {
button: MouseButton::Left,
pos,
modifiers,
} => {
if self.scrollbar_begin_drag(*pos) {
crate::animation::request_draw();
return EventResult::Consumed;
}
let target = self.hit_test_pos(*pos);
let clicks = self.multi_click.register(*pos);
self.begin_pointer_selection(target, clicks, modifiers.shift);
self.selecting_drag = true;
self.focus_time = Some(Instant::now());
crate::animation::request_draw();
EventResult::Consumed
}
Event::MouseDown {
button: MouseButton::Right,
pos,
..
} => {
if self.context_menu_enabled {
self.open_context_menu(*pos);
EventResult::Consumed
} else {
EventResult::Ignored
}
}
Event::MouseUp {
button: MouseButton::Left,
..
} => {
self.scrollbar_end_drag();
self.selecting_drag = false;
EventResult::Consumed
}
Event::MouseWheel { delta_y, .. } => {
if self.scroll_by_wheel(*delta_y) {
crate::animation::request_draw();
EventResult::Consumed
} else {
EventResult::Ignored
}
}
Event::FocusGained => {
self.focused = true;
self.focus_time = Some(Instant::now());
crate::animation::request_draw();
EventResult::Ignored
}
Event::FocusLost => {
self.focused = false;
self.selecting_drag = false;
crate::animation::request_draw();
EventResult::Ignored
}
Event::KeyDown { key, modifiers } => self.handle_key(key, modifiers),
_ => EventResult::Ignored,
}
}
fn hit_test_local(&self, p: crate::geometry::Point) -> bool {
p.x >= 0.0 && p.x <= self.bounds.width && p.y >= 0.0 && p.y <= self.bounds.height
}
fn handle_key(&mut self, key: &Key, modifiers: &crate::event::Modifiers) -> EventResult {
let shift = modifiers.shift;
let cmd = modifiers.ctrl || modifiers.meta;
let caret = self.core.borrow().caret();
match key {
Key::ArrowLeft => {
let target = if cmd {
self.word_target(caret, -1)
} else {
self.char_target(caret, -1)
};
self.core.borrow_mut().set_caret(target, shift);
}
Key::ArrowRight => {
let target = if cmd {
self.word_target(caret, 1)
} else {
self.char_target(caret, 1)
};
self.core.borrow_mut().set_caret(target, shift);
}
Key::ArrowUp => {
let target = self.pos_by_visual_line(caret, -1);
self.core.borrow_mut().set_caret(target, shift);
}
Key::ArrowDown => {
let target = self.pos_by_visual_line(caret, 1);
self.core.borrow_mut().set_caret(target, shift);
}
Key::Home => {
let target = if cmd {
DocPos::new(0, 0)
} else {
self.caret_line_bounds(caret).0
};
self.core.borrow_mut().set_caret(target, shift);
}
Key::End => {
let target = if cmd {
self.core.borrow().doc().end_pos()
} else {
self.caret_line_bounds(caret).1
};
self.core.borrow_mut().set_caret(target, shift);
}
Key::PageUp => {
let n = self.page_lines(caret) as isize;
let target = self.pos_by_visual_line(caret, -n);
self.core.borrow_mut().set_caret(target, shift);
}
Key::PageDown => {
let n = self.page_lines(caret) as isize;
let target = self.pos_by_visual_line(caret, n);
self.core.borrow_mut().set_caret(target, shift);
}
// Ctrl (or Alt) + Backspace/Delete removes a whole word, mirroring
// egui's `delete_previous_word` / `delete_next_word`. The span is
// exactly what a Ctrl+Arrow motion traverses (same `word_target`).
Key::Backspace if cmd || modifiers.alt => self.delete_word_backward(),
Key::Delete if cmd || modifiers.alt => self.delete_word_forward(),
Key::Backspace => self.core.borrow_mut().backspace(),
Key::Delete => self.core.borrow_mut().delete_forward(),
Key::Enter => self.core.borrow_mut().split(),
Key::Char('a') | Key::Char('A') if cmd => self.core.borrow_mut().select_all(),
Key::Char('c') | Key::Char('C') if cmd => {
self.copy_selection();
}
Key::Char('x') | Key::Char('X') if cmd => {
if self.copy_selection() {
self.core.borrow_mut().backspace();
}
}
Key::Char('v') | Key::Char('V') if cmd => {
self.paste_clipboard();
}
Key::Char('z') | Key::Char('Z') if cmd && shift => {
self.core.borrow_mut().redo();
}
Key::Char('z') | Key::Char('Z') if cmd => {
self.core.borrow_mut().undo();
}
Key::Char('y') | Key::Char('Y') if cmd => {
self.core.borrow_mut().redo();
}
Key::Char(c) if !cmd => {
let mut buf = [0u8; 4];
self.core.borrow_mut().insert(c.encode_utf8(&mut buf));
}
// Tab / Shift+Tab indent or outdent every touched block, reusing the
// toolbar's exact commands (a list item's "level" is `block.indent`,
// so the same command covers list items and plain blocks). Consuming
// these keeps the App from stealing focus mid-edit; Ctrl/Meta+Tab is
// left Ignored so it stays a focus-traversal escape hatch (the App
// routes it directly anyway — this is defence in depth).
Key::Tab if !cmd => {
let command = if shift {
RichCommand::Outdent
} else {
RichCommand::Indent
};
self.core.borrow_mut().exec(&command);
}
_ => return EventResult::Ignored,
}
let caret = self.core.borrow().caret();
self.ensure_pos_visible(caret);
self.focus_time = Some(Instant::now());
crate::animation::request_draw();
EventResult::Consumed
}
/// Copy the current selection to both clipboards: the styled fragment into
/// the in-process rich slot (keyed by the plain-text fingerprint) and the
/// plain text into the system clipboard so external apps get text. Returns
/// `true` when something was selected (Cut uses this to know whether to
/// delete). A collapsed selection leaves both clipboards untouched.
///
/// `pub(super)` so the right-click context menu (`context_menu.rs`) shares
/// the exact styled-clipboard behaviour instead of duplicating it.
pub(super) fn copy_selection(&mut self) -> bool {
let (text, fragment) = {
let core = self.core.borrow();
(core.selected_plain_text(), core.selected_fragment())
};
if text.is_empty() {
return false;
}
super::super::rich_clipboard::set(text.clone(), fragment);
crate::clipboard::set_text(&text);
true
}
/// Paste at the caret. When the system clipboard text still matches the
/// fingerprint of our last styled Copy/Cut (same session, clipboard
/// unchanged), reinsert the styled fragment; otherwise insert the external
/// plain text, inheriting the caret's style.
///
/// `pub(super)` so the right-click context menu shares this exact paste
/// behaviour rather than duplicating it.
pub(super) fn paste_clipboard(&mut self) {
let Some(text) = crate::clipboard::get_text() else {
return;
};
if let Some(fragment) = super::super::rich_clipboard::matching(&text) {
self.core.borrow_mut().insert_fragment(&fragment);
} else {
self.core.borrow_mut().insert(&text);
}
}
/// One char left (`-1`) or right (`+1`) from `caret`, crossing block
/// boundaries at the paragraph edges.
fn char_target(&self, caret: DocPos, dir: i32) -> DocPos {
let core = self.core.borrow();
let doc = core.doc();
let text = doc
.blocks
.get(caret.block)
.map(|b| b.text())
.unwrap_or_default();
if dir < 0 {
if caret.byte > 0 {
DocPos::new(caret.block, prev_char_boundary(&text, caret.byte))
} else if caret.block > 0 {
let prev_len = doc.blocks[caret.block - 1].text_len();
DocPos::new(caret.block - 1, prev_len)
} else {
caret
}
} else if caret.byte < text.len() {
DocPos::new(caret.block, next_char_boundary(&text, caret.byte))
} else if caret.block + 1 < doc.blocks.len() {
DocPos::new(caret.block + 1, 0)
} else {
caret
}
}
/// One word left/right from `caret` within the flattened block text,
/// crossing paragraph boundaries when already at an edge.
fn word_target(&self, caret: DocPos, dir: i32) -> DocPos {
let core = self.core.borrow();
let doc = core.doc();
let Some(block) = doc.blocks.get(caret.block) else {
return caret;
};
let text = block.text();
let bytes = text.as_bytes();
let is_word = |b: u8| b.is_ascii_alphanumeric() || b == b'_' || b >= 0x80;
if dir < 0 {
if caret.byte == 0 {
return if caret.block > 0 {
DocPos::new(caret.block - 1, doc.blocks[caret.block - 1].text_len())
} else {
caret
};
}
let mut i = caret.byte;
while i > 0 && !is_word(bytes[i - 1]) {
i -= 1;
}
while i > 0 && is_word(bytes[i - 1]) {
i -= 1;
}
DocPos::new(caret.block, i)
} else {
let len = text.len();
if caret.byte >= len {
return if caret.block + 1 < doc.blocks.len() {
DocPos::new(caret.block + 1, 0)
} else {
caret
};
}
let mut i = caret.byte;
while i < len && is_word(bytes[i]) {
i += 1;
}
while i < len && !is_word(bytes[i]) {
i += 1;
}
DocPos::new(caret.block, i)
}
}
/// Delete from the caret back to the previous word boundary
/// (Ctrl/Alt+Backspace). An active selection takes precedence — only it is
/// removed, exactly as plain [`backspace`](RichEditCore::backspace) does.
/// The boundary is [`word_target`](Self::word_target)'s, so the deleted span
/// matches a Ctrl+ArrowLeft motion, including a merge into the previous block
/// when the caret sits at a block start.
fn delete_word_backward(&mut self) {
if !self.core.borrow().selection().is_empty() {
self.core.borrow_mut().backspace();
return;
}
let caret = self.core.borrow().caret();
let target = self.word_target(caret, -1);
if target == caret {
return;
}
// Select caret → target, then let `backspace` remove the selection: this
// is one document mutation (one `bump_doc`), hence one undo step, and
// reuses the cross-block merge path when `target` lies in a prior block.
self.core.borrow_mut().set_selection(caret, target);
self.core.borrow_mut().backspace();
}
/// Delete from the caret forward to the next word boundary
/// (Ctrl/Alt+Delete). Selection precedence and single-undo-step semantics
/// mirror [`delete_word_backward`](Self::delete_word_backward).
fn delete_word_forward(&mut self) {
if !self.core.borrow().selection().is_empty() {
self.core.borrow_mut().delete_forward();
return;
}
let caret = self.core.borrow().caret();
let target = self.word_target(caret, 1);
if target == caret {
return;
}
self.core.borrow_mut().set_selection(caret, target);
self.core.borrow_mut().delete_forward();
}
/// Caret/selection update for a fresh pointer press. `clicks` is the
/// multi-click count (1 = single, 2 = double, 3 = triple). Double selects
/// the word under `target`, triple selects the whole block; `shift` extends
/// the existing selection instead.
pub(super) fn begin_pointer_selection(&mut self, target: DocPos, clicks: u32, shift: bool) {
if shift {
self.select_granularity = SelectGranularity::Char;
self.select_pivot = (target, target);
self.core.borrow_mut().set_caret(target, true);
return;
}
match clicks {
n if n >= 3 => {
self.select_granularity = SelectGranularity::Line;
let (a, b) = self.block_range_at_pos(target);
self.select_pivot = (a, b);
self.core.borrow_mut().set_selection(a, b);
}
2 => {
self.select_granularity = SelectGranularity::Word;
let (a, b) = self.word_range_at_pos(target);
self.select_pivot = (a, b);
self.core.borrow_mut().set_selection(a, b);
}
_ => {
self.select_granularity = SelectGranularity::Char;
self.select_pivot = (target, target);
self.core.borrow_mut().set_caret(target, false);
}
}
}
/// Extend the selection during a drag, honouring the granularity the
/// initiating click established. `target` is the caret position under the
/// pointer.
pub(super) fn extend_selection_drag(&mut self, target: DocPos) {
match self.select_granularity {
SelectGranularity::Char => self.core.borrow_mut().set_caret(target, true),
SelectGranularity::Word => {
let (pivot_start, pivot_end) = self.select_pivot;
let (cs, ce) = self.word_range_at_pos(target);
if target >= pivot_end {
self.core.borrow_mut().set_selection(pivot_start, ce);
} else {
self.core.borrow_mut().set_selection(pivot_end, cs);
}
}
SelectGranularity::Line => {
let (pivot_start, pivot_end) = self.select_pivot;
let (cs, ce) = self.block_range_at_pos(target);
if target >= pivot_end {
self.core.borrow_mut().set_selection(pivot_start, ce);
} else {
self.core.borrow_mut().set_selection(pivot_end, cs);
}
}
}
}
/// `[start, end)` document range of the word under `pos`, within its block.
/// Uses the same word classification as [`word_target`](Self::word_target)
/// (ASCII alphanumerics, `_`, and any non-ASCII byte are "word" bytes) so
/// double-click selection and Ctrl+arrow navigation agree.
fn word_range_at_pos(&self, pos: DocPos) -> (DocPos, DocPos) {
let core = self.core.borrow();
let doc = core.doc();
let Some(block) = doc.blocks.get(pos.block) else {
return (pos, pos);
};
let text = block.text();
let bytes = text.as_bytes();
let is_word = |b: u8| b.is_ascii_alphanumeric() || b == b'_' || b >= 0x80;
let clamp = pos.byte.min(text.len());
// Class of the char at the click; past the block end there is no char,
// so treat it as a non-word boundary (select the trailing run, if any).
let anchor_class = clamp < text.len() && is_word(bytes[clamp]);
let mut start = clamp;
while start > 0 && is_word(bytes[start - 1]) == anchor_class {
start -= 1;
}
let mut end = clamp;
while end < text.len() && is_word(bytes[end]) == anchor_class {
end += 1;
}
(DocPos::new(pos.block, start), DocPos::new(pos.block, end))
}
/// The whole block (triple-click line selection) containing `pos`, from its
/// start to its end byte.
fn block_range_at_pos(&self, pos: DocPos) -> (DocPos, DocPos) {
let core = self.core.borrow();
let len = core
.doc()
.blocks
.get(pos.block)
.map(|b| b.text_len())
.unwrap_or(0);
(DocPos::new(pos.block, 0), DocPos::new(pos.block, len))
}
}