ltk/event_loop/text_editing/
insert_delete.rs

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
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>

use crate::app::App;
use crate::event_loop::app_data::AppData;
use crate::event_loop::surface::SurfaceFocus;
use crate::tree::find_handlers;
use crate::widget::WidgetHandlers;

impl<A: App> AppData<A>
{
	pub( crate ) fn handle_text_insert( &mut self, focus: SurfaceFocus, text: &str )
	{
		let idx = match self.surface( focus ).focused_idx { Some( i ) => i, None => return };

		// If a selection is active, replace it. The deletion path
		// folds anchor=cursor and updates `pending_text_values`, so
		// the rest of this fn keeps the same shape after.
		let _ = self.delete_selection( focus );

		let current_value = if let Some( pending ) = self.surface( focus ).pending_text_values.get( &idx )
		{
			pending.clone()
		} else {
			find_handlers( &self.surface( focus ).widget_rects, idx )
				.and_then( |h| h.current_value() )
				.map( |s| s.to_string() )
				.unwrap_or_default()
		};

		// `select_on_focus` fields keep the cursor pinned to the end
		// of the *displayed* value. The pending value the user just
		// typed (e.g. "2") may render shorter than the post-update
		// display value (e.g. "02" after a `format!("{:02}")`
		// normalisation in the app's on_change handler), so anchoring
		// the cursor at "end of pending" would land it mid-string in
		// the next render. `usize::MAX` is a sentinel: every consumer
		// (`draw`, arrow-key handlers, `byte_offset_at`) clamps via
		// `cursor.min( value.len() )`, which resolves to "end of
		// whatever value we eventually render". Without this, typing
		// a second digit would insert into the middle of the
		// normalised string ("0|2" + "3" → "032" → 32 instead of 23).
		let select_on_focus = matches!(
			find_handlers( &self.surface( focus ).widget_rects, idx ),
			Some( WidgetHandlers::TextEdit { select_on_focus: true, .. } ),
		);

		let new_value;
		{
			let ss = self.surface_mut( focus );
			let cursor      = ss.cursor_state.entry( idx ).or_insert( current_value.len() );
			let safe_cursor = (*cursor).min( current_value.len() );
			let mut v       = current_value.clone();
			v.insert_str( safe_cursor, text );
			let next_cursor = if select_on_focus { usize::MAX } else { safe_cursor + text.len() };
			*ss.cursor_state.entry( idx ).or_insert( 0 ) = next_cursor;
			*ss.selection_anchor.entry( idx ).or_insert( 0 ) = next_cursor;
			ss.pending_text_values.insert( idx, v.clone() );
			ss.request_redraw();
			new_value = v;
		}

		let msg = find_handlers( &self.surface( focus ).widget_rects, idx )
			.and_then( |h| h.text_change_msg( &new_value ) );
		if let Some( m ) = msg
		{
			self.pending_msgs.push( m );
		}
	}

	/// Forward delete — the `Delete` (Supr) key. Mirrors
	/// [`Self::handle_backspace`] but removes the character *after*
	/// the cursor instead of before. Selection-aware: if a range is
	/// active it is removed in one step, exactly like backspace.
	pub( crate ) fn handle_delete_forward( &mut self, focus: SurfaceFocus )
	{
		let idx = match self.surface( focus ).focused_idx { Some( i ) => i, None => return };

		if let Some( new_value ) = self.delete_selection( focus )
		{
			let msg = find_handlers( &self.surface( focus ).widget_rects, idx )
				.and_then( |h| h.text_change_msg( &new_value ) );
			if let Some( m ) = msg { self.pending_msgs.push( m ); }
			return;
		}

		let current_value = if let Some( pending ) = self.surface( focus ).pending_text_values.get( &idx )
		{
			pending.clone()
		} else {
			find_handlers( &self.surface( focus ).widget_rects, idx )
				.and_then( |h| h.current_value() )
				.map( |s| s.to_string() )
				.unwrap_or_default()
		};

		let cursor_val = self.surface( focus ).cursor_state.get( &idx ).copied()
			.unwrap_or( current_value.len() );
		let safe_cursor_pre = cursor_val.min( current_value.len() );
		if safe_cursor_pre >= current_value.len() { return; }
		// Width of the char *starting* at the cursor — UTF-8 aware so
		// `é` / `🦀` come out as one keypress.
		let next_char = current_value[safe_cursor_pre..].chars().next();
		let step = match next_char { Some( c ) => c.len_utf8(), None => return };
		let mut new_value = current_value.clone();
		new_value.replace_range( safe_cursor_pre..safe_cursor_pre + step, "" );
		// `select_on_focus` fields keep the cursor at the end of the
		// post-update displayed value via the `usize::MAX` sentinel —
		// see `handle_text_insert` for the reasoning.
		let select_on_focus = matches!(
			find_handlers( &self.surface( focus ).widget_rects, idx ),
			Some( WidgetHandlers::TextEdit { select_on_focus: true, .. } ),
		);
		let next_cursor = if select_on_focus { usize::MAX } else { safe_cursor_pre };
		{
			let ss = self.surface_mut( focus );
			// Cursor stays put — the char to its right is gone, so the
			// remaining tail shifts left under it.
			*ss.cursor_state.entry( idx ).or_insert( 0 ) = next_cursor;
			*ss.selection_anchor.entry( idx ).or_insert( 0 ) = next_cursor;
			ss.pending_text_values.insert( idx, new_value.clone() );
			ss.request_redraw();
		}

		let msg = find_handlers( &self.surface( focus ).widget_rects, idx )
			.and_then( |h| h.text_change_msg( &new_value ) );
		if let Some( m ) = msg
		{
			self.pending_msgs.push( m );
		}
	}

