1#![allow(unused)]
2
3use crate::{
4 Action, AnyWindowHandle, BackgroundExecutor, Bounds, ClipboardItem, CursorStyle, DisplayId,
5 ForegroundExecutor, Keymap, LinuxDispatcher, LinuxDisplay, LinuxTextSystem, LinuxWindow,
6 LinuxWindowState, Menu, PathPromptOptions, Platform, PlatformDisplay, PlatformInput,
7 PlatformTextSystem, PlatformWindow, Point, Result, SemanticVersion, Size, Task, WindowOptions,
8};
9
10use async_task::Runnable;
11use collections::{HashMap, HashSet};
12use futures::channel::oneshot;
13use parking_lot::Mutex;
14
15use std::{
16 path::{Path, PathBuf},
17 rc::Rc,
18 sync::Arc,
19 time::Duration,
20};
21use time::UtcOffset;
22use xcb::{x, Xid as _};
23
24xcb::atoms_struct! {
25 #[derive(Debug)]
26 pub(crate) struct XcbAtoms {
27 pub wm_protocols => b"WM_PROTOCOLS",
28 pub wm_del_window => b"WM_DELETE_WINDOW",
29 wm_state => b"_NET_WM_STATE",
30 wm_state_maxv => b"_NET_WM_STATE_MAXIMIZED_VERT",
31 wm_state_maxh => b"_NET_WM_STATE_MAXIMIZED_HORZ",
32 }
33}
34
35pub(crate) struct LinuxPlatform {
36 xcb_connection: Arc<xcb::Connection>,
37 x_root_index: i32,
38 atoms: XcbAtoms,
39 background_executor: BackgroundExecutor,
40 foreground_executor: ForegroundExecutor,
41 main_receiver: flume::Receiver<Runnable>,
42 text_system: Arc<LinuxTextSystem>,
43 state: Mutex<LinuxPlatformState>,
44}
45
46pub(crate) struct LinuxPlatformState {
47 quit_requested: bool,
48 windows: HashMap<x::Window, Arc<LinuxWindowState>>,
49}
50
51impl Default for LinuxPlatform {
52 fn default() -> Self {
53 Self::new()
54 }
55}
56
57impl LinuxPlatform {
58 pub(crate) fn new() -> Self {
59 let (xcb_connection, x_root_index) = xcb::Connection::connect(None).unwrap();
60 let atoms = XcbAtoms::intern_all(&xcb_connection).unwrap();
61
62 let xcb_connection = Arc::new(xcb_connection);
63 let (main_sender, main_receiver) = flume::unbounded::<Runnable>();
64 let dispatcher = Arc::new(LinuxDispatcher::new(
65 main_sender,
66 &xcb_connection,
67 x_root_index,
68 ));
69
70 Self {
71 xcb_connection,
72 x_root_index,
73 atoms,
74 background_executor: BackgroundExecutor::new(dispatcher.clone()),
75 foreground_executor: ForegroundExecutor::new(dispatcher.clone()),
76 main_receiver,
77 text_system: Arc::new(LinuxTextSystem::new()),
78 state: Mutex::new(LinuxPlatformState {
79 quit_requested: false,
80 windows: HashMap::default(),
81 }),
82 }
83 }
84}
85
86impl Platform for LinuxPlatform {
87 fn background_executor(&self) -> BackgroundExecutor {
88 self.background_executor.clone()
89 }
90
91 fn foreground_executor(&self) -> ForegroundExecutor {
92 self.foreground_executor.clone()
93 }
94
95 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
96 self.text_system.clone()
97 }
98
99 fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
100 on_finish_launching();
101 //Note: here and below, don't keep the lock() open when calling
102 // into window functions as they may invoke callbacks that need
103 // to immediately access the platform (self).
104 while !self.state.lock().quit_requested {
105 let event = self.xcb_connection.wait_for_event().unwrap();
106 match event {
107 xcb::Event::X(x::Event::ClientMessage(ev)) => {
108 if let x::ClientMessageData::Data32([atom, ..]) = ev.data() {
109 if atom == self.atoms.wm_del_window.resource_id() {
110 // window "x" button clicked by user, we gracefully exit
111 let window = self.state.lock().windows.remove(&ev.window()).unwrap();
112 window.destroy();
113 }
114 }
115 }
116 xcb::Event::X(x::Event::Expose(ev)) => {
117 let window = {
118 let state = self.state.lock();
119 Arc::clone(&state.windows[&ev.window()])
120 };
121 window.expose();
122 }
123 xcb::Event::X(x::Event::ConfigureNotify(ev)) => {
124 let bounds = Bounds {
125 origin: Point {
126 x: ev.x().into(),
127 y: ev.y().into(),
128 },
129 size: Size {
130 width: ev.width().into(),
131 height: ev.height().into(),
132 },
133 };
134 let window = {
135 let state = self.state.lock();
136 Arc::clone(&state.windows[&ev.window()])
137 };
138 window.configure(bounds)
139 }
140 _ => {}
141 }
142
143 if let Ok(runnable) = self.main_receiver.try_recv() {
144 runnable.run();
145 }
146 }
147 }
148
149 fn quit(&self) {
150 self.state.lock().quit_requested = true;
151 }
152
153 fn restart(&self) {}
154
155 fn activate(&self, ignoring_other_apps: bool) {}
156
157 fn hide(&self) {}
158
159 fn hide_other_apps(&self) {}
160
161 fn unhide_other_apps(&self) {}
162
163 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
164 let setup = self.xcb_connection.get_setup();
165 setup
166 .roots()
167 .enumerate()
168 .map(|(root_id, _)| {
169 Rc::new(LinuxDisplay::new(&self.xcb_connection, root_id as i32))
170 as Rc<dyn PlatformDisplay>
171 })
172 .collect()
173 }
174
175 fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
176 Some(Rc::new(LinuxDisplay::new(
177 &self.xcb_connection,
178 id.0 as i32,
179 )))
180 }
181
182 fn active_window(&self) -> Option<AnyWindowHandle> {
183 None
184 }
185
186 fn open_window(
187 &self,
188 handle: AnyWindowHandle,
189 options: WindowOptions,
190 ) -> Box<dyn PlatformWindow> {
191 let x_window = self.xcb_connection.generate_id();
192
193 let window_ptr = Arc::new(LinuxWindowState::new(
194 options,
195 &self.xcb_connection,
196 self.x_root_index,
197 x_window,
198 &self.atoms,
199 ));
200
201 self.state
202 .lock()
203 .windows
204 .insert(x_window, Arc::clone(&window_ptr));
205 Box::new(LinuxWindow(window_ptr))
206 }
207
208 fn set_display_link_output_callback(
209 &self,
210 display_id: DisplayId,
211 callback: Box<dyn FnMut() + Send>,
212 ) {
213 log::warn!("unimplemented: set_display_link_output_callback");
214 }
215
216 fn start_display_link(&self, display_id: DisplayId) {}
217
218 fn stop_display_link(&self, display_id: DisplayId) {}
219
220 fn open_url(&self, url: &str) {}
221
222 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {}
223
224 fn prompt_for_paths(
225 &self,
226 options: PathPromptOptions,
227 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
228 unimplemented!()
229 }
230
231 fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
232 unimplemented!()
233 }
234
235 fn reveal_path(&self, path: &Path) {}
236
237 fn on_become_active(&self, callback: Box<dyn FnMut()>) {}
238
239 fn on_resign_active(&self, callback: Box<dyn FnMut()>) {}
240
241 fn on_quit(&self, callback: Box<dyn FnMut()>) {}
242
243 fn on_reopen(&self, callback: Box<dyn FnMut()>) {}
244
245 fn on_event(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {}
246
247 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {}
248
249 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {}
250
251 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {}
252
253 fn os_name(&self) -> &'static str {
254 "Linux"
255 }
256
257 fn double_click_interval(&self) -> Duration {
258 Duration::default()
259 }
260
261 fn os_version(&self) -> Result<SemanticVersion> {
262 Ok(SemanticVersion {
263 major: 1,
264 minor: 0,
265 patch: 0,
266 })
267 }
268
269 fn app_version(&self) -> Result<SemanticVersion> {
270 Ok(SemanticVersion {
271 major: 1,
272 minor: 0,
273 patch: 0,
274 })
275 }
276
277 fn app_path(&self) -> Result<PathBuf> {
278 unimplemented!()
279 }
280
281 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
282
283 fn local_timezone(&self) -> UtcOffset {
284 UtcOffset::UTC
285 }
286
287 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
288 unimplemented!()
289 }
290
291 fn set_cursor_style(&self, style: CursorStyle) {}
292
293 fn should_auto_hide_scrollbars(&self) -> bool {
294 false
295 }
296
297 fn write_to_clipboard(&self, item: ClipboardItem) {}
298
299 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
300 None
301 }
302
303 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
304 unimplemented!()
305 }
306
307 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
308 unimplemented!()
309 }
310
311 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
312 unimplemented!()
313 }
314}
315
316#[cfg(test)]
317mod tests {
318 use crate::ClipboardItem;
319
320 use super::*;
321
322 fn build_platform() -> LinuxPlatform {
323 let platform = LinuxPlatform::new();
324 platform
325 }
326}