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

use std::collections::HashMap;

use super::app_data::AppData;
use super::surface::SurfaceFocus;
use crate::app::{ App, OverlayId };
use crate::tree::{ find_handlers, find_widget };
use crate::types::{ Point, WidgetId };
use crate::widget::WidgetHandlers;
use crate::widget::scroll::offset_into_view;
use crate::platform::Platform;

impl<A: App, P: Platform> AppData<A, P>
{
	/// Push `on_dismiss` for every active xdg-popup overlay whose
	/// anchor widget was not hit by a press at `pos` (logical pixels
	/// in main-surface space). Used to compensate for compositors
	/// (notably Mutter) that route pointer button events to the main
	/// surface while a popup grab is technically active, instead of
	/// breaking the grab. The check skips presses on the trigger pill
	/// itself so the trigger's own `toggle` message keeps owning that
	/// transition.
	pub( crate ) fn dismiss_main_outside_popups( &mut self, pos: Point )
	{
		if self.overlays.is_empty() { return; }
		let specs = self.app.overlays();
		for spec in specs
		{
			// Only xdg-popups need the main-side fallback: they grab
			// the seat and rely on the compositor to break the grab on
			// outside input, which Mutter does not do reliably. Layer-
			// shell overlays own their own `input_region` and dispatch
			// dismissal from the overlay tap path, so firing it again
			// from a press on the main surface produces a duplicate
			// dismiss that races other intents (e.g. forge's topbar
			// taps that route a separate IPC into the same overlay).
			let Some( anchor_id ) = spec.anchor_widget_id else { continue; };
			let anchor_rect = self.main.frame.widget_rects.iter()
				.find( | w | w.id == Some( anchor_id ) )
				.map( | w | w.rect );
			let on_anchor = anchor_rect
				.map( | r | pos.x >= r.x && pos.x < r.x + r.width
				          && pos.y >= r.y && pos.y < r.y + r.height )
				.unwrap_or( false );
			if !on_anchor
			{
				if let Some( msg ) = spec.on_dismiss
				{
					self.pending_msgs.push( msg );
				}
			}
		}
	}

	/// Push `on_dismiss` for every active xdg-popup overlay
	/// unconditionally (used by keyboard Escape handling — there is
	/// no spatial test to do).
	pub( crate ) fn dismiss_all_popups( &mut self )
	{
		if self.overlays.is_empty() { return; }
		let specs = self.app.overlays();
		for spec in specs
		{
			if spec.anchor_widget_id.is_some()
			{
				if let Some( msg ) = spec.on_dismiss
				{
					self.pending_msgs.push( msg );
				}
			}
		}
	}

	/// Look up the dismiss message for an overlay (tap on empty area).
	/// Returns `None` if the overlay has no `on_dismiss` set or was removed.
	pub( crate ) fn overlay_dismiss_msg( &self, id: OverlayId ) -> Option<A::Message>
	{
		self.app.overlays().into_iter()
			.find( |s| s.id == id )
			.and_then( |s| s.on_dismiss )
	}

	/// After a rebuild: a focused text input that vanished from the frame
	/// would otherwise keep the text-input protocol (and the OSK) active.
	pub( crate ) fn reconcile_text_focus( &mut self, focus: SurfaceFocus )
	{
		if surface_focused_text_input( self.surface( focus ) ) { return; }
		let ss = self.surface_mut( focus );
		if let Some( idx ) = ss.focused_idx.take()
		{
			ss.pending_text_values.remove( &idx );
		}
		ss.focused_id = None;
		ss.request_redraw();
		self.deactivate_text_input();
		self.app.on_text_input_focused( false );
		self.dirty_caches();
	}

	/// Focus what a press landed on, unless that widget leaves the focus where it was.
	pub( crate ) fn focus_pressed( &mut self, focus: SurfaceFocus, hit: Option<usize> )
	{
		let rects = &self.surface( focus ).frame.widget_rects;
		if hit.and_then( |idx| find_widget( rects, idx ) ).is_some_and( |w| !w.focus_on_press ) { return; }
		self.show_focus_ring( focus, false );
		self.set_focus( focus, hit );
	}

