Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion openless-all/app/crates/openless-core/src/shortcut_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ pub const SIDE_SPECIFIC_NON_DICTATION_MSG: &str =
"Side-specific modifier shortcuts are only supported for dictation start/stop.";

pub fn reject_side_specific_non_dictation(binding: &ShortcutBinding) -> Result<(), String> {
if binding.primary == "MacDictationKey" {
return Err("The Mac Dictation key is only supported for dictation start/stop.".into());
}
if binding_requires_side_aware_hook(binding) {
return Err(SIDE_SPECIFIC_NON_DICTATION_MSG.to_string());
}
Expand Down Expand Up @@ -193,6 +196,10 @@ pub fn binding_from_legacy_trigger(trigger: HotkeyTrigger) -> ShortcutBinding {
}

pub fn validate_shortcut_binding(binding: &ShortcutBinding) -> Result<(), ShortcutBindingError> {
#[cfg(target_os = "macos")]
if binding.primary == "MacDictationKey" && binding.modifiers.is_empty() {
return Ok(());
}
if legacy_modifier_trigger(binding).is_some() {
return Ok(());
}
Expand Down Expand Up @@ -278,6 +285,14 @@ fn validate_primary(raw: &str) -> Result<(), ShortcutBindingError> {
| "F10"
| "F11"
| "F12"
| "F13"
| "F14"
| "F15"
| "F16"
| "F17"
| "F18"
| "F19"
| "F20"
) {
return Ok(());
}
Expand Down Expand Up @@ -785,7 +800,11 @@ mod tests {
fn validates_shared_shortcut_grammar_without_a_native_hotkey_crate() {
assert!(validate_shortcut_binding(&combo("D", &["cmd", "shift"])).is_ok());
assert!(validate_shortcut_binding(&combo("?", &["shift"])).is_ok());
assert!(validate_shortcut_binding(&combo("F12", &[])).is_ok());
for number in 1..=20 {
assert!(validate_shortcut_binding(&combo(&format!("F{number}"), &[])).is_ok());
}
assert!(validate_shortcut_binding(&combo(" f20 ", &[])).is_ok());
assert!(validate_shortcut_binding(&combo("F21", &[])).is_err());
assert_eq!(
validate_shortcut_binding(&combo("D", &["hyper"])),
Err(ShortcutBindingError::UnsupportedModifier("hyper".into()))
Expand Down
49 changes: 49 additions & 0 deletions openless-all/app/src-tauri/src/combo_hotkey.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ pub struct ComboHotkeyMonitor {

struct Inner {
registered: Mutex<Option<RegisteredHotkey>>,
#[cfg(target_os = "macos")]
native_dictation: Mutex<Option<crate::macos_dictation_key::Monitor>>,
tx: Sender<ComboHotkeyEvent>,
}

Expand All @@ -67,6 +69,18 @@ impl ComboHotkeyMonitor {
binding: ShortcutBinding,
tx: Sender<ComboHotkeyEvent>,
) -> Result<Self, ComboHotkeyError> {
#[cfg(target_os = "macos")]
if is_native_dictation(&binding) {
let native = crate::macos_dictation_key::Monitor::start(tx.clone())
.map_err(ComboHotkeyError::RegisterFailed)?;
return Ok(Self {
inner: Arc::new(Inner {
registered: Mutex::new(None),
native_dictation: Mutex::new(Some(native)),
tx,
}),
});
}
let runtime = GlobalHotkeyRuntime::shared()
.map_err(|e| ComboHotkeyError::ManagerInitFailed(e.to_string()))?;

Expand All @@ -87,13 +101,26 @@ impl ComboHotkeyMonitor {
Ok(Self {
inner: Arc::new(Inner {
registered: Mutex::new(Some(registered)),
#[cfg(target_os = "macos")]
native_dictation: Mutex::new(None),
tx,
}),
})
}

/// 替换当前注册的组合键(用户在设置里改了组合键时)。
pub fn update_binding(&self, binding: ShortcutBinding) -> Result<(), ComboHotkeyError> {
#[cfg(target_os = "macos")]
if is_native_dictation(&binding) {
if self.native_dictation_active() {
return Ok(());
}
let native = crate::macos_dictation_key::Monitor::start(self.inner.tx.clone())
.map_err(ComboHotkeyError::RegisterFailed)?;
*self.inner.native_dictation.lock() = Some(native);
self.inner.registered.lock().take();
return Ok(());
}
let next = parse_binding(&binding)?;
let mut current = self.inner.registered.lock();
if let Some(prev) = current.as_ref() {
Expand All @@ -115,13 +142,31 @@ impl ComboHotkeyMonitor {
})
.map_err(|e| ComboHotkeyError::RegisterFailed(format!("spawn forward thread: {e}")))?;
*current = Some(registered);
#[cfg(target_os = "macos")]
self.inner.native_dictation.lock().take();
Ok(())
}
}

#[cfg(target_os = "macos")]
fn is_native_dictation(binding: &ShortcutBinding) -> bool {
binding.primary == crate::macos_dictation_key::PRIMARY && binding.modifiers.is_empty()
}
#[cfg(target_os = "macos")]
impl ComboHotkeyMonitor {
pub fn native_dictation_active(&self) -> bool {
self.inner
.native_dictation
.lock()
.as_ref()
.is_some_and(|m| m.active())
}
}
impl Drop for ComboHotkeyMonitor {
fn drop(&mut self) {
self.inner.registered.lock().take();
#[cfg(target_os = "macos")]
self.inner.native_dictation.lock().take();
}
}

Expand All @@ -145,6 +190,10 @@ fn forward_loop(hotkey_id: u32, rx: Receiver<GlobalHotKeyEvent>, tx: Sender<Comb

/// 测试一个组合键是否可以注册(不实际注册,仅验证格式)。
pub fn validate_binding(binding: &ShortcutBinding) -> Result<(), ComboHotkeyError> {
#[cfg(target_os = "macos")]
if is_native_dictation(binding) {
return Ok(());
}
parse_binding(binding)?;
Ok(())
}
Expand Down
39 changes: 20 additions & 19 deletions openless-all/app/src-tauri/src/commands/hotkeys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,16 @@ pub fn validate_shortcut_binding(binding: ShortcutBinding) -> Result<(), String>
}

#[tauri::command]
pub fn set_dictation_hotkey(
pub async fn set_dictation_hotkey(
coord: CoordinatorState<'_>,
binding: ShortcutBinding,
) -> Result<(), String> {
crate::shortcut_binding::validate_binding(&binding).map_err(|e| e.to_string())?;
reject_bare_shift_dictation_shortcut(&binding)?;
let mut prefs = coord.backend().get_preferences();
prefs.dictation_hotkey = binding;
sync_dictation_hotkey_legacy_fields(&mut prefs);
reject_hotkey_collisions(&prefs)?;
super::settings::persist_strict_settings(&coord, prefs)
let coord = Arc::clone(coord.inner());
tauri::async_runtime::spawn_blocking(move || {
super::settings::replace_dictation_hotkey(&coord, binding)
})
.await
.map_err(|error| error.to_string())?
}

#[tauri::command]
Expand Down Expand Up @@ -120,19 +119,21 @@ pub fn validate_combo_hotkey(binding: ComboBinding) -> Result<(), String> {

/// 设置自定义录音组合键并热更新 monitor。
#[tauri::command]
pub fn set_combo_hotkey(coord: CoordinatorState<'_>, binding: ComboBinding) -> Result<(), String> {
let mut prefs = coord.backend().get_preferences();
pub async fn set_combo_hotkey(
coord: CoordinatorState<'_>,
binding: ComboBinding,
) -> Result<(), String> {
let shortcut = ShortcutBinding {
primary: binding.primary.clone(),
modifiers: binding.modifiers.clone(),
primary: binding.primary,
modifiers: binding.modifiers,
};
reject_bare_shift_dictation_shortcut(&shortcut)?;
crate::combo_hotkey::validate_binding(&shortcut).map_err(|e| e.to_string())?;
prefs.custom_combo_hotkey = Some(binding);
prefs.dictation_hotkey = shortcut;
sync_dictation_hotkey_legacy_fields(&mut prefs);
reject_hotkey_collisions(&prefs)?;
super::settings::persist_strict_settings(&coord, prefs)
crate::combo_hotkey::validate_binding(&shortcut).map_err(|error| error.to_string())?;
let coord = Arc::clone(coord.inner());
tauri::async_runtime::spawn_blocking(move || {
super::settings::replace_dictation_hotkey(&coord, shortcut)
})
.await
.map_err(|error| error.to_string())?
}

#[cfg(test)]
Expand Down
36 changes: 36 additions & 0 deletions openless-all/app/src-tauri/src/commands/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -576,3 +576,39 @@ pub async fn app_download_and_install_android_update(
Err("应用内更新仅支持 Android".to_string())
}
}

/// Replace the single dictation binding under the existing settings transaction.
pub(crate) fn replace_dictation_hotkey(
coord: &Coordinator,
binding: ShortcutBinding,
) -> Result<(), String> {
let _host_guard = coord.lock_settings_host();
let mut prefs = coord.backend().get_preferences();
crate::shortcut_binding::validate_binding(&binding).map_err(|error| error.to_string())?;
reject_bare_shift_dictation_shortcut(&binding)?;
#[cfg(target_os = "macos")]
{
let native = crate::macos_dictation_key::PRIMARY;
if prefs.dictation_hotkey.primary == native || binding.primary == native {
if coord.dictation_shortcut_is_busy() {
return Err("macDictationKeyBusy".into());
}
if binding == prefs.dictation_hotkey {
// No settings effect is generated for an unchanged binding.
return coord.try_update_native_dictation_binding();
}
}
}
prefs.dictation_hotkey = binding;
sync_dictation_hotkey_legacy_fields(&mut prefs);
reject_hotkey_collisions(&prefs)?;
coord
.backend()
.update_settings(
prefs,
openless_core::SettingsUpdateOptions::STRICT,
&TauriSettingsRuntime::new(coord),
)
.map(|_| ())
.map_err(|error| error.to_string())
}
29 changes: 24 additions & 5 deletions openless-all/app/src-tauri/src/coordinator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ mod capsule_focus;
#[path = "coordinator/dictation_core.rs"]
mod dictation;
mod hotkey_loops;
#[cfg(target_os = "macos")]
mod native_dictation_key;
mod qa;
#[cfg(all(not(mobile), target_os = "windows"))]
pub(crate) mod selection_voice_session;
Expand Down Expand Up @@ -1464,11 +1466,28 @@ impl Coordinator {
if previous.style_packs != next.style_packs {
self.try_update_style_pack_hotkey_bindings()?;
}
if previous.dictation != next.dictation || previous.dictation_mode != next.dictation_mode {
self.update_hotkey_binding();
}
if previous.dictation != next.dictation {
self.update_combo_hotkey_binding();
#[cfg(target_os = "macos")]
let native_transition = previous.dictation.primary == crate::macos_dictation_key::PRIMARY
|| next.dictation.primary == crate::macos_dictation_key::PRIMARY;
#[cfg(not(target_os = "macos"))]
let native_transition = false;
if native_transition {
#[cfg(target_os = "macos")]
if previous.dictation != next.dictation
|| previous.dictation_mode != next.dictation_mode
{
self.try_update_native_dictation_binding()?;
self.update_modifier_shortcut_bindings();
}
} else {
if previous.dictation != next.dictation
|| previous.dictation_mode != next.dictation_mode
{
self.update_hotkey_binding();
}
if previous.dictation != next.dictation {
self.update_combo_hotkey_binding();
}
}
if previous.qa != next.qa {
self.update_qa_hotkey_binding();
Expand Down
108 changes: 108 additions & 0 deletions openless-all/app/src-tauri/src/coordinator/native_dictation_key.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
//! Synchronous native-key registration participates in the Core settings transaction.
use super::*;

impl Coordinator {
pub(crate) fn dictation_shortcut_is_busy(&self) -> bool {
!matches!(
self.backend().snapshot().dictation.phase,
openless_core::DictationPhase::Idle
| openless_core::DictationPhase::Completed
| openless_core::DictationPhase::Cancelled
| openless_core::DictationPhase::Failed
)
}

/// Keep the previous listener until replacement registration succeeds. The
/// caller is a worker thread; Carbon ownership changes run on the UI thread.
pub(crate) fn try_update_native_dictation_binding(&self) -> Result<(), String> {
let target = hotkey_runtime_target(&self.inner);
let inner = Arc::clone(&self.inner);
let (done_tx, done_rx) = mpsc::sync_channel(1);
// Cancel queued work on timeout. Once a callback has started, wait for
// its acknowledgement before Core can roll back the runtime target.
// This gate never nests with the target mutex on the calling thread.
let cancelled = Arc::new(Mutex::new(false));
let callback_cancelled = Arc::clone(&cancelled);
self.inner.host.run_on_main_thread(move || {
let cancelled = callback_cancelled.lock();
let result = (|| {
if *cancelled || hotkey_runtime_target(&inner) != target {
return Err("macDictationKeyChanged".into());
}
let binding = target.dictation.clone();
let trigger = crate::shortcut_binding::legacy_modifier_trigger(&binding);
if trigger.is_some() || is_unconfigured_shortcut(&binding) {
if trigger.is_some() && inner.hotkey.lock().is_none() {
return Err("macDictationKeyUnavailable".into());
}
inner.combo_hotkey.lock().take();
inner.side_aware_combo.lock().take();
} else if crate::shortcut_binding::binding_requires_side_aware_hook(&binding) {
let mut slot = inner.side_aware_combo.lock();
if let Some(monitor) = slot.as_ref() {
// A failed native registration leaves this route alive.
// Reuse its sender: dropping an old side-aware handle
// after creating another would clear the singleton route.
monitor
.update_binding(binding)
.map_err(|error| error.to_string())?;
} else {
let (tx, rx) = mpsc::channel();
let monitor =
crate::side_aware_combo::SideAwareComboMonitor::start(binding, tx)
.map_err(|error| error.to_string())?;
let bridge_inner = Arc::clone(&inner);
std::thread::Builder::new()
.name("openless-side-combo-bridge".into())
.spawn(move || combo_hotkey_bridge_loop(bridge_inner, rx))
.map_err(|error| error.to_string())?;
*slot = Some(monitor);
}
inner.combo_hotkey.lock().take();
} else {
let mut slot = inner.combo_hotkey.lock();
if let Some(monitor) = slot.as_ref() {
monitor
.update_binding(binding)
.map_err(|error| error.to_string())?;
} else {
let (tx, rx) = mpsc::channel();
let monitor = ComboHotkeyMonitor::start(binding, tx)
.map_err(|error| error.to_string())?;
let bridge_inner = Arc::clone(&inner);
std::thread::Builder::new()
.name("openless-combo-hotkey-bridge".into())
.spawn(move || combo_hotkey_bridge_loop(bridge_inner, rx))
.map_err(|error| error.to_string())?;
*slot = Some(monitor);
}
inner.side_aware_combo.lock().take();
}
if let Some(monitor) = inner.hotkey.lock().as_ref() {
monitor.update_binding(crate::types::HotkeyBinding {
trigger: trigger.unwrap_or(crate::types::HotkeyTrigger::Custom),
mode: target.dictation_mode,
keys: None,
});
}
Ok(())
})();
let _ = done_tx.send(result);
})?;
match done_rx.recv_timeout(std::time::Duration::from_secs(5)) {
Ok(result) => result,
Err(_) => {
let mut cancelled = cancelled.lock();
// A running callback may have finished while we acquired the
// gate. Its real result takes precedence over the timeout.
match done_rx.try_recv() {
Ok(result) => result,
Err(_) => {
*cancelled = true;
Err("macDictationKeyUnavailable".into())
}
}
}
}
}
}
Loading