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