ltk/event_loop/
overlays_reconcile.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
306
307
308
309
310
311
312
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>

use std::collections::HashSet;

use smithay_client_toolkit::
{
	compositor::Surface,
	shell::
	{
		WaylandSurface,
		xdg::
		{
			XdgPositioner, XdgSurface,
			popup::Popup,
		},
	},
};
use wayland_protocols::xdg::shell::client::xdg_positioner::
{
	Anchor as PositionerAnchor,
	ConstraintAdjustment,
	Gravity,
};

use crate::app::App;
use crate::types::Rect;
use super::{ AppData, LayerConfig, SurfaceFocus, SurfaceKind, SurfaceState };

/// Sync `data.overlays` with the app's current `App::overlays()` spec list:
/// destroy any overlay whose id disappeared and create a fresh `SurfaceState`
/// for every id that just appeared. Created surfaces are materialized
/// immediately if an output is already available; otherwise they stay
/// [`SurfaceKind::Pending`] and the `new_output` handler will bring them up.
pub( super ) fn reconcile_overlays<A: App>( data: &mut AppData<A> )
{
	let mut specs = data.app.overlays();
	if let Some( ts ) = data.tooltip_overlay() { specs.push( ts ); }
	let next_ids: Vec<_> = specs.iter().map( |s| s.id ).collect();
	let wanted: HashSet<crate::app::OverlayId> = next_ids.iter().copied().collect();

	// Drop overlays that disappeared from the spec list. If the overlay had
	// an in-flight drag (long-press fired), migrate that state to `main` so
	// the motion / release that follows still routes through the app's drag
	// handlers — apps typically hide the overlay *because* of the long-press,
	// and we must not lose the drag state with the surface.
	let removed: Vec<_> = data.overlays.keys()
		.filter( |id| !wanted.contains( id ) )
		.copied()
		.collect();
	for id in removed
	{
		if let Some( ss ) = data.overlays.remove( &id )
		{
			if ss.gesture.long_press_fired
			{
				data.main.gesture.long_press_fired  = true;
				data.main.gesture.long_press_origin = ss.gesture.long_press_origin;
				// Keep the primary touch slot with the migrated drag so motion / release still route through the gesture machine.
				if data.main.primary_touch_id.is_none()
				{
					data.main.primary_touch_id = ss.primary_touch_id;
				}
			}
		}
	}
	// Clear any stale per-device focus pointing at a destroyed overlay.
	if let SurfaceFocus::Overlay( id ) = data.pointer_focus
	{
		if !data.overlays.contains_key( &id ) { data.pointer_focus = SurfaceFocus::Main; }
	}
	if let SurfaceFocus::Overlay( id ) = data.keyboard_focus
	{
		if !data.overlays.contains_key( &id ) { data.keyboard_focus = SurfaceFocus::Main; }
	}
	// Rewrite touch_focus entries pointing at a destroyed overlay to Main
	// rather than dropping them. Dropping would make subsequent motion/up
	// events for the same touch id default to Main *without* the long-press
	// drag state, turning a release into a stray tap.
	for f in data.touch_focus.values_mut()
	{
		if let SurfaceFocus::Overlay( id ) = *f
		{
			if !data.overlays.contains_key( &id ) { *f = SurfaceFocus::Main; }
		}
	}

	// Create overlays that just appeared. Uses field-level borrow splitting so
	// the shared borrows of `layer_shell` / `xdg_shell` / `compositor_state`
	// / `output_state` / `qh` can coexist with the mutable borrow of
	// `overlays` inside the loop.
	let layer_shell_opt = data.layer_shell.as_ref();
	let xdg_shell_opt   = data.xdg_shell.as_ref();
	let output_opt      = data.output_state.outputs().next();
	let cs              = &data.compositor_state;
	let qh              = &data.qh;
	let grab_seat   = data.seat_state.seats().next();
	let grab_serial = data.last_input_serial;
	// Snapshot the parent xdg_surface (only an xdg toplevel can host
	// xdg-popups; layer-shell parents would need a different code path
	// via `LayerSurface::get_popup`, which we do not currently support).
	let parent_xdg = match data.main.surface
	{
		SurfaceKind::Window( ref w ) => Some( w.xdg_surface().clone() ),
		_ => None,
	};
	let parent_scale_i = data.main.scale_factor.max( 1 );
	let parent_scale   = parent_scale_i as f32;
	// `OverlaySpec::size` is physical pixels (the app's layout space); the
	// layer-shell `set_size` is logical. They only coincide at scale 1, so
	// convert here — without it a scale-2 overlay requests a surface twice
	// its intended size. `0 = fill` survives the divide.
	let to_logical_size = move | ( w, h ): ( u32, u32 ) | -> ( u32, u32 )
	{
		(
			( w as f32 / parent_scale ).round() as u32,
			( h as f32 / parent_scale ).round() as u32,
		)
	};
	// Snapshot the previous-frame anchor lookup table so we can resolve
	// `anchor_widget_id` → `Rect` without holding a borrow on `data.main`
	// across the overlay-mut loop below.
	let main_widget_rects = &data.main.widget_rects;
	let overlays_m = &mut data.overlays;
	for spec in &specs
	{
		if let Some( ss ) = overlays_m.get_mut( &spec.id )
		{
			// Already-live overlay: propagate size changes to the layer
			// surface so apps can animate an overlay's dimensions (e.g. a
			// slide-down panel whose height grows each frame). The very
			// first size was applied at `materialize` time and recorded in
			// `last_requested_size`, so we only commit when it actually
			// differs. Commit is needed after `set_size` so the compositor
			// sends a configure; the usual `on_configure` path picks up the
			// new dimensions and drives the redraw. Popups don't grow /
			// shrink mid-life — close and reopen instead.
			if spec.size != ss.last_requested_size
			{
				if let SurfaceKind::Layer( ref layer_surface ) = ss.surface
				{
					let ( lw, lh ) = to_logical_size( spec.size );
					layer_surface.set_size( lw, lh );
					layer_surface.commit();
					ss.last_requested_size = spec.size;
				}
			}
			// Compare the anchor at integer logical-pixel resolution:
			// floating-point jitter would otherwise call `reposition`
			// every frame, which several compositors react to by
			// dropping the popup grab.
			if let SurfaceKind::Popup( ref popup ) = ss.surface
			{
				if let ( Some( anchor_id ), Some( xdg_shell ) ) = ( spec.anchor_widget_id, xdg_shell_opt )
				{
					if let Some( anchor_rect ) = main_widget_rects.iter()
						.find( |w| w.id == Some( anchor_id ) )
						.map( |w| w.rect )
					{
						let to_logical = | r: Rect |
						{
							(
								( r.x      / parent_scale ).round() as i32,
								( r.y      / parent_scale ).round() as i32,
								( r.width  / parent_scale ).round().max( 1.0 ) as i32,
								( r.height / parent_scale ).round().max( 1.0 ) as i32,
							)
						};
						let new_q  = to_logical( anchor_rect );
						let moved  = ss.last_popup_anchor.map( |r| to_logical( r ) != new_q ).unwrap_or( true );
						if moved
						{
							if let Ok( positioner ) = XdgPositioner::new( xdg_shell )
							{
								let ( ax, ay, aw, ah ) = new_q;
								let ( spec_w, spec_h ) = spec.size;
								let popup_w = if spec_w == 0 { aw } else { spec_w.max( 1 ) as i32 };
								let popup_h = spec_h.max( 1 ) as i32;
								positioner.set_size( popup_w, popup_h );
								positioner.set_anchor_rect( ax, ay, aw, ah );
								positioner.set_anchor( PositionerAnchor::Bottom );
								positioner.set_gravity( Gravity::Bottom );
								positioner.set_constraint_adjustment(
									ConstraintAdjustment::FlipY | ConstraintAdjustment::SlideX,
								);
								ss.popup_reposition_token = ss.popup_reposition_token.wrapping_add( 1 );
								popup.reposition( &positioner, ss.popup_reposition_token );
								ss.last_popup_anchor = Some( anchor_rect );
							}
						}
					}
				}
			}
			continue;
		}
		// `anchor_widget_id = Some(_)` → xdg-popup path; `None` →
		// wlr-layer-shell path.
		if let Some( anchor_id ) = spec.anchor_widget_id
		{
			let Some( xdg_shell ) = xdg_shell_opt else
			{
				eprintln!( "ltk: ignoring popup overlay {:?} — main surface is not an xdg-shell window", spec.id );
				continue;
			};
			let Some( ref parent ) = parent_xdg else
			{
				eprintln!( "ltk: ignoring popup overlay {:?} — no xdg parent surface", spec.id );
				continue;
			};
			let Some( anchor_rect ) = main_widget_rects.iter()
				.find( |w| w.id == Some( anchor_id ) )
				.map( |w| w.rect )
			else
			{
				eprintln!( "ltk: popup overlay {:?} could not find anchor widget id {:?}", spec.id, anchor_id );
				continue;
			};
			let positioner = match XdgPositioner::new( xdg_shell )
			{
				Ok( p )  => p,
				Err( e ) =>
				{
					eprintln!( "ltk: XdgPositioner::new failed for popup {:?}: {e}", spec.id );
					continue;
				}
			};
			// Convert the requested popup size and the anchor rect from
			// physical pixels (the layout coordinate space) to logical
			// pixels — the positioner expresses everything in window
			// geometry, which is logical. `size.0 == 0` is the
			// "match anchor width" convention (paralleling the
			// layer-shell `0 = fill` semantic): the popup is sized to
			// the trigger pill so combos / selects render flush with
			// the field they belong to.
			let ax = ( anchor_rect.x      / parent_scale ).round() as i32;
			let ay = ( anchor_rect.y      / parent_scale ).round() as i32;
			let aw = ( anchor_rect.width  / parent_scale ).round().max( 1.0 ) as i32;
			let ah = ( anchor_rect.height / parent_scale ).round().max( 1.0 ) as i32;
			let ( spec_w, spec_h ) = spec.size;
			let popup_w = if spec_w == 0 { aw } else { spec_w.max( 1 ) as i32 };
			let popup_h = spec_h.max( 1 ) as i32;
			positioner.set_size( popup_w, popup_h );
			positioner.set_anchor_rect( ax, ay, aw, ah );
			positioner.set_anchor( PositionerAnchor::Bottom );
			positioner.set_gravity( Gravity::Bottom );
			positioner.set_constraint_adjustment(
				ConstraintAdjustment::FlipY | ConstraintAdjustment::SlideX,
			);
			// xdg_popup.grab must be issued before the first commit
			// (error 0 `invalid_grab` otherwise). `Popup::new` commits
			// internally, so the lower-level `from_surface` path is
			// the only one that lets the grab land in time.
			let surface = match Surface::new( cs, qh )
			{
				Ok( s )  => s,
				Err( e ) =>
				{
					eprintln!( "ltk: Surface::new failed for popup overlay {:?}: {e}", spec.id );
					continue;
				}
			};
			let popup = match Popup::from_surface( Some( parent ), &positioner, qh, surface, xdg_shell )
			{
				Ok( p )  => p,
				Err( e ) =>
				{
					eprintln!( "ltk: Popup::from_surface failed for overlay {:?}: {e}", spec.id );
					continue;
				}
			};
			if let Some( ref seat ) = grab_seat
			{
				popup.xdg_popup().grab( seat, grab_serial );
			}
			popup.wl_surface().commit();
			let mut ss = SurfaceState::<A::Message>::new( SurfaceKind::Popup( popup ), 0.0, String::new() );
			ss.last_requested_size = spec.size;
			ss.last_popup_anchor   = Some( anchor_rect );
			overlays_m.insert( spec.id, ss );
			continue;
		}
		// wlr-layer-shell path.
		let Some( layer_shell ) = layer_shell_opt else
		{
			eprintln!( "ltk: ignoring layer-shell overlay {:?} — wlr-layer-shell not available", spec.id );
			continue;
		};
		let cfg = LayerConfig
		{
			layer:              spec.layer.to_wlr_layer(),
			exclusive_zone:     spec.exclusive_zone,
			anchor:             spec.anchor,
			size:               to_logical_size( spec.size ),
			keyboard_exclusive: spec.keyboard_exclusive,
			namespace:          "ltk-overlay",
		};
		let mut surface = SurfaceKind::Pending( cfg );
		if let Some( ref output ) = output_opt
		{
			surface.materialize( cs, layer_shell, qh, output );
		}
		let mut ss = SurfaceState::<A::Message>::new( surface, 0.0, String::new() );
		// Inherit the parent's scale so the first configure allocates a
		// HiDPI buffer and lays out at the right size from frame one,
		// instead of rendering at scale 1 until `scale_factor_changed`
		// lands a frame or two later.
		ss.scale_factor        = parent_scale_i;
		ss.last_requested_size = spec.size;
		ss.layer_anchor        = Some( spec.anchor );
		overlays_m.insert( spec.id, ss );
	}
}