gazo 0.0.3

Gazo is a library to get a screen capture from Wayland compositors implementing the wlr_screencopy protocol, like Sway.
Documentation
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
// this module handles most of the wayland compositor communication
use std::{ffi, fs, os::unix::io::FromRawFd};

use nix::sys::memfd;
use wayland_client::{
	self,
	protocol::{wl_buffer, wl_callback, wl_output, wl_registry, wl_shm, wl_shm_pool},
	Connection, Dispatch, QueueHandle,
};
use wayland_protocols::xdg::xdg_output::zv1::client::{zxdg_output_manager_v1, zxdg_output_v1};
use wayland_protocols_wlr::screencopy::v1::client::{
	zwlr_screencopy_frame_v1, zwlr_screencopy_manager_v1,
};

use crate::rectangle;

// represents a wayland output
pub(crate) struct OutputInfo
{
	pub wl_output: wl_output::WlOutput,
	pub name: Option<String>,
	pub output_logical_position: Option<rectangle::Position>,
	pub output_logical_size: Option<rectangle::Size>,
	pub transform: Option<wl_output::Transform>,
	pub scale_factor: i32,
	pub image_file: Option<fs::File>,
	pub image_mmap: Option<memmap2::MmapMut>,
	pub image_mmap_size: Option<rectangle::Size>,
	pub image_logical_position: Option<rectangle::Position>,
	pub image_logical_size: Option<rectangle::Size>,
	pub image_pixel_format: Option<wl_shm::Format>,
	pub image_ready: bool,
}

// a state that stores relevant information and dispatches events
pub(crate) struct State
{
	pub done: bool,
	pub wlr_screencopy_manager: Option<zwlr_screencopy_manager_v1::ZwlrScreencopyManagerV1>,
	pub xdg_output_manager: Option<zxdg_output_manager_v1::ZxdgOutputManagerV1>,
	pub wl_shm: Option<wl_shm::WlShm>,
	pub output_infos: Vec<OutputInfo>,
}

// bind globals to State
impl Dispatch<wl_registry::WlRegistry, ()> for State
{
	fn event(
		state: &mut Self,
		registry: &wl_registry::WlRegistry,
		event: wl_registry::Event,
		_: &(),
		_connection: &Connection,
		queue_handle: &QueueHandle<Self>,
	)
	{
		if let wl_registry::Event::Global {
			name,
			interface,
			version: _,
		} = event
		{
			match &interface[..]
			{
				// get the screencopy manager (used to request capture of an output)
				"zwlr_screencopy_manager_v1" =>
				{
					let wlr_screencopy_manager =
						registry.bind::<zwlr_screencopy_manager_v1::ZwlrScreencopyManagerV1, _, _>(
							name,
							3,
							queue_handle,
							(),
						);

					state.wlr_screencopy_manager = Some(wlr_screencopy_manager);
				}
				// get the xdg output manager (used to obtain information of outputs)
				"zxdg_output_manager_v1" =>
				{
					let xdg_output_manager = registry
						.bind::<zxdg_output_manager_v1::ZxdgOutputManagerV1, _, _>(
							name,
							3,
							queue_handle,
							(),
						);

					state.xdg_output_manager = Some(xdg_output_manager);
				}
				// get the shared memeory object (used to create shared memory pools)
				"wl_shm" =>
				{
					let wl_shm = registry.bind::<wl_shm::WlShm, _, _>(name, 1, queue_handle, ());

					state.wl_shm = Some(wl_shm);
				}
				// get the outputs for capture
				"wl_output" =>
				{
					let wl_output = registry.bind::<wl_output::WlOutput, _, _>(
						name,
						4,
						queue_handle,
						state.output_infos.len(),
					);

					state.output_infos.push(OutputInfo {
						wl_output,
						name: None,
						output_logical_position: None,
						output_logical_size: None,
						transform: None,
						scale_factor: 1,
						image_file: None,
						image_mmap: None,
						image_mmap_size: None,
						image_logical_position: None,
						image_logical_size: None,
						image_pixel_format: None,
						image_ready: false,
					});
				}
				_ =>
				{}
			}
		}
	}
}