	/// Respond to `zwp_text_input_v3.delete_surrounding_text`. Both
	/// arguments are **UTF-8 byte counts** measured from the cursor.
	/// IMEs (Mozc, Anthy, IBus-pinyin) emit this routinely to commit a
	/// preedit on top of pre-existing surrounding text. The previous
	/// implementation iterated `before_length` calls to `handle_backspace`,
	/// treating the byte count as a number of characters — corrupting
	/// any non-ASCII input. This method does a single bytes-aware
	/// replace_range that snaps to UTF-8 char boundaries.
	pub( crate ) fn handle_delete_surrounding( &mut self, focus: SurfaceFocus, before_bytes: u32, after_bytes: u32 )
	{
		let idx = match self.surface( focus ).focused_idx { Some( i ) => i, None => return };

		let _ = self.delete_selection( focus );

		let current_value = if let Some( pending ) = self.surface( focus ).pending_text_values.get( &idx )
		{
			pending.clone()
		} else {
			find_handlers( &self.surface( focus ).widget_rects, idx )
				.and_then( |h| h.current_value() )
				.map( |s| s.to_string() )
				.unwrap_or_default()
		};

		let cursor_val  = self.surface( focus ).cursor_state.get( &idx ).copied()
			.unwrap_or( current_value.len() );
		let safe_cursor = cursor_val.min( current_value.len() );

		// `before_bytes` of UTF-8 walked back from the cursor, snapping
		// to char boundaries — if the byte count lands mid-codepoint we
		// expand outward to swallow the whole codepoint (matches what
		// GTK / Qt do under the same protocol).
		let start_byte =
		{
			let mut pos = safe_cursor;
			for ( i, _ ) in current_value[..safe_cursor].char_indices().rev()
			{
				if ( safe_cursor - pos ) as u32 >= before_bytes { break; }
				pos = i;
			}
			pos
		};

		let end_byte =
		{
			let mut pos = safe_cursor;
			for ( i, ch ) in current_value[safe_cursor..].char_indices()
			{
				if ( pos - safe_cursor ) as u32 >= after_bytes { break; }
				pos = safe_cursor + i + ch.len_utf8();
			}
			pos
		};

		if start_byte >= end_byte { return; }

		let mut new_value = current_value.clone();
		new_value.replace_range( start_byte..end_byte, "" );

		let select_on_focus = matches!(
			find_handlers( &self.surface( focus ).widget_rects, idx ),
			Some( WidgetHandlers::TextEdit { select_on_focus: true, .. } ),
		);
		let next_cursor = if select_on_focus { usize::MAX } else { start_byte };

		{
			let ss = self.surface_mut( focus );
			*ss.cursor_state.entry( idx ).or_insert( 0 ) = next_cursor;
			*ss.selection_anchor.entry( idx ).or_insert( 0 ) = next_cursor;
			ss.pending_text_values.insert( idx, new_value.clone() );
			ss.request_redraw();
		}

		let msg = find_handlers( &self.surface( focus ).widget_rects, idx )
			.and_then( |h| h.text_change_msg( &new_value ) );
		if let Some( m ) = msg
		{
			self.pending_msgs.push( m );
		}
	}

	pub( crate ) fn handle_backspace( &mut self, focus: SurfaceFocus )
	{
		let idx = match self.surface( focus ).focused_idx { Some( i ) => i, None => return };

		// Selection-aware: if a selection is active, backspace just
		// deletes the range. The on_change message is emitted from
		// here so the app sees a single text update.
		if let Some( new_value ) = self.delete_selection( focus )
		{
			let msg = find_handlers( &self.surface( focus ).widget_rects, idx )
				.and_then( |h| h.text_change_msg( &new_value ) );
			if let Some( m ) = msg { self.pending_msgs.push( m ); }
			return;
		}

		let current_value = if let Some( pending ) = self.surface( focus ).pending_text_values.get( &idx )
		{
			pending.clone()
		} else {
			find_handlers( &self.surface( focus ).widget_rects, idx )
				.and_then( |h| h.current_value() )
				.map( |s| s.to_string() )
				.unwrap_or_default()
		};

		// Scoped block to release the immutable borrow of `self` (via
		// `self.surface( focus )`) before taking a mutable one below.
		let cursor_val = self.surface( focus ).cursor_state.get( &idx ).copied()
			.unwrap_or( current_value.len() );
		if cursor_val == 0 { return; }
		let safe_cursor      = cursor_val.min( current_value.len() );
		let chars: Vec<char> = current_value[..safe_cursor].chars().collect();
		if chars.is_empty() { return; }

		let removed_char  = *chars.last().unwrap();
		let new_cursor    = safe_cursor - removed_char.len_utf8();
		let mut new_value = current_value.clone();
		new_value.remove( new_cursor );
		// `select_on_focus` fields keep the cursor at the end of the
		// post-update displayed value via the `usize::MAX` sentinel —
		// see `handle_text_insert` for the reasoning.
		let select_on_focus = matches!(
			find_handlers( &self.surface( focus ).widget_rects, idx ),
			Some( WidgetHandlers::TextEdit { select_on_focus: true, .. } ),
		);
		let next_cursor = if select_on_focus { usize::MAX } else { new_cursor };
		{
			let ss = self.surface_mut( focus );
			*ss.cursor_state.entry( idx ).or_insert( 0 ) = next_cursor;
			*ss.selection_anchor.entry( idx ).or_insert( 0 ) = next_cursor;
			ss.pending_text_values.insert( idx, new_value.clone() );
			ss.request_redraw();
		}

		let msg = find_handlers( &self.surface( focus ).widget_rects, idx )
			.and_then( |h| h.text_change_msg( &new_value ) );
		if let Some( m ) = msg
		{
			self.pending_msgs.push( m );
		}
	}
}