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