	/// The ring is drawn only when the keyboard moved the focus, so its index alone does not tell the partial redraw.
	pub( crate ) fn show_focus_ring( &mut self, focus: SurfaceFocus, visible: bool )
	{
		let ss = self.surface_mut( focus );
		if ss.focus_visible == visible { return; }
		ss.focus_visible = visible;
		ss.content_dirty = true;
		ss.request_redraw();
	}

	pub( crate ) fn set_focus( &mut self, focus: SurfaceFocus, idx: Option<usize> )
	{
		let was_text_input;
		let is_text_input;
		let secure;
		let purpose;
		let focus_msg;
		{
			let ss = self.surface_mut( focus );

			focus_msg = idx
				.filter( |i| ss.focused_idx != Some( *i ) )
				.and_then( |i| find_handlers( &ss.frame.widget_rects, i ) )
				.and_then( |h| match h
				{
					WidgetHandlers::TextEdit { on_focus, .. } => on_focus.clone(),
					_                                         => None,
				} );

			is_text_input = idx
				.and_then( |i| find_handlers( &ss.frame.widget_rects, i ) )
				.map( |h| h.is_text_input() )
				.unwrap_or( false );
			secure = idx
				.and_then( |i| find_handlers( &ss.frame.widget_rects, i ) )
				.map( |h| matches!( h, WidgetHandlers::TextEdit { secure: true, .. } ) )
				.unwrap_or( false );
			purpose = idx
				.and_then( |i| find_handlers( &ss.frame.widget_rects, i ) )
				.map( |h| h.input_purpose() )
				.unwrap_or_default();
			was_text_input = ss.focused_idx
				.and_then( |i| find_handlers( &ss.frame.widget_rects, i ) )
				.map( |h| h.is_text_input() )
				.unwrap_or( false );

			// Clear pending text value when losing focus
			if let Some( prev_idx ) = ss.focused_idx
			{
				if idx != Some( prev_idx )
				{
					ss.pending_text_values.remove( &prev_idx );
				}
			}

			ss.focused_idx = idx;
			ss.focused_id  = idx.and_then( |i|
			{
				ss.frame.widget_rects.iter()
					.find( |w| w.flat_idx == i )
					.and_then( |w| w.id )
			} );
			ss.request_redraw();

			// Sync cursor to the end of the value when focusing a text
			// input, via the `usize::MAX` sentinel ("end of whatever
			// value is rendered" — every consumer clamps with
			// `cursor.min( value.len() )`). A concrete `value.len()`
			// snapshot here would go stale if the value keeps growing
			// after focus (e.g. updated externally over IPC), leaving
			// later insertions mid-string. Default behaviour collapses
			// the selection to the cursor — focus changes always
			// discard any prior selection state. Fields built with
			// `.select_on_focus( true )` instead anchor the selection
			// at `0` so the whole value is highlighted, ready to be
			// replaced by the next keystroke (typical for numeric
			// pickers).
			if is_text_input
			{
				if let Some( i ) = idx
				{
					let handler = find_handlers( &ss.frame.widget_rects, i );
					let anchor  = match handler
					{
						Some( WidgetHandlers::TextEdit { select_on_focus: true, .. } ) => 0,
						_ => usize::MAX,
					};
					ss.frame.cursor_state.insert( i, usize::MAX );
					ss.frame.selection_anchor.insert( i, anchor );
				}
			}
		}

		if let Some( msg ) = focus_msg { self.pending_msgs.push( msg ); }

		if was_text_input && !is_text_input
		{
			self.deactivate_text_input();
			self.hide_osk( focus );
			self.app.on_text_input_focused( false );
			self.dirty_caches();
		}
		else if is_text_input && !was_text_input
		{
			self.activate_text_input( secure, purpose );
			self.show_osk( focus );
			self.app.on_text_input_focused( true );
			self.dirty_caches();
		}
		else if is_text_input
		{
			// Focus moved between text fields: refresh the content type so a
			// password field is flagged even without re-activating.
			self.activate_text_input( secure, purpose );
			self.show_osk( focus );
		}
	}

