get_registry/common/
singletons.rs1use crate::common::protocols::wayland::wl_display::WlDisplay;
2use crate::common::protocols::wayland::wl_fixes::WlFixes;
3use crate::common::protocols::wayland::wl_registry::WlRegistry;
4use parking_lot::Mutex;
5use std::collections::HashMap;
6use wl_client::proxy;
7use wl_client::proxy::OwnedProxy;
8
9pub struct Singletons {
10 wl_registry: WlRegistry,
11 map: HashMap<String, (u32, u32)>,
12}
13
14impl Singletons {
15 pub fn get<P>(&self, min: u32, max: u32) -> P
16 where
17 P: OwnedProxy,
18 {
19 match self.get_opt(min, max) {
20 Some(p) => p,
21 _ => {
22 panic!(
23 "Compositor does not support {} ({}..={}) but it is required for this example",
24 P::INTERFACE,
25 min,
26 max,
27 );
28 }
29 }
30 }
31
32 pub fn get_opt<P>(&self, min: u32, max: u32) -> Option<P>
33 where
34 P: OwnedProxy,
35 {
36 let &(name, comp_max) = self.map.get(P::INTERFACE)?;
37 let version = comp_max.min(max);
38 if version < min {
39 return None;
40 }
41 Some(self.wl_registry.bind(name, version))
42 }
43}
44
45impl Drop for Singletons {
46 fn drop(&mut self) {
47 if let Some(fixes) = self.get_opt::<WlFixes>(1, 1) {
48 fixes.destroy_registry(&self.wl_registry);
49 fixes.destroy();
50 }
51 proxy::destroy(&self.wl_registry);
52 }
53}
54
55pub fn get_singletons(display: &WlDisplay) -> Singletons {
56 let map = Mutex::new(HashMap::new());
57
58 let queue = proxy::queue(display);
59 let wl_registry = display.get_registry();
60
61 queue.dispatch_scope_blocking(|scope| {
62 scope.set_event_handler(
63 &wl_registry,
64 WlRegistry::on_global(|_, name, interface, version| {
65 map.lock().insert(interface.to_owned(), (name, version));
66 }),
67 );
68 queue.dispatch_roundtrip_blocking().unwrap();
69 });
70
71 Singletons {
72 wl_registry,
73 map: map.into_inner(),
74 }
75}
76
77pub async fn get_singletons_async(display: &WlDisplay) -> Singletons {
78 let map = Mutex::new(HashMap::new());
79
80 let queue = proxy::queue(display);
81 let wl_registry = display.get_registry();
82
83 queue
84 .dispatch_scope_async(async |scope| {
85 scope.set_event_handler(
86 &wl_registry,
87 WlRegistry::on_global(|_, name, interface, version| {
88 map.lock().insert(interface.to_owned(), (name, version));
89 }),
90 );
91 queue.dispatch_roundtrip_async().await.unwrap();
92 })
93 .await;
94
95 Singletons {
96 wl_registry,
97 map: map.into_inner(),
98 }
99}