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

use smithay_client_toolkit::
{
	compositor::CompositorState,
	output::OutputState,
	registry::RegistryState,
	seat::SeatState,
	shell::
	{
		WaylandSurface,
		wlr_layer::LayerShell,
		xdg::
		{
			XdgShell,
			window::WindowDecorations,
		},
	},
	shm::Shm,
	subcompositor::SubcompositorState,
};
use smithay_client_toolkit::reexports::client::Connection;
use smithay_client_toolkit::reexports::calloop::EventLoop;
use smithay_client_toolkit::reexports::calloop_wayland_source::WaylandSource;
use wayland_protocols::wp::text_input::zv3::client::zwp_text_input_manager_v3::ZwpTextInputManagerV3;

use crate::app::App;
use crate::event_loop::{ AppData, RunError, Sources, SurfaceState };

use super::{ LayerConfig, SurfaceKind, WaylandPlatform, WaylandSurfaceState };
use super::overlays_reconcile::reconcile_overlays;
use super::subsurface::reconcile_subsurfaces;

/// Run the application, panicking on init failure. Thin wrapper over
/// [`try_run`] kept for backwards-compatibility — embedders that need
/// to recover from a missing compositor or a stripped-down driver
/// should call [`try_run`] instead.
pub( crate ) fn run<A: App>( app: A )
{
	if let Err( e ) = try_run( app )
	{
		panic!( "ltk::run failed during init: {e}" );
	}
}

