mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* free imported model definitions after rename and removal * silence test-only lints on linux The new state-machine tests keep macOS-only helpers and imports; clippy on Linux denies them as unused, and one test cloned a selection only to compare it. * borrow the model definition on macOS-only paths Meeting audio import and Parakeet's macOS load path still passed the ModelRef by value to model_path, is_installed, and validate_gguf_artifact. * address review nits on the imported model definitions Track every rename build with its own Weak, restore the moved doc comments verbatim, name the new registry tests in the feature map, and use is_gguf for the plain runtime checks.
1372 lines
48 KiB
Rust
1372 lines
48 KiB
Rust
//! The General pane: listener status, the Dictation, Output, and Application
|
||
//! cards with the shortcuts in their place, Advanced options behind a
|
||
//! disclosure, and recording shortcuts through the host.
|
||
|
||
use std::time::{Duration, Instant};
|
||
|
||
use rune::{Edge, El, Key, KeyEvent, Transition, Tx, col, row, spacer, text};
|
||
|
||
use super::controls::{
|
||
ButtonKind, Choice, DESCRIPTION, KEY_GAP, KeySize, METRICS, Paint, button, keycap, note,
|
||
pulsing_dot, section, setting_row, status_dot,
|
||
};
|
||
use super::host;
|
||
use super::{Menu, Request, Service, ShortcutTarget, Ui};
|
||
use crate::app_settings::{AppSettings, HotkeyBinding, HotkeyKey, HotkeyModifiers, ModifierSide};
|
||
use crate::desktop::host::{
|
||
DesktopAction, DesktopGrantedShortcut, DesktopShortcut, DesktopUpdateStatus,
|
||
};
|
||
use crate::desktop::i18n::{tr, tr_fill};
|
||
use crate::dictation::ShortcutMode;
|
||
use crate::transcription::models::{self as transcription_models, ModelPreparationStage};
|
||
|
||
mod grants;
|
||
|
||
pub(super) use self::grants::{gnome_clash_note, granted};
|
||
use self::grants::{on_gnome, portal_grant};
|
||
|
||
static CHECK: &rune::Icon = &rune_theme_opencode::icons::CHECK_SMALL;
|
||
|
||
/// How long a newly saved shortcut shows "Saved".
|
||
const SAVED_FOR: Duration = Duration::from_secs(1);
|
||
/// How long to wait for the service to start a requested shortcut edit.
|
||
const EDIT_START_TIMEOUT: Duration = Duration::from_secs(3);
|
||
|
||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||
pub(super) enum Capture {
|
||
Idle,
|
||
/// Waiting for the chord; `message` explains a rejected one, and `held`
|
||
/// shows the modifiers releasing them would record.
|
||
Listening {
|
||
target: ShortcutTarget,
|
||
message: Option<&'static str>,
|
||
held: HotkeyModifiers,
|
||
},
|
||
/// Sent to the service, which validates, registers, and saves it.
|
||
Saving {
|
||
target: ShortcutTarget,
|
||
since: Instant,
|
||
seen_edit: bool,
|
||
},
|
||
/// `until` is on the poll clock, set by the first poll that sees it.
|
||
Saved {
|
||
target: ShortcutTarget,
|
||
until: Option<f64>,
|
||
},
|
||
}
|
||
|
||
/// A chord the host recorded outside the window's key events (Windows
|
||
/// polls the keyboard, since modifier-only chords never reach the window).
|
||
#[cfg_attr(target_os = "linux", allow(dead_code))]
|
||
pub(super) enum Chord {
|
||
/// The modifiers held so far, shown while the chord is in progress.
|
||
Held(HotkeyModifiers),
|
||
Captured(Result<HotkeyBinding, &'static str>),
|
||
Cancelled,
|
||
}
|
||
|
||
/// Follows the host's side of a shortcut edit.
|
||
pub(super) fn advance_capture(ui: &mut Ui, clock: f64, tx: &mut Tx) -> bool {
|
||
let mut changed = false;
|
||
loop {
|
||
let chord = match &mut ui.service {
|
||
Service::Live(backend) => backend.take_chord(),
|
||
_ => None,
|
||
};
|
||
let (Some(chord), Capture::Listening { target, .. }) = (chord, ui.capture) else {
|
||
break;
|
||
};
|
||
match chord {
|
||
Chord::Held(modifiers) => {
|
||
hold(ui, modifiers);
|
||
changed = true;
|
||
}
|
||
Chord::Captured(binding) => {
|
||
record(ui, target, binding);
|
||
return true;
|
||
}
|
||
Chord::Cancelled => {
|
||
cancel_capture(ui);
|
||
return true;
|
||
}
|
||
}
|
||
}
|
||
if changed {
|
||
return true;
|
||
}
|
||
let editing = ui.view.as_ref().is_some_and(|view| view.editing);
|
||
match ui.capture {
|
||
Capture::Saving {
|
||
target,
|
||
since,
|
||
seen_edit,
|
||
} => {
|
||
let finished = if seen_edit {
|
||
!editing
|
||
} else if editing {
|
||
ui.capture = Capture::Saving {
|
||
target,
|
||
since,
|
||
seen_edit: true,
|
||
};
|
||
return false;
|
||
} else {
|
||
since.elapsed() >= EDIT_START_TIMEOUT
|
||
};
|
||
if finished {
|
||
ui.capture = Capture::Saved {
|
||
target,
|
||
until: None,
|
||
};
|
||
}
|
||
finished
|
||
}
|
||
Capture::Saved {
|
||
target,
|
||
until: None,
|
||
} => {
|
||
ui.capture = Capture::Saved {
|
||
target,
|
||
until: Some(clock + SAVED_FOR.as_secs_f64()),
|
||
};
|
||
tx.wake_after(SAVED_FOR);
|
||
false
|
||
}
|
||
Capture::Saved {
|
||
until: Some(until), ..
|
||
} if clock >= until => {
|
||
ui.capture = Capture::Idle;
|
||
true
|
||
}
|
||
_ => false,
|
||
}
|
||
}
|
||
|
||
/// Records a shortcut while capture listens; otherwise leaves keys alone.
|
||
/// Where the host records chords itself, the window only takes Escape and
|
||
/// keeps every other key out of the page.
|
||
pub(super) fn on_key(ui: &mut Ui, event: &KeyEvent, _: &mut Tx) -> bool {
|
||
let Capture::Listening { target, .. } = ui.capture else {
|
||
return false;
|
||
};
|
||
if event.key == Key::Escape {
|
||
cancel_capture(ui);
|
||
return true;
|
||
}
|
||
if host::RECORDS_KEY_EVENTS {
|
||
match event.key {
|
||
Key::Modifier { modifier, pressed } => {
|
||
modifier_alone(ui, modifier, pressed, event.mods)
|
||
}
|
||
_ => record(ui, target, recorded_binding(event)),
|
||
}
|
||
}
|
||
true
|
||
}
|
||
|
||
/// Where the window records key events (Linux), a modifier pressed on its
|
||
/// own shows among the held keys, and releasing them all without a key
|
||
/// says why Linux can't bind that and what it can: a key with them. The
|
||
/// GlobalShortcuts portal and X11 grabs take a key plus modifiers, never a
|
||
/// modifier alone or one side of it.
|
||
fn modifier_alone(ui: &mut Ui, modifier: rune::Modifier, pressed: bool, mods: rune::Mods) {
|
||
let Capture::Listening { message, held, .. } = &mut ui.capture else {
|
||
return;
|
||
};
|
||
if pressed {
|
||
use rune::Modifier as M;
|
||
let slot = match modifier {
|
||
M::ControlLeft | M::ControlRight => &mut held.control,
|
||
M::AltLeft | M::AltRight => &mut held.option,
|
||
M::ShiftLeft | M::ShiftRight => &mut held.shift,
|
||
M::SuperLeft | M::SuperRight => &mut held.command,
|
||
_ => return,
|
||
};
|
||
let side = match modifier.side() {
|
||
Some(rune::KeySide::Left) => ModifierSide::Left,
|
||
Some(rune::KeySide::Right) => ModifierSide::Right,
|
||
None => ModifierSide::Either,
|
||
};
|
||
*slot = Some(match (*slot, side) {
|
||
(Some(ModifierSide::Left), ModifierSide::Right)
|
||
| (Some(ModifierSide::Right), ModifierSide::Left) => ModifierSide::Both,
|
||
(Some(current), _) => current,
|
||
(None, side) => side,
|
||
});
|
||
*message = None;
|
||
return;
|
||
}
|
||
if mods.ctrl || mods.alt || mods.shift || mods.logo {
|
||
return;
|
||
}
|
||
let peak = std::mem::take(held);
|
||
if !peak.is_empty() {
|
||
*message = Some(modifier_only_hint(peak));
|
||
}
|
||
}
|
||
|
||
/// The nearest chord Linux binds to modifiers held alone: the same
|
||
/// modifiers, one side or either, with a key.
|
||
pub(super) fn modifier_only_hint(peak: HotkeyModifiers) -> &'static str {
|
||
let both =
|
||
[peak.control, peak.option, peak.shift, peak.command].contains(&Some(ModifierSide::Both));
|
||
if both {
|
||
tr("Linux can't bind both sides. Use one with a key, like Space")
|
||
} else {
|
||
tr("Linux needs a key too. Hold these and press one, like Space")
|
||
}
|
||
}
|
||
|
||
/// Saves a recorded chord, or keeps listening with why it was rejected.
|
||
/// Plain ⌫ (or Delete) turns a shortcut that can be off off.
|
||
fn record(ui: &mut Ui, target: ShortcutTarget, binding: Result<HotkeyBinding, &'static str>) {
|
||
if can_turn_off(target) && binding.as_ref().is_ok_and(HotkeyBinding::is_bare_erase) {
|
||
cancel_capture(ui);
|
||
if ui.update(|settings| turn_off(settings, target)) {
|
||
ui.capture = Capture::Saved {
|
||
target,
|
||
until: None,
|
||
};
|
||
}
|
||
return;
|
||
}
|
||
let message = match binding.and_then(|binding| {
|
||
validate(&ui.settings, target, &binding)?;
|
||
Ok(binding)
|
||
}) {
|
||
Ok(binding) if host::HOST_SAVES_SHORTCUTS => {
|
||
ui.send(Request::SetShortcut {
|
||
target,
|
||
shortcut: desktop_shortcut(&binding),
|
||
});
|
||
if matches!(ui.service, Service::Fixture(_)) {
|
||
set_binding(&mut ui.settings, target, binding);
|
||
}
|
||
ui.capture = Capture::Saving {
|
||
target,
|
||
since: Instant::now(),
|
||
seen_edit: false,
|
||
};
|
||
return;
|
||
}
|
||
Ok(binding) => {
|
||
// The window saves the binding; the host restarts its listener
|
||
// with it.
|
||
cancel_capture(ui);
|
||
if ui.update(|settings| set_binding(settings, target, binding)) {
|
||
ui.capture = Capture::Saved {
|
||
target,
|
||
until: None,
|
||
};
|
||
}
|
||
return;
|
||
}
|
||
Err(message) => message,
|
||
};
|
||
ui.capture = Capture::Listening {
|
||
target,
|
||
message: Some(message),
|
||
held: HotkeyModifiers::default(),
|
||
};
|
||
}
|
||
|
||
/// Shows the modifiers held so far; pressing any clears a rejection.
|
||
pub(super) fn hold(ui: &mut Ui, modifiers: HotkeyModifiers) {
|
||
if let Capture::Listening { message, held, .. } = &mut ui.capture {
|
||
if !modifiers.is_empty() {
|
||
*message = None;
|
||
}
|
||
*held = modifiers;
|
||
}
|
||
}
|
||
|
||
pub(super) fn begin_capture(ui: &mut Ui, target: ShortcutTarget) {
|
||
if let Capture::Listening { target: active, .. } = ui.capture {
|
||
cancel_capture(ui);
|
||
if active == target {
|
||
return;
|
||
}
|
||
}
|
||
ui.send(Request::CaptureShortcutFor(target));
|
||
ui.capture = Capture::Listening {
|
||
target,
|
||
message: None,
|
||
held: HotkeyModifiers::default(),
|
||
};
|
||
}
|
||
|
||
pub(super) fn cancel_capture(ui: &mut Ui) {
|
||
if matches!(ui.capture, Capture::Listening { .. }) {
|
||
ui.send(Request::CancelShortcut);
|
||
}
|
||
ui.capture = Capture::Idle;
|
||
}
|
||
|
||
/// The chord a key press records, in the key names Linux registers.
|
||
pub(super) fn recorded_binding(event: &KeyEvent) -> Result<HotkeyBinding, &'static str> {
|
||
let name = match &event.key {
|
||
Key::Text(text) if text == " " => "space".to_string(),
|
||
Key::Text(text) if text.chars().count() == 1 => text.to_lowercase(),
|
||
Key::Command(letter) => letter.to_string(),
|
||
Key::Function(number) => format!("f{number}"),
|
||
Key::Enter => "enter".into(),
|
||
Key::Tab => "tab".into(),
|
||
Key::Backspace => "backspace".into(),
|
||
Key::Delete => "delete".into(),
|
||
Key::Left => "left".into(),
|
||
Key::Right => "right".into(),
|
||
Key::Up => "up".into(),
|
||
Key::Down => "down".into(),
|
||
Key::Home => "home".into(),
|
||
Key::End => "end".into(),
|
||
Key::PageUp => "pageup".into(),
|
||
Key::PageDown => "pagedown".into(),
|
||
Key::Insert => "insert".into(),
|
||
Key::PrintScreen => "print".into(),
|
||
Key::ContextMenu => "menu".into(),
|
||
Key::Pause => "pause".into(),
|
||
Key::ScrollLock => "scrolllock".into(),
|
||
_ => return Err(tr("Unsupported key")),
|
||
};
|
||
let held = |down: bool| down.then_some(ModifierSide::Either);
|
||
let modifiers = HotkeyModifiers {
|
||
control: held(event.mods.ctrl),
|
||
option: held(event.mods.alt),
|
||
shift: held(event.mods.shift),
|
||
command: held(event.mods.logo),
|
||
function: false,
|
||
};
|
||
// The § key alone, and Menu, Pause, or Scroll Lock, are checked against
|
||
// their Labs toggles in `validate` (Linux).
|
||
let lone_labs_key = cfg!(target_os = "linux")
|
||
&& (HotkeyKey::section_name(&name) || HotkeyKey::special_name(&name));
|
||
// Plain ⌫ or Delete turns an optional shortcut off (`record`);
|
||
// `validate` refuses it as a binding.
|
||
let erase = matches!(event.key, Key::Backspace | Key::Delete);
|
||
if modifiers.is_empty() && !matches!(event.key, Key::Function(_)) && !lone_labs_key && !erase {
|
||
return Err(tr("Add a modifier"));
|
||
}
|
||
Ok(HotkeyBinding {
|
||
modifiers,
|
||
key: Some(HotkeyKey::named(&name)),
|
||
})
|
||
}
|
||
|
||
pub(super) fn validate(
|
||
settings: &AppSettings,
|
||
target: ShortcutTarget,
|
||
binding: &HotkeyBinding,
|
||
) -> Result<(), &'static str> {
|
||
use crate::app_settings::{ShortcutRefusal, ShortcutValidationError, validate_shortcut};
|
||
let slot = super::shortcut_rule::slot_of(target);
|
||
validate_shortcut(settings, settings, slot, binding, |_, binding| {
|
||
host::validate_hotkey(target, binding)
|
||
})
|
||
.map_err(|error| match error {
|
||
ShortcutValidationError::Host(message) => message,
|
||
ShortcutValidationError::Policy(refusal) => match refusal {
|
||
ShortcutRefusal::BarePrimaryClick
|
||
| ShortcutRefusal::BareErase
|
||
| ShortcutRefusal::NeedsSectionKeyLab
|
||
| ShortcutRefusal::NeedsNavigationKeyLab { .. }
|
||
| ShortcutRefusal::NeedsSpecialKeysLab { alone: true, .. }
|
||
| ShortcutRefusal::NeedsModifierForKey { .. } => tr("Add a modifier"),
|
||
ShortcutRefusal::NeedsMouseShortcutsLab
|
||
| ShortcutRefusal::NeedsMicrophoneKeyLab
|
||
| ShortcutRefusal::MicrophoneKeyOnScreenshot
|
||
| ShortcutRefusal::NeedsSpecialKeysLab { alone: false, .. } => tr("Unsupported key"),
|
||
ShortcutRefusal::InUse => tr("Already in use"),
|
||
},
|
||
})
|
||
}
|
||
|
||
/// Whether `binding` overlaps a shortcut `target` must not share: the other
|
||
/// active shortcuts.
|
||
pub(super) fn conflicts(
|
||
settings: &AppSettings,
|
||
target: ShortcutTarget,
|
||
binding: &HotkeyBinding,
|
||
) -> bool {
|
||
settings.hotkey_in_use(super::shortcut_rule::slot_of(target), binding)
|
||
}
|
||
|
||
pub(super) fn desktop_shortcut(binding: &HotkeyBinding) -> DesktopShortcut {
|
||
let modifiers = binding.modifiers;
|
||
DesktopShortcut {
|
||
alt: modifiers.option.is_some(),
|
||
control: modifiers.control.is_some(),
|
||
function: false,
|
||
key: binding
|
||
.key
|
||
.as_ref()
|
||
.map(HotkeyKey::name)
|
||
.unwrap_or_default(),
|
||
platform: modifiers.command.is_some(),
|
||
shift: modifiers.shift.is_some(),
|
||
}
|
||
}
|
||
|
||
pub(super) fn binding(settings: &AppSettings, target: ShortcutTarget) -> Option<&HotkeyBinding> {
|
||
super::shortcut_rule::slot_of(target).get(settings)
|
||
}
|
||
|
||
pub(super) fn set_binding(
|
||
settings: &mut AppSettings,
|
||
target: ShortcutTarget,
|
||
binding: HotkeyBinding,
|
||
) {
|
||
super::shortcut_rule::slot_of(target).set(settings, binding);
|
||
}
|
||
|
||
/// The shortcuts in General and Output that can be off: plain ⌫ while
|
||
/// recording one turns it off.
|
||
pub(super) fn can_turn_off(target: ShortcutTarget) -> bool {
|
||
super::shortcut_rule::slot_of(target).can_turn_off()
|
||
}
|
||
|
||
/// Turns off a shortcut [`can_turn_off`] allows; others keep their binding.
|
||
pub(super) fn turn_off(settings: &mut AppSettings, target: ShortcutTarget) {
|
||
super::shortcut_rule::slot_of(target).turn_off(settings);
|
||
}
|
||
|
||
/// A shortcut row's Reset: puts `default` back as `target`'s
|
||
/// shortcut under the rules a recorded one meets. A default another
|
||
/// shortcut already uses changes nothing and opens the recorder with the
|
||
/// usual conflict, so another can be recorded.
|
||
pub(super) fn restore_default(ui: &mut Ui, target: ShortcutTarget, default: HotkeyBinding) {
|
||
match validate(&ui.settings, target, &default) {
|
||
Ok(()) => {
|
||
cancel_capture(ui);
|
||
ui.update(|settings| set_binding(settings, target, default.clone()));
|
||
}
|
||
Err(message) => {
|
||
if !matches!(ui.capture, Capture::Listening { target: active, .. } if active == target)
|
||
{
|
||
begin_capture(ui, target);
|
||
}
|
||
if let Capture::Listening { message: shown, .. } = &mut ui.capture {
|
||
*shown = Some(message);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The tone volume the slider shows: zero while tones are off.
|
||
pub(super) fn sound_volume(settings: &AppSettings) -> f32 {
|
||
if settings.sound_effects {
|
||
settings.sound_effect_volume.clamp(0.0, 1.0)
|
||
} else {
|
||
0.0
|
||
}
|
||
}
|
||
|
||
pub(super) fn toggle_menu(ui: &mut Ui, menu: Menu) {
|
||
ui.open = (ui.open != Some(menu)).then_some(menu);
|
||
if matches!(ui.open, Some(Menu::Microphone)) {
|
||
refresh_microphones(ui);
|
||
}
|
||
}
|
||
|
||
/// Lists the microphones again, and what System default resolves to, on a
|
||
/// worker thread; [`poll_microphones`] adopts the result. A change during a
|
||
/// listing in flight is listed again after it.
|
||
pub(super) fn refresh_microphones(ui: &mut Ui) {
|
||
if matches!(ui.service, Service::Fixture(_)) || ui.microphones_listing.is_some() {
|
||
return;
|
||
}
|
||
ui.microphones_route = Some(crate::audio::input_route_generation());
|
||
let (sender, receiver) = std::sync::mpsc::sync_channel(1);
|
||
let spawned = std::thread::Builder::new()
|
||
.name("hex-microphones".into())
|
||
.spawn(move || {
|
||
let _ = sender.send(crate::audio::input_devices().map_err(|error| error.to_string()));
|
||
});
|
||
match spawned {
|
||
Ok(_) => ui.microphones_listing = Some(receiver),
|
||
Err(error) => ui.microphones = Err(error.to_string()),
|
||
}
|
||
}
|
||
|
||
/// Adopts a finished listing. Returns whether the microphones changed.
|
||
pub(super) fn poll_microphones(ui: &mut Ui) -> bool {
|
||
let Some(listing) = &ui.microphones_listing else {
|
||
return false;
|
||
};
|
||
let listed = match listing.try_recv() {
|
||
Ok(listed) => listed,
|
||
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
|
||
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
|
||
Err("the microphone list stopped".to_owned())
|
||
}
|
||
};
|
||
ui.microphones_listing = None;
|
||
let changed = ui.microphones != listed;
|
||
ui.microphones = listed;
|
||
changed
|
||
}
|
||
|
||
/// A saved microphone the input list no longer names. Only a list that
|
||
/// names inputs can tell.
|
||
pub(super) fn missing_microphone(ui: &Ui) -> Option<&str> {
|
||
let listed = ui.microphones.as_ref().ok();
|
||
ui.settings.microphone.as_deref().filter(|saved| {
|
||
listed.is_some_and(|devices| {
|
||
!devices.names.is_empty() && !devices.names.iter().any(|name| name == saved)
|
||
})
|
||
})
|
||
}
|
||
|
||
/// The microphone menu's choices, shared by General and the tour: System
|
||
/// default with the input it resolves to, every listed input, and a saved
|
||
/// one that is missing. Choosing saves through `Ui::update`.
|
||
pub(super) fn microphone_choices(ui: &Ui) -> Vec<Choice> {
|
||
let settings = &ui.settings;
|
||
let listed = ui.microphones.as_ref().ok();
|
||
let off = listed.and_then(|devices| devices.off_with_lid_closed.as_deref());
|
||
let mut devices = vec![Choice {
|
||
label: tr("System default").to_owned(),
|
||
detail: listed.and_then(|devices| devices.system_default.clone()),
|
||
selected: settings.microphone.is_none(),
|
||
choose: Box::new(|ui: &mut Ui| {
|
||
ui.open = None;
|
||
ui.update(|settings| settings.microphone = None);
|
||
}),
|
||
}];
|
||
if let Some(listed) = listed {
|
||
devices.extend(listed.names.iter().map(|device| {
|
||
let name = device.clone();
|
||
Choice {
|
||
label: device.clone(),
|
||
detail: (off == Some(device.as_str()))
|
||
.then(|| tr("off while the lid is closed").to_owned()),
|
||
selected: settings.microphone.as_deref() == Some(device),
|
||
choose: Box::new(move |ui: &mut Ui| {
|
||
ui.open = None;
|
||
let name = name.clone();
|
||
ui.update(|settings| settings.microphone = Some(name));
|
||
}),
|
||
}
|
||
}));
|
||
}
|
||
if let Some(saved) = missing_microphone(ui) {
|
||
devices.push(Choice {
|
||
label: saved.to_owned(),
|
||
detail: Some(tr("not connected").to_owned()),
|
||
selected: true,
|
||
choose: Box::new(|ui: &mut Ui| ui.open = None),
|
||
});
|
||
}
|
||
devices
|
||
}
|
||
|
||
pub(super) fn error_notes(p: Paint, error: &str) -> [El; 2] {
|
||
[
|
||
note(
|
||
"error-title",
|
||
tr("Hex could not apply this change."),
|
||
p.danger(),
|
||
),
|
||
note("error", error, p.muted()),
|
||
]
|
||
}
|
||
|
||
pub(super) fn listener_card(ui: &Ui, p: Paint) -> (String, El) {
|
||
let running = ui.running();
|
||
let status = match &ui.view {
|
||
Some(view) => tr(view.listener.status.name()).to_string(),
|
||
None if matches!(ui.service, Service::Fixture(_)) || ui.connection_error.is_some() => {
|
||
tr("Service disconnected").to_string()
|
||
}
|
||
None => tr("Connecting…").to_string(),
|
||
};
|
||
// The key the desktop granted, which it may have changed in its own
|
||
// settings (#723), else the one Hex records.
|
||
let shortcut = match portal_grant(ui, ShortcutTarget::Dictation) {
|
||
Some(DesktopGrantedShortcut {
|
||
trigger: Some(trigger),
|
||
..
|
||
}) => trigger.clone(),
|
||
_ => ui.settings.dictation_hotkey.keycaps().join("+"),
|
||
};
|
||
let no_model = super::general::missing_model(ui).is_some();
|
||
let hint = match (running, ui.settings.shortcut_mode) {
|
||
_ if no_model => tr("Hex can't dictate until a speech model is installed").to_string(),
|
||
_ if !ui.records_shortcuts() => {
|
||
tr("Ready anywhere · Use your desktop's shortcuts to dictate").to_string()
|
||
}
|
||
(true, ShortcutMode::Toggle) => tr_fill(
|
||
"Ready anywhere · Press {} to start and stop dictating",
|
||
&shortcut,
|
||
),
|
||
(true, ShortcutMode::Hold) => tr_fill("Ready anywhere · Hold {} to dictate", &shortcut),
|
||
(false, _) => tr_fill("Enable Hex to dictate into any app with {}", &shortcut),
|
||
};
|
||
let search = format!("{status} {hint} {} {}", tr("Enable"), tr("Disable"));
|
||
let failure = ui
|
||
.view
|
||
.as_ref()
|
||
.and_then(|view| {
|
||
view.listener
|
||
.warning
|
||
.as_deref()
|
||
.or(view.listener.last_failure.as_deref())
|
||
})
|
||
.map(|failure| {
|
||
let explanation = crate::desktop::activity::failure_explanation(failure);
|
||
(
|
||
tr_fill("Last dictation failed: {}", &explanation),
|
||
p.danger(),
|
||
)
|
||
})
|
||
.or_else(|| {
|
||
ui.view
|
||
.as_ref()
|
||
.and_then(|view| view.listener.notice.clone())
|
||
.map(|notice| (notice, p.warning()))
|
||
});
|
||
let error = ui
|
||
.error
|
||
.clone()
|
||
.or_else(|| ui.connection_error.clone())
|
||
.or_else(|| {
|
||
ui.view
|
||
.as_ref()
|
||
.and_then(|view| view.operation_error.clone())
|
||
});
|
||
let action_label = if running { tr("Disable") } else { tr("Enable") };
|
||
let action = if running {
|
||
button(
|
||
p,
|
||
"toggle-listening",
|
||
action_label,
|
||
ButtonKind::Secondary,
|
||
|ui: &mut Ui, _| ui.send(Request::Desktop(DesktopAction::StopListening)),
|
||
)
|
||
} else {
|
||
button(
|
||
p,
|
||
"toggle-listening",
|
||
action_label,
|
||
ButtonKind::Primary,
|
||
|ui: &mut Ui, _| ui.send(Request::Desktop(DesktopAction::StartListening)),
|
||
)
|
||
};
|
||
let summary = row()
|
||
.key("listener")
|
||
.min_h(METRICS.row_h_described)
|
||
.px(METRICS.row_px)
|
||
.py(8.0)
|
||
.gap(12.0)
|
||
.center_y()
|
||
.child(status_dot(if running && !no_model {
|
||
p.success()
|
||
} else {
|
||
p.muted()
|
||
}))
|
||
.child(
|
||
col()
|
||
.key("copy")
|
||
.grow(1.0)
|
||
.shrink()
|
||
.gap(2.0)
|
||
.child(
|
||
text(status)
|
||
.key("status")
|
||
.font(p.k.ty.ui_medium)
|
||
.color(p.text()),
|
||
)
|
||
.child(
|
||
text(hint)
|
||
.key("hint")
|
||
.font(DESCRIPTION)
|
||
.color(if no_model { p.danger() } else { p.muted() })
|
||
.wrap(),
|
||
)
|
||
.children(failure.map(|(failure, color)| {
|
||
text(failure)
|
||
.key("failure")
|
||
.font(DESCRIPTION)
|
||
.color(color)
|
||
.wrap()
|
||
})),
|
||
)
|
||
.child(action);
|
||
let mut rows = vec![summary];
|
||
if let Some(error) = error {
|
||
rows.extend(error_notes(p, &error));
|
||
}
|
||
(search, section(p, "listening", tr("Status"), rows))
|
||
}
|
||
|
||
/// The desktop kept `target`'s shortcut for itself: the note under its row.
|
||
pub(super) fn refused_note(ui: &Ui, p: Paint, target: ShortcutTarget) -> Option<El> {
|
||
portal_grant(ui, target)
|
||
.is_some_and(|shortcut| shortcut.trigger.is_none() && !shortcut.unconfirmed)
|
||
.then(|| {
|
||
note(
|
||
"refused",
|
||
if binding(&ui.settings, target).is_some_and(|binding| binding.key.as_ref().is_some_and(HotkeyKey::is_mouse)) {
|
||
tr("Configure mouse shortcuts in your Wayland desktop using the hex commands")
|
||
} else {
|
||
tr("Your desktop kept a shortcut for itself. Record another one, or free it in your desktop's keyboard settings (on niri, remove its bind from config.kdl).")
|
||
},
|
||
p.danger(),
|
||
)
|
||
})
|
||
}
|
||
|
||
/// Without a shortcuts portal the desktop's keybindings own every shortcut:
|
||
/// the commands to bind there.
|
||
pub(super) fn desktop_commands(ui: &Ui, p: Paint) -> El {
|
||
let mut rows = vec![
|
||
note(
|
||
"no-portal",
|
||
tr(
|
||
"Your desktop has no shortcuts portal. Bind these commands in its keyboard settings.",
|
||
),
|
||
p.muted(),
|
||
),
|
||
command_row(
|
||
p,
|
||
"hold",
|
||
tr("Hold to dictate"),
|
||
tr("Bind start to the key press and stop to its release"),
|
||
&["hex dictation start", "hex dictation stop"],
|
||
),
|
||
command_row(
|
||
p,
|
||
"toggle",
|
||
tr("Toggle dictation"),
|
||
tr("Press to start dictating, press again to transcribe"),
|
||
&["hex dictation toggle"],
|
||
),
|
||
command_row(
|
||
p,
|
||
"paste-last",
|
||
tr("Paste last dictation"),
|
||
tr("Re-paste the most recent dictation"),
|
||
&["hex paste-last"],
|
||
),
|
||
command_row(
|
||
p,
|
||
"raw-dictation",
|
||
tr("Dictate without processing"),
|
||
tr("Paste your words as Hex heard them, skipping every step"),
|
||
&["hex dictation toggle --raw"],
|
||
),
|
||
];
|
||
// Annotate's shortcut goes through the same portal, so it needs a command
|
||
// here too while the feature is on.
|
||
#[cfg(hex_capture)]
|
||
if ui.platform.scrawl.is_some() && ui.settings.capture.enabled {
|
||
rows.push(command_row(
|
||
p,
|
||
"annotate",
|
||
tr("Annotate"),
|
||
tr("Start and stop an annotation"),
|
||
&["hex annotate toggle"],
|
||
));
|
||
}
|
||
// GNOME without a shortcuts portal (GNOME 46 and older, #781): Hex writes
|
||
// the commands into GNOME's own custom shortcuts.
|
||
if on_gnome() {
|
||
rows.insert(1, gnome_shortcuts_row(ui, p));
|
||
}
|
||
section(p, "desktop-shortcuts", tr("Desktop shortcuts"), rows)
|
||
}
|
||
|
||
/// Adds or removes Hex's GNOME custom keyboard shortcuts.
|
||
fn gnome_shortcuts_row(ui: &Ui, p: Paint) -> El {
|
||
let on = ui.settings.gnome_keyboard_shortcuts;
|
||
let description = if on {
|
||
tr(
|
||
"Added to GNOME Settings › Keyboard › Custom Shortcuts while Hex is enabled. GNOME runs them on the key press, so your dictation shortcut toggles dictation. Change the keys there.",
|
||
)
|
||
} else {
|
||
tr(
|
||
"Adds dictation, paste last and Annotate to GNOME Settings › Keyboard › Custom Shortcuts with your shortcuts. GNOME runs them on the key press, so dictation toggles.",
|
||
)
|
||
};
|
||
let action = button(
|
||
p,
|
||
"gnome-shortcuts-control",
|
||
if on {
|
||
tr("Remove")
|
||
} else {
|
||
tr("Add GNOME keyboard shortcuts")
|
||
},
|
||
ButtonKind::Secondary,
|
||
move |ui: &mut Ui, _| {
|
||
ui.update(|settings| settings.gnome_keyboard_shortcuts = !on);
|
||
},
|
||
);
|
||
setting_row(
|
||
p,
|
||
"gnome-shortcuts",
|
||
tr("GNOME keyboard shortcuts"),
|
||
Some(description),
|
||
action,
|
||
)
|
||
}
|
||
|
||
pub(super) fn command_row(
|
||
p: Paint,
|
||
key: &str,
|
||
title: &str,
|
||
description: &str,
|
||
commands: &[&str],
|
||
) -> El {
|
||
let lines = col()
|
||
.key("commands")
|
||
.gap(2.0)
|
||
.children(commands.iter().enumerate().map(|(index, command)| {
|
||
text(*command)
|
||
.key(format!("command{index}"))
|
||
.font(p.k.ty.mono)
|
||
.color(p.muted())
|
||
.align(rune::Align::End)
|
||
}));
|
||
setting_row(p, key, title, Some(description), lines)
|
||
}
|
||
|
||
/// Lists keyboard input sources every few seconds while General shows the
|
||
/// switching rows. The window lists them itself on Windows and Linux.
|
||
#[cfg(not(target_os = "macos"))]
|
||
pub(super) fn poll_input_sources(ui: &mut Ui, clock: f64) -> bool {
|
||
let switching =
|
||
ui.platform.caps.keyboard_model_switching && ui.settings.keyboard_model_switching.enabled;
|
||
if !switching {
|
||
let changed = !ui.platform.input_sources.is_empty();
|
||
ui.platform.input_sources.clear();
|
||
return changed;
|
||
}
|
||
if ui.pane != super::Pane::General
|
||
|| !ui.live()
|
||
|| !ui.window.as_ref().is_some_and(rune::AppHandle::is_visible)
|
||
|| clock < ui.input_sources_listed_at + 2.0
|
||
{
|
||
return false;
|
||
}
|
||
ui.input_sources_listed_at = clock;
|
||
let listed = crate::keyboard_input_sources::enabled();
|
||
let changed = ui.platform.input_sources != listed;
|
||
ui.platform.input_sources = listed;
|
||
changed
|
||
}
|
||
|
||
/// One row per enabled input source: "Don't switch" or an installed model,
|
||
/// then a language that model supports, as the Language row offers it.
|
||
pub(super) fn input_source_rows(ui: &Ui, p: Paint, layer: &mut Vec<El>) -> Vec<El> {
|
||
ui.platform
|
||
.input_sources
|
||
.iter()
|
||
.enumerate()
|
||
.map(|(index, source)| {
|
||
let mapped = ui
|
||
.settings
|
||
.keyboard_model_switching
|
||
.mappings
|
||
.get(&source.id)
|
||
.cloned();
|
||
let source_id = source.id.clone();
|
||
let key = format!("input-source{index}");
|
||
let model_key = format!("input-source-model{index}");
|
||
let language_key = format!("input-source-language{index}");
|
||
super::speech_model::setting(
|
||
ui,
|
||
p,
|
||
super::speech_model::SpeechRow {
|
||
key: &key,
|
||
model_key: &model_key,
|
||
language_key: &language_key,
|
||
title: &source.name,
|
||
description: None,
|
||
choice: mapped,
|
||
model_menu: Menu::InputSourceModel(index),
|
||
language_menu: Menu::InputSourceLanguage(index),
|
||
},
|
||
|model, fallback| source.language_for(model, fallback),
|
||
move |ui, choice| {
|
||
ui.update(|settings| match choice {
|
||
Some(choice) => {
|
||
settings
|
||
.keyboard_model_switching
|
||
.mappings
|
||
.insert(source_id.clone(), choice);
|
||
}
|
||
None => {
|
||
settings
|
||
.keyboard_model_switching
|
||
.mappings
|
||
.remove(&source_id);
|
||
}
|
||
});
|
||
},
|
||
layer,
|
||
)
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
/// The speech model row's description: preparation progress or its error.
|
||
pub(super) fn transcription_status(ui: &Ui, p: Paint) -> Option<(String, rune::Color)> {
|
||
let transcription = &ui.view.as_ref()?.transcription;
|
||
if let Some(error) = &transcription.error {
|
||
return Some((error.clone(), p.danger()));
|
||
}
|
||
let Some(model) = transcription.preparing else {
|
||
return super::model_import::selection_notice(ui).map(|notice| (notice, p.warning()));
|
||
};
|
||
let name = transcription_models::definition(model).name.to_string();
|
||
let stage = match transcription.preparation_stage {
|
||
Some(ModelPreparationStage::Verifying) => tr("Verifying model").to_string(),
|
||
Some(ModelPreparationStage::Loading) => tr("Loading model").to_string(),
|
||
_ => format!(
|
||
"{} {:.0} MB",
|
||
tr("Downloading"),
|
||
transcription.downloaded_bytes as f64 / 1_000_000.0
|
||
),
|
||
};
|
||
Some((format!("{name} · {stage}"), p.accent()))
|
||
}
|
||
|
||
/// What a recorder shows; each change rolls up into it from below.
|
||
#[derive(Clone, Copy, PartialEq)]
|
||
pub(super) enum Face {
|
||
/// What pressing does (Change shortcut), or that it just saved; the
|
||
/// shortcut's keys sit in their tray beside the recorder.
|
||
Shortcut {
|
||
saved: bool,
|
||
},
|
||
Listening(Prompt),
|
||
}
|
||
|
||
#[derive(Clone, Copy, PartialEq)]
|
||
pub(super) enum Prompt {
|
||
Press,
|
||
/// Why the last chord was rejected.
|
||
Rejected(&'static str),
|
||
/// The modifiers held so far.
|
||
Held(HotkeyModifiers),
|
||
Saving,
|
||
}
|
||
|
||
const RECORDER_HEIGHT: f32 = 28.0;
|
||
/// Between the recorder's edge and a keycap at that edge.
|
||
const RECORDER_CAP_INSET: f32 = 3.0;
|
||
/// How far held keys that overflow the recorder fade out, and the room
|
||
/// above and below them their shadows keep inside that clip.
|
||
const HELD_FADE: f32 = 8.0;
|
||
const HELD_SHADOW_ROOM: f32 = (RECORDER_HEIGHT - KeySize::Small.height()) / 2.0;
|
||
|
||
/// The recorders' keys for Labs › More dictation shortcuts' rows (macOS):
|
||
/// one static key per row, in the rows' order.
|
||
#[cfg(target_os = "macos")]
|
||
const EXTRA_HOTKEY_KEYS: [&str; crate::app_settings::MAX_EXTRA_DICTATION_SHORTCUTS] = [
|
||
"extra-dictation-hotkey-1",
|
||
"extra-dictation-hotkey-2",
|
||
"extra-dictation-hotkey-3",
|
||
"extra-dictation-hotkey-4",
|
||
];
|
||
|
||
/// The recorder's key for `target`.
|
||
pub(super) fn hotkey_key(target: ShortcutTarget) -> &'static str {
|
||
match target {
|
||
ShortcutTarget::Dictation => "dictation-hotkey",
|
||
ShortcutTarget::PasteLast => "paste-last-hotkey",
|
||
ShortcutTarget::RawDictation => "raw-dictation-hotkey",
|
||
#[cfg(target_os = "linux")]
|
||
ShortcutTarget::TypedText => "typed-text-hotkey",
|
||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||
ShortcutTarget::TerminalPaste => "terminal-paste-hotkey",
|
||
ShortcutTarget::Cancel => "cancel-hotkey",
|
||
#[cfg(hex_capture)]
|
||
ShortcutTarget::Capture => "capture-hotkey",
|
||
#[cfg(all(hex_capture, target_os = "macos"))]
|
||
ShortcutTarget::CaptureReplay => "capture-replay-hotkey",
|
||
ShortcutTarget::SecondDictation => "second-dictation-hotkey",
|
||
// Settings keeps at most four rows, so every one has its own key.
|
||
#[cfg(target_os = "macos")]
|
||
ShortcutTarget::ExtraDictation(index) => EXTRA_HOTKEY_KEYS
|
||
.get(index)
|
||
.copied()
|
||
.unwrap_or("extra-dictation-hotkey"),
|
||
#[cfg(target_os = "macos")]
|
||
ShortcutTarget::Screenshot => "screenshot-hotkey",
|
||
#[cfg(target_os = "macos")]
|
||
ShortcutTarget::ScreenshotRecord => "screenshot-record-hotkey",
|
||
}
|
||
}
|
||
|
||
/// What `target`'s recorder shows now.
|
||
pub(super) fn face(ui: &Ui, target: ShortcutTarget) -> Face {
|
||
match ui.capture {
|
||
Capture::Listening {
|
||
target: active,
|
||
message,
|
||
held,
|
||
} if active == target => Face::Listening(match message {
|
||
Some(message) => Prompt::Rejected(message),
|
||
None if held.is_empty() => Prompt::Press,
|
||
None => Prompt::Held(held),
|
||
}),
|
||
Capture::Saving { target: active, .. } if active == target => {
|
||
Face::Listening(Prompt::Saving)
|
||
}
|
||
Capture::Saved { target: active, .. } if active == target => Face::Shortcut { saved: true },
|
||
_ => Face::Shortcut { saved: false },
|
||
}
|
||
}
|
||
|
||
/// In from below, out through the top, both inside the recorder's clip.
|
||
fn roll() -> Transition {
|
||
Transition::push(Edge::Bottom)
|
||
}
|
||
|
||
pub(super) fn face_label(face: Face) -> &'static str {
|
||
match face {
|
||
Face::Shortcut { saved: false } => tr("Change shortcut"),
|
||
Face::Shortcut { saved: true } => tr("Saved"),
|
||
Face::Listening(Prompt::Press | Prompt::Held(_)) => tr("Press shortcut"),
|
||
Face::Listening(Prompt::Rejected(message)) => message,
|
||
Face::Listening(Prompt::Saving) => tr("Saving…"),
|
||
}
|
||
}
|
||
|
||
/// One face of the recorder at its full height. Only the shown face
|
||
/// (`live`) pulses.
|
||
pub(super) fn recorder_face(p: Paint, face: Face, live: bool) -> El {
|
||
let label_style = p.k.ty.ui_medium.lh(16.0);
|
||
let label = |key: &str, copy: &str, color| text(copy).key(key).font(label_style).color(color);
|
||
let face_row = |key: &str| row().key(key).h(RECORDER_HEIGHT).gap(8.0).center_y();
|
||
match face {
|
||
Face::Shortcut { saved } => {
|
||
let what = if saved {
|
||
row()
|
||
.key("saved")
|
||
.gap(2.0)
|
||
.center_y()
|
||
.child(rune::icon(CHECK, 16.0).key("check").color(p.success()))
|
||
.child(label("label", tr("Saved"), p.text()))
|
||
} else {
|
||
row()
|
||
.key("change")
|
||
.child(label("label", tr("Change shortcut"), p.text()))
|
||
};
|
||
face_row("shortcut")
|
||
.px(11.0)
|
||
.center()
|
||
.child(what.transition(roll()))
|
||
}
|
||
Face::Listening(prompt) => {
|
||
let dot = match prompt {
|
||
Prompt::Saving => status_dot(p.muted()),
|
||
_ if live => pulsing_dot(p.danger()),
|
||
_ => status_dot(p.danger()),
|
||
};
|
||
let prompt_el =
|
||
match prompt {
|
||
Prompt::Press => label("prompt", tr("Press shortcut"), p.text()),
|
||
Prompt::Rejected(message) => label("rejected", message, p.danger()),
|
||
Prompt::Held(held) => {
|
||
let held = held_caps(&HotkeyBinding {
|
||
modifiers: held,
|
||
key: None,
|
||
});
|
||
// Held keys stand on the recorder, down. Too many
|
||
// to fit fade out at the right, so Esc stays.
|
||
row()
|
||
.key("held")
|
||
.gap(4.0)
|
||
.center_y()
|
||
.shrink()
|
||
.py(HELD_SHADOW_ROOM)
|
||
.pr(HELD_FADE)
|
||
.clip_fade(0.0, 0.0, HELD_FADE, 0.0)
|
||
.child(row().key("keys").gap(KEY_GAP).children(
|
||
held.iter().enumerate().map(|(index, cap)| {
|
||
keycap(p, index, cap, KeySize::Small, true)
|
||
}),
|
||
))
|
||
.child(label("ellipsis", "…", p.muted()))
|
||
}
|
||
Prompt::Saving => label("saving", tr("Saving…"), p.muted()),
|
||
};
|
||
let face = face_row("listening")
|
||
.pl(11.0)
|
||
.pr(RECORDER_CAP_INSET)
|
||
.child(dot)
|
||
.child(prompt_el.transition(roll()));
|
||
if prompt == Prompt::Saving {
|
||
return face;
|
||
}
|
||
face.child(spacer()).child(
|
||
keycap(p, 0, ESCAPE_KEYCAP, KeySize::Small, false)
|
||
.key("escape")
|
||
.label(tr("Esc to cancel")),
|
||
)
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The Escape key's legend, as the keyboard prints it.
|
||
const ESCAPE_KEYCAP: &str = if cfg!(target_os = "macos") {
|
||
"esc"
|
||
} else {
|
||
"Esc"
|
||
};
|
||
|
||
/// The keys held while recording, each with its side, so an extra key or
|
||
/// the second Option shows before it is recorded: compact on the Mac
|
||
/// (L⌥ R⌥), named elsewhere.
|
||
fn held_caps(held: &HotkeyBinding) -> Vec<String> {
|
||
if cfg!(target_os = "macos") {
|
||
held.keycaps()
|
||
} else {
|
||
shortcut_caps(held, false)
|
||
}
|
||
}
|
||
|
||
/// A shortcut's keycaps, naming the side a modifier must be pressed on
|
||
/// unless a side picker beside them already shows it.
|
||
pub(super) fn shortcut_caps(binding: &HotkeyBinding, side_picker: bool) -> Vec<String> {
|
||
binding
|
||
.sided_keycaps()
|
||
.into_iter()
|
||
.map(|(cap, side)| match side {
|
||
ModifierSide::Left if !side_picker => format!("{} {cap}", tr("Left")),
|
||
ModifierSide::Right if !side_picker => format!("{} {cap}", tr("Right")),
|
||
_ => cap,
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
/// Stable or Dev shows only while this install updates itself: test,
|
||
/// source, managed, and package-manager installs never check a channel.
|
||
pub(super) fn updates_itself(ui: &Ui) -> bool {
|
||
ui.view.as_ref().is_some_and(|view| {
|
||
matches!(
|
||
view.update_status,
|
||
DesktopUpdateStatus::Checking
|
||
| DesktopUpdateStatus::Current
|
||
| DesktopUpdateStatus::Failed
|
||
| DesktopUpdateStatus::Downloading
|
||
| DesktopUpdateStatus::Available
|
||
| DesktopUpdateStatus::ReadyToRestart
|
||
| DesktopUpdateStatus::SwitchAvailable { .. }
|
||
)
|
||
})
|
||
}
|
||
|
||
/// Issue 767: the window takes Menu alone only with Labs › Special keys
|
||
/// alone on.
|
||
#[cfg(all(test, target_os = "linux"))]
|
||
mod special_keys_tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn menu_alone_needs_its_labs_toggle() {
|
||
let menu = HotkeyBinding {
|
||
modifiers: HotkeyModifiers::default(),
|
||
key: Some(HotkeyKey::named("menu")),
|
||
};
|
||
let mut settings = AppSettings::default();
|
||
assert_eq!(
|
||
validate(&settings, ShortcutTarget::Dictation, &menu),
|
||
Err(tr("Add a modifier"))
|
||
);
|
||
settings.labs.standalone_special_keys = true;
|
||
assert_eq!(
|
||
validate(&settings, ShortcutTarget::Dictation, &menu),
|
||
Ok(())
|
||
);
|
||
}
|
||
|
||
/// Issue 1187: the recorder takes Scroll Lock, Pause, and Menu alone.
|
||
#[test]
|
||
fn recorder_takes_special_keys_alone() {
|
||
let mut settings = AppSettings::default();
|
||
settings.labs.standalone_special_keys = true;
|
||
for (key, name) in [
|
||
(Key::ScrollLock, "scroll lock"),
|
||
(Key::Pause, "pause"),
|
||
(Key::ContextMenu, "menu"),
|
||
] {
|
||
let binding = recorded_binding(&KeyEvent {
|
||
key,
|
||
mods: Default::default(),
|
||
})
|
||
.unwrap();
|
||
assert_eq!(binding.key.as_ref().unwrap().name(), name);
|
||
assert_eq!(
|
||
validate(&settings, ShortcutTarget::Dictation, &binding),
|
||
Ok(())
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Issue 1050: the ISO section key alone needs Labs › § key alone on
|
||
/// Linux and macOS; with a modifier it records as before. Linux's recorder
|
||
/// checks the lab itself; macOS's recorder records the chord and `validate`
|
||
/// refuses it here, before saving.
|
||
#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
|
||
mod section_key_tests {
|
||
use super::*;
|
||
use crate::app_settings::ISO_SECTION_KEY_CODE;
|
||
|
||
#[test]
|
||
fn section_alone_needs_its_labs_toggle() {
|
||
let section = HotkeyBinding {
|
||
modifiers: HotkeyModifiers::default(),
|
||
key: Some(HotkeyKey::named("§")),
|
||
};
|
||
let with_control = HotkeyBinding {
|
||
modifiers: HotkeyModifiers::control_option(),
|
||
key: Some(HotkeyKey::named("§")),
|
||
};
|
||
let mut settings = AppSettings::default();
|
||
assert_eq!(
|
||
validate(&settings, ShortcutTarget::Dictation, §ion),
|
||
Err(tr("Add a modifier"))
|
||
);
|
||
assert_eq!(
|
||
validate(&settings, ShortcutTarget::Dictation, &with_control),
|
||
Ok(())
|
||
);
|
||
settings.labs.section_key_alone = true;
|
||
assert_eq!(
|
||
validate(&settings, ShortcutTarget::Dictation, §ion),
|
||
Ok(())
|
||
);
|
||
assert_eq!(section.keycaps(), ["§"]);
|
||
}
|
||
|
||
/// macOS labels the section key by what it types on a dead-key layout,
|
||
/// `{code: 10, label: "^"}`; validation still knows it is the section
|
||
/// key.
|
||
#[test]
|
||
fn a_dead_key_section_binding_needs_its_labs_toggle_on_macos() {
|
||
if !cfg!(target_os = "macos") {
|
||
return;
|
||
}
|
||
let dead_key = HotkeyBinding {
|
||
modifiers: HotkeyModifiers::default(),
|
||
key: Some(HotkeyKey {
|
||
code: ISO_SECTION_KEY_CODE,
|
||
label: "^".into(),
|
||
}),
|
||
};
|
||
assert!(dead_key.is_lone_section_key());
|
||
let mut settings = AppSettings::default();
|
||
assert_eq!(
|
||
validate(&settings, ShortcutTarget::Dictation, &dead_key),
|
||
Err(tr("Add a modifier"))
|
||
);
|
||
settings.labs.section_key_alone = true;
|
||
assert_eq!(
|
||
validate(&settings, ShortcutTarget::Dictation, &dead_key),
|
||
Ok(())
|
||
);
|
||
}
|
||
}
|
||
|
||
/// Issue 181: any shortcut on the microphone (dictation) key needs Labs ›
|
||
/// Microphone key alone on macOS, with or without a modifier. macOS's
|
||
/// recorder records the chord and `validate` refuses it here, before saving,
|
||
/// with the same "Unsupported key" the key gave before. Dictation, Cancel,
|
||
/// and Screenshots all go through this check.
|
||
#[cfg(all(test, target_os = "macos"))]
|
||
#[path = "settings_microphone_key_tests.rs"]
|
||
mod microphone_key_tests;
|
||
|
||
/// Plain ⌫ while recording turns an optional shortcut off; a required one
|
||
/// ignores it, and ⌫ with a modifier records like any key.
|
||
#[cfg(test)]
|
||
mod erase_tests {
|
||
use super::*;
|
||
use crate::app_settings::ModifierSide;
|
||
|
||
fn erase(modifiers: HotkeyModifiers) -> HotkeyBinding {
|
||
let key = if cfg!(target_os = "macos") {
|
||
HotkeyKey {
|
||
code: 51,
|
||
label: "Delete".into(),
|
||
}
|
||
} else {
|
||
HotkeyKey::named("backspace")
|
||
};
|
||
HotkeyBinding {
|
||
modifiers,
|
||
key: Some(key),
|
||
}
|
||
}
|
||
|
||
fn recording(target: ShortcutTarget) -> Ui {
|
||
let mut ui = super::super::scenes::mac_fixture();
|
||
ui.settings.paste_last_hotkey = Some(HotkeyBinding::paste_last_default());
|
||
begin_capture(&mut ui, target);
|
||
ui
|
||
}
|
||
|
||
#[test]
|
||
fn plain_erase_turns_an_optional_shortcut_off() {
|
||
let mut ui = recording(ShortcutTarget::PasteLast);
|
||
record(
|
||
&mut ui,
|
||
ShortcutTarget::PasteLast,
|
||
Ok(erase(HotkeyModifiers::default())),
|
||
);
|
||
assert_eq!(ui.settings.paste_last_hotkey, None);
|
||
assert!(matches!(ui.capture, Capture::Saved { .. }));
|
||
}
|
||
|
||
#[test]
|
||
fn a_required_shortcut_ignores_plain_erase() {
|
||
let mut ui = recording(ShortcutTarget::Dictation);
|
||
let dictation = ui.settings.dictation_hotkey.clone();
|
||
record(
|
||
&mut ui,
|
||
ShortcutTarget::Dictation,
|
||
Ok(erase(HotkeyModifiers::default())),
|
||
);
|
||
assert_eq!(ui.settings.dictation_hotkey, dictation);
|
||
assert!(matches!(
|
||
ui.capture,
|
||
Capture::Listening {
|
||
message: Some(_),
|
||
..
|
||
}
|
||
));
|
||
assert!(!can_turn_off(ShortcutTarget::Dictation));
|
||
assert!(!can_turn_off(ShortcutTarget::Cancel));
|
||
}
|
||
|
||
#[test]
|
||
fn erase_with_a_modifier_records() {
|
||
let mut ui = recording(ShortcutTarget::PasteLast);
|
||
let chord = erase(HotkeyModifiers {
|
||
control: Some(ModifierSide::Either),
|
||
..HotkeyModifiers::default()
|
||
});
|
||
assert!(!chord.is_bare_erase());
|
||
record(&mut ui, ShortcutTarget::PasteLast, Ok(chord.clone()));
|
||
assert_eq!(ui.settings.paste_last_hotkey, Some(chord));
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod gnome_keys_tests {
|
||
use super::grants::gnome_keeps;
|
||
|
||
#[test]
|
||
fn gnome_keeps_its_window_menu_key_however_it_is_written() {
|
||
assert!(gnome_keeps("Alt+Space"));
|
||
assert!(gnome_keeps("alt+space"));
|
||
assert!(gnome_keeps("Ctrl+Alt+Delete"));
|
||
assert!(gnome_keeps("Shift+Alt+Tab"));
|
||
assert!(!gnome_keeps("Ctrl+Alt+Space"));
|
||
assert!(!gnome_keeps("F9"));
|
||
assert!(!gnome_keeps("Super+D"));
|
||
}
|
||
}
|