1#![allow(unused)]
2
3use std::any::{type_name, Any};
4use std::cell::{self, RefCell};
5use std::env;
6use std::ffi::OsString;
7use std::fs::File;
8use std::io::Read;
9use std::ops::{Deref, DerefMut};
10use std::os::fd::{AsRawFd, FromRawFd};
11use std::panic::Location;
12use std::rc::Weak;
13use std::{
14 path::{Path, PathBuf},
15 process::Command,
16 rc::Rc,
17 sync::Arc,
18 time::Duration,
19};
20
21use anyhow::anyhow;
22use ashpd::desktop::file_chooser::{OpenFileRequest, SaveFileRequest};
23use async_task::Runnable;
24use calloop::channel::Channel;
25use calloop::{EventLoop, LoopHandle, LoopSignal};
26use filedescriptor::FileDescriptor;
27use flume::{Receiver, Sender};
28use futures::channel::oneshot;
29use mio::Waker;
30use parking_lot::Mutex;
31use time::UtcOffset;
32use util::ResultExt;
33use wayland_client::Connection;
34use wayland_protocols::wp::cursor_shape::v1::client::wp_cursor_shape_device_v1::Shape;
35use xkbcommon::xkb::{self, Keycode, Keysym, State};
36
37use crate::platform::linux::wayland::WaylandClient;
38use crate::{
39 px, Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CosmicTextSystem, CursorStyle,
40 DisplayId, ForegroundExecutor, Keymap, Keystroke, LinuxDispatcher, Menu, MenuItem, Modifiers,
41 OwnedMenu, PathPromptOptions, Pixels, Platform, PlatformDisplay, PlatformInputHandler,
42 PlatformTextSystem, PlatformWindow, Point, PromptLevel, Result, SemanticVersion, SharedString,
43 Size, Task, WindowAppearance, WindowOptions, WindowParams,
44};
45
46use super::x11::X11Client;
47
48pub(crate) const SCROLL_LINES: f64 = 3.0;
49
50// Values match the defaults on GTK.
51// Taken from https://github.com/GNOME/gtk/blob/main/gtk/gtksettings.c#L320
52pub(crate) const DOUBLE_CLICK_INTERVAL: Duration = Duration::from_millis(400);
53pub(crate) const DOUBLE_CLICK_DISTANCE: Pixels = px(5.0);
54pub(crate) const KEYRING_LABEL: &str = "zed-github-account";
55
56pub trait LinuxClient {
57 fn compositor_name(&self) -> &'static str;
58 fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R;
59 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
60 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
61 fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>>;
62
63 fn open_window(
64 &self,
65 handle: AnyWindowHandle,
66 options: WindowParams,
67 ) -> anyhow::Result<Box<dyn PlatformWindow>>;
68 fn set_cursor_style(&self, style: CursorStyle);
69 fn open_uri(&self, uri: &str);
70 fn write_to_primary(&self, item: ClipboardItem);
71 fn write_to_clipboard(&self, item: ClipboardItem);
72 fn read_from_primary(&self) -> Option<ClipboardItem>;
73 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
74 fn active_window(&self) -> Option<AnyWindowHandle>;
75 fn run(&self);
76}
77
78#[derive(Default)]
79pub(crate) struct PlatformHandlers {
80 pub(crate) open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
81 pub(crate) quit: Option<Box<dyn FnMut()>>,
82 pub(crate) reopen: Option<Box<dyn FnMut()>>,
83 pub(crate) app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
84 pub(crate) will_open_app_menu: Option<Box<dyn FnMut()>>,
85 pub(crate) validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
86}
87
88pub trait QuitSignal {
89 fn quit(&mut self);
90}
91
92impl QuitSignal for LoopSignal {
93 fn quit(&mut self) {
94 self.stop();
95 }
96}
97
98pub(crate) struct LinuxCommon {
99 pub(crate) background_executor: BackgroundExecutor,
100 pub(crate) foreground_executor: ForegroundExecutor,
101 pub(crate) text_system: Arc<CosmicTextSystem>,
102 pub(crate) appearance: WindowAppearance,
103 pub(crate) auto_hide_scrollbars: bool,
104 pub(crate) callbacks: PlatformHandlers,
105 pub(crate) quit_signal: Box<dyn QuitSignal>,
106 pub(crate) menus: Vec<OwnedMenu>,
107}
108
109impl LinuxCommon {
110 pub fn new(
111 quit_signal: Box<dyn QuitSignal>,
112 main_waker: Option<Arc<Waker>>,
113 ) -> (Self, Channel<Runnable>) {
114 let (main_sender, main_receiver) = calloop::channel::channel::<Runnable>();
115 let text_system = Arc::new(CosmicTextSystem::new());
116 let callbacks = PlatformHandlers::default();
117
118 let dispatcher = Arc::new(LinuxDispatcher::new(main_sender.clone(), main_waker));
119
120 let background_executor = BackgroundExecutor::new(dispatcher.clone());
121
122 let common = LinuxCommon {
123 background_executor,
124 foreground_executor: ForegroundExecutor::new(dispatcher.clone()),
125 text_system,
126 appearance: WindowAppearance::Light,
127 auto_hide_scrollbars: false,
128 callbacks,
129 quit_signal,
130 menus: Vec::new(),
131 };
132
133 (common, main_receiver)
134 }
135}
136
137impl<P: LinuxClient + 'static> Platform for P {
138 fn background_executor(&self) -> BackgroundExecutor {
139 self.with_common(|common| common.background_executor.clone())
140 }
141
142 fn foreground_executor(&self) -> ForegroundExecutor {
143 self.with_common(|common| common.foreground_executor.clone())
144 }
145
146 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
147 self.with_common(|common| common.text_system.clone())
148 }
149
150 fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
151 on_finish_launching();
152
153 LinuxClient::run(self);
154
155 self.with_common(|common| {
156 if let Some(mut fun) = common.callbacks.quit.take() {
157 fun();
158 }
159 });
160 }
161
162 fn quit(&self) {
163 self.with_common(|common| common.quit_signal.quit());
164 }
165
166 fn compositor_name(&self) -> &'static str {
167 self.compositor_name()
168 }
169
170 fn restart(&self, binary_path: Option<PathBuf>) {
171 use std::os::unix::process::CommandExt as _;
172
173 // get the process id of the current process
174 let app_pid = std::process::id().to_string();
175 // get the path to the executable
176 let app_path = if let Some(path) = binary_path {
177 path
178 } else {
179 match self.app_path() {
180 Ok(path) => path,
181 Err(err) => {
182 log::error!("Failed to get app path: {:?}", err);
183 return;
184 }
185 }
186 };
187
188 log::info!("Restarting process, using app path: {:?}", app_path);
189
190 // Script to wait for the current process to exit and then restart the app.
191 // We also wait for possibly open TCP sockets by the process to be closed,
192 // since on Linux it's not guaranteed that a process' resources have been
193 // cleaned up when `kill -0` returns.
194 let script = format!(
195 r#"
196 while kill -O {pid} 2>/dev/null; do
197 sleep 0.1
198 done
199
200 while lsof -nP -iTCP -a -p {pid} 2>/dev/null; do
201 sleep 0.1
202 done
203
204 {app_path}
205 "#,
206 pid = app_pid,
207 app_path = app_path.display()
208 );
209
210 // execute the script using /bin/bash
211 let restart_process = Command::new("/bin/bash")
212 .arg("-c")
213 .arg(script)
214 .process_group(0)
215 .spawn();
216
217 match restart_process {
218 Ok(_) => self.quit(),
219 Err(e) => log::error!("failed to spawn restart script: {:?}", e),
220 }
221 }
222
223 fn activate(&self, ignoring_other_apps: bool) {
224 log::info!("activate is not implemented on Linux, ignoring the call")
225 }
226
227 fn hide(&self) {
228 log::info!("hide is not implemented on Linux, ignoring the call")
229 }
230
231 fn hide_other_apps(&self) {
232 log::info!("hide_other_apps is not implemented on Linux, ignoring the call")
233 }
234
235 fn unhide_other_apps(&self) {
236 log::info!("unhide_other_apps is not implemented on Linux, ignoring the call")
237 }
238
239 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
240 self.primary_display()
241 }
242
243 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
244 self.displays()
245 }
246
247 fn active_window(&self) -> Option<AnyWindowHandle> {
248 self.active_window()
249 }
250
251 fn open_window(
252 &self,
253 handle: AnyWindowHandle,
254 options: WindowParams,
255 ) -> anyhow::Result<Box<dyn PlatformWindow>> {
256 self.open_window(handle, options)
257 }
258
259 fn open_url(&self, url: &str) {
260 self.open_uri(url);
261 }
262
263 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
264 self.with_common(|common| common.callbacks.open_urls = Some(callback));
265 }
266
267 fn prompt_for_paths(
268 &self,
269 options: PathPromptOptions,
270 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
271 let (done_tx, done_rx) = oneshot::channel();
272 self.foreground_executor()
273 .spawn(async move {
274 let title = if options.multiple {
275 if !options.files {
276 "Open folders"
277 } else {
278 "Open files"
279 }
280 } else {
281 if !options.files {
282 "Open folder"
283 } else {
284 "Open file"
285 }
286 };
287
288 let result = OpenFileRequest::default()
289 .modal(true)
290 .title(title)
291 .accept_label("Select")
292 .multiple(options.multiple)
293 .directory(options.directories)
294 .send()
295 .await
296 .ok()
297 .and_then(|request| request.response().ok())
298 .and_then(|response| {
299 response
300 .uris()
301 .iter()
302 .map(|uri| uri.to_file_path().ok())
303 .collect()
304 });
305
306 done_tx.send(result);
307 })
308 .detach();
309 done_rx
310 }
311
312 fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
313 let (done_tx, done_rx) = oneshot::channel();
314 let directory = directory.to_owned();
315 self.foreground_executor()
316 .spawn(async move {
317 let result = SaveFileRequest::default()
318 .modal(true)
319 .title("Select new path")
320 .accept_label("Accept")
321 .send()
322 .await
323 .ok()
324 .and_then(|request| request.response().ok())
325 .and_then(|response| {
326 response
327 .uris()
328 .first()
329 .and_then(|uri| uri.to_file_path().ok())
330 });
331
332 done_tx.send(result);
333 })
334 .detach();
335
336 done_rx
337 }
338
339 fn reveal_path(&self, path: &Path) {
340 if path.is_dir() {
341 open::that_detached(path);
342 return;
343 }
344 // If `path` is a file, the system may try to open it in a text editor
345 let dir = path.parent().unwrap_or(Path::new(""));
346 open::that_detached(dir);
347 }
348
349 fn on_quit(&self, callback: Box<dyn FnMut()>) {
350 self.with_common(|common| {
351 common.callbacks.quit = Some(callback);
352 });
353 }
354
355 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
356 self.with_common(|common| {
357 common.callbacks.reopen = Some(callback);
358 });
359 }
360
361 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
362 self.with_common(|common| {
363 common.callbacks.app_menu_action = Some(callback);
364 });
365 }
366
367 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
368 self.with_common(|common| {
369 common.callbacks.will_open_app_menu = Some(callback);
370 });
371 }
372
373 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
374 self.with_common(|common| {
375 common.callbacks.validate_app_menu_command = Some(callback);
376 });
377 }
378
379 fn app_path(&self) -> Result<PathBuf> {
380 // get the path of the executable of the current process
381 let exe_path = std::env::current_exe()?;
382 Ok(exe_path)
383 }
384
385 fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {
386 self.with_common(|common| {
387 common.menus = menus.into_iter().map(|menu| menu.owned()).collect();
388 })
389 }
390
391 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
392 self.with_common(|common| Some(common.menus.clone()))
393 }
394
395 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap) {}
396
397 fn local_timezone(&self) -> UtcOffset {
398 UtcOffset::UTC
399 }
400
401 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
402 Err(anyhow::Error::msg(
403 "Platform<LinuxPlatform>::path_for_auxiliary_executable is not implemented yet",
404 ))
405 }
406
407 fn set_cursor_style(&self, style: CursorStyle) {
408 self.set_cursor_style(style)
409 }
410
411 fn should_auto_hide_scrollbars(&self) -> bool {
412 self.with_common(|common| common.auto_hide_scrollbars)
413 }
414
415 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
416 let url = url.to_string();
417 let username = username.to_string();
418 let password = password.to_vec();
419 self.background_executor().spawn(async move {
420 let keyring = oo7::Keyring::new().await?;
421 keyring.unlock().await?;
422 keyring
423 .create_item(
424 KEYRING_LABEL,
425 &vec![("url", &url), ("username", &username)],
426 password,
427 true,
428 )
429 .await?;
430 Ok(())
431 })
432 }
433
434 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
435 let url = url.to_string();
436 self.background_executor().spawn(async move {
437 let keyring = oo7::Keyring::new().await?;
438 keyring.unlock().await?;
439
440 let items = keyring.search_items(&vec![("url", &url)]).await?;
441
442 for item in items.into_iter() {
443 if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
444 let attributes = item.attributes().await?;
445 let username = attributes
446 .get("username")
447 .ok_or_else(|| anyhow!("Cannot find username in stored credentials"))?;
448 let secret = item.secret().await?;
449
450 // we lose the zeroizing capabilities at this boundary,
451 // a current limitation GPUI's credentials api
452 return Ok(Some((username.to_string(), secret.to_vec())));
453 } else {
454 continue;
455 }
456 }
457 Ok(None)
458 })
459 }
460
461 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
462 let url = url.to_string();
463 self.background_executor().spawn(async move {
464 let keyring = oo7::Keyring::new().await?;
465 keyring.unlock().await?;
466
467 let items = keyring.search_items(&vec![("url", &url)]).await?;
468
469 for item in items.into_iter() {
470 if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
471 item.delete().await?;
472 return Ok(());
473 }
474 }
475
476 Ok(())
477 })
478 }
479
480 fn window_appearance(&self) -> WindowAppearance {
481 self.with_common(|common| common.appearance)
482 }
483
484 fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
485 Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
486 }
487
488 fn write_to_primary(&self, item: ClipboardItem) {
489 self.write_to_primary(item)
490 }
491
492 fn write_to_clipboard(&self, item: ClipboardItem) {
493 self.write_to_clipboard(item)
494 }
495
496 fn read_from_primary(&self) -> Option<ClipboardItem> {
497 self.read_from_primary()
498 }
499
500 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
501 self.read_from_clipboard()
502 }
503
504 fn add_recent_document(&self, _path: &Path) {}
505}
506
507pub(super) fn open_uri_internal(uri: &str, activation_token: Option<&str>) {
508 let mut last_err = None;
509 for mut command in open::commands(uri) {
510 if let Some(token) = activation_token {
511 command.env("XDG_ACTIVATION_TOKEN", token);
512 }
513 match command.spawn() {
514 Ok(_) => return,
515 Err(err) => last_err = Some(err),
516 }
517 }
518 log::error!("failed to open uri: {uri:?}, last error: {last_err:?}");
519}
520
521pub(super) fn is_within_click_distance(a: Point<Pixels>, b: Point<Pixels>) -> bool {
522 let diff = a - b;
523 diff.x.abs() <= DOUBLE_CLICK_DISTANCE && diff.y.abs() <= DOUBLE_CLICK_DISTANCE
524}
525
526pub(super) fn get_xkb_compose_state(cx: &xkb::Context) -> Option<xkb::compose::State> {
527 let mut locales = Vec::default();
528 if let Some(locale) = std::env::var_os("LC_CTYPE") {
529 locales.push(locale);
530 }
531 locales.push(OsString::from("C"));
532 let mut state: Option<xkb::compose::State> = None;
533 for locale in locales {
534 if let Ok(table) =
535 xkb::compose::Table::new_from_locale(&cx, &locale, xkb::compose::COMPILE_NO_FLAGS)
536 {
537 state = Some(xkb::compose::State::new(
538 &table,
539 xkb::compose::STATE_NO_FLAGS,
540 ));
541 break;
542 }
543 }
544 state
545}
546
547pub(super) unsafe fn read_fd(mut fd: FileDescriptor) -> Result<String> {
548 let mut file = File::from_raw_fd(fd.as_raw_fd());
549
550 let mut buffer = String::new();
551 file.read_to_string(&mut buffer)?;
552
553 // Normalize the text to unix line endings, otherwise
554 // copying from eg: firefox inserts a lot of blank
555 // lines, and that is super annoying.
556 let result = buffer.replace("\r\n", "\n");
557 Ok(result)
558}
559
560impl CursorStyle {
561 pub(super) fn to_shape(&self) -> Shape {
562 match self {
563 CursorStyle::Arrow => Shape::Default,
564 CursorStyle::IBeam => Shape::Text,
565 CursorStyle::Crosshair => Shape::Crosshair,
566 CursorStyle::ClosedHand => Shape::Grabbing,
567 CursorStyle::OpenHand => Shape::Grab,
568 CursorStyle::PointingHand => Shape::Pointer,
569 CursorStyle::ResizeLeft => Shape::WResize,
570 CursorStyle::ResizeRight => Shape::EResize,
571 CursorStyle::ResizeLeftRight => Shape::EwResize,
572 CursorStyle::ResizeUp => Shape::NResize,
573 CursorStyle::ResizeDown => Shape::SResize,
574 CursorStyle::ResizeUpDown => Shape::NsResize,
575 CursorStyle::ResizeColumn => Shape::ColResize,
576 CursorStyle::ResizeRow => Shape::RowResize,
577 CursorStyle::IBeamCursorForVerticalLayout => Shape::VerticalText,
578 CursorStyle::OperationNotAllowed => Shape::NotAllowed,
579 CursorStyle::DragLink => Shape::Alias,
580 CursorStyle::DragCopy => Shape::Copy,
581 CursorStyle::ContextualMenu => Shape::ContextMenu,
582 }
583 }
584
585 pub(super) fn to_icon_name(&self) -> String {
586 // Based on cursor names from https://gitlab.gnome.org/GNOME/adwaita-icon-theme (GNOME)
587 // and https://github.com/KDE/breeze (KDE). Both of them seem to be also derived from
588 // Web CSS cursor names: https://developer.mozilla.org/en-US/docs/Web/CSS/cursor#values
589 match self {
590 CursorStyle::Arrow => "arrow",
591 CursorStyle::IBeam => "text",
592 CursorStyle::Crosshair => "crosshair",
593 CursorStyle::ClosedHand => "grabbing",
594 CursorStyle::OpenHand => "grab",
595 CursorStyle::PointingHand => "pointer",
596 CursorStyle::ResizeLeft => "w-resize",
597 CursorStyle::ResizeRight => "e-resize",
598 CursorStyle::ResizeLeftRight => "ew-resize",
599 CursorStyle::ResizeUp => "n-resize",
600 CursorStyle::ResizeDown => "s-resize",
601 CursorStyle::ResizeUpDown => "ns-resize",
602 CursorStyle::ResizeColumn => "col-resize",
603 CursorStyle::ResizeRow => "row-resize",
604 CursorStyle::IBeamCursorForVerticalLayout => "vertical-text",
605 CursorStyle::OperationNotAllowed => "not-allowed",
606 CursorStyle::DragLink => "alias",
607 CursorStyle::DragCopy => "copy",
608 CursorStyle::ContextualMenu => "context-menu",
609 }
610 .to_string()
611 }
612}
613
614impl Keystroke {
615 pub(super) fn from_xkb(state: &State, modifiers: Modifiers, keycode: Keycode) -> Self {
616 let mut modifiers = modifiers;
617
618 let key_utf32 = state.key_get_utf32(keycode);
619 let key_utf8 = state.key_get_utf8(keycode);
620 let key_sym = state.key_get_one_sym(keycode);
621
622 let key = match key_sym {
623 Keysym::Return => "enter".to_owned(),
624 Keysym::Prior => "pageup".to_owned(),
625 Keysym::Next => "pagedown".to_owned(),
626 Keysym::ISO_Left_Tab => "tab".to_owned(),
627
628 Keysym::comma => ",".to_owned(),
629 Keysym::period => ".".to_owned(),
630 Keysym::less => "<".to_owned(),
631 Keysym::greater => ">".to_owned(),
632 Keysym::slash => "/".to_owned(),
633 Keysym::question => "?".to_owned(),
634
635 Keysym::semicolon => ";".to_owned(),
636 Keysym::colon => ":".to_owned(),
637 Keysym::apostrophe => "'".to_owned(),
638 Keysym::quotedbl => "\"".to_owned(),
639
640 Keysym::bracketleft => "[".to_owned(),
641 Keysym::braceleft => "{".to_owned(),
642 Keysym::bracketright => "]".to_owned(),
643 Keysym::braceright => "}".to_owned(),
644 Keysym::backslash => "\\".to_owned(),
645 Keysym::bar => "|".to_owned(),
646
647 Keysym::grave => "`".to_owned(),
648 Keysym::asciitilde => "~".to_owned(),
649 Keysym::exclam => "!".to_owned(),
650 Keysym::at => "@".to_owned(),
651 Keysym::numbersign => "#".to_owned(),
652 Keysym::dollar => "$".to_owned(),
653 Keysym::percent => "%".to_owned(),
654 Keysym::asciicircum => "^".to_owned(),
655 Keysym::ampersand => "&".to_owned(),
656 Keysym::asterisk => "*".to_owned(),
657 Keysym::parenleft => "(".to_owned(),
658 Keysym::parenright => ")".to_owned(),
659 Keysym::minus => "-".to_owned(),
660 Keysym::underscore => "_".to_owned(),
661 Keysym::equal => "=".to_owned(),
662 Keysym::plus => "+".to_owned(),
663
664 _ => xkb::keysym_get_name(key_sym).to_lowercase(),
665 };
666
667 if modifiers.shift {
668 // we only include the shift for upper-case letters by convention,
669 // so don't include for numbers and symbols, but do include for
670 // tab/enter, etc.
671 if key.chars().count() == 1 && key_utf8 == key {
672 modifiers.shift = false;
673 }
674 }
675
676 // Ignore control characters (and DEL) for the purposes of ime_key
677 let ime_key =
678 (key_utf32 >= 32 && key_utf32 != 127 && !key_utf8.is_empty()).then_some(key_utf8);
679
680 Keystroke {
681 modifiers,
682 key,
683 ime_key,
684 }
685 }
686
687 /**
688 * Returns which symbol the dead key represents
689 * https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values#dead_keycodes_for_linux
690 */
691 pub fn underlying_dead_key(keysym: Keysym) -> Option<String> {
692 match keysym {
693 Keysym::dead_grave => Some("`".to_owned()),
694 Keysym::dead_acute => Some("´".to_owned()),
695 Keysym::dead_circumflex => Some("^".to_owned()),
696 Keysym::dead_tilde => Some("~".to_owned()),
697 Keysym::dead_perispomeni => Some("͂".to_owned()),
698 Keysym::dead_macron => Some("¯".to_owned()),
699 Keysym::dead_breve => Some("˘".to_owned()),
700 Keysym::dead_abovedot => Some("˙".to_owned()),
701 Keysym::dead_diaeresis => Some("¨".to_owned()),
702 Keysym::dead_abovering => Some("˚".to_owned()),
703 Keysym::dead_doubleacute => Some("˝".to_owned()),
704 Keysym::dead_caron => Some("ˇ".to_owned()),
705 Keysym::dead_cedilla => Some("¸".to_owned()),
706 Keysym::dead_ogonek => Some("˛".to_owned()),
707 Keysym::dead_iota => Some("ͅ".to_owned()),
708 Keysym::dead_voiced_sound => Some("゙".to_owned()),
709 Keysym::dead_semivoiced_sound => Some("゚".to_owned()),
710 Keysym::dead_belowdot => Some("̣̣".to_owned()),
711 Keysym::dead_hook => Some("̡".to_owned()),
712 Keysym::dead_horn => Some("̛".to_owned()),
713 Keysym::dead_stroke => Some("̶̶".to_owned()),
714 Keysym::dead_abovecomma => Some("̓̓".to_owned()),
715 Keysym::dead_psili => Some("᾿".to_owned()),
716 Keysym::dead_abovereversedcomma => Some("ʽ".to_owned()),
717 Keysym::dead_dasia => Some("῾".to_owned()),
718 Keysym::dead_doublegrave => Some("̏".to_owned()),
719 Keysym::dead_belowring => Some("˳".to_owned()),
720 Keysym::dead_belowmacron => Some("̱".to_owned()),
721 Keysym::dead_belowcircumflex => Some("ꞈ".to_owned()),
722 Keysym::dead_belowtilde => Some("̰".to_owned()),
723 Keysym::dead_belowbreve => Some("̮".to_owned()),
724 Keysym::dead_belowdiaeresis => Some("̤".to_owned()),
725 Keysym::dead_invertedbreve => Some("̯".to_owned()),
726 Keysym::dead_belowcomma => Some("̦".to_owned()),
727 Keysym::dead_currency => None,
728 Keysym::dead_lowline => None,
729 Keysym::dead_aboveverticalline => None,
730 Keysym::dead_belowverticalline => None,
731 Keysym::dead_longsolidusoverlay => None,
732 Keysym::dead_a => None,
733 Keysym::dead_A => None,
734 Keysym::dead_e => None,
735 Keysym::dead_E => None,
736 Keysym::dead_i => None,
737 Keysym::dead_I => None,
738 Keysym::dead_o => None,
739 Keysym::dead_O => None,
740 Keysym::dead_u => None,
741 Keysym::dead_U => None,
742 Keysym::dead_small_schwa => Some("ə".to_owned()),
743 Keysym::dead_capital_schwa => Some("Ə".to_owned()),
744 Keysym::dead_greek => None,
745 _ => None,
746 }
747 }
748}
749
750impl Modifiers {
751 pub(super) fn from_xkb(keymap_state: &State) -> Self {
752 let shift = keymap_state.mod_name_is_active(xkb::MOD_NAME_SHIFT, xkb::STATE_MODS_EFFECTIVE);
753 let alt = keymap_state.mod_name_is_active(xkb::MOD_NAME_ALT, xkb::STATE_MODS_EFFECTIVE);
754 let control =
755 keymap_state.mod_name_is_active(xkb::MOD_NAME_CTRL, xkb::STATE_MODS_EFFECTIVE);
756 let platform =
757 keymap_state.mod_name_is_active(xkb::MOD_NAME_LOGO, xkb::STATE_MODS_EFFECTIVE);
758 Modifiers {
759 shift,
760 alt,
761 control,
762 platform,
763 function: false,
764 }
765 }
766}
767
768#[cfg(test)]
769mod tests {
770 use super::*;
771 use crate::{px, Point};
772
773 #[test]
774 fn test_is_within_click_distance() {
775 let zero = Point::new(px(0.0), px(0.0));
776 assert_eq!(
777 is_within_click_distance(zero, Point::new(px(5.0), px(5.0))),
778 true
779 );
780 assert_eq!(
781 is_within_click_distance(zero, Point::new(px(-4.9), px(5.0))),
782 true
783 );
784 assert_eq!(
785 is_within_click_distance(Point::new(px(3.0), px(2.0)), Point::new(px(-2.0), px(-2.0))),
786 true
787 );
788 assert_eq!(
789 is_within_click_distance(zero, Point::new(px(5.0), px(5.1))),
790 false
791 );
792 }
793}