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

//! Putting a painted canvas on screen: through a `wl_shm` buffer for the software renderer, through `eglSwapBuffers` for the GPU one, together with the damage, opaque and input regions and the frame callback of the commit.

use std::sync::Arc;

use smithay_client_toolkit::compositor::{ CompositorState, Region };
use smithay_client_toolkit::reexports::client::protocol::{ wl_shm, wl_surface::WlSurface };
use smithay_client_toolkit::shm::Shm;

use crate::app::App;
use crate::draw::fit_canvas;
use crate::egl_context::egl_damage;
use crate::event_loop::perf::RasterTrace;
use crate::platform::Presentation;
use crate::render::Canvas;
use crate::types::{ Color, Rect };

use super::{ WaylandPlatform, WaylandSurfaceState };

/// Pick the best wl_shm format for our RGBA-premultiplied pixmap.
/// Abgr8888 matches tiny-skia's byteorder on little-endian systems (plain
/// memcpy). Falls back to mandatory Argb8888 when not advertised.
/// Returns `(format, swap_rb)`.
pub( crate ) fn pick_shm_format( shm: &Shm ) -> ( wl_shm::Format, bool )
{
	if shm.formats().contains( &wl_shm::Format::Abgr8888 )
	{
		( wl_shm::Format::Abgr8888, false )
	} else {
		( wl_shm::Format::Argb8888, true )
	}
}

/// The GPU path when both the process and the surface have EGL, the SHM pool otherwise.
pub( super ) fn prepare_canvas<A: App>
(
	platform: &WaylandPlatform<A>,
	surface:  &mut WaylandSurfaceState,
	canvas:   &mut Option<Canvas>,
	pw:       u32,
	ph:       u32,
	scale:    f32,
) -> bool
{
	if let ( Some( ctx ), Some( es ) ) = ( platform.egl_context.as_ref(), surface.egl_surface.as_ref() )
	{
		if ctx.make_current( es ).is_err() { return false; }
		surface.raster_trace = RasterTrace::begin();
		fit_canvas( canvas, pw, ph, scale, || Canvas::new_gles( Arc::clone( ctx.gl() ), ctx.version, pw, ph ) );
		return true;
	}
	if surface.pool.is_none() { return false; }
	fit_canvas( canvas, pw, ph, scale, || Canvas::new( pw, ph ) );
	true
}

pub( super ) fn present<A: App>
(
	platform: &WaylandPlatform<A>,
	surface:  &mut WaylandSurfaceState,
	canvas:   &mut Canvas,
	frame:    &Presentation<'_>,
) -> bool
{
	let ( pw, ph ) = canvas.size();
	let Some( ( ctx, es ) ) = platform.egl_context.as_ref().zip( surface.egl_surface.as_ref() ) else
	{
		return present_shm( platform, surface, canvas, frame );
	};
	canvas.present();
	if let Some( t ) = surface.raster_trace.take()
	{
		t.end( ctx.gl(), if frame.damage.is_empty() { "full" } else { "partial" }, pw, ph );
	}
	describe( platform, surface.surface.wl_surface(), &mut surface.opaque_full, frame );
	// Attaches, damages and commits in one go.
	let _ = ctx.swap_buffers_with_damage( es, &egl_damage( frame.damage, pw, ph ) );
	true
}

fn present_shm<A: App>
(
	platform: &WaylandPlatform<A>,
	surface:  &mut WaylandSurfaceState,
	canvas:   &mut Canvas,
	frame:    &Presentation<'_>,
) -> bool
{
	let ( pw, ph ) = canvas.size();
	let ( format, swap_rb ) = pick_shm_format( &platform.shm );
	let Some( pool ) = surface.pool.as_mut() else { return false };
	let Ok( ( buffer, pixels ) ) = pool.create_buffer( pw as i32, ph as i32, ( pw * 4 ) as i32, format ) else { return false };
	canvas.write_to_wayland_buf( pixels, swap_rb );

	let wl_surface = surface.surface.wl_surface();
	buffer.attach_to( wl_surface ).expect( "attach" );
	if frame.damage.is_empty()
	{
		wl_surface.damage_buffer( 0, 0, pw as i32, ph as i32 );
	} else {
		for r in frame.damage
		{
			wl_surface.damage_buffer( r.x as i32, r.y as i32, r.width as i32, r.height as i32 );
		}
	}
	describe( platform, wl_surface, &mut surface.opaque_full, frame );
	wl_surface.commit();
	true
}

