platform.rs

  1#![allow(unused)]
  2
  3use std::env;
  4use std::{
  5    path::{Path, PathBuf},
  6    rc::Rc,
  7    sync::Arc,
  8    time::Duration,
  9};
 10
 11use async_task::Runnable;
 12use flume::{Receiver, Sender};
 13use futures::channel::oneshot;
 14use parking_lot::Mutex;
 15use time::UtcOffset;
 16use wayland_client::Connection;
 17
 18use crate::platform::linux::client::Client;
 19use crate::platform::linux::client_dispatcher::ClientDispatcher;
 20use crate::platform::linux::wayland::{WaylandClient, WaylandClientDispatcher};
 21use crate::platform::{X11Client, X11ClientDispatcher, XcbAtoms};
 22use crate::{
 23    Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DisplayId,
 24    ForegroundExecutor, Keymap, LinuxDispatcher, LinuxTextSystem, Menu, PathPromptOptions,
 25    Platform, PlatformDisplay, PlatformInput, PlatformTextSystem, PlatformWindow, Result,
 26    SemanticVersion, Task, WindowOptions,
 27};
 28
 29#[derive(Default)]
 30pub(crate) struct Callbacks {
 31    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 32    become_active: Option<Box<dyn FnMut()>>,
 33    resign_active: Option<Box<dyn FnMut()>>,
 34    pub(crate) quit: Option<Box<dyn FnMut()>>,
 35    reopen: Option<Box<dyn FnMut()>>,
 36    event: Option<Box<dyn FnMut(PlatformInput) -> bool>>,
 37    app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
 38    will_open_app_menu: Option<Box<dyn FnMut()>>,
 39    validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 40}
 41
 42pub(crate) struct LinuxPlatformInner {
 43    pub(crate) background_executor: BackgroundExecutor,
 44    pub(crate) foreground_executor: ForegroundExecutor,
 45    pub(crate) main_receiver: flume::Receiver<Runnable>,
 46    pub(crate) text_system: Arc<LinuxTextSystem>,
 47    pub(crate) callbacks: Mutex<Callbacks>,
 48    pub(crate) state: Mutex<LinuxPlatformState>,
 49}
 50
 51pub(crate) struct LinuxPlatform {
 52    client: Arc<dyn Client>,
 53    inner: Arc<LinuxPlatformInner>,
 54}
 55
 56pub(crate) struct LinuxPlatformState {
 57    pub(crate) quit_requested: bool,
 58}
 59
 60impl Default for LinuxPlatform {
 61    fn default() -> Self {
 62        Self::new()
 63    }
 64}
 65
 66impl LinuxPlatform {
 67    pub(crate) fn new() -> Self {
 68        let wayland_display = env::var_os("WAYLAND_DISPLAY");
 69        let use_wayland = wayland_display.is_some() && !wayland_display.unwrap().is_empty();
 70
 71        let (main_sender, main_receiver) = flume::unbounded::<Runnable>();
 72        let text_system = Arc::new(LinuxTextSystem::new());
 73        let callbacks = Mutex::new(Callbacks::default());
 74        let state = Mutex::new(LinuxPlatformState {
 75            quit_requested: false,
 76        });
 77
 78        if use_wayland {
 79            Self::new_wayland(main_sender, main_receiver, text_system, callbacks, state)
 80        } else {
 81            Self::new_x11(main_sender, main_receiver, text_system, callbacks, state)
 82        }
 83    }
 84
 85    fn new_wayland(
 86        main_sender: Sender<Runnable>,
 87        main_receiver: Receiver<Runnable>,
 88        text_system: Arc<LinuxTextSystem>,
 89        callbacks: Mutex<Callbacks>,
 90        state: Mutex<LinuxPlatformState>,
 91    ) -> Self {
 92        let conn = Arc::new(Connection::connect_to_env().unwrap());
 93        let client_dispatcher: Arc<dyn ClientDispatcher + Send + Sync> =
 94            Arc::new(WaylandClientDispatcher::new(&conn));
 95        let dispatcher = Arc::new(LinuxDispatcher::new(main_sender, &client_dispatcher));
 96        let inner = Arc::new(LinuxPlatformInner {
 97            background_executor: BackgroundExecutor::new(dispatcher.clone()),
 98            foreground_executor: ForegroundExecutor::new(dispatcher.clone()),
 99            main_receiver,
100            text_system,
101            callbacks,
102            state,
103        });
104        let client = Arc::new(WaylandClient::new(Arc::clone(&inner), Arc::clone(&conn)));
105        Self {
106            client,
107            inner: Arc::clone(&inner),
108        }
109    }
110
111    fn new_x11(
112        main_sender: Sender<Runnable>,
113        main_receiver: Receiver<Runnable>,
114        text_system: Arc<LinuxTextSystem>,
115        callbacks: Mutex<Callbacks>,
116        state: Mutex<LinuxPlatformState>,
117    ) -> Self {
118        let (xcb_connection, x_root_index) =
119            xcb::Connection::connect_with_extensions(None, &[xcb::Extension::Present], &[])
120                .unwrap();
121        let atoms = XcbAtoms::intern_all(&xcb_connection).unwrap();
122        let xcb_connection = Arc::new(xcb_connection);
123        let client_dispatcher: Arc<dyn ClientDispatcher + Send + Sync> =
124            Arc::new(X11ClientDispatcher::new(&xcb_connection, x_root_index));
125        let dispatcher = Arc::new(LinuxDispatcher::new(main_sender, &client_dispatcher));
126        let inner = Arc::new(LinuxPlatformInner {
127            background_executor: BackgroundExecutor::new(dispatcher.clone()),
128            foreground_executor: ForegroundExecutor::new(dispatcher.clone()),
129            main_receiver,
130            text_system,
131            callbacks,
132            state,
133        });
134        let client = Arc::new(X11Client::new(
135            Arc::clone(&inner),
136            xcb_connection,
137            x_root_index,
138            atoms,
139        ));
140        Self {
141            client,
142            inner: Arc::clone(&inner),
143        }
144    }
145}
146
147impl Platform for LinuxPlatform {
148    fn background_executor(&self) -> BackgroundExecutor {
149        self.inner.background_executor.clone()
150    }
151
152    fn foreground_executor(&self) -> ForegroundExecutor {
153        self.inner.foreground_executor.clone()
154    }
155
156    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
157        self.inner.text_system.clone()
158    }
159
160    fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
161        self.client.run(on_finish_launching)
162    }
163
164    fn quit(&self) {
165        self.inner.state.lock().quit_requested = true;
166    }
167
168    //todo!(linux)
169    fn restart(&self) {}
170
171    //todo!(linux)
172    fn activate(&self, ignoring_other_apps: bool) {}
173
174    //todo!(linux)
175    fn hide(&self) {}
176
177    //todo!(linux)
178    fn hide_other_apps(&self) {}
179
180    //todo!(linux)
181    fn unhide_other_apps(&self) {}
182
183    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
184        self.client.displays()
185    }
186
187    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
188        self.client.display(id)
189    }
190
191    //todo!(linux)
192    fn active_window(&self) -> Option<AnyWindowHandle> {
193        None
194    }
195
196    fn open_window(
197        &self,
198        handle: AnyWindowHandle,
199        options: WindowOptions,
200    ) -> Box<dyn PlatformWindow> {
201        self.client.open_window(handle, options)
202    }
203
204    fn open_url(&self, url: &str) {
205        unimplemented!()
206    }
207
208    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
209        self.inner.callbacks.lock().open_urls = Some(callback);
210    }
211
212    fn prompt_for_paths(
213        &self,
214        options: PathPromptOptions,
215    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
216        unimplemented!()
217    }
218
219    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
220        unimplemented!()
221    }
222
223    fn reveal_path(&self, path: &Path) {
224        unimplemented!()
225    }
226
227    fn on_become_active(&self, callback: Box<dyn FnMut()>) {
228        self.inner.callbacks.lock().become_active = Some(callback);
229    }
230
231    fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
232        self.inner.callbacks.lock().resign_active = Some(callback);
233    }
234
235    fn on_quit(&self, callback: Box<dyn FnMut()>) {
236        self.inner.callbacks.lock().quit = Some(callback);
237    }
238
239    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
240        self.inner.callbacks.lock().reopen = Some(callback);
241    }
242
243    fn on_event(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
244        self.inner.callbacks.lock().event = Some(callback);
245    }
246
247    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
248        self.inner.callbacks.lock().app_menu_action = Some(callback);
249    }
250
251    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
252        self.inner.callbacks.lock().will_open_app_menu = Some(callback);
253    }
254
255    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
256        self.inner.callbacks.lock().validate_app_menu_command = Some(callback);
257    }
258
259    fn os_name(&self) -> &'static str {
260        "Linux"
261    }
262
263    fn double_click_interval(&self) -> Duration {
264        Duration::default()
265    }
266
267    fn os_version(&self) -> Result<SemanticVersion> {
268        Ok(SemanticVersion {
269            major: 1,
270            minor: 0,
271            patch: 0,
272        })
273    }
274
275    fn app_version(&self) -> Result<SemanticVersion> {
276        Ok(SemanticVersion {
277            major: 1,
278            minor: 0,
279            patch: 0,
280        })
281    }
282
283    fn app_path(&self) -> Result<PathBuf> {
284        unimplemented!()
285    }
286
287    //todo!(linux)
288    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
289
290    fn local_timezone(&self) -> UtcOffset {
291        UtcOffset::UTC
292    }
293
294    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
295        unimplemented!()
296    }
297
298    //todo!(linux)
299    fn set_cursor_style(&self, style: CursorStyle) {}
300
301    //todo!(linux)
302    fn should_auto_hide_scrollbars(&self) -> bool {
303        false
304    }
305
306    //todo!(linux)
307    fn write_to_clipboard(&self, item: ClipboardItem) {}
308
309    //todo!(linux)
310    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
311        None
312    }
313
314    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
315        unimplemented!()
316    }
317
318    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
319        unimplemented!()
320    }
321
322    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
323        unimplemented!()
324    }
325
326    fn window_appearance(&self) -> crate::WindowAppearance {
327        crate::WindowAppearance::Light
328    }
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334
335    fn build_platform() -> LinuxPlatform {
336        let platform = LinuxPlatform::new();
337        platform
338    }
339}