	/// Scroll the viewport that clipped the widget with `id` so the widget
	/// lands inside it on the next frame. No-op when no scroll reported
	/// the id as clipped.
	pub( crate ) fn reveal_clipped_widget( &mut self, id: WidgetId )
	{
		for ss in std::iter::once( &mut self.main ).chain( self.overlays.values_mut() )
		{
			let Some( &( _, scroll_idx, target ) ) = ss.frame.scroll_clipped.iter().find( |( w, _, _ )| *w == id ) else { continue };
			let Some( &( viewport, _, axis ) ) = ss.frame.scroll_rects.iter().find( |( _, i, _ )| *i == scroll_idx ) else { continue };
			let entry = ss.frame.scroll_offsets.entry( scroll_idx ).or_insert( ( 0.0, 0.0 ) );
			if axis.allows_x()
			{
				entry.0 = offset_into_view( entry.0, target.x, target.width, viewport.width );
			}
			if axis.allows_y()
			{
				entry.1 = offset_into_view( entry.1, target.y, target.height, viewport.height );
			}
			ss.request_redraw();
			return;
		}
	}
}

/// After a rebuild, move the focus and its text state to the focused id's new index, or drop it when that widget is gone; `true` when it changed.
pub( crate ) fn follow_focused_id<Msg: Clone, S>( ss: &mut super::surface::SurfaceState<Msg, S> ) -> bool
{
	let ( Some( id ), Some( old ) ) = ( ss.focused_id, ss.focused_idx ) else { return false };
	if find_widget( &ss.frame.widget_rects, old ).is_some_and( |w| w.id == Some( id ) ) { return false; }
	let Some( new ) = ss.frame.widget_rects.iter().find( |w| w.id == Some( id ) ).map( |w| w.flat_idx ) else
	{
		if ss.frame.scroll_clipped.iter().any( |( clipped, .. )| *clipped == id ) { return false; }
		ss.focused_idx = None;
		ss.focused_id  = None;
		return true;
	};
	move_entry( &mut ss.pending_text_values, old, new );
	move_entry( &mut ss.frame.cursor_state, old, new );
	move_entry( &mut ss.frame.selection_anchor, old, new );
	move_entry( &mut ss.frame.text_scroll, old, new );
	ss.focused_idx = Some( new );
	true
}

fn move_entry<V>( map: &mut HashMap<usize, V>, from: usize, to: usize )
{
	match map.remove( &from )
	{
		Some( value ) => { map.insert( to, value ); }
		None          => { map.remove( &to ); }
	}
}

/// The focus is held by index, so a rebuild can leave it on a widget that never takes it, where Enter would press it.
pub( crate ) fn drop_misplaced_focus<Msg: Clone, S>( ss: &mut super::surface::SurfaceState<Msg, S> )
{
	let misplaced = ss.focused_idx
		.and_then( |idx| find_widget( &ss.frame.widget_rects, idx ) )
		.is_some_and( |w| !w.focus_on_press );
	if misplaced
	{
		ss.focused_idx = None;
		ss.focused_id  = None;
	}
}

/// Whether the surface's focused widget is a text input in its current frame.
pub( crate ) fn surface_focused_text_input<Msg: Clone, S>( ss: &super::surface::SurfaceState<Msg, S> ) -> bool
{
	let by_id = ss.focused_id.and_then( |id|
	{
		ss.frame.widget_rects.iter().find( |w| w.id == Some( id ) ).map( |w| &w.handlers )
	} );
	by_id
		.or_else( || ss.focused_idx.and_then( |i| find_handlers( &ss.frame.widget_rects, i ) ) )
		.is_some_and( |h| h.is_text_input() )
}