/// The state that rides on the commit besides the buffer. The frame callback must be asked before the commit so the compositor ties it to this frame.
fn describe<A: App>( platform: &WaylandPlatform<A>, wl_surface: &WlSurface, opaque_applied: &mut Option<Vec<Rect>>, frame: &Presentation<'_> )
{
	let scale = frame.scale.round().max( 1.0 ) as u32;
	sync_opaque_region( wl_surface, &platform.compositor_state, opaque_applied, frame.bg, frame.opaque_region, frame.width, frame.height, scale );
	apply_input_region( wl_surface, &platform.compositor_state, frame.input_region, scale );
	if let Some( focus ) = frame.frame
	{
		let _ = wl_surface.frame( &platform.qh, focus );
	}
}

/// The opaque part of a `width × height` logical surface at `scale`, in physical rects: all of it when `bg` is opaque, else `region`.
fn opaque_rects( bg: Color, region: Option<&[Rect]>, width: u32, height: u32, scale: u32 ) -> Vec<Rect>
{
	let s = scale.max( 1 ) as f32;
	if bg.a >= 1.0
	{
		vec![ Rect { x: 0.0, y: 0.0, width: width as f32 * s, height: height as f32 * s } ]
	} else {
		region.map( |r| r.to_vec() ).unwrap_or_default()
	}
}

/// Declare the opaque part of the surface so the compositor can skip blending it and repainting what lies underneath. `applied` remembers the rects last sent.
pub( crate ) fn sync_opaque_region(
	wl_surface: &WlSurface,
	compositor: &CompositorState,
	applied:    &mut Option<Vec<Rect>>,
	bg:         Color,
	region:     Option<&[Rect]>,
	width:      u32,
	height:     u32,
	scale:      u32,
)
{
	let rects = opaque_rects( bg, region, width, height, scale );
	if applied.as_ref() == Some( &rects ) { return; }
	if rects.is_empty()
	{
		wl_surface.set_opaque_region( None );
	} else if let Ok( wl_region ) = Region::new( compositor ) {
		let s = scale.max( 1 ) as f32;
		for r in &rects
		{
			wl_region.add(
				( r.x      / s ).round() as i32,
				( r.y      / s ).round() as i32,
				( r.width  / s ).round() as i32,
				( r.height / s ).round() as i32,
			);
		}
		wl_surface.set_opaque_region( Some( wl_region.wl_region() ) );
	}
	*applied = Some( rects );
}

/// Apply or clear the surface's input region (set by
/// `App::input_region`). `None` restores the default of "receive
/// input everywhere"; `Some(&[])` makes the surface pointer-through.
pub( crate ) fn apply_input_region(
	wl_surface:   &WlSurface,
	compositor:   &CompositorState,
	input_region: Option<&[Rect]>,
	scale:        u32,
)
{
	if let Some( regions ) = input_region
	{
		if let Ok( region ) = Region::new( compositor )
		{
			// `Rect`s are physical (layout space); `wl_region` is logical.
			let s = scale.max( 1 ) as f32;
			for r in regions
			{
				region.add(
					( r.x      / s ).round() as i32,
					( r.y      / s ).round() as i32,
					( r.width  / s ).round() as i32,
					( r.height / s ).round() as i32,
				);
			}
			wl_surface.set_input_region( Some( region.wl_region() ) );
		}
	} else {
		wl_surface.set_input_region( None );
	}
}

#[ cfg( test ) ]
mod tests
{
	use super::opaque_rects;
	use crate::types::{ Color, Rect };

	fn rect( x: f32, y: f32, width: f32, height: f32 ) -> Rect
	{
		Rect { x, y, width, height }
	}

	#[ test ]
	fn an_opaque_background_covers_the_physical_surface()
	{
		let region = [ rect( 0.0, 0.0, 1.0, 1.0 ) ];
		assert_eq!( opaque_rects( Color::rgb( 0.0, 0.0, 0.0 ), Some( &region ), 400, 300, 2 ), vec![ rect( 0.0, 0.0, 800.0, 600.0 ) ] );
	}

	#[ test ]
	fn a_translucent_background_takes_the_app_region()
	{
		let region = [ rect( 0.0, 0.0, 100.0, 50.0 ) ];
		assert_eq!( opaque_rects( Color::rgba( 0.0, 0.0, 0.0, 0.5 ), Some( &region ), 400, 300, 1 ), region.to_vec() );
		assert!( opaque_rects( Color::rgba( 0.0, 0.0, 0.0, 0.0 ), None, 400, 300, 1 ).is_empty() );
	}
}