/// Run the application, returning a typed error on init failure.
/// The dispatch loop's runtime errors still panic — they are non-
/// recoverable once the surface is on screen, and the surface state
/// machine cannot be unwound cleanly from this entry point.
pub( crate ) fn try_run<A: App>( mut app: A ) -> Result<(), RunError>
{
	let conn = Connection::connect_to_env()
		.map_err( |e| RunError::NoWaylandConnection( format!( "{e}" ) ) )?;
	let ( globals, queue ) =
		smithay_client_toolkit::reexports::client::globals::registry_queue_init( &conn )
			.map_err( |e| RunError::RegistryInit( format!( "{e:?}" ) ) )?;
	let qh = queue.handle();

	let mut event_loop: EventLoop<AppData<A>> = EventLoop::try_new()
		.map_err( |e| RunError::EventLoop( format!( "EventLoop::try_new: {e}" ) ) )?;
	WaylandSource::new( conn.clone(), queue )
		.insert( event_loop.handle() )
		.map_err( |e| RunError::EventLoop( format!( "WaylandSource::insert: {e:?}" ) ) )?;

	super::session::install_signal_source( &event_loop.handle() )?;

	let compositor = CompositorState::bind( &globals, &qh )
		.map_err( |e| RunError::MissingProtocol { name: "wl_compositor", detail: format!( "{e:?}" ) } )?;
	let shm        = Shm::bind( &globals, &qh )
		.map_err( |e| RunError::MissingProtocol { name: "wl_shm",        detail: format!( "{e:?}" ) } )?;

	// Optional: compositors lacking wl_subcompositor leave this None and
	// App::subsurfaces() silently degrades to no subsurfaces.
	let subcompositor = SubcompositorState::bind( compositor.wl_compositor().clone(), &globals, &qh ).ok();

	// Try to bring EGL up. On failure (no libEGL, no compatible config,
	// LTK_FORCE_SOFTWARE=1, ES2/ES3 context creation refused…) we log the
	// reason and every surface falls back to the SHM path.
	let egl_context = match crate::egl_context::EglContext::new( &conn )
	{
		// Shared by the surfaces of this thread only; `Arc` is what the surfaces and subsurfaces hold.
		#[ allow( clippy::arc_with_non_send_sync ) ]
		Ok( ctx )    => Some( std::sync::Arc::new( ctx ) ),
		Err( reason ) =>
		{
			crate::egl_context::log_software_fallback( &reason );
			None
		}
	};
	crate::render::set_software_render( egl_context.is_none() );

	// Bind layer-shell up front. Both the main surface (when requested via
	// ShellMode::Layer) and every overlay returned by App::overlays() share
	// this single binding.
	let layer_shell_opt: Option<LayerShell> = LayerShell::bind( &globals, &qh ).ok();

	// Backwards compatibility: window_config() overrides shell_mode()
	let force_window = app.window_config()
		.map( |( t, id )| ( t.to_string(), id.to_string() ) );

	let session_enabled = force_window.is_some() || matches!( app.shell_mode(), crate::app::ShellMode::Window );
	let mut session = if session_enabled
	{
		super::session::SessionRuntime::bootstrap( &mut app )
	} else {
		super::session::SessionRuntime::disabled()
	};
	if session_enabled
	{
		session.bind( &globals, &qh );
	}
	let app_id = app.app_id().to_string();
	if let Some( ( _, ref cfg_id ) ) = force_window
	{
		if cfg_id != &app_id
		{
			eprintln!( "ltk: window_config app_id {cfg_id:?} differs from App::app_id {app_id:?}; App::app_id wins" );
		}
	}

	let bind_xdg = |globals: &smithay_client_toolkit::reexports::client::globals::GlobalList, qh: &smithay_client_toolkit::reexports::client::QueueHandle<AppData<A>>|
		-> Result<XdgShell, RunError>
	{
		XdgShell::bind( globals, qh )
			.map_err( |e| RunError::MissingProtocol { name: "xdg_wm_base", detail: format!( "{e:?}" ) } )
	};

	// Skipped when going fullscreen: Mutter rejects the fullscreen
	// request if a min_size constrains it.
	// Fitted before the first commit, a hint too big for the screen never reaches a compositor that would rescale the window to honour it.
	let prefitted_size_hint = app.window_size_hint()
		.filter( |_| !app.start_fullscreen() )
		.and_then( |hint| super::output_probe::output_logical_size( &conn, &globals ).map( |output| super::window_fit::fit_within( hint, super::window_fit::output_share( output ) ) ) );
	let apply_size_hint = |window: &smithay_client_toolkit::shell::xdg::window::Window|
	{
		if app.start_fullscreen() { return; }
		match prefitted_size_hint.or( app.window_size_hint() )
		{
			Some( ( w, h ) ) =>
			{
				window.set_min_size( Some( ( w, h ) ) );
				window.set_max_size( Some( ( w, h ) ) );
			}
			None =>
			{
				window.set_min_size( Some( ( 360, 480 ) ) );
			}
		}
	};

	let apply_fullscreen = |window: &smithay_client_toolkit::shell::xdg::window::Window|
	{
		if app.start_fullscreen()
		{
			window.set_fullscreen( None );
		}
	};

	// `restore_toplevel` must precede the first commit, so the session
	// attach sits right before `commit()`.
	let make_window = |xdg: &XdgShell, title: &str, session: &mut super::session::SessionRuntime, attach: bool|
	{
		let surface = compositor.create_surface( &qh );
		let window  = xdg.create_window( surface, WindowDecorations::RequestServer, &qh );
		window.set_title( title );
		window.set_app_id( app_id.as_str() );
		apply_size_hint( &window );
		apply_fullscreen( &window );
		if attach
		{
			session.attach_toplevel( &window, &qh );
		}
		window.commit();
		window
	};

	let ( surface_kind, xdg_shell ) = if let Some( ( ref title, _ ) ) = force_window
	{
		let xdg    = bind_xdg( &globals, &qh )?;
		let window = make_window( &xdg, title.as_str(), &mut session, true );
		( SurfaceKind::Window( window ), Some( xdg ) )
	} else {
		// Use shell_mode() to determine surface type
		use crate::app::ShellMode;
		match app.shell_mode()
		{
			ShellMode::SessionLock => {
				// Lock surface is created in SessionLockHandler::locked once the
				// compositor grants the lock; until then a placeholder.
				( SurfaceKind::PendingLock, None )
			}
			ShellMode::Window => {
				let xdg    = bind_xdg( &globals, &qh )?;
				let window = make_window( &xdg, &app.window_title(), &mut session, true );
				( SurfaceKind::Window( window ), Some( xdg ) )
			}
			ShellMode::Layer( layer ) => {
				if layer_shell_opt.is_some()
				{
					// Defer surface creation until new_output fires: if we create the layer
					// surface before the compositor has any output ready (e.g. sway startup),
					// the compositor cannot assign it and logs an error.
					let cfg = LayerConfig {
						layer:              layer.to_wlr_layer(),
						exclusive_zone:     app.exclusive_zone(),
						anchor:             app.layer_anchor(),
						size:               app.layer_size(),
						keyboard_exclusive: app.keyboard_exclusive(),
						namespace:          "ltk-sctk",
					};
					( SurfaceKind::Pending( cfg ), None )
				} else {
					eprintln!( "ltk: wlr-layer-shell not available, falling back to xdg window" );
					let xdg    = bind_xdg( &globals, &qh )?;
					let window = make_window( &xdg, &app.window_title(), &mut session, false );
					( SurfaceKind::Window( window ), Some( xdg ) )
				}
			}
		}
	};
	// Layer-shell apps still get xdg_wm_base when the compositor has it, so
	// a `Layer::Window` overlay can be created later.
	let xdg_shell = xdg_shell.or_else( || XdgShell::bind( &globals, &qh ).ok() );

	// Bind the session-lock manager and request the lock. We don't keep the
	// `SessionLockState` (the manager) around: it has no `Drop`, so the
	// manager object persists in the connection, and the lock lifecycle runs
	// entirely off the returned `SessionLock` + its surfaces.
	let session_lock =
		if force_window.is_none() && matches!( app.shell_mode(), crate::app::ShellMode::SessionLock )
		{
			smithay_client_toolkit::session_lock::SessionLockState::new( &globals, &qh )
				.lock( &qh )
				.ok()
		} else {
			None
		};

	let text_input_manager: Option<ZwpTextInputManagerV3> = globals.bind( &qh, 1..=1, () ).ok();
	let builtin_osk = text_input_manager.is_none() || std::env::var_os( "LTK_BUILTIN_OSK" ).is_some_and( |v| v == "1" );
	// wl_data_device_manager: optional. Required for cross-application
	// copy/paste; absence means the clipboard stays process-local.
	let data_device_manager =
		smithay_client_toolkit::data_device_manager::DataDeviceManagerState::bind( &globals, &qh ).ok();
	let primary = super::primary_selection::PrimarySelection::new(
		smithay_client_toolkit::primary_selection::PrimarySelectionManagerState::bind( &globals, &qh ).ok() );
	let ( clipboard_inbox_tx, clipboard_inbox_rx ) = std::sync::mpsc::channel();
	let ( drop_inbox_tx, drop_inbox_rx ) = super::data_device::drop_inbox();
	// AT-SPI2 / accessibility. `try_new` returns `None` when the
	// platform adapter cannot be created (no daemon on the bus,
	// headless CI, etc.) — the runtime then runs with no
	// accessibility tree, which is the previous behaviour.
	let a11y = crate::a11y::A11yState::try_new( &app_id, &app_id );
	// xdg-activation-v1: optional. Compositors that don't carry the
	// global leave `activation_state` as `None` and the inbound /
	// outbound activation paths silently degrade to no-ops.
	let activation_state =
		smithay_client_toolkit::activation::ActivationState::bind( &globals, &qh ).ok();
	// `$XDG_ACTIVATION_TOKEN` is the cross-desktop convention for an
	// incoming activation token (the launcher that spawned us set it
	// in the new process's environment). Honoured exactly once, after
	// the main surface receives its first configure — that is the
	// earliest moment we can call `xdg_activation_v1.activate`.
	let activation_token_pending = std::env::var( "XDG_ACTIVATION_TOKEN" ).ok().filter( |t| !t.is_empty() );
	// Avoid the token leaking into any child process the app spawns —
	// it is single-use and would be invalid the second time anyway.
	if activation_token_pending.is_some()
	{
		// SAFETY: removing an env var is sound only when no other thread
		// is reading the environment concurrently. We are still in the
		// init phase before `set_channel_sender`, so the app has had
		// no opportunity to spawn worker threads yet.
		unsafe { std::env::remove_var( "XDG_ACTIVATION_TOKEN" ); }
	}

	// `ext-foreign-toplevel-list-v1`. SCTK's `ForeignToplevelList` handles the
	// bind + dispatch routing; absence of the global is fine, the inner
	// `GlobalProxy` then yields no toplevels and `App::on_toplevel_event` never
	// fires. The list is built unconditionally so apps that override the
	// callback always see a consistent stream when the compositor does carry
	// the protocol.
	let foreign_toplevel_list = smithay_client_toolkit::foreign_toplevel_list::ForeignToplevelList::new( &globals, &qh );

	let titlebar_height = if force_window.is_some() { 36.0 } else { 0.0 };
	let titlebar_title  = force_window.map( |( t, _ )| t ).unwrap_or_default();

	let pending_size_hint_unpin = !app.start_fullscreen() && app.window_size_hint().is_some() && app.window_resizable();
	let pending_size_hint_fit   = !app.start_fullscreen() && app.window_size_hint().is_some() && prefitted_size_hint.is_none();

	let platform = WaylandPlatform
	{
		registry_state:     RegistryState::new( &globals ),
		seat_state:         SeatState::new( &globals, &qh ),
		output_state:       OutputState::new( &globals, &qh ),
		compositor_state:   compositor,
		subcompositor,
		shm,
		egl_context,
		session_lock,
		xdg_shell,
		layer_shell:        layer_shell_opt,
		keyboard:           None,
		pointer:            None,
		touch:              None,
		cursor_shape_manager:
			smithay_client_toolkit::seat::pointer::cursor_shape::CursorShapeManager::bind( &globals, &qh ).ok(),
		cursor_shape_device:       None,
		last_pointer_enter_serial: 0,
		last_pointer_serial:       0,
		last_input_serial:         0,
		text_input_manager,
		text_input:         None,
		activation_state,
		activation_token_pending,
		session,
		data_device_manager,
		data_device:        None,
		clipboard_source:   None,
		primary,
		clipboard_inbox_tx,
		clipboard_inbox_rx,
		drop_position:      None,
		drop_mime:          None,
		drop_inbox_tx,
		drop_inbox_rx,
		pending_fullscreen: app.start_fullscreen(),
		pending_size_hint_unpin,
		pending_size_hint_fit,
		fitted_size_hint:   prefitted_size_hint,
		canvas_pool:        Vec::new(),
		foreign_toplevel_list,
		main_output:        None,
		subsurfaces:        std::collections::HashMap::new(),
		subsurface_gles_canvas: None,
		qh:                 qh.clone(),
	};

	let mut main_wl = WaylandSurfaceState::from( surface_kind );
	main_wl.titlebar_base = titlebar_height;
	let main     = SurfaceState::new( main_wl, titlebar_height, titlebar_title );
	let mut data = AppData::new( app, platform, main, Sources::new( event_loop.handle() ), builtin_osk, a11y );
	data.install_sources()?;

	if data.platform.session.store.is_some()
	{
		super::session::install_save_timer( &event_loop.handle() )?;
	}

	while !data.exit_requested
	{
		// Sleep until a Wayland event, a calloop timer or channel, or a
		// deadline of the runtime's. Pacing is driven by `wl_surface.frame`
		// callbacks, so an idle / off-screen / VRR display blocks
		// indefinitely instead of polling at a fixed rate.
		let timeout = data.next_wakeup();
		match event_loop.dispatch( timeout, &mut data )
		{
			Ok( () ) => {},
			Err( calloop::Error::IoError( ref e ) )
				if matches!( e.kind(), std::io::ErrorKind::BrokenPipe | std::io::ErrorKind::ConnectionReset ) =>
			{
				// On a fatal `wl_display.error` the compositor closes the
				// socket; the backend has the typed error stashed but the
				// dispatch result only carries the resulting `BrokenPipe`.
				if let Some( pe ) = conn.protocol_error()
				{
					eprintln!(
						"ltk: wayland protocol error — interface={} object_id={} code={}: {}",
						pe.object_interface, pe.object_id, pe.code, pe.message
					);
				}
				else
				{
					eprintln!( "ltk: wayland connection lost ({e}); exiting" );
				}
				data.exit_requested = true;
				continue;
			}
			Err( calloop::Error::OtherError( ref e ) ) =>
			{
				// wayland-client surfaces the closed-socket condition as an
				// OtherError wrapping a WaylandError::Io(BrokenPipe) — one
				// level deeper than a direct io::Error. Walk the source()
				// chain so we catch it regardless of how many wrapper types
				// sit between calloop and the raw io::Error.
				let mut src: Option<&dyn std::error::Error> = Some( e.as_ref() );
				let mut is_closed = false;
				while let Some( err ) = src
				{
					if let Some( io ) = err.downcast_ref::<std::io::Error>()
					{
						if matches!( io.kind(),
							std::io::ErrorKind::BrokenPipe | std::io::ErrorKind::ConnectionReset )
						{
							is_closed = true;
							break;
						}
					}
					src = err.source();
				}
				if is_closed
				{
					eprintln!( "ltk: wayland connection lost; exiting" );
					data.exit_requested = true;
					continue;
				}
				panic!( "dispatch: {e:?}" );
			}
			Err( e ) => panic!( "dispatch: {e:?}" ),
		}

		// Latest writer wins; payloads are capped at 16 MiB by the worker that reads them.
		while let Ok( text ) = data.platform.clipboard_inbox_rx.try_recv()
		{
			data.clipboard = text;
		}
		if let Some( text ) = data.platform.primary.drain()
		{
			data.primary_selection = text;
		}
		while let Ok( p ) = data.platform.drop_inbox_rx.try_recv()
		{
			data.app.on_drop_received( p.x as f32, p.y as f32, &p.mime, &p.text );
		}
		request_activation_tokens( &mut data );

		data.before_draw();

		// For a session-lock surface, unlock first: exiting without
		// unlocking leaves the compositor's lock in place by design.
		if data.app.requested_exit()
		{
			if let Some( lock ) = data.platform.session_lock.take()
			{
				lock.unlock();
				let _ = conn.roundtrip();
			}
		}

		// Drop any overlays whose id disappeared and create new ones for ids
		// that just appeared. Specs are re-queried next frame for drawing.
		reconcile_overlays( &mut data );

		// Subsurfaces must map with the main surface's first buffer, not a frame later.
		if !data.first_frame_committed
		{
			reconcile_subsurfaces( &mut data );
		}

		// The compositor decides our cadence: when no surface is due we just
		// loop back to `dispatch( None )` and sleep.
		let drawn = data.draw_due();

		// Every iteration, decoupled from the main redraw cadence: a finger
		// drag emits motion events faster than frame callbacks clear
		// `frame_pending`, so gating this on a main draw would pin the
		// subsurface between frames. A position-only change is just
		// set_position + a bare parent commit; no-ops when nothing moved.
		reconcile_subsurfaces( &mut data );

		data.after_draw( drawn );
	}

	data.platform.session.on_exit( &data.app );

	Ok( () )
}

/// Issue the xdg-activation tokens the app asked for. The tag rides in
/// `RequestData::app_id` and comes back through
/// `ActivationHandler::new_token` as the token. When the compositor never
/// advertised the global, answer with an empty token so the caller still
/// proceeds (falling back to its own matching).
fn request_activation_tokens<A: App>( data: &mut AppData<A> )
{
	for tag in data.app.take_activation_requests()
	{
		match data.platform.activation_state
		{
			Some( ref activation ) =>
			{
				let req = smithay_client_toolkit::activation::RequestData {
					app_id:          Some( tag ),
					seat_and_serial: None,
					surface:         data.main.platform.surface.try_wl_surface().cloned(),
				};
				activation.request_token::<AppData<A>>( &data.platform.qh, req );
			}
			None =>
			{
				if let Some( msg ) = data.app.on_activation_token( tag, String::new() )
				{
					data.pending_msgs.push( msg );
				}
			}
		}
	}
}