platform.rs

  1#![allow(unused)]
  2
  3use std::cell::RefCell;
  4use std::env;
  5use std::{
  6    path::{Path, PathBuf},
  7    rc::Rc,
  8    sync::Arc,
  9    time::Duration,
 10};
 11
 12use ashpd::desktop::file_chooser::{OpenFileRequest, SaveFileRequest};
 13use async_task::Runnable;
 14use calloop::{EventLoop, LoopHandle, LoopSignal};
 15use flume::{Receiver, Sender};
 16use futures::channel::oneshot;
 17use parking_lot::Mutex;
 18use time::UtcOffset;
 19use wayland_client::Connection;
 20
 21use crate::platform::linux::client::Client;
 22use crate::platform::linux::wayland::WaylandClient;
 23use crate::{
 24    Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DisplayId,
 25    ForegroundExecutor, Keymap, LinuxDispatcher, LinuxTextSystem, Menu, PathPromptOptions,
 26    Platform, PlatformDisplay, PlatformInput, PlatformTextSystem, PlatformWindow, Result,
 27    SemanticVersion, Task, WindowOptions,
 28};
 29
 30use super::x11::X11Client;
 31
 32#[derive(Default)]
 33pub(crate) struct Callbacks {
 34    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 35    become_active: Option<Box<dyn FnMut()>>,
 36    resign_active: Option<Box<dyn FnMut()>>,
 37    quit: Option<Box<dyn FnMut()>>,
 38    reopen: Option<Box<dyn FnMut()>>,
 39    event: Option<Box<dyn FnMut(PlatformInput) -> bool>>,
 40    app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
 41    will_open_app_menu: Option<Box<dyn FnMut()>>,
 42    validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 43}
 44
 45pub(crate) struct LinuxPlatformInner {
 46    pub(crate) event_loop: RefCell<EventLoop<'static, ()>>,
 47    pub(crate) loop_handle: Rc<LoopHandle<'static, ()>>,
 48    pub(crate) loop_signal: LoopSignal,
 49    pub(crate) background_executor: BackgroundExecutor,
 50    pub(crate) foreground_executor: ForegroundExecutor,
 51    pub(crate) text_system: Arc<LinuxTextSystem>,
 52    pub(crate) callbacks: RefCell<Callbacks>,
 53}
 54
 55pub(crate) struct LinuxPlatform {
 56    client: Rc<dyn Client>,
 57    inner: Rc<LinuxPlatformInner>,
 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) = calloop::channel::channel::<Runnable>();
 72        let text_system = Arc::new(LinuxTextSystem::new());
 73        let callbacks = RefCell::new(Callbacks::default());
 74
 75        let event_loop = EventLoop::try_new().unwrap();
 76        event_loop
 77            .handle()
 78            .insert_source(main_receiver, |event, _, _| {
 79                if let calloop::channel::Event::Msg(runnable) = event {
 80                    runnable.run();
 81                }
 82            });
 83
 84        let dispatcher = Arc::new(LinuxDispatcher::new(main_sender));
 85
 86        let inner = Rc::new(LinuxPlatformInner {
 87            loop_handle: Rc::new(event_loop.handle()),
 88            loop_signal: event_loop.get_signal(),
 89            event_loop: RefCell::new(event_loop),
 90            background_executor: BackgroundExecutor::new(dispatcher.clone()),
 91            foreground_executor: ForegroundExecutor::new(dispatcher.clone()),
 92            text_system,
 93            callbacks,
 94        });
 95
 96        if use_wayland {
 97            Self {
 98                client: Rc::new(WaylandClient::new(Rc::clone(&inner))),
 99                inner,
100            }
101        } else {
102            Self {
103                client: X11Client::new(Rc::clone(&inner)),
104                inner,
105            }
106        }
107    }
108}
109
110impl Platform for LinuxPlatform {
111    fn background_executor(&self) -> BackgroundExecutor {
112        self.inner.background_executor.clone()
113    }
114
115    fn foreground_executor(&self) -> ForegroundExecutor {
116        self.inner.foreground_executor.clone()
117    }
118
119    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
120        self.inner.text_system.clone()
121    }
122
123    fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
124        on_finish_launching();
125
126        self.inner
127            .event_loop
128            .borrow_mut()
129            .run(None, &mut (), |&mut ()| {})
130            .expect("Run loop failed");
131
132        if let Some(mut fun) = self.inner.callbacks.borrow_mut().quit.take() {
133            fun();
134        }
135    }
136
137    fn quit(&self) {
138        self.inner.loop_signal.stop();
139    }
140
141    // todo(linux)
142    fn restart(&self) {}
143
144    // todo(linux)
145    fn activate(&self, ignoring_other_apps: bool) {}
146
147    // todo(linux)
148    fn hide(&self) {}
149
150    // todo(linux)
151    fn hide_other_apps(&self) {}
152
153    // todo(linux)
154    fn unhide_other_apps(&self) {}
155
156    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
157        self.client.displays()
158    }
159
160    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
161        self.client.display(id)
162    }
163
164    // todo(linux)
165    fn active_window(&self) -> Option<AnyWindowHandle> {
166        None
167    }
168
169    fn open_window(
170        &self,
171        handle: AnyWindowHandle,
172        options: WindowOptions,
173    ) -> Box<dyn PlatformWindow> {
174        self.client.open_window(handle, options)
175    }
176
177    fn open_url(&self, url: &str) {
178        open::that(url);
179    }
180
181    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
182        self.inner.callbacks.borrow_mut().open_urls = Some(callback);
183    }
184
185    fn prompt_for_paths(
186        &self,
187        options: PathPromptOptions,
188    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
189        let (done_tx, done_rx) = oneshot::channel();
190        self.inner
191            .foreground_executor
192            .spawn(async move {
193                let title = if options.multiple {
194                    if !options.files {
195                        "Open folders"
196                    } else {
197                        "Open files"
198                    }
199                } else {
200                    if !options.files {
201                        "Open folder"
202                    } else {
203                        "Open file"
204                    }
205                };
206
207                let result = OpenFileRequest::default()
208                    .modal(true)
209                    .title(title)
210                    .accept_label("Select")
211                    .multiple(options.multiple)
212                    .directory(options.directories)
213                    .send()
214                    .await
215                    .ok()
216                    .and_then(|request| request.response().ok())
217                    .and_then(|response| {
218                        response
219                            .uris()
220                            .iter()
221                            .map(|uri| uri.to_file_path().ok())
222                            .collect()
223                    });
224
225                done_tx.send(result);
226            })
227            .detach();
228        done_rx
229    }
230
231    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
232        let (done_tx, done_rx) = oneshot::channel();
233        let directory = directory.to_owned();
234        self.inner
235            .foreground_executor
236            .spawn(async move {
237                let result = SaveFileRequest::default()
238                    .modal(true)
239                    .title("Select new path")
240                    .accept_label("Accept")
241                    .send()
242                    .await
243                    .ok()
244                    .and_then(|request| request.response().ok())
245                    .and_then(|response| {
246                        response
247                            .uris()
248                            .first()
249                            .and_then(|uri| uri.to_file_path().ok())
250                    });
251
252                done_tx.send(result);
253            })
254            .detach();
255        done_rx
256    }
257
258    fn reveal_path(&self, path: &Path) {
259        if path.is_dir() {
260            open::that(path);
261            return;
262        }
263        // If `path` is a file, the system may try to open it in a text editor
264        let dir = path.parent().unwrap_or(Path::new(""));
265        open::that(dir);
266    }
267
268    fn on_become_active(&self, callback: Box<dyn FnMut()>) {
269        self.inner.callbacks.borrow_mut().become_active = Some(callback);
270    }
271
272    fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
273        self.inner.callbacks.borrow_mut().resign_active = Some(callback);
274    }
275
276    fn on_quit(&self, callback: Box<dyn FnMut()>) {
277        self.inner.callbacks.borrow_mut().quit = Some(callback);
278    }
279
280    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
281        self.inner.callbacks.borrow_mut().reopen = Some(callback);
282    }
283
284    fn on_event(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
285        self.inner.callbacks.borrow_mut().event = Some(callback);
286    }
287
288    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
289        self.inner.callbacks.borrow_mut().app_menu_action = Some(callback);
290    }
291
292    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
293        self.inner.callbacks.borrow_mut().will_open_app_menu = Some(callback);
294    }
295
296    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
297        self.inner.callbacks.borrow_mut().validate_app_menu_command = Some(callback);
298    }
299
300    fn os_name(&self) -> &'static str {
301        "Linux"
302    }
303
304    fn double_click_interval(&self) -> Duration {
305        Duration::default()
306    }
307
308    fn os_version(&self) -> Result<SemanticVersion> {
309        Ok(SemanticVersion {
310            major: 1,
311            minor: 0,
312            patch: 0,
313        })
314    }
315
316    fn app_version(&self) -> Result<SemanticVersion> {
317        Ok(SemanticVersion {
318            major: 1,
319            minor: 0,
320            patch: 0,
321        })
322    }
323
324    fn app_path(&self) -> Result<PathBuf> {
325        unimplemented!()
326    }
327
328    // todo(linux)
329    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
330
331    fn local_timezone(&self) -> UtcOffset {
332        UtcOffset::UTC
333    }
334
335    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
336        unimplemented!()
337    }
338
339    // todo(linux)
340    fn set_cursor_style(&self, style: CursorStyle) {}
341
342    // todo(linux)
343    fn should_auto_hide_scrollbars(&self) -> bool {
344        false
345    }
346
347    // todo(linux)
348    fn write_to_clipboard(&self, item: ClipboardItem) {}
349
350    // todo(linux)
351    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
352        None
353    }
354
355    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
356        unimplemented!()
357    }
358
359    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
360        unimplemented!()
361    }
362
363    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
364        unimplemented!()
365    }
366
367    fn window_appearance(&self) -> crate::WindowAppearance {
368        crate::WindowAppearance::Light
369    }
370}
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375
376    fn build_platform() -> LinuxPlatform {
377        let platform = LinuxPlatform::new();
378        platform
379    }
380}