// sent after all globals have been enumerated
impl Dispatch<wl_callback::WlCallback, ()> for State
{
	fn event(
		state: &mut Self,
		_wl_callback: &wl_callback::WlCallback,
		event: wl_callback::Event,
		_: &(),
		_connection: &Connection,
		_queue_handle: &QueueHandle<Self>,
	)
	{
		if let wl_callback::Event::Done { callback_data: _ } = event
		{
			state.done = true;
		}
	}
}

// dispatch for output events like geometry and name information
impl Dispatch<wl_output::WlOutput, usize> for State
{
	fn event(
		state: &mut Self,
		_wl_output: &wl_output::WlOutput,
		event: wl_output::Event,
		index: &usize,
		_connection: &Connection,
		_queue_handle: &QueueHandle<Self>,
	)
	{
		// store relevant information in the output_info
		match event
		{
			wl_output::Event::Geometry { transform, .. } =>
			{
				state.output_infos[*index].transform = transform.into_result().ok();
			}
			wl_output::Event::Name { name } =>
			{
				state.output_infos[*index].name = Some(name);
			}
			wl_output::Event::Scale { factor } =>
			{
				state.output_infos[*index].scale_factor = factor;
			}
			_ =>
			{}
		}
	}
}

// xdg protocol handler for additional output information like position and size
impl Dispatch<zxdg_output_v1::ZxdgOutputV1, usize> for State
{
	fn event(
		state: &mut Self,
		_xdg_output: &zxdg_output_v1::ZxdgOutputV1,
		event: zxdg_output_v1::Event,
		index: &usize,
		_connection: &Connection,
		_queue_handle: &QueueHandle<Self>,
	)
	{
		match event
		{
			// logical position is the position in the compositor space accounting for transforms
			zxdg_output_v1::Event::LogicalPosition { x, y } =>
			{
				state.output_infos[*index].output_logical_position =
					Some(rectangle::Position::new(x, y));
			}
			// like logical position but for size
			zxdg_output_v1::Event::LogicalSize { width, height } =>
			{
				state.output_infos[*index].output_logical_size =
					Some(rectangle::Size::new(width, height));
			}
			_ =>
			{}
		}
	}
}

// handle screencopy events
impl Dispatch<zwlr_screencopy_frame_v1::ZwlrScreencopyFrameV1, usize> for State
{
	fn event(
		state: &mut Self,
		wlr_screencopy_frame: &zwlr_screencopy_frame_v1::ZwlrScreencopyFrameV1,
		event: zwlr_screencopy_frame_v1::Event,
		index: &usize,
		_connection: &Connection,
		queue_handle: &QueueHandle<Self>,
	)
	{
		match event
		{
			// compositor is asking gazo to create a buffer for it to put the screencopy in
			// TODO: handle other buffer events
			zwlr_screencopy_frame_v1::Event::Buffer {
				format,
				width,
				height,
				stride,
			} =>
			{
				let format = format.into_result().unwrap();

				// check for valid format
				state.output_infos[*index].image_pixel_format = match format
				{
					wl_shm::Format::Argb8888
					| wl_shm::Format::Xrgb8888
					| wl_shm::Format::Xbgr8888 => Some(format),
					_ => return,
				};

				state.output_infos[*index].image_mmap_size =
					Some(rectangle::Size::new(width as i32, height as i32));

				// allocate memory with a file descriptor
				let raw_fd = memfd::memfd_create(
					ffi::CStr::from_bytes_with_nul(b"gato\0").unwrap(),
					memfd::MemFdCreateFlag::MFD_CLOEXEC | memfd::MemFdCreateFlag::MFD_ALLOW_SEALING,
				)
				.unwrap();

				state.output_infos[*index].image_file =
					Some(unsafe { fs::File::from_raw_fd(raw_fd) });

				// set file size
				state.output_infos[*index]
					.image_file
					.as_mut()
					.unwrap()
					.set_len((width * height * 4) as u64)
					.expect("Failed to allocate memory for screencopy.");

				// create pool from memory
				let wl_shm_pool = state.wl_shm.as_ref().unwrap().create_pool(
					raw_fd,
					(width * height * 4) as i32,
					queue_handle,
					(),
				);

				// create buffer from pool
				let wl_buffer = wl_shm_pool.create_buffer(
					0,
					width as i32,
					height as i32,
					stride as i32,
					format,
					queue_handle,
					(),
				);

				// request copy of screen into buffer
				wlr_screencopy_frame.copy(&wl_buffer);
			}
			// buffer has been filled with screen data
			zwlr_screencopy_frame_v1::Event::Ready {
				tv_sec_hi: _,
				tv_sec_lo: _,
				tv_nsec: _,
			} =>
			{
				// create an mmap
				state.output_infos[*index].image_mmap = Some(unsafe {
					memmap2::MmapMut::map_mut(
						state.output_infos[*index].image_file.as_ref().unwrap(),
					)
					.expect("Failed to create memory mapping")
				});

				// mark image as ready
				state.output_infos[*index].image_ready = true;
			}
			_ =>
			{}
		}
	}
}

