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 anyhow::anyhow;
 13use ashpd::desktop::file_chooser::{OpenFileRequest, SaveFileRequest};
 14use async_task::Runnable;
 15use calloop::{EventLoop, LoopHandle, LoopSignal};
 16use flume::{Receiver, Sender};
 17use futures::channel::oneshot;
 18use parking_lot::Mutex;
 19use time::UtcOffset;
 20use wayland_client::Connection;
 21
 22use crate::platform::linux::client::Client;
 23use crate::platform::linux::wayland::WaylandClient;
 24use crate::{
 25    Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DisplayId,
 26    ForegroundExecutor, Keymap, LinuxDispatcher, LinuxTextSystem, Menu, PathPromptOptions,
 27    Platform, PlatformDisplay, PlatformInput, PlatformTextSystem, PlatformWindow, Result,
 28    SemanticVersion, Task, WindowOptions,
 29};
 30
 31use super::x11::X11Client;
 32
 33#[derive(Default)]
 34pub(crate) struct Callbacks {
 35    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 36    become_active: Option<Box<dyn FnMut()>>,
 37    resign_active: Option<Box<dyn FnMut()>>,
 38    quit: Option<Box<dyn FnMut()>>,
 39    reopen: Option<Box<dyn FnMut()>>,
 40    event: Option<Box<dyn FnMut(PlatformInput) -> bool>>,
 41    app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
 42    will_open_app_menu: Option<Box<dyn FnMut()>>,
 43    validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 44}
 45
 46pub(crate) struct LinuxPlatformInner {
 47    pub(crate) event_loop: RefCell<EventLoop<'static, ()>>,
 48    pub(crate) loop_handle: Rc<LoopHandle<'static, ()>>,
 49    pub(crate) loop_signal: LoopSignal,
 50    pub(crate) background_executor: BackgroundExecutor,
 51    pub(crate) foreground_executor: ForegroundExecutor,
 52    pub(crate) text_system: Arc<LinuxTextSystem>,
 53    pub(crate) callbacks: RefCell<Callbacks>,
 54}
 55
 56pub(crate) struct LinuxPlatform {
 57    client: Rc<dyn Client>,
 58    inner: Rc<LinuxPlatformInner>,
 59}
 60
 61impl Default for LinuxPlatform {
 62    fn default() -> Self {
 63        Self::new()
 64    }
 65}
 66
 67impl LinuxPlatform {
 68    pub(crate) fn new() -> Self {
 69        let wayland_display = env::var_os("WAYLAND_DISPLAY");
 70        let use_wayland = wayland_display.is_some() && !wayland_display.unwrap().is_empty();
 71
 72        let (main_sender, main_receiver) = calloop::channel::channel::<Runnable>();
 73        let text_system = Arc::new(LinuxTextSystem::new());
 74        let callbacks = RefCell::new(Callbacks::default());
 75
 76        let event_loop = EventLoop::try_new().unwrap();
 77        event_loop
 78            .handle()
 79            .insert_source(main_receiver, |event, _, _| {
 80                if let calloop::channel::Event::Msg(runnable) = event {
 81                    runnable.run();
 82                }
 83            });
 84
 85        let dispatcher = Arc::new(LinuxDispatcher::new(main_sender));
 86
 87        let inner = Rc::new(LinuxPlatformInner {
 88            loop_handle: Rc::new(event_loop.handle()),
 89            loop_signal: event_loop.get_signal(),
 90            event_loop: RefCell::new(event_loop),
 91            background_executor: BackgroundExecutor::new(dispatcher.clone()),
 92            foreground_executor: ForegroundExecutor::new(dispatcher.clone()),
 93            text_system,
 94            callbacks,
 95        });
 96
 97        if use_wayland {
 98            Self {
 99                client: Rc::new(WaylandClient::new(Rc::clone(&inner))),
100                inner,
101            }
102        } else {
103            Self {
104                client: X11Client::new(Rc::clone(&inner)),
105                inner,
106            }
107        }
108    }
109}
110
111const KEYRING_LABEL: &str = "zed-github-account";
112
113impl Platform for LinuxPlatform {
114    fn background_executor(&self) -> BackgroundExecutor {
115        self.inner.background_executor.clone()
116    }
117
118    fn foreground_executor(&self) -> ForegroundExecutor {
119        self.inner.foreground_executor.clone()
120    }
121
122    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
123        self.inner.text_system.clone()
124    }
125
126    fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
127        on_finish_launching();
128
129        self.inner
130            .event_loop
131            .borrow_mut()
132            .run(None, &mut (), |&mut ()| {})
133            .expect("Run loop failed");
134
135        if let Some(mut fun) = self.inner.callbacks.borrow_mut().quit.take() {
136            fun();
137        }
138    }
139
140    fn quit(&self) {
141        self.inner.loop_signal.stop();
142    }
143
144    // todo(linux)
145    fn restart(&self) {}
146
147    // todo(linux)
148    fn activate(&self, ignoring_other_apps: bool) {}
149
150    // todo(linux)
151    fn hide(&self) {}
152
153    // todo(linux)
154    fn hide_other_apps(&self) {}
155
156    // todo(linux)
157    fn unhide_other_apps(&self) {}
158
159    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
160        self.client.displays()
161    }
162
163    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
164        self.client.display(id)
165    }
166
167    // todo(linux)
168    fn active_window(&self) -> Option<AnyWindowHandle> {
169        None
170    }
171
172    fn open_window(
173        &self,
174        handle: AnyWindowHandle,
175        options: WindowOptions,
176    ) -> Box<dyn PlatformWindow> {
177        self.client.open_window(handle, options)
178    }
179
180    fn open_url(&self, url: &str) {
181        open::that(url);
182    }
183
184    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
185        self.inner.callbacks.borrow_mut().open_urls = Some(callback);
186    }
187
188    fn prompt_for_paths(
189        &self,
190        options: PathPromptOptions,
191    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
192        let (done_tx, done_rx) = oneshot::channel();
193        self.inner
194            .foreground_executor
195            .spawn(async move {
196                let title = if options.multiple {
197                    if !options.files {
198                        "Open folders"
199                    } else {
200                        "Open files"
201                    }
202                } else {
203                    if !options.files {
204                        "Open folder"
205                    } else {
206                        "Open file"
207                    }
208                };
209
210                let result = OpenFileRequest::default()
211                    .modal(true)
212                    .title(title)
213                    .accept_label("Select")
214                    .multiple(options.multiple)
215                    .directory(options.directories)
216                    .send()
217                    .await
218                    .ok()
219                    .and_then(|request| request.response().ok())
220                    .and_then(|response| {
221                        response
222                            .uris()
223                            .iter()
224                            .map(|uri| uri.to_file_path().ok())
225                            .collect()
226                    });
227
228                done_tx.send(result);
229            })
230            .detach();
231        done_rx
232    }
233
234    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
235        let (done_tx, done_rx) = oneshot::channel();
236        let directory = directory.to_owned();
237        self.inner
238            .foreground_executor
239            .spawn(async move {
240                let result = SaveFileRequest::default()
241                    .modal(true)
242                    .title("Select new path")
243                    .accept_label("Accept")
244                    .send()
245                    .await
246                    .ok()
247                    .and_then(|request| request.response().ok())
248                    .and_then(|response| {
249                        response
250                            .uris()
251                            .first()
252                            .and_then(|uri| uri.to_file_path().ok())
253                    });
254
255                done_tx.send(result);
256            })
257            .detach();
258        done_rx
259    }
260
261    fn reveal_path(&self, path: &Path) {
262        if path.is_dir() {
263            open::that(path);
264            return;
265        }
266        // If `path` is a file, the system may try to open it in a text editor
267        let dir = path.parent().unwrap_or(Path::new(""));
268        open::that(dir);
269    }
270
271    fn on_become_active(&self, callback: Box<dyn FnMut()>) {
272        self.inner.callbacks.borrow_mut().become_active = Some(callback);
273    }
274
275    fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
276        self.inner.callbacks.borrow_mut().resign_active = Some(callback);
277    }
278
279    fn on_quit(&self, callback: Box<dyn FnMut()>) {
280        self.inner.callbacks.borrow_mut().quit = Some(callback);
281    }
282
283    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
284        self.inner.callbacks.borrow_mut().reopen = Some(callback);
285    }
286
287    fn on_event(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
288        self.inner.callbacks.borrow_mut().event = Some(callback);
289    }
290
291    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
292        self.inner.callbacks.borrow_mut().app_menu_action = Some(callback);
293    }
294
295    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
296        self.inner.callbacks.borrow_mut().will_open_app_menu = Some(callback);
297    }
298
299    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
300        self.inner.callbacks.borrow_mut().validate_app_menu_command = Some(callback);
301    }
302
303    fn os_name(&self) -> &'static str {
304        "Linux"
305    }
306
307    fn double_click_interval(&self) -> Duration {
308        Duration::default()
309    }
310
311    fn os_version(&self) -> Result<SemanticVersion> {
312        Ok(SemanticVersion {
313            major: 1,
314            minor: 0,
315            patch: 0,
316        })
317    }
318
319    fn app_version(&self) -> Result<SemanticVersion> {
320        Ok(SemanticVersion {
321            major: 1,
322            minor: 0,
323            patch: 0,
324        })
325    }
326
327    //todo!(linux)
328    fn app_path(&self) -> Result<PathBuf> {
329        Err(anyhow::Error::msg(
330            "Platform<LinuxPlatform>::app_path is not implemented yet",
331        ))
332    }
333
334    // todo(linux)
335    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
336
337    fn local_timezone(&self) -> UtcOffset {
338        UtcOffset::UTC
339    }
340
341    //todo!(linux)
342    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
343        Err(anyhow::Error::msg(
344            "Platform<LinuxPlatform>::path_for_auxiliary_executable is not implemented yet",
345        ))
346    }
347
348    fn set_cursor_style(&self, style: CursorStyle) {
349        self.client.set_cursor_style(style)
350    }
351
352    // todo(linux)
353    fn should_auto_hide_scrollbars(&self) -> bool {
354        false
355    }
356
357    fn write_to_clipboard(&self, item: ClipboardItem) {
358        let clipboard = self.client.get_clipboard();
359        clipboard.borrow_mut().set_contents(item.text);
360    }
361
362    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
363        let clipboard = self.client.get_clipboard();
364        let contents = clipboard.borrow_mut().get_contents();
365        match contents {
366            Ok(text) => Some(ClipboardItem {
367                metadata: None,
368                text,
369            }),
370            _ => None,
371        }
372    }
373
374    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
375        let url = url.to_string();
376        let username = username.to_string();
377        let password = password.to_vec();
378        self.background_executor().spawn(async move {
379            let keyring = oo7::Keyring::new().await?;
380            keyring.unlock().await?;
381            keyring
382                .create_item(
383                    KEYRING_LABEL,
384                    &vec![("url", &url), ("username", &username)],
385                    password,
386                    true,
387                )
388                .await?;
389            Ok(())
390        })
391    }
392
393    //todo!(linux): add trait methods for accessing the primary selection
394
395    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
396        let url = url.to_string();
397        self.background_executor().spawn(async move {
398            let keyring = oo7::Keyring::new().await?;
399            keyring.unlock().await?;
400
401            let items = keyring.search_items(&vec![("url", &url)]).await?;
402
403            for item in items.into_iter() {
404                if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
405                    let attributes = item.attributes().await?;
406                    let username = attributes
407                        .get("username")
408                        .ok_or_else(|| anyhow!("Cannot find username in stored credentials"))?;
409                    let secret = item.secret().await?;
410
411                    // we lose the zeroizing capabilities at this boundary,
412                    // a current limitation GPUI's credentials api
413                    return Ok(Some((username.to_string(), secret.to_vec())));
414                } else {
415                    continue;
416                }
417            }
418            Ok(None)
419        })
420    }
421
422    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
423        let url = url.to_string();
424        self.background_executor().spawn(async move {
425            let keyring = oo7::Keyring::new().await?;
426            keyring.unlock().await?;
427
428            let items = keyring.search_items(&vec![("url", &url)]).await?;
429
430            for item in items.into_iter() {
431                if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
432                    item.delete().await?;
433                    return Ok(());
434                }
435            }
436
437            Ok(())
438        })
439    }
440
441    fn window_appearance(&self) -> crate::WindowAppearance {
442        crate::WindowAppearance::Light
443    }
444
445    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
446        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
447    }
448}
449
450#[cfg(test)]
451mod tests {
452    use super::*;
453
454    fn build_platform() -> LinuxPlatform {
455        let platform = LinuxPlatform::new();
456        platform
457    }
458}