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