// unused dispatches //
impl Dispatch<wl_shm::WlShm, ()> for State
{
	fn event(
		_state: &mut Self,
		_wl_shm: &wl_shm::WlShm,
		_event: wl_shm::Event,
		_: &(),
		_connection: &Connection,
		_queue_handle: &QueueHandle<Self>,
	)
	{
	}
}

impl Dispatch<wl_shm_pool::WlShmPool, ()> for State
{
	fn event(
		_state: &mut Self,
		_wl_shm_pool: &wl_shm_pool::WlShmPool,
		_event: wl_shm_pool::Event,
		_: &(),
		_connection: &Connection,
		_queue_handle: &QueueHandle<Self>,
	)
	{
	}
}

impl Dispatch<wl_buffer::WlBuffer, ()> for State
{
	fn event(
		_state: &mut Self,
		_wl_buffer: &wl_buffer::WlBuffer,
		_event: wl_buffer::Event,
		_: &(),
		_connection: &Connection,
		_queue_handle: &QueueHandle<Self>,
	)
	{
	}
}

impl Dispatch<zwlr_screencopy_manager_v1::ZwlrScreencopyManagerV1, ()> for State
{
	fn event(
		_state: &mut Self,
		_wlr_screencopy_manager: &zwlr_screencopy_manager_v1::ZwlrScreencopyManagerV1,
		_event: zwlr_screencopy_manager_v1::Event,
		_: &(),
		_connection: &Connection,
		_queue_handle: &QueueHandle<Self>,
	)
	{
	}
}

impl Dispatch<zxdg_output_manager_v1::ZxdgOutputManagerV1, ()> for State
{
	fn event(
		_state: &mut Self,
		_xdg_output_manager: &zxdg_output_manager_v1::ZxdgOutputManagerV1,
		_event: zxdg_output_manager_v1::Event,
		_: &(),
		_connection: &Connection,
		_queue_handle: &QueueHandle<Self>,
	)
	{
	}
}
// end unused dispatches //

// function to initialize a State and its OutputInfo Vec
pub(crate) fn connect_and_get_output_info(
) -> Result<(State, wayland_client::EventQueue<State>), crate::Error>
{
	let connection = Connection::connect_to_env()?;

	let mut event_queue = connection.new_event_queue();

	// wayland global object
	let wl_display = connection.display();

	// create a registry object to list and bind globals
	wl_display.get_registry(&event_queue.handle(), ());

	// ask the compositor to emit a 'done' event once globals have been enumerated
	wl_display.sync(&event_queue.handle(), ());

	let mut state = State {
		done: false,
		wlr_screencopy_manager: None,
		xdg_output_manager: None,
		wl_shm: None,
		output_infos: Vec::new(),
	};

	// run until done event has been sent for enumerating globals
	while !state.done
	{
		event_queue.blocking_dispatch(&mut state)?;
	}

	// get xdg output for logical position and size
	for (i, output_info) in state.output_infos.iter_mut().enumerate()
	{
		state.xdg_output_manager.as_ref().unwrap().get_xdg_output(
			&output_info.wl_output,
			&event_queue.handle(),
			i,
		);
	}

	// run until all information about the outputs has been sent
	while state.output_infos.iter().any(|output_info| {
		output_info.output_logical_position.is_none()
			|| output_info.output_logical_size.is_none()
			|| output_info.transform.is_none()
	})
	{
		event_queue.blocking_dispatch(&mut state)?;
	}

	Ok((state, event_queue))
}