mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* feat(settings): one settings.json on every OS with a one-time Windows and Linux migration AppSettings compiles on macOS, Windows, and Linux and is the only persisted settings file. Shortcuts use one HotkeyBinding: macOS identifies the key by its layout-resolved code; Windows and Linux by the key name in its label, which their input layers translate. The first launch adopts windows-settings.json or linux-settings.json and keeps the old file as *.migrated. WindowsSettings and LinuxSettings remain as runtime views projected from AppSettings for the dictation loops, and their save merges back into settings.json. * feat(ui): open the shared AppWindow on macOS, Windows, and Linux app_window.rs is the one desktop window. Each OS supplies a platform module (app_window/macos.rs, windows.rs, linux.rs) with the same items: its window state, a Capabilities struct that decides which panes and rows exist, window chrome, and the actions only its runtime can perform. - macOS keeps its look; Meetings, Commands, the HUD Lab, permission prompts, Sparkle, and the Dock icon move into app_window/macos.rs. - Windows opens AppWindow under its 40 px caption with a full-height sidebar, Segoe UI, and Fluent icons. The tray, HUD window, and listener host stay in windows_app.rs; saved settings reach the host through WindowsDesktopHost::apply_settings. Shortcuts record by polling the keyboard state. - Linux's Settings process opens AppWindow, saves settings.json, and asks hex.service to reload it (Request::ReloadSettings). - New shared rows, shown only where a capability allows: the Enabled/Disabled listener card, Enable on launch, Recording indicator, Interface language, Software updates, and Terminal paste. - onboarding, login_item, application_catalog, transcription_preparation, personal_commands, and the command modules compile on every OS. - HEX_LEGACY_UI=1 keeps the previous Windows and Linux screens until they are deleted. * test(linux): service IPC checks read settings.json and cover ReloadSettings * fix(ui): drag the window by its caption and empty sidebar, and keep settings controls unclipped - The Windows caption row occludes the shared window's focus-on-click so Windows receives the press for dragging, Aero Snap, double-click maximize, and the caption buttons. - Empty sidebar space moves the window on every OS: the caption hit test on Windows, performWindowDragWithEvent on macOS, start_window_move on Linux. - Settings rows keep their controls at intrinsic width; the copy column shrinks and wraps, and a control wraps below the copy only when the row is narrower than both. Shortcut controls size word keycaps (Ctrl, Space) by their labels. * fix(macos): pass the main-thread marker to NSEvent::window * refactor(windows): delete the legacy Windows screens and WindowsSettings The Windows host keeps the listener, tray, and HUD and reads AppSettings directly. WindowsHotkey moves into windows_input as the keyboard hook's binding type; windows_migration reads the beta's windows-settings.json once. The Windows-only desktop_* panes, windows_desktop_host, and HEX_LEGACY_UI on Windows are gone. * refactor(linux): delete LinuxApp and LinuxSettings; the service records shortcuts and prepares models The Settings window asks hex.service to record the dictation shortcut (Wayland reads physical keys in the service; X11 records in the window and the service registers it) and to prepare models, so closing Settings never cancels a download. The service saves only what it owns on top of the current settings.json. LinuxHotkey moves into linux_input; linux_migration reads the beta's linux-settings.json once. Modes > Transformations shows the custom transformations workspace setup where there is no Commands pane. * fix(linux): compile the service tests and IPC check against settings.json * fix(ui): hide While dictating, Microphone mode, and Double-tap only where the runtime lacks them * feat(settings): switch English dictation to Parakeet Unified English once On the first load of settings that predate it, every user dictating in English moves to the streaming English model, on every OS and for migrated Windows and Linux beta files. settings.json records the switch in a new migrations list, so it runs once and a later choice sticks. The previous model stays downloaded and in the recent models. Other languages and Auto keep their model. * fix(linux): start the listener at service launch only when Enable on launch is on
388 lines
12 KiB
Rust
388 lines
12 KiB
Rust
//! First-run setup state. macOS gates dictation on three privacy
|
|
//! permissions; Windows and Linux have no such grants, so their permission
|
|
//! states are always ready and only the transcription model step applies.
|
|
|
|
use std::fs::{self, OpenOptions};
|
|
#[cfg(unix)]
|
|
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
|
use std::path::Path;
|
|
#[cfg(target_os = "macos")]
|
|
use std::process::Command;
|
|
|
|
#[cfg(target_os = "macos")]
|
|
use block2::RcBlock;
|
|
#[cfg(target_os = "macos")]
|
|
use objc2::msg_send;
|
|
#[cfg(target_os = "macos")]
|
|
use objc2::runtime::{AnyClass, Bool};
|
|
#[cfg(target_os = "macos")]
|
|
use objc2_foundation::NSString;
|
|
|
|
use crate::transcription_models::TranscriptionSelection;
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
pub enum PermissionState {
|
|
Ready,
|
|
NeedsRequest,
|
|
NeedsSettings,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
pub enum PermissionKind {
|
|
Microphone,
|
|
InputMonitoring,
|
|
Accessibility,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
pub enum PermissionAction {
|
|
RequestMicrophone,
|
|
OpenMicrophoneSettings,
|
|
OpenInputMonitoringSettings,
|
|
OpenAccessibilitySettings,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
pub struct PermissionWarning {
|
|
pub kind: PermissionKind,
|
|
pub action: PermissionAction,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
pub struct SetupStatus {
|
|
pub microphone: PermissionState,
|
|
pub input_monitoring: PermissionState,
|
|
pub accessibility: PermissionState,
|
|
pub transcription_model: bool,
|
|
}
|
|
|
|
impl SetupStatus {
|
|
pub fn ready(self) -> bool {
|
|
self.microphone == PermissionState::Ready
|
|
&& self.input_monitoring == PermissionState::Ready
|
|
&& self.accessibility == PermissionState::Ready
|
|
&& self.transcription_model
|
|
}
|
|
}
|
|
|
|
pub fn permission_warnings(status: SetupStatus) -> Vec<PermissionWarning> {
|
|
let mut warnings = Vec::with_capacity(3);
|
|
match status.microphone {
|
|
PermissionState::Ready => {}
|
|
PermissionState::NeedsRequest => warnings.push(PermissionWarning {
|
|
kind: PermissionKind::Microphone,
|
|
action: PermissionAction::RequestMicrophone,
|
|
}),
|
|
PermissionState::NeedsSettings => warnings.push(PermissionWarning {
|
|
kind: PermissionKind::Microphone,
|
|
action: PermissionAction::OpenMicrophoneSettings,
|
|
}),
|
|
}
|
|
if status.input_monitoring != PermissionState::Ready {
|
|
warnings.push(PermissionWarning {
|
|
kind: PermissionKind::InputMonitoring,
|
|
action: PermissionAction::OpenInputMonitoringSettings,
|
|
});
|
|
}
|
|
if status.accessibility != PermissionState::Ready {
|
|
warnings.push(PermissionWarning {
|
|
kind: PermissionKind::Accessibility,
|
|
action: PermissionAction::OpenAccessibilitySettings,
|
|
});
|
|
}
|
|
warnings
|
|
}
|
|
|
|
pub fn completion_recorded() -> bool {
|
|
let Ok(directory) = crate::app_paths::support_dir() else {
|
|
return false;
|
|
};
|
|
completion_recorded_at(&directory)
|
|
}
|
|
|
|
pub fn record_completion() -> color_eyre::Result<()> {
|
|
let directory = crate::app_paths::support_dir()?;
|
|
record_completion_at(&directory)
|
|
}
|
|
|
|
pub(crate) fn completion_recorded_at(directory: &Path) -> bool {
|
|
if directory.join("onboarding-complete").is_file() {
|
|
return true;
|
|
}
|
|
if directory.join("onboarding-pending").is_file() || !directory.join("settings.json").is_file()
|
|
{
|
|
return false;
|
|
}
|
|
if let Err(error) = record_completion_at(directory) {
|
|
tracing::warn!(%error, "could not migrate onboarding completion");
|
|
}
|
|
true
|
|
}
|
|
|
|
pub(crate) fn record_pending_at(directory: &Path) -> color_eyre::Result<()> {
|
|
fs::create_dir_all(directory)?;
|
|
write_owner_only_marker(&directory.join("onboarding-pending"), false)?;
|
|
sync_directory(directory)?;
|
|
Ok(())
|
|
}
|
|
|
|
pub(crate) fn record_completion_at(directory: &Path) -> color_eyre::Result<()> {
|
|
fs::create_dir_all(directory)?;
|
|
let destination = directory.join("onboarding-complete");
|
|
let temporary = directory.join(".onboarding-complete.tmp");
|
|
write_owner_only_marker(&temporary, true)?;
|
|
fs::rename(temporary, destination)?;
|
|
sync_directory(directory)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Windows cannot open a directory as a file; its renames are durable once
|
|
/// the call returns.
|
|
fn sync_directory(directory: &Path) -> color_eyre::Result<()> {
|
|
#[cfg(unix)]
|
|
fs::File::open(directory)?.sync_all()?;
|
|
#[cfg(not(unix))]
|
|
let _ = directory;
|
|
Ok(())
|
|
}
|
|
|
|
fn write_owner_only_marker(path: &Path, truncate: bool) -> color_eyre::Result<()> {
|
|
let mut options = OpenOptions::new();
|
|
options.create(true).truncate(truncate).write(true);
|
|
#[cfg(unix)]
|
|
options.mode(0o600);
|
|
let file = options.open(path)?;
|
|
#[cfg(unix)]
|
|
file.set_permissions(fs::Permissions::from_mode(0o600))?;
|
|
file.sync_all()?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn status(selection: &TranscriptionSelection) -> SetupStatus {
|
|
let transcription_model = crate::transcription_models::validate(selection)
|
|
.is_ok_and(|model| crate::transcription_models::is_installed(model, &selection.language));
|
|
status_with_transcription_model(transcription_model)
|
|
}
|
|
|
|
#[cfg(target_os = "macos")]
|
|
pub fn status_with_transcription_model(transcription_model: bool) -> SetupStatus {
|
|
SetupStatus {
|
|
microphone: microphone_state(),
|
|
input_monitoring: settings(CGPreflightListenEventAccess()),
|
|
accessibility: settings(CGPreflightPostEventAccess()),
|
|
transcription_model,
|
|
}
|
|
}
|
|
|
|
#[cfg(not(target_os = "macos"))]
|
|
pub fn status_with_transcription_model(transcription_model: bool) -> SetupStatus {
|
|
SetupStatus {
|
|
microphone: PermissionState::Ready,
|
|
input_monitoring: PermissionState::Ready,
|
|
accessibility: PermissionState::Ready,
|
|
transcription_model,
|
|
}
|
|
}
|
|
|
|
#[cfg(target_os = "macos")]
|
|
pub fn request_microphone() {
|
|
let Some(class) = AnyClass::get(c"AVCaptureDevice") else {
|
|
tracing::error!("AVCaptureDevice is unavailable");
|
|
return;
|
|
};
|
|
let handler = RcBlock::new(|granted: Bool| {
|
|
tracing::info!(
|
|
granted = granted.as_bool(),
|
|
"microphone permission request finished"
|
|
);
|
|
});
|
|
unsafe {
|
|
let _: () = msg_send![
|
|
class,
|
|
requestAccessForMediaType: &*AVMediaTypeAudio,
|
|
completionHandler: &*handler
|
|
];
|
|
}
|
|
}
|
|
|
|
#[cfg(target_os = "macos")]
|
|
pub fn open_permission_settings(permission: &str) {
|
|
let pane = match permission {
|
|
"microphone" => "Privacy_Microphone",
|
|
"input" => "Privacy_ListenEvent",
|
|
"accessibility" => "Privacy_Accessibility",
|
|
_ => "Privacy",
|
|
};
|
|
if let Err(error) = Command::new("/usr/bin/open")
|
|
.arg(format!(
|
|
"x-apple.systempreferences:com.apple.preference.security?{pane}"
|
|
))
|
|
.spawn()
|
|
{
|
|
tracing::error!(%error, "could not open Privacy & Security settings");
|
|
}
|
|
}
|
|
|
|
#[cfg(target_os = "macos")]
|
|
fn microphone_state() -> PermissionState {
|
|
let Some(class) = AnyClass::get(c"AVCaptureDevice") else {
|
|
return PermissionState::NeedsRequest;
|
|
};
|
|
let status: isize =
|
|
unsafe { msg_send![class, authorizationStatusForMediaType: &*AVMediaTypeAudio] };
|
|
microphone_authorization_state(status)
|
|
}
|
|
|
|
#[cfg(target_os = "macos")]
|
|
const fn settings(value: bool) -> PermissionState {
|
|
if value {
|
|
PermissionState::Ready
|
|
} else {
|
|
PermissionState::NeedsSettings
|
|
}
|
|
}
|
|
|
|
#[cfg(any(target_os = "macos", test))]
|
|
const fn microphone_authorization_state(status: isize) -> PermissionState {
|
|
match status {
|
|
0 => PermissionState::NeedsRequest,
|
|
3 => PermissionState::Ready,
|
|
_ => PermissionState::NeedsSettings,
|
|
}
|
|
}
|
|
|
|
#[cfg(target_os = "macos")]
|
|
#[link(name = "AVFoundation", kind = "framework")]
|
|
unsafe extern "C" {
|
|
static AVMediaTypeAudio: *const NSString;
|
|
}
|
|
|
|
#[cfg(target_os = "macos")]
|
|
#[link(name = "CoreGraphics", kind = "framework")]
|
|
unsafe extern "C" {
|
|
safe fn CGPreflightListenEventAccess() -> bool;
|
|
safe fn CGPreflightPostEventAccess() -> bool;
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn missing_commands_model_does_not_block_dictation_setup() {
|
|
let mut status = SetupStatus {
|
|
microphone: PermissionState::Ready,
|
|
input_monitoring: PermissionState::Ready,
|
|
accessibility: PermissionState::Ready,
|
|
transcription_model: true,
|
|
};
|
|
assert!(status.ready());
|
|
status.transcription_model = false;
|
|
assert!(!status.ready());
|
|
status.transcription_model = true;
|
|
status.microphone = PermissionState::NeedsRequest;
|
|
assert!(!status.ready());
|
|
status.microphone = PermissionState::Ready;
|
|
status.input_monitoring = PermissionState::NeedsSettings;
|
|
assert!(!status.ready());
|
|
status.input_monitoring = PermissionState::Ready;
|
|
status.accessibility = PermissionState::NeedsSettings;
|
|
assert!(!status.ready());
|
|
}
|
|
|
|
#[test]
|
|
fn denied_microphone_permission_requires_system_settings() {
|
|
assert_eq!(
|
|
microphone_authorization_state(0),
|
|
PermissionState::NeedsRequest
|
|
);
|
|
assert_eq!(
|
|
microphone_authorization_state(2),
|
|
PermissionState::NeedsSettings
|
|
);
|
|
assert_eq!(microphone_authorization_state(3), PermissionState::Ready);
|
|
}
|
|
|
|
#[test]
|
|
fn healthy_permissions_have_no_warning_projection() {
|
|
assert!(permission_warnings(ready_status()).is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn warning_projection_preserves_permission_order_and_actions() {
|
|
let warnings = permission_warnings(SetupStatus {
|
|
microphone: PermissionState::NeedsRequest,
|
|
input_monitoring: PermissionState::NeedsSettings,
|
|
accessibility: PermissionState::NeedsSettings,
|
|
..ready_status()
|
|
});
|
|
assert_eq!(
|
|
warnings,
|
|
[
|
|
PermissionWarning {
|
|
kind: PermissionKind::Microphone,
|
|
action: PermissionAction::RequestMicrophone,
|
|
},
|
|
PermissionWarning {
|
|
kind: PermissionKind::InputMonitoring,
|
|
action: PermissionAction::OpenInputMonitoringSettings,
|
|
},
|
|
PermissionWarning {
|
|
kind: PermissionKind::Accessibility,
|
|
action: PermissionAction::OpenAccessibilitySettings,
|
|
},
|
|
]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn denied_microphone_maps_to_settings_in_warning_projection() {
|
|
let warning = permission_warnings(SetupStatus {
|
|
microphone: PermissionState::NeedsSettings,
|
|
..ready_status()
|
|
});
|
|
assert_eq!(warning[0].action, PermissionAction::OpenMicrophoneSettings);
|
|
}
|
|
|
|
#[test]
|
|
fn existing_rust_settings_migrate_onboarding_completion() {
|
|
let directory =
|
|
std::env::temp_dir().join(format!("hex-onboarding-migration-{}", std::process::id()));
|
|
let _ = fs::remove_dir_all(&directory);
|
|
fs::create_dir_all(&directory).unwrap();
|
|
fs::write(directory.join("settings.json"), b"{}").unwrap();
|
|
|
|
assert!(completion_recorded_at(&directory));
|
|
let marker = directory.join("onboarding-complete");
|
|
assert!(marker.is_file());
|
|
#[cfg(unix)]
|
|
assert_eq!(
|
|
fs::metadata(marker).unwrap().permissions().mode() & 0o777,
|
|
0o600
|
|
);
|
|
|
|
fs::remove_dir_all(directory).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn fresh_install_does_not_skip_onboarding() {
|
|
let directory =
|
|
std::env::temp_dir().join(format!("hex-onboarding-fresh-{}", std::process::id()));
|
|
let _ = fs::remove_dir_all(&directory);
|
|
fs::create_dir_all(&directory).unwrap();
|
|
|
|
assert!(!completion_recorded_at(&directory));
|
|
assert!(!directory.join("onboarding-complete").exists());
|
|
|
|
fs::remove_dir_all(directory).unwrap();
|
|
}
|
|
|
|
fn ready_status() -> SetupStatus {
|
|
SetupStatus {
|
|
microphone: PermissionState::Ready,
|
|
input_monitoring: PermissionState::Ready,
|
|
accessibility: PermissionState::Ready,
|
|
transcription_model: true,
|
|
}
|
|
}
|
|
}
|