Skip to content

Visual Studio Code, rebuilt in Rust

Rust
7.8 KB
Raw Blame
//! System-wide keybindings: `"systemWide": true` in keybindings.json registers the key as an OS global shortcut that
//! runs its command while another application is active. systemWideKeybindings.ts selects the bindings,
//! globalKeybindingsMainService.ts keeps the OS registrations in step with them, and `HotKeys` registers with
//! Carbon's RegisterEventHotKey on macOS and X11 key grabs or the GlobalShortcuts portal on Linux, as Electron's
//! globalShortcut does.

use std::collections::HashSet;

use serde_json::Value;

use crate::keybindings::{self, Chord, Item};

#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "linux")]
pub use linux::HotKeys;
#[cfg(target_os = "macos")]
pub use macos::HotKeys;
#[cfg(target_os = "windows")]
mod windows;
#[cfg(target_os = "windows")]
pub use windows::HotKeys;

#[derive(Clone, Debug, PartialEq)]
pub struct Candidate {
    pub accelerator: String,
    pub chord: Chord,
    pub command: String,
    pub args: Option<Value>,
    pub user_settings_label: String,
    pub has_when: bool,
}

#[derive(Debug, PartialEq)]
pub struct Rejection {
    pub command: String,
    pub user_settings_label: String,
}

#[derive(Debug, Default, PartialEq)]
pub struct Selection {
    pub candidates: Vec<Candidate>,
    pub unsupported: Vec<Rejection>,
    pub duplicates: Vec<Rejection>,
}

/// `selectSystemWideKeybindings` without a window context: the user's system-wide keybindings with an Electron
/// accelerator, the first one winning an accelerator. Only chat's screenshot action marks a default rule
/// system-wide, so the defaults branch selects nothing in the port.
pub fn select(items: &[Item]) -> Selection {
    let mut selection = Selection::default();
    let mut seen = HashSet::new();
    for item in items {
        if !item.system_wide || item.is_default || item.command.is_empty() || item.keybinding.is_empty() {
            continue;
        }
        let user_settings_label = keybindings::user_settings_label(&item.keybinding);
        let Some(accelerator) = keybindings::electron_accelerator(&item.keybinding) else {
            selection.unsupported.push(Rejection { command: item.command.clone(), user_settings_label });
            continue;
        };
        if !seen.insert(accelerator.clone()) {
            selection.duplicates.push(Rejection { command: item.command.clone(), user_settings_label });
            continue;
        }
        let chord = item.keybinding[0];
        selection.candidates.push(Candidate { accelerator, chord, command: item.command.clone(), args: item.args.clone(), user_settings_label, has_when: item.when.is_some() });
    }
    selection
}

/// Electron's `globalShortcut`: `register` is false when the OS or another application holds the accelerator.
pub trait ShortcutRegistry {
    fn register(&mut self, binding: &Candidate) -> bool;
    fn unregister(&mut self, accelerator: &str);
}

/// `GlobalKeybindingsMainService` for the port's one window.
pub struct GlobalShortcuts<R> {
    pub registry: R,
    bindings: Vec<Candidate>,
    registered: HashSet<String>,
    failed: HashSet<String>,
}

impl<R: ShortcutRegistry> GlobalShortcuts<R> {
    pub fn new(registry: R) -> Self {
        GlobalShortcuts { registry, bindings: Vec::new(), registered: HashSet::new(), failed: HashSet::new() }
    }

    /// `updateKeybindings` and `reconcile`: unregisters what is no longer wanted, registers the rest (retrying
    /// earlier failures) and returns the labels that failed.
    pub fn update(&mut self, candidates: Vec<Candidate>) -> Vec<String> {
        let mut bindings: Vec<Candidate> = Vec::new();
        for candidate in candidates {
            if bindings.iter().any(|binding| binding.accelerator == candidate.accelerator) {
                eprintln!("[GlobalKeybindings] duplicate accelerator '{}', keeping first", candidate.accelerator);
                continue;
            }
            bindings.push(candidate);
        }
        self.bindings = bindings;

        let unwanted: Vec<String> = self.registered.iter().filter(|accelerator| self.binding(accelerator).is_none()).cloned().collect();
        for accelerator in unwanted {
            self.registry.unregister(&accelerator);
            self.registered.remove(&accelerator);
            self.failed.remove(&accelerator);
        }
        for binding in &self.bindings {
            if self.registered.contains(&binding.accelerator) {
                continue;
            }
            if self.registry.register(binding) {
                self.registered.insert(binding.accelerator.clone());
                self.failed.remove(&binding.accelerator);
            } else {
                self.failed.insert(binding.accelerator.clone());
                eprintln!("[GlobalKeybindings] failed to register accelerator '{}' (already taken by the OS or another application)", binding.accelerator);
            }
        }
        self.bindings.iter().filter(|binding| self.failed.contains(&binding.accelerator)).map(|binding| binding.user_settings_label.clone()).collect()
    }

    /// The binding a registered accelerator runs when it fires (`onTrigger` reads the current one).
    pub fn binding(&self, accelerator: &str) -> Option<&Candidate> {
        self.bindings.iter().find(|binding| binding.accelerator == accelerator)
    }
}

/// SystemWideKeybindingsContribution: the registrations once started, and the warnings each sync returns for
/// the workbench to notify.
#[derive(Default)]
pub struct SystemWide {
    pub shortcuts: Option<GlobalShortcuts<HotKeys>>,
    candidates: Vec<Candidate>,
    warned_when_labels: HashSet<String>,
    reported_failures: Vec<String>,
}

impl SystemWide {
    pub fn set_keybindings(&mut self, items: &[Item]) -> Vec<String> {
        let selection = select(items);
        for rejection in &selection.unsupported {
            eprintln!("[SystemWideKeybindings] '{}' cannot be registered as a system-wide shortcut (only single key combinations are supported).", rejection.user_settings_label);
        }
        for rejection in &selection.duplicates {
            eprintln!("[SystemWideKeybindings] duplicate system-wide accelerator for '{}', keeping the first binding.", rejection.user_settings_label);
        }
        let mut newly_warned = Vec::new();
        for candidate in &selection.candidates {
            if candidate.has_when && self.warned_when_labels.insert(candidate.user_settings_label.clone()) {
                newly_warned.push(candidate.user_settings_label.clone());
            }
        }
        let mut warnings = Vec::new();
        if !newly_warned.is_empty() {
            warnings.push(format!("The \"when\" clause is ignored for system-wide keybindings ({}); they are always active while {} is running.", newly_warned.join(", "), crate::product::name_long()));
        }
        self.candidates = selection.candidates;
        warnings.extend(self.sync());
        warnings
    }

    pub fn start(&mut self, hot_keys: HotKeys) -> Option<String> {
        self.shortcuts = Some(GlobalShortcuts::new(hot_keys));
        self.sync()
    }

    /// The binding of the hot key Carbon reported pressed.
    pub fn pressed(&self, id: u32) -> Option<&Candidate> {
        let shortcuts = self.shortcuts.as_ref()?;
        shortcuts.binding(shortcuts.registry.accelerator(id)?)
    }

    fn sync(&mut self) -> Option<String> {
        let shortcuts = self.shortcuts.as_mut()?;
        let mut failed = shortcuts.update(self.candidates.clone());
        failed.sort();
        if failed == self.reported_failures {
            return None;
        }
        let warning = (!failed.is_empty()).then(|| {
            format!("Some system-wide keybindings could not be registered ({}); the key combination may already be taken by the operating system or another application.", failed.join(", "))
        });
        self.reported_failures = failed;
        warning
    }
}

#[cfg(test)]
mod tests;