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