forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9ff2f83Ivan Molodetskikh1 year ago2099 commits

client.rs526 lines, 15.5 KiBHistoryRawDownload
1use std::cmp::min;
2use std::collections::HashMap;
3use std::fmt;
4use std::fmt::Write as _;
5use std::os::unix::net::UnixStream;
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::sync::Arc;
8use std::time::Duration;
9
10use calloop::EventLoop;
11use calloop_wayland_source::WaylandSource;
12use single_pixel_buffer::v1::client::wp_single_pixel_buffer_manager_v1::WpSinglePixelBufferManagerV1;
13use smithay::reexports::wayland_protocols::wp::single_pixel_buffer;
14use smithay::reexports::wayland_protocols::wp::viewporter::client::wp_viewport::WpViewport;
15use smithay::reexports::wayland_protocols::wp::viewporter::client::wp_viewporter::WpViewporter;
16use smithay::reexports::wayland_protocols::xdg::shell::client::xdg_surface::{self, XdgSurface};
17use smithay::reexports::wayland_protocols::xdg::shell::client::xdg_toplevel::{self, XdgToplevel};
18use smithay::reexports::wayland_protocols::xdg::shell::client::xdg_wm_base::{self, XdgWmBase};
19use wayland_backend::client::Backend;
20use wayland_client::globals::Global;
21use wayland_client::protocol::wl_buffer::{self, WlBuffer};
22use wayland_client::protocol::wl_callback::{self, WlCallback};
23use wayland_client::protocol::wl_compositor::WlCompositor;
24use wayland_client::protocol::wl_display::WlDisplay;
25use wayland_client::protocol::wl_output::{self, WlOutput};
26use wayland_client::protocol::wl_registry::{self, WlRegistry};
27use wayland_client::protocol::wl_surface::{self, WlSurface};
28use wayland_client::{Connection, Dispatch, Proxy as _, QueueHandle};
29
30use crate::utils::id::IdCounter;
31
32pub struct Client {
33 pub id: ClientId,
34 pub event_loop: EventLoop<'static, State>,
35 pub connection: Connection,
36 pub qh: QueueHandle<State>,
37 pub display: WlDisplay,
38 pub state: State,
39}
40
41pub struct State {
42 pub qh: QueueHandle<State>,
43
44 pub globals: Vec<Global>,
45 pub outputs: HashMap<WlOutput, String>,
46
47 pub compositor: Option<WlCompositor>,
48 pub xdg_wm_base: Option<XdgWmBase>,
49 pub spbm: Option<WpSinglePixelBufferManagerV1>,
50 pub viewporter: Option<WpViewporter>,
51
52 pub windows: Vec<Window>,
53}
54
55pub struct Window {
56 pub qh: QueueHandle<State>,
57 pub spbm: WpSinglePixelBufferManagerV1,
58
59 pub surface: WlSurface,
60 pub xdg_surface: XdgSurface,
61 pub xdg_toplevel: XdgToplevel,
62 pub viewport: WpViewport,
63 pub pending_configure: Configure,
64 pub configures_received: Vec<(u32, Configure)>,
65 pub close_requested: bool,
66
67 pub configures_looked_at: usize,
68}
69
70#[derive(Debug, Clone, Default)]
71pub struct Configure {
72 pub size: (i32, i32),
73 pub bounds: Option<(i32, i32)>,
74 pub states: Vec<xdg_toplevel::State>,
75}
76
77#[derive(Default)]
78pub struct SyncData {
79 pub done: AtomicBool,
80}
81
82static CLIENT_ID_COUNTER: IdCounter = IdCounter::new();
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
85pub struct ClientId(u64);
86
87impl ClientId {
88 fn next() -> ClientId {
89 ClientId(CLIENT_ID_COUNTER.next())
90 }
91}
92
93impl fmt::Display for Configure {
94 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95 write!(f, "size: {} × {}, ", self.size.0, self.size.1)?;
96 if let Some(bounds) = self.bounds {
97 write!(f, "bounds: {} × {}, ", bounds.0, bounds.1)?;
98 } else {
99 write!(f, "bounds: none, ")?;
100 }
101 write!(f, "states: {:?}", self.states)?;
102 Ok(())
103 }
104}
105
106impl Client {
107 pub fn new(stream: UnixStream) -> Self {
108 let id = ClientId::next();
109
110 let event_loop = EventLoop::try_new().unwrap();
111 let backend = Backend::connect(stream).unwrap();
112 let connection = Connection::from_backend(backend);
113 let queue = connection.new_event_queue();
114 let qh = queue.handle();
115 WaylandSource::new(connection.clone(), queue)
116 .insert(event_loop.handle())
117 .unwrap();
118
119 let display = connection.display();
120 let _registry = display.get_registry(&qh, ());
121 connection.flush().unwrap();
122
123 let state = State {
124 qh: qh.clone(),
125 globals: Vec::new(),
126 outputs: HashMap::new(),
127 compositor: None,
128 xdg_wm_base: None,
129 spbm: None,
130 viewporter: None,
131 windows: Vec::new(),
132 };
133
134 Self {
135 id,
136 event_loop,
137 connection,
138 qh,
139 display,
140 state,
141 }
142 }
143
144 pub fn dispatch(&mut self) {
145 self.event_loop
146 .dispatch(Duration::ZERO, &mut self.state)
147 .unwrap();
148 }
149
150 pub fn send_sync(&self) -> Arc<SyncData> {
151 let data = Arc::new(SyncData::default());
152 self.display.sync(&self.qh, data.clone());
153 self.connection.flush().unwrap();
154 data
155 }
156
157 pub fn create_window(&mut self) -> &mut Window {
158 self.state.create_window()
159 }
160
161 pub fn window(&mut self, surface: &WlSurface) -> &mut Window {
162 self.state.window(surface)
163 }
164
165 pub fn output(&mut self, name: &str) -> WlOutput {
166 self.state
167 .outputs
168 .iter()
169 .find(|(_, v)| *v == name)
170 .unwrap()
171 .0
172 .clone()
173 }
174}
175
176impl State {
177 pub fn create_window(&mut self) -> &mut Window {
178 let compositor = self.compositor.as_ref().unwrap();
179 let xdg_wm_base = self.xdg_wm_base.as_ref().unwrap();
180 let viewporter = self.viewporter.as_ref().unwrap();
181
182 let surface = compositor.create_surface(&self.qh, ());
183 let xdg_surface = xdg_wm_base.get_xdg_surface(&surface, &self.qh, ());
184 let xdg_toplevel = xdg_surface.get_toplevel(&self.qh, ());
185 let viewport = viewporter.get_viewport(&surface, &self.qh, ());
186
187 let window = Window {
188 qh: self.qh.clone(),
189 spbm: self.spbm.clone().unwrap(),
190
191 surface,
192 xdg_surface,
193 xdg_toplevel,
194 viewport,
195 pending_configure: Configure::default(),
196 configures_received: Vec::new(),
197 close_requested: false,
198
199 configures_looked_at: 0,
200 };
201
202 self.windows.push(window);
203 self.windows.last_mut().unwrap()
204 }
205
206 pub fn window(&mut self, surface: &WlSurface) -> &mut Window {
207 self.windows
208 .iter_mut()
209 .find(|w| w.surface == *surface)
210 .unwrap()
211 }
212}
213
214impl Window {
215 pub fn commit(&self) {
216 self.surface.commit();
217 }
218
219 pub fn ack_last(&self) {
220 let serial = self.configures_received.last().unwrap().0;
221 self.xdg_surface.ack_configure(serial);
222 }
223
224 pub fn ack_last_and_commit(&self) {
225 self.ack_last();
226 self.commit();
227 }
228
229 pub fn attach_new_buffer(&self) {
230 let buffer = self.spbm.create_u32_rgba_buffer(0, 0, 0, 0, &self.qh, ());
231 self.surface.attach(Some(&buffer), 0, 0);
232 }
233
234 pub fn set_size(&self, w: u16, h: u16) {
235 self.viewport.set_destination(i32::from(w), i32::from(h));
236 }
237
238 pub fn set_fullscreen(&self, output: Option<&WlOutput>) {
239 self.xdg_toplevel.set_fullscreen(output);
240 }
241
242 pub fn unset_fullscreen(&self) {
243 self.xdg_toplevel.unset_fullscreen();
244 }
245
246 pub fn set_parent(&self, parent: Option<&XdgToplevel>) {
247 self.xdg_toplevel.set_parent(parent);
248 }
249
250 pub fn set_title(&self, title: &str) {
251 self.xdg_toplevel.set_title(title.to_owned());
252 }
253
254 pub fn recent_configures(&mut self) -> impl Iterator<Item = &Configure> {
255 let start = self.configures_looked_at;
256 self.configures_looked_at = self.configures_received.len();
257 self.configures_received[start..].iter().map(|(_, c)| c)
258 }
259
260 pub fn format_recent_configures(&mut self) -> String {
261 let mut buf = String::new();
262 for configure in self.recent_configures() {
263 if !buf.is_empty() {
264 buf.push('\n');
265 }
266 write!(buf, "{configure}").unwrap();
267 }
268 buf
269 }
270}
271
272impl Dispatch<WlCallback, Arc<SyncData>> for State {
273 fn event(
274 _state: &mut Self,
275 _proxy: &WlCallback,
276 event: <WlCallback as wayland_client::Proxy>::Event,
277 data: &Arc<SyncData>,
278 _conn: &Connection,
279 _qhandle: &QueueHandle<Self>,
280 ) {
281 match event {
282 wl_callback::Event::Done { .. } => data.done.store(true, Ordering::Relaxed),
283 _ => unreachable!(),
284 }
285 }
286}
287
288impl Dispatch<WlRegistry, ()> for State {
289 fn event(
290 state: &mut Self,
291 registry: &WlRegistry,
292 event: <WlRegistry as wayland_client::Proxy>::Event,
293 _data: &(),
294 _conn: &Connection,
295 qh: &QueueHandle<Self>,
296 ) {
297 match event {
298 wl_registry::Event::Global {
299 name,
300 interface,
301 version,
302 } => {
303 if interface == WlCompositor::interface().name {
304 let version = min(version, WlCompositor::interface().version);
305 state.compositor = Some(registry.bind(name, version, qh, ()));
306 } else if interface == XdgWmBase::interface().name {
307 let version = min(version, XdgWmBase::interface().version);
308 state.xdg_wm_base = Some(registry.bind(name, version, qh, ()));
309 } else if interface == WpSinglePixelBufferManagerV1::interface().name {
310 let version = min(version, WpSinglePixelBufferManagerV1::interface().version);
311 state.spbm = Some(registry.bind(name, version, qh, ()));
312 } else if interface == WpViewporter::interface().name {
313 let version = min(version, WpViewporter::interface().version);
314 state.viewporter = Some(registry.bind(name, version, qh, ()));
315 } else if interface == WlOutput::interface().name {
316 let version = min(version, WlOutput::interface().version);
317 let output = registry.bind(name, version, qh, ());
318 state.outputs.insert(output, String::new());
319 }
320
321 let global = Global {
322 name,
323 interface,
324 version,
325 };
326 state.globals.push(global);
327 }
328 wl_registry::Event::GlobalRemove { .. } => (),
329 _ => unreachable!(),
330 }
331 }
332}
333
334impl Dispatch<WlOutput, ()> for State {
335 fn event(
336 state: &mut Self,
337 output: &WlOutput,
338 event: <WlOutput as wayland_client::Proxy>::Event,
339 _data: &(),
340 _conn: &Connection,
341 _qhandle: &QueueHandle<Self>,
342 ) {
343 match event {
344 wl_output::Event::Geometry { .. } => (),
345 wl_output::Event::Mode { .. } => (),
346 wl_output::Event::Done => (),
347 wl_output::Event::Scale { .. } => (),
348 wl_output::Event::Name { name } => {
349 *state.outputs.get_mut(output).unwrap() = name;
350 }
351 wl_output::Event::Description { .. } => (),
352 _ => unreachable!(),
353 }
354 }
355}
356
357impl Dispatch<WlCompositor, ()> for State {
358 fn event(
359 _state: &mut Self,
360 _proxy: &WlCompositor,
361 _event: <WlCompositor as wayland_client::Proxy>::Event,
362 _data: &(),
363 _conn: &Connection,
364 _qhandle: &QueueHandle<Self>,
365 ) {
366 unreachable!()
367 }
368}
369
370impl Dispatch<XdgWmBase, ()> for State {
371 fn event(
372 _state: &mut Self,
373 xdg_wm_base: &XdgWmBase,
374 event: <XdgWmBase as wayland_client::Proxy>::Event,
375 _data: &(),
376 _conn: &Connection,
377 _qhandle: &QueueHandle<Self>,
378 ) {
379 match event {
380 xdg_wm_base::Event::Ping { serial } => {
381 xdg_wm_base.pong(serial);
382 }
383 _ => unreachable!(),
384 }
385 }
386}
387
388impl Dispatch<WlSurface, ()> for State {
389 fn event(
390 _state: &mut Self,
391 _proxy: &WlSurface,
392 event: <WlSurface as wayland_client::Proxy>::Event,
393 _data: &(),
394 _conn: &Connection,
395 _qhandle: &QueueHandle<Self>,
396 ) {
397 match event {
398 wl_surface::Event::Enter { .. } => (),
399 wl_surface::Event::Leave { .. } => (),
400 wl_surface::Event::PreferredBufferScale { .. } => (),
401 wl_surface::Event::PreferredBufferTransform { .. } => (),
402 _ => unreachable!(),
403 }
404 }
405}
406
407impl Dispatch<XdgSurface, ()> for State {
408 fn event(
409 state: &mut Self,
410 xdg_surface: &XdgSurface,
411 event: <XdgSurface as wayland_client::Proxy>::Event,
412 _data: &(),
413 _conn: &Connection,
414 _qhandle: &QueueHandle<Self>,
415 ) {
416 match event {
417 xdg_surface::Event::Configure { serial } => {
418 let window = state
419 .windows
420 .iter_mut()
421 .find(|w| w.xdg_surface == *xdg_surface)
422 .unwrap();
423 let configure = window.pending_configure.clone();
424 window.configures_received.push((serial, configure));
425 }
426 _ => unreachable!(),
427 }
428 }
429}
430
431impl Dispatch<XdgToplevel, ()> for State {
432 fn event(
433 state: &mut Self,
434 xdg_toplevel: &XdgToplevel,
435 event: <XdgToplevel as wayland_client::Proxy>::Event,
436 _data: &(),
437 _conn: &Connection,
438 _qhandle: &QueueHandle<Self>,
439 ) {
440 let window = state
441 .windows
442 .iter_mut()
443 .find(|w| w.xdg_toplevel == *xdg_toplevel)
444 .unwrap();
445
446 match event {
447 xdg_toplevel::Event::Configure {
448 width,
449 height,
450 states,
451 } => {
452 let configure = &mut window.pending_configure;
453 configure.size = (width, height);
454 configure.states = states
455 .chunks_exact(4)
456 .flat_map(TryInto::<[u8; 4]>::try_into)
457 .map(u32::from_ne_bytes)
458 .flat_map(xdg_toplevel::State::try_from)
459 .collect();
460 }
461 xdg_toplevel::Event::Close => {
462 window.close_requested = true;
463 }
464 xdg_toplevel::Event::ConfigureBounds { width, height } => {
465 window.pending_configure.bounds = Some((width, height));
466 }
467 xdg_toplevel::Event::WmCapabilities { .. } => (),
468 _ => unreachable!(),
469 }
470 }
471}
472
473impl Dispatch<WlBuffer, ()> for State {
474 fn event(
475 _state: &mut Self,
476 _proxy: &WlBuffer,
477 event: <WlBuffer as wayland_client::Proxy>::Event,
478 _data: &(),
479 _conn: &Connection,
480 _qhandle: &QueueHandle<Self>,
481 ) {
482 match event {
483 wl_buffer::Event::Release => (),
484 _ => unreachable!(),
485 }
486 }
487}
488
489impl Dispatch<WpSinglePixelBufferManagerV1, ()> for State {
490 fn event(
491 _state: &mut Self,
492 _proxy: &WpSinglePixelBufferManagerV1,
493 _event: <WpSinglePixelBufferManagerV1 as wayland_client::Proxy>::Event,
494 _data: &(),
495 _conn: &Connection,
496 _qhandle: &QueueHandle<Self>,
497 ) {
498 unreachable!()
499 }
500}
501
502impl Dispatch<WpViewporter, ()> for State {
503 fn event(
504 _state: &mut Self,
505 _proxy: &WpViewporter,
506 _event: <WpViewporter as wayland_client::Proxy>::Event,
507 _data: &(),
508 _conn: &Connection,
509 _qhandle: &QueueHandle<Self>,
510 ) {
511 unreachable!()
512 }
513}
514
515impl Dispatch<WpViewport, ()> for State {
516 fn event(
517 _state: &mut Self,
518 _proxy: &WpViewport,
519 _event: <WpViewport as wayland_client::Proxy>::Event,
520 _data: &(),
521 _conn: &Connection,
522 _qhandle: &QueueHandle<Self>,
523 ) {
524 unreachable!()
525 }
526}