mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* feat(ui): add design tokens and one shared component set * style(ui): adopt the design system across the Settings window panes * style(ui): adopt the design system in the picker, inputs, capsules, and Linux * docs: add the design system guide and point agents to it * fix(ui): keep truncated lines at their final width and restore the sparkle icon * fix(ui): shape truncated lines at paint time against their final width * feat(ui): add overflow-menu, detail-header, and baseline primitives - Icon::Ellipsis, dropdown_menu, danger_menu_item, disabled_menu_item, and menu_separator for one reusable overflow menu - detail_header / detail_title / detail_body: one fixed, edge-to-edge ruled header for every detail card - list_section_label for group headings in list cards - baseline_offset puts smaller text on a larger line's baseline - MENU_WIDTH / MENU_OFFSET tokens; section labels inset to card text; pane_list centres its empty state * feat(ui): meetings overflow menu, neutral recording button, polish pass Meetings detail keeps Copy transcript and Rename visible and moves Copy summary, Reveal, Summarize/Regenerate, and Delete… into a … menu. Delete keeps its two-step confirmation in the action row; refusal rules are unchanged. Stop & transcribe is a Secondary button with a red dot and the elapsed time; the sidebar Update is Secondary with an accent dot. Polish: shared detail headers in Meetings, History, and Commands; timestamp and detail-row baselines; section labels on the card text edge; wider side segments; transcript labels on the bubble text; one menu width; Commands context moved into the detail; ... -> …; no closing period on one-phrase descriptions. Adds the --open-meeting-actions preview flag. * docs: document the accent and overflow-menu rules * fix(ui): history detail rows, delete confirmation row, side segments - History metadata rows sit directly in the detail body so values keep the full width (they collapsed to one character per line) - An armed meeting delete replaces the action row; actions wrap - Left / Either / Right selector width follows its segment widths - Ellipsis draws one icon size up to match the other glyphs optically * fix(ui): detail rows wrap long values inside the detail body * fix(ui): keep the detail body a block so detail rows wrap * fix(ui): detail rows fill their column again * refactor(ui): simplify design tokens, shared components, and meeting error banners
10390 lines
397 KiB
Rust
10390 lines
397 KiB
Rust
use std::cell::RefCell;
|
|
use std::collections::HashMap;
|
|
use std::path::PathBuf;
|
|
use std::process::Command as ProcessCommand;
|
|
use std::rc::Rc;
|
|
use std::sync::mpsc::{Receiver, SyncSender, TrySendError, sync_channel};
|
|
use std::thread;
|
|
use std::time::{Duration, Instant};
|
|
|
|
use gpui::{
|
|
AnyElement, App, Bounds, Context, Div, Entity, FocusHandle, Focusable, FontWeight, IntoElement,
|
|
KeyDownEvent, Modifiers as GpuiModifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent,
|
|
MouseMoveEvent, PathPromptOptions, Pixels, Point, Render, ScrollHandle, SharedString,
|
|
Subscription, Timer, TitlebarOptions, Window, WindowBounds, WindowHandle, WindowOptions,
|
|
actions, deferred, div, img, prelude::*, px, relative, rgb, rgba, size,
|
|
};
|
|
|
|
use crate::app_settings::{
|
|
AppSettings, DictationMode, HotkeyBinding, HotkeyKey, HotkeyModifiers, ModifierSide,
|
|
RecordingAudioBehavior, TextReplacement,
|
|
};
|
|
use crate::application_catalog::InstalledApplication;
|
|
use crate::commands::{CommandConfig, CommandInfo, CommandScope};
|
|
use crate::design_tokens::*;
|
|
use crate::desktop_activity::DesktopActivity;
|
|
use crate::desktop_transcription_picker::{
|
|
ModelDeletion, TranscriptionPickerDelegate, TranscriptionPickerModel,
|
|
TranscriptionPickerProgress, TranscriptionPickerStatus, TranscriptionPickerView,
|
|
render_transcription_picker as render_shared_transcription_picker,
|
|
transcription_selection_is_active,
|
|
};
|
|
use crate::desktop_ui::{
|
|
ButtonKind, Icon, NavigationIcon, Tone, busy_label, button, danger_menu_item, detail_body,
|
|
detail_header, detail_placeholder, detail_row, detail_title, disabled_menu_item,
|
|
disclosure_button, disclosure_frame, dropdown_menu, empty_state, error_message, error_panel,
|
|
hotkey_keycaps, icon, icon_button, inline_error, list_row, list_row_meta, list_row_title,
|
|
list_section_label, listener_status, menu, menu_item, menu_separator, mix_color,
|
|
navigation_item, pane_body, pane_content, pane_detail, pane_header, pane_header_with_action,
|
|
pane_list, pane_scroll_body, panel, panel_header, section_label, segmented_control,
|
|
segmented_item, settings_copy, settings_row, settings_section_label, sidebar_frame,
|
|
sliding_segmented_control, sliding_segmented_item, small_button, status_dot, tag, toggle,
|
|
truncated_line, window_frame,
|
|
};
|
|
use crate::developer_control::DeveloperPane;
|
|
use crate::dictation_indicator::{DictationIndicatorEvent, DictationIndicatorSender, HudTuning};
|
|
use crate::dictation_processor::{ModelCatalog, ModelChoice};
|
|
use crate::events::{
|
|
CommandOutcome, DictationPhase, EventReader, TranscriptPhase, VoiceEvent, VoiceState, now_ms,
|
|
};
|
|
use crate::history::{History, HistoryEntry, HistoryKind, HistoryRetention};
|
|
use crate::login_item::{LoginItemRequest, LoginItemResponse, LoginItemStatus, LoginItemWorker};
|
|
use crate::meeting::{
|
|
self, MeetingManifest, MeetingRequest, MeetingSource, MeetingStatus, TranscriptEntry,
|
|
};
|
|
use crate::onboarding::{
|
|
PermissionAction, PermissionKind, PermissionState, PermissionWarning, SetupStatus,
|
|
};
|
|
use crate::personal_commands::{HostState, StatusContext, StatusSnapshot, StatusTransformation};
|
|
use crate::recognition::CommandModelStatus;
|
|
use crate::text_input::{
|
|
Changed as TextChanged, Dismissed as TextDismissed, Navigate as TextNavigate,
|
|
Submitted as TextSubmitted, TextInput,
|
|
};
|
|
use crate::transcription_models::{
|
|
ModelDefinition, ModelRuntime, TranscriptionModelId, TranscriptionSelection, definition,
|
|
language_name, validate,
|
|
};
|
|
use crate::transcription_preparation::{PreparationStatus, TranscriptionPreparation};
|
|
|
|
const WINDOW_WIDTH: f32 = 1040.0;
|
|
const WINDOW_HEIGHT: f32 = 700.0;
|
|
const MINIMUM_WIDTH: f32 = 860.0;
|
|
const MINIMUM_HEIGHT: f32 = 560.0;
|
|
const HOTKEY_MIN_WIDTH: f32 = 148.0;
|
|
/// Left / Either / Right segment widths.
|
|
const HOTKEY_SIDE_WIDTHS: [f32; 3] = [40.0, 50.0, 40.0];
|
|
/// The side segments plus the control's 2 px padding and 1 px border per side.
|
|
const HOTKEY_SIDE_SELECTOR_WIDTH: f32 =
|
|
HOTKEY_SIDE_WIDTHS[0] + HOTKEY_SIDE_WIDTHS[1] + HOTKEY_SIDE_WIDTHS[2] + 6.0;
|
|
const OPENCODE_INSTALL_RETRY_INTERVAL: Duration = Duration::from_secs(60);
|
|
const PERMISSION_REFRESH_INTERVAL: Duration = Duration::from_secs(5);
|
|
const MAX_OPENCODE_ERROR_BYTES: usize = 4 * 1024;
|
|
const ACTIVITY_LIMIT: usize = 100;
|
|
const OPENCODE_BETA_DOCS_URL: &str = "https://v2.opencode.ai/";
|
|
|
|
fn sidebar_update_button(
|
|
status: crate::sparkle::UpdateStatus,
|
|
preview: bool,
|
|
) -> Option<gpui::Stateful<Div>> {
|
|
(status == crate::sparkle::UpdateStatus::UpdateAvailable).then(|| {
|
|
button(ButtonKind::Secondary, status_dot(ACCENT_TEXT))
|
|
.child("Update")
|
|
.id("check-for-updates-sidebar")
|
|
.on_click(move |_, window, cx| {
|
|
if !preview {
|
|
window.dispatch_action(Box::new(CheckForUpdates), cx);
|
|
window.refresh();
|
|
}
|
|
})
|
|
})
|
|
}
|
|
|
|
/// The microphone menu is deferred above the settings panel and occludes
|
|
/// everything beneath it, so hovering or choosing a device never reaches the
|
|
/// controls under the menu. A mouse-down anywhere else dismisses it.
|
|
fn microphone_picker_menu(
|
|
choices: Vec<Option<String>>,
|
|
selected: Option<String>,
|
|
error: Option<String>,
|
|
choose: impl Fn(&Option<String>, &mut Window, &mut App) + 'static,
|
|
dismiss: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
|
|
) -> gpui::Stateful<Div> {
|
|
let choose = Rc::new(choose);
|
|
dropdown_menu()
|
|
.id("microphone-picker")
|
|
.debug_selector(|| "microphone-picker".into())
|
|
.right_0()
|
|
.w(px(DISCLOSURE_WIDTH))
|
|
.max_h(px(240.0))
|
|
.overflow_y_scroll()
|
|
.on_mouse_down_out(dismiss)
|
|
.children(choices.into_iter().enumerate().map(|(index, device)| {
|
|
let is_selected = selected == device;
|
|
let label = device.clone().unwrap_or_else(|| "Automatic".into());
|
|
let choose = choose.clone();
|
|
menu_item(is_selected)
|
|
.id(("microphone-choice", index))
|
|
.debug_selector(move || format!("microphone-choice-{index}"))
|
|
.child(truncated_line(FOOTNOTE, label))
|
|
.on_click(move |_, window, cx| {
|
|
cx.stop_propagation();
|
|
choose(&device, window, cx);
|
|
})
|
|
}))
|
|
.when_some(error, |picker, error| picker.child(inline_error(error)))
|
|
}
|
|
|
|
fn settings_pane(title: &'static str, scroll_id: &'static str, content: Div) -> AnyElement {
|
|
div()
|
|
.size_full()
|
|
.flex()
|
|
.flex_col()
|
|
.child(pane_header(title))
|
|
.child(pane_scroll_body(
|
|
scroll_id,
|
|
content
|
|
.relative()
|
|
.debug_selector(|| "settings-content".into()),
|
|
))
|
|
.into_any_element()
|
|
}
|
|
|
|
actions!(
|
|
hex,
|
|
[
|
|
CloseWindow,
|
|
CheckForUpdates,
|
|
RetryCommands,
|
|
HideApplication,
|
|
MinimizeWindow,
|
|
QuitApplication,
|
|
ShowCommands,
|
|
ShowHistory,
|
|
ShowModes,
|
|
ShowSettings,
|
|
ShowVoiceAction,
|
|
ToggleFullscreen,
|
|
]
|
|
);
|
|
|
|
/// Opens the app shell, or focuses and refreshes an existing shell window.
|
|
#[allow(clippy::too_many_arguments)]
|
|
pub fn open_or_focus(
|
|
app_window: &Rc<RefCell<Option<WindowHandle<AppWindow>>>>,
|
|
event_path: PathBuf,
|
|
commands: CommandConfig,
|
|
meeting_requests: SyncSender<MeetingRequest>,
|
|
indicator: DictationIndicatorSender,
|
|
recognition_start: Option<SyncSender<()>>,
|
|
history: Option<History>,
|
|
cx: &mut App,
|
|
) -> gpui::Result<WindowHandle<AppWindow>> {
|
|
if let Some(handle) = app_window.borrow().as_ref().copied()
|
|
&& handle
|
|
.update(cx, |this, window, cx| {
|
|
if this.event_reader.path() != event_path {
|
|
this.event_reader = EventReader::open(event_path.clone());
|
|
}
|
|
this.meeting_requests = meeting_requests.clone();
|
|
this.indicator = indicator.clone();
|
|
this.recognition_start = recognition_start.clone();
|
|
this.history = history.clone();
|
|
this.refresh(cx);
|
|
window.activate_window();
|
|
})
|
|
.is_ok()
|
|
{
|
|
cx.activate(true);
|
|
return Ok(handle);
|
|
}
|
|
|
|
open_new(
|
|
app_window,
|
|
event_path,
|
|
commands,
|
|
meeting_requests,
|
|
indicator,
|
|
recognition_start,
|
|
history,
|
|
None,
|
|
cx,
|
|
)
|
|
}
|
|
|
|
/// Commit through the live editor when present, preserving its unsaved settings.
|
|
/// Quiet startup does not require creating or focusing a Settings window.
|
|
pub fn commit_transcription_selection(
|
|
app_window: &Rc<RefCell<Option<WindowHandle<AppWindow>>>>,
|
|
selection: TranscriptionSelection,
|
|
cx: &mut App,
|
|
) -> Result<AppSettings, String> {
|
|
let handle = app_window.borrow().as_ref().copied();
|
|
if let Some(handle) = handle
|
|
&& let Ok(result) = handle.update(cx, |this, _, cx| {
|
|
this.apply_transcription_selection(selection.clone(), cx)?;
|
|
cx.notify();
|
|
Ok(this.settings.clone())
|
|
})
|
|
{
|
|
return result;
|
|
}
|
|
let mut settings = AppSettings::load().map_err(|error| error.to_string())?;
|
|
settings
|
|
.save_transcription(selection)
|
|
.map_err(|error| error.to_string())?;
|
|
Ok(settings)
|
|
}
|
|
|
|
pub fn menu_transcription_selection(
|
|
app_window: &Rc<RefCell<Option<WindowHandle<AppWindow>>>>,
|
|
model: TranscriptionModelId,
|
|
fallback: &AppSettings,
|
|
cx: &mut App,
|
|
) -> TranscriptionSelection {
|
|
let handle = app_window.borrow().as_ref().copied();
|
|
handle
|
|
.and_then(|handle| {
|
|
handle
|
|
.update(cx, |this, _, _| {
|
|
this.settings.transcription_for_model(model)
|
|
})
|
|
.ok()
|
|
})
|
|
.unwrap_or_else(|| fallback.transcription_for_model(model))
|
|
}
|
|
|
|
pub fn refresh_transcription_menu(
|
|
app_window: &Rc<RefCell<Option<WindowHandle<AppWindow>>>>,
|
|
fallback: &AppSettings,
|
|
status: &PreparationStatus,
|
|
cx: &mut App,
|
|
) {
|
|
let handle = app_window.borrow().as_ref().copied();
|
|
if handle.is_some_and(|handle| {
|
|
handle
|
|
.update(cx, |this, _, _| {
|
|
crate::status_item::update_transcription(&this.settings, status);
|
|
})
|
|
.is_ok()
|
|
}) {
|
|
return;
|
|
}
|
|
crate::status_item::update_transcription(fallback, status);
|
|
}
|
|
|
|
pub fn open_preview(
|
|
app_window: &Rc<RefCell<Option<WindowHandle<AppWindow>>>>,
|
|
event_path: PathBuf,
|
|
commands: CommandConfig,
|
|
meeting_requests: SyncSender<MeetingRequest>,
|
|
indicator: DictationIndicatorSender,
|
|
preview: AppWindowPreview,
|
|
cx: &mut App,
|
|
) -> gpui::Result<WindowHandle<AppWindow>> {
|
|
if let Some(handle) = app_window.borrow().as_ref().copied()
|
|
&& handle
|
|
.update(cx, |_, window, _| window.activate_window())
|
|
.is_ok()
|
|
{
|
|
cx.activate(true);
|
|
return Ok(handle);
|
|
}
|
|
open_new(
|
|
app_window,
|
|
event_path,
|
|
commands,
|
|
meeting_requests,
|
|
indicator,
|
|
None,
|
|
None,
|
|
Some(preview),
|
|
cx,
|
|
)
|
|
}
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
fn open_new(
|
|
app_window: &Rc<RefCell<Option<WindowHandle<AppWindow>>>>,
|
|
event_path: PathBuf,
|
|
commands: CommandConfig,
|
|
meeting_requests: SyncSender<MeetingRequest>,
|
|
indicator: DictationIndicatorSender,
|
|
recognition_start: Option<SyncSender<()>>,
|
|
history: Option<History>,
|
|
preview: Option<AppWindowPreview>,
|
|
cx: &mut App,
|
|
) -> gpui::Result<WindowHandle<AppWindow>> {
|
|
let preview_mode = preview.is_some();
|
|
let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
|
|
let handle = cx.open_window(
|
|
WindowOptions {
|
|
window_bounds: Some(WindowBounds::Windowed(bounds)),
|
|
titlebar: Some(TitlebarOptions {
|
|
title: Some("Hex".into()),
|
|
appears_transparent: true,
|
|
..Default::default()
|
|
}),
|
|
is_resizable: !preview_mode,
|
|
is_minimizable: true,
|
|
window_min_size: Some(size(px(MINIMUM_WIDTH), px(MINIMUM_HEIGHT))),
|
|
tabbing_identifier: preview_mode.then(|| "hex-preview".into()),
|
|
..Default::default()
|
|
},
|
|
|window, cx| {
|
|
cx.new(|cx| {
|
|
AppWindow::new(
|
|
event_path,
|
|
commands,
|
|
meeting_requests,
|
|
indicator,
|
|
recognition_start,
|
|
history,
|
|
preview,
|
|
window,
|
|
cx,
|
|
)
|
|
})
|
|
},
|
|
)?;
|
|
*app_window.borrow_mut() = Some(handle);
|
|
cx.activate(true);
|
|
Ok(handle)
|
|
}
|
|
|
|
#[derive(Clone, Copy)]
|
|
pub enum PreviewModelState {
|
|
Actual,
|
|
Installed,
|
|
Missing,
|
|
Downloading,
|
|
Error,
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct AppWindowPreview {
|
|
pub pane: DeveloperPane,
|
|
pub transcription_picker: Option<(String, PreviewModelState)>,
|
|
pub onboarding: bool,
|
|
pub confirm_model_deletion: bool,
|
|
pub collapse_mode_processing: bool,
|
|
pub open_transformation_picker: bool,
|
|
pub select_global_mode: bool,
|
|
pub voice_action_enabled: bool,
|
|
pub opencode_unavailable: bool,
|
|
pub permissions_missing: bool,
|
|
pub model_missing: bool,
|
|
pub command_model_missing: bool,
|
|
pub open_history_retention: bool,
|
|
pub confirm_release_microphone: bool,
|
|
pub update_available: bool,
|
|
pub meetings_enabled: bool,
|
|
pub screen_recording_missing: bool,
|
|
pub meeting_recording: bool,
|
|
pub confirm_meeting_delete: bool,
|
|
pub open_meeting_actions: bool,
|
|
pub meetings_empty: bool,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
|
enum Pane {
|
|
HudLab,
|
|
Meetings,
|
|
Commands,
|
|
Activity,
|
|
History,
|
|
Modes,
|
|
VoiceAction,
|
|
#[default]
|
|
Settings,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
enum HudDemoState {
|
|
Recording,
|
|
Transcribing,
|
|
Processing,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
enum HudControl {
|
|
LineCount,
|
|
Curvature,
|
|
Speed,
|
|
Blur,
|
|
Glow,
|
|
Depth,
|
|
LightAngle,
|
|
Outline,
|
|
}
|
|
|
|
const HUD_MAX_SPEED: f32 = 24.0;
|
|
|
|
impl Pane {
|
|
fn on_reopen(self, status: SetupStatus) -> Self {
|
|
if crate::onboarding::permission_warnings(status).is_empty() {
|
|
self
|
|
} else {
|
|
Self::Settings
|
|
}
|
|
}
|
|
|
|
const ALL: [Self; 8] = [
|
|
Self::Settings,
|
|
Self::Modes,
|
|
Self::Commands,
|
|
Self::VoiceAction,
|
|
Self::History,
|
|
Self::HudLab,
|
|
Self::Meetings,
|
|
Self::Activity,
|
|
];
|
|
|
|
fn all(developer_features: bool, meetings: bool) -> Vec<Self> {
|
|
Self::ALL
|
|
.into_iter()
|
|
.filter(|pane| match pane {
|
|
Self::Settings
|
|
| Self::Modes
|
|
| Self::Commands
|
|
| Self::VoiceAction
|
|
| Self::History => true,
|
|
Self::Meetings => developer_features || meetings,
|
|
Self::HudLab | Self::Activity => developer_features,
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
fn label(self) -> &'static str {
|
|
match self {
|
|
Self::HudLab => "HUD Lab",
|
|
Self::Meetings => "Meetings",
|
|
Self::Commands => "Commands",
|
|
Self::Activity => "Activity",
|
|
Self::History => "History",
|
|
Self::Modes => "Modes",
|
|
Self::VoiceAction => "Voice Action",
|
|
Self::Settings => "Settings",
|
|
}
|
|
}
|
|
|
|
fn icon(self) -> NavigationIcon {
|
|
match self {
|
|
Self::Settings => NavigationIcon::Settings,
|
|
Self::Modes => NavigationIcon::Modes,
|
|
Self::VoiceAction => NavigationIcon::VoiceAction,
|
|
Self::History => NavigationIcon::History,
|
|
Self::Commands => NavigationIcon::Commands,
|
|
Self::Meetings => NavigationIcon::Meetings,
|
|
Self::Activity => NavigationIcon::Activity,
|
|
Self::HudLab => NavigationIcon::HudLab,
|
|
}
|
|
}
|
|
|
|
fn from_developer(pane: DeveloperPane) -> Self {
|
|
match pane {
|
|
DeveloperPane::Settings => Self::Settings,
|
|
DeveloperPane::Modes => Self::Modes,
|
|
DeveloperPane::VoiceAction => Self::VoiceAction,
|
|
DeveloperPane::History => Self::History,
|
|
DeveloperPane::HudLab => Self::HudLab,
|
|
DeveloperPane::Commands => Self::Commands,
|
|
DeveloperPane::Meetings => Self::Meetings,
|
|
DeveloperPane::Activity => Self::Activity,
|
|
}
|
|
}
|
|
|
|
fn developer(self) -> DeveloperPane {
|
|
match self {
|
|
Self::Settings => DeveloperPane::Settings,
|
|
Self::Modes => DeveloperPane::Modes,
|
|
Self::VoiceAction => DeveloperPane::VoiceAction,
|
|
Self::History => DeveloperPane::History,
|
|
Self::HudLab => DeveloperPane::HudLab,
|
|
Self::Commands => DeveloperPane::Commands,
|
|
Self::Meetings => DeveloperPane::Meetings,
|
|
Self::Activity => DeveloperPane::Activity,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
struct CatalogCommand {
|
|
task: String,
|
|
scope: CommandScope,
|
|
phrase: String,
|
|
aliases: Vec<String>,
|
|
description: String,
|
|
id: String,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
enum PersonalWorkspaceState {
|
|
Missing,
|
|
Creating,
|
|
Ready,
|
|
Error,
|
|
}
|
|
|
|
fn personal_workspace_state(
|
|
config_exists: bool,
|
|
creating: bool,
|
|
status: &StatusSnapshot,
|
|
) -> PersonalWorkspaceState {
|
|
if creating {
|
|
PersonalWorkspaceState::Creating
|
|
} else if config_exists {
|
|
if status.host_state == HostState::Unavailable && status.active_generation.is_none() {
|
|
PersonalWorkspaceState::Error
|
|
} else {
|
|
PersonalWorkspaceState::Ready
|
|
}
|
|
} else {
|
|
PersonalWorkspaceState::Missing
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, PartialEq)]
|
|
struct TranscriptLine {
|
|
source: MeetingSource,
|
|
clock: String,
|
|
text: String,
|
|
pause_before_ms: Option<u64>,
|
|
}
|
|
|
|
struct MeetingPreview {
|
|
recording: bool,
|
|
confirm_delete: bool,
|
|
open_actions: bool,
|
|
empty: bool,
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
enum MeetingTranscript {
|
|
Empty,
|
|
Loaded(Vec<TranscriptLine>),
|
|
Unavailable(String),
|
|
}
|
|
|
|
struct ToggleSpring {
|
|
position: f32,
|
|
velocity: f32,
|
|
target: f32,
|
|
last_frame: Instant,
|
|
}
|
|
|
|
struct ProcessingInput {
|
|
entity: Entity<TextInput>,
|
|
_subscriptions: Vec<Subscription>,
|
|
}
|
|
|
|
struct ModeInputs {
|
|
name: ProcessingInput,
|
|
browser_hosts: ProcessingInput,
|
|
prompt: ProcessingInput,
|
|
model: ProcessingInput,
|
|
deadline: ProcessingInput,
|
|
processing_toggle: ToggleSpring,
|
|
replacements: Vec<ReplacementInputs>,
|
|
}
|
|
|
|
struct ModeEditor {
|
|
// Authoritative editor draft; AppSettings receives a projection only when
|
|
// constructing a save candidate, never by keeping parallel indices in sync.
|
|
settings: DictationMode,
|
|
inputs: ModeInputs,
|
|
}
|
|
|
|
struct ModeEditors {
|
|
default_mode: ModeEditor,
|
|
modes: Vec<ModeEditor>,
|
|
}
|
|
|
|
impl ModeEditors {
|
|
fn project(&self, settings: &mut AppSettings) {
|
|
settings.dictation_processing.default_mode = self.default_mode.settings.clone();
|
|
settings.dictation_processing.modes =
|
|
self.modes.iter().map(|row| row.settings.clone()).collect();
|
|
}
|
|
}
|
|
|
|
struct VoiceActionInputs {
|
|
model: ProcessingInput,
|
|
enabled_toggle: ToggleSpring,
|
|
error: Option<String>,
|
|
}
|
|
|
|
struct ReplacementInputs {
|
|
matched_phrase: ProcessingInput,
|
|
output: ProcessingInput,
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
struct TransformationDrag {
|
|
selection: ModeSelection,
|
|
id: String,
|
|
name: String,
|
|
position: Point<Pixels>,
|
|
}
|
|
|
|
impl TransformationDrag {
|
|
fn at(mut self, position: Point<Pixels>) -> Self {
|
|
self.position = position;
|
|
self
|
|
}
|
|
}
|
|
|
|
impl Render for TransformationDrag {
|
|
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
|
|
div()
|
|
.pl(self.position.x - px(90.0))
|
|
.pt(self.position.y - px(17.0))
|
|
.child(
|
|
div()
|
|
.w(px(180.0))
|
|
.h(px(CONTROL_HEIGHT))
|
|
.px_3()
|
|
.flex()
|
|
.items_center()
|
|
.rounded(RADIUS_CONTROL)
|
|
.border_1()
|
|
.border_color(rgb(LINE_STRONG))
|
|
.bg(rgb(SURFACE_SELECTED))
|
|
.shadow_lg()
|
|
.text_body()
|
|
.text_color(rgb(TEXT_PRIMARY))
|
|
.child(self.name.clone()),
|
|
)
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Copy, Eq, PartialEq)]
|
|
enum ModeSelection {
|
|
Default,
|
|
Custom(usize),
|
|
}
|
|
|
|
#[derive(Clone, Copy, Eq, PartialEq)]
|
|
enum ModelPickerTarget {
|
|
Mode(ModeSelection),
|
|
VoiceAction,
|
|
}
|
|
|
|
/// Shared parts of the OpenCode model picker rendered by every surface that
|
|
/// selects a model: Modes processing and Voice Action.
|
|
struct ProcessingPicker {
|
|
catalog_status: String,
|
|
model_control: AnyElement,
|
|
refresh_control: Option<AnyElement>,
|
|
suggestions: Option<Div>,
|
|
has_variants: bool,
|
|
variant_control: Div,
|
|
}
|
|
|
|
enum ModelCatalogState {
|
|
Loading,
|
|
Loaded(ModelCatalog),
|
|
Missing,
|
|
Failed(String),
|
|
}
|
|
|
|
struct OpenCodeUnavailableCopy {
|
|
title: &'static str,
|
|
description: &'static str,
|
|
error: Option<String>,
|
|
can_retry: bool,
|
|
retry_label: &'static str,
|
|
can_open_setup: bool,
|
|
}
|
|
|
|
#[derive(Clone, Copy)]
|
|
enum OpenCodeFeature {
|
|
VoiceAction,
|
|
Transformation,
|
|
}
|
|
|
|
fn opencode_unavailable_copy(
|
|
state: &ModelCatalogState,
|
|
feature: OpenCodeFeature,
|
|
) -> Option<OpenCodeUnavailableCopy> {
|
|
match state {
|
|
ModelCatalogState::Loading => Some(OpenCodeUnavailableCopy {
|
|
title: "Checking for OpenCode",
|
|
description: match feature {
|
|
OpenCodeFeature::VoiceAction => {
|
|
"Voice Action will be available after Hex connects to OpenCode."
|
|
}
|
|
OpenCodeFeature::Transformation => {
|
|
"OpenCode transformation will be available after Hex connects to OpenCode."
|
|
}
|
|
},
|
|
error: None,
|
|
can_retry: false,
|
|
retry_label: "Retry",
|
|
can_open_setup: false,
|
|
}),
|
|
ModelCatalogState::Missing => Some(OpenCodeUnavailableCopy {
|
|
title: match feature {
|
|
OpenCodeFeature::VoiceAction => "Voice Action requires OpenCode",
|
|
OpenCodeFeature::Transformation => "Transformation requires OpenCode",
|
|
},
|
|
description: match feature {
|
|
OpenCodeFeature::VoiceAction => {
|
|
"Install and configure OpenCode to turn spoken instructions into paste-ready text."
|
|
}
|
|
OpenCodeFeature::Transformation => {
|
|
"Install and configure OpenCode to transform dictated text."
|
|
}
|
|
},
|
|
error: None,
|
|
can_retry: true,
|
|
retry_label: "Check again",
|
|
can_open_setup: true,
|
|
}),
|
|
ModelCatalogState::Failed(error) => Some(OpenCodeUnavailableCopy {
|
|
title: "OpenCode is unavailable",
|
|
description: "Hex could not load the OpenCode model catalog.",
|
|
error: Some(error.clone()),
|
|
can_retry: true,
|
|
retry_label: "Retry",
|
|
can_open_setup: false,
|
|
}),
|
|
ModelCatalogState::Loaded(_) => None,
|
|
}
|
|
}
|
|
|
|
fn bounded_opencode_error(error: &str) -> String {
|
|
if error.len() <= MAX_OPENCODE_ERROR_BYTES {
|
|
return error.into();
|
|
}
|
|
let mut end = MAX_OPENCODE_ERROR_BYTES;
|
|
while !error.is_char_boundary(end) {
|
|
end -= 1;
|
|
}
|
|
format!("{}…", &error[..end])
|
|
}
|
|
|
|
fn start_model_catalog_load() -> Receiver<ModelCatalogState> {
|
|
let (sender, receiver) = sync_channel(1);
|
|
thread::spawn(move || {
|
|
let state = if crate::dictation_processor::opencode_installed() {
|
|
match crate::dictation_processor::load_model_catalog() {
|
|
Ok(catalog) => ModelCatalogState::Loaded(catalog),
|
|
Err(error) => {
|
|
let error = bounded_opencode_error(&error.to_string());
|
|
tracing::warn!(%error, "could not load OpenCode model catalog");
|
|
ModelCatalogState::Failed(error)
|
|
}
|
|
}
|
|
} else {
|
|
ModelCatalogState::Missing
|
|
};
|
|
let _ = sender.send(state);
|
|
});
|
|
receiver
|
|
}
|
|
|
|
struct ModelPresentation {
|
|
name: String,
|
|
provider: String,
|
|
#[cfg(test)]
|
|
key: String,
|
|
is_default: bool,
|
|
}
|
|
|
|
enum ApplicationCatalogState {
|
|
Loading,
|
|
Loaded(Vec<InstalledApplication>),
|
|
}
|
|
|
|
impl ApplicationCatalogState {
|
|
fn application_named(&self, name: &str) -> Option<&InstalledApplication> {
|
|
let Self::Loaded(applications) = self else {
|
|
return None;
|
|
};
|
|
applications
|
|
.iter()
|
|
.find(|application| application.name == name)
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
enum HotkeyKind {
|
|
Dictation,
|
|
Edit,
|
|
PasteLast,
|
|
}
|
|
|
|
fn set_hotkey_binding(settings: &mut AppSettings, kind: HotkeyKind, binding: HotkeyBinding) {
|
|
match kind {
|
|
HotkeyKind::Dictation => {
|
|
if binding.key.is_none() {
|
|
settings.double_tap_only = false;
|
|
}
|
|
settings.dictation_hotkey = binding;
|
|
}
|
|
HotkeyKind::Edit => settings.edit_hotkey = binding,
|
|
HotkeyKind::PasteLast => settings.paste_last_hotkey = Some(binding),
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
enum MicrophonePolicyChange {
|
|
SetCommands(bool),
|
|
SetReleaseWhileIdle(bool),
|
|
KeepReadyAndEnableCommands,
|
|
DisableCommandsAndRelease,
|
|
}
|
|
|
|
enum HotkeyCaptureState {
|
|
Idle,
|
|
Listening {
|
|
kind: HotkeyKind,
|
|
modifiers: HotkeyModifiers,
|
|
message: Option<&'static str>,
|
|
started_at: Instant,
|
|
},
|
|
Saved {
|
|
kind: HotkeyKind,
|
|
saved_at: Instant,
|
|
},
|
|
}
|
|
|
|
impl HotkeyCaptureState {
|
|
fn is_listening(&self) -> bool {
|
|
matches!(self, Self::Listening { .. })
|
|
}
|
|
}
|
|
|
|
impl ToggleSpring {
|
|
fn new(enabled: bool) -> Self {
|
|
let position = if enabled { 1.0 } else { 0.0 };
|
|
Self::at(position)
|
|
}
|
|
|
|
fn at(position: f32) -> Self {
|
|
Self {
|
|
position,
|
|
velocity: 0.0,
|
|
target: position,
|
|
last_frame: Instant::now(),
|
|
}
|
|
}
|
|
|
|
fn set_enabled(&mut self, enabled: bool) {
|
|
self.set_target(if enabled { 1.0 } else { 0.0 });
|
|
}
|
|
|
|
fn set_target(&mut self, target: f32) {
|
|
if self.target == target {
|
|
return;
|
|
}
|
|
self.target = target;
|
|
self.last_frame = Instant::now();
|
|
}
|
|
|
|
fn advance(&mut self, elapsed: Duration) {
|
|
/// Critically damped spring stiffness in rad/s; higher settles faster.
|
|
const STIFFNESS: f32 = 40.0;
|
|
let mut remaining = elapsed.as_secs_f32().min(0.1);
|
|
while remaining > 0.0 {
|
|
let dt = remaining.min(1.0 / 240.0);
|
|
let acceleration = -STIFFNESS.powi(2) * (self.position - self.target)
|
|
- 2.0 * STIFFNESS * self.velocity;
|
|
self.velocity += acceleration * dt;
|
|
self.position += self.velocity * dt;
|
|
remaining -= dt;
|
|
}
|
|
if self.is_settled() {
|
|
self.position = self.target;
|
|
self.velocity = 0.0;
|
|
}
|
|
}
|
|
|
|
fn render_position(&mut self, window: &mut Window) -> f32 {
|
|
let now = Instant::now();
|
|
self.advance(now.duration_since(self.last_frame));
|
|
self.last_frame = now;
|
|
if !self.is_settled() {
|
|
window.request_animation_frame();
|
|
}
|
|
self.position
|
|
}
|
|
|
|
fn is_settled(&self) -> bool {
|
|
(self.position - self.target).abs() < 0.001 && self.velocity.abs() < 0.01
|
|
}
|
|
|
|
fn enabled(&self) -> bool {
|
|
self.target >= 0.5
|
|
}
|
|
}
|
|
|
|
/// Root GPUI entity for the production app shell.
|
|
pub struct AppWindow {
|
|
preview: bool,
|
|
pane: Pane,
|
|
event_reader: EventReader,
|
|
activity: DesktopActivity,
|
|
meeting_requests: SyncSender<MeetingRequest>,
|
|
indicator: DictationIndicatorSender,
|
|
hud_tuning: HudTuning,
|
|
hud_demo: HudDemoState,
|
|
hud_queued: usize,
|
|
hud_dragging: Option<HudControl>,
|
|
hud_copied: bool,
|
|
recognition_start: Option<SyncSender<()>>,
|
|
setup_status: SetupStatus,
|
|
setup_visible: bool,
|
|
onboarding_completed: bool,
|
|
permission_refresh_at: Instant,
|
|
settings: AppSettings,
|
|
settings_load_error: Option<String>,
|
|
#[cfg(test)]
|
|
settings_save_override: Option<fn(&AppSettings) -> color_eyre::Result<()>>,
|
|
microphone_devices: Vec<String>,
|
|
microphone_picker_open: bool,
|
|
microphone_picker_error: Option<String>,
|
|
launch_at_login_status: Option<LoginItemStatus>,
|
|
login_item_worker: Option<LoginItemWorker>,
|
|
launch_at_login_error: Option<String>,
|
|
launch_at_login_toggle: ToggleSpring,
|
|
update_status: crate::sparkle::UpdateStatus,
|
|
update_status_changed_at: Instant,
|
|
commands_toggle: ToggleSpring,
|
|
command_model_status: CommandModelStatus,
|
|
release_microphone_toggle: ToggleSpring,
|
|
pending_microphone_policy: Option<MicrophonePolicyChange>,
|
|
double_tap_toggle: ToggleSpring,
|
|
double_tap_only_visibility: ToggleSpring,
|
|
dock_icon_toggle: ToggleSpring,
|
|
incremental_toggle: ToggleSpring,
|
|
meetings_toggle: ToggleSpring,
|
|
meeting_notes_toggle: ToggleSpring,
|
|
screen_recording_permitted: bool,
|
|
meeting_folder_error: Option<String>,
|
|
sound_volume_spring: ToggleSpring,
|
|
recording_audio_spring: ToggleSpring,
|
|
variant_picker_open: Option<ModelPickerTarget>,
|
|
transcription_hints: ProcessingInput,
|
|
transcription_picker_language: Option<String>,
|
|
transcription_status: PreparationStatus,
|
|
transcription_preparation: TranscriptionPreparation,
|
|
transcription_preview_installed: Option<bool>,
|
|
transcription_deletion: Option<TranscriptionModelId>,
|
|
transcription_deletion_error: Option<String>,
|
|
mode_editors: ModeEditors,
|
|
voice_action_inputs: VoiceActionInputs,
|
|
selected_mode: ModeSelection,
|
|
model_catalog: ModelCatalogState,
|
|
model_catalog_receiver: Option<Receiver<ModelCatalogState>>,
|
|
model_catalog_retry_at: Instant,
|
|
application_catalog: ApplicationCatalogState,
|
|
application_catalog_receiver: Option<Receiver<Vec<InstalledApplication>>>,
|
|
application_search: ProcessingInput,
|
|
application_picker_open: bool,
|
|
application_picker_error: Option<String>,
|
|
transformation_picker_open: bool,
|
|
application_picker_highlight: usize,
|
|
model_picker_highlight: usize,
|
|
mode_delete_armed: bool,
|
|
mode_context_menu: Option<Point<Pixels>>,
|
|
settings_save_generation: u64,
|
|
settings_dirty: bool,
|
|
hotkey_capture: HotkeyCaptureState,
|
|
hotkey_capture_animation: ToggleSpring,
|
|
hotkey_width_spring: ToggleSpring,
|
|
hotkey_side_animations: [ToggleSpring; 3],
|
|
hotkey_side_selection_springs: [ToggleSpring; 3],
|
|
window_focus: FocusHandle,
|
|
hotkey_focus: FocusHandle,
|
|
_hotkey_blur_subscription: Subscription,
|
|
_activation_subscription: Subscription,
|
|
meetings: Vec<MeetingManifest>,
|
|
meetings_error: Option<String>,
|
|
meeting_runtime_error: Option<String>,
|
|
meeting_refresh_started_ms: Option<u64>,
|
|
meeting_stop_pending: bool,
|
|
selected_meeting: Option<String>,
|
|
meeting_transcript: MeetingTranscript,
|
|
meeting_transcript_id: Option<String>,
|
|
meeting_transcript_reader: meeting::TranscriptReader,
|
|
meeting_transcript_scroll: ScrollHandle,
|
|
/// Coalesced turns of the selected meeting, for Copy Transcript.
|
|
meeting_turns: Vec<TranscriptEntry>,
|
|
meeting_search: ProcessingInput,
|
|
/// Lowercased searchable text per meeting, loaded when a search starts.
|
|
meeting_search_text: HashMap<String, String>,
|
|
meeting_rename: Option<(String, ProcessingInput)>,
|
|
meeting_delete_armed: Option<String>,
|
|
/// The detail's overflow menu of less common meeting actions is open.
|
|
meeting_actions_open: bool,
|
|
meeting_action_error: Option<String>,
|
|
meeting_copied: Option<(String, &'static str)>,
|
|
/// Deterministic transcripts for the Meetings preview.
|
|
meeting_preview_transcripts: Option<HashMap<String, Vec<TranscriptEntry>>>,
|
|
compiled_commands: Vec<CatalogCommand>,
|
|
commands: Vec<CatalogCommand>,
|
|
personal_commands_status: StatusSnapshot,
|
|
personal_workspace: PathBuf,
|
|
personal_workspace_receiver: Option<Receiver<Result<PathBuf, String>>>,
|
|
personal_workspace_error: Option<String>,
|
|
personal_commands_prompt_copied: bool,
|
|
command_search: ProcessingInput,
|
|
selected_command: Option<String>,
|
|
events: Vec<VoiceEvent>,
|
|
current_context: (Option<String>, Option<String>),
|
|
selected_event: Option<usize>,
|
|
history: Option<History>,
|
|
history_search: ProcessingInput,
|
|
history_entries: Vec<HistoryEntry>,
|
|
selected_history: Option<u64>,
|
|
history_error: Option<String>,
|
|
history_clear_armed: bool,
|
|
history_retention_open: bool,
|
|
history_copied: Option<u64>,
|
|
}
|
|
|
|
impl AppWindow {
|
|
#[allow(clippy::too_many_arguments)]
|
|
fn new(
|
|
event_path: PathBuf,
|
|
commands: CommandConfig,
|
|
meeting_requests: SyncSender<MeetingRequest>,
|
|
indicator: DictationIndicatorSender,
|
|
recognition_start: Option<SyncSender<()>>,
|
|
history: Option<History>,
|
|
preview: Option<AppWindowPreview>,
|
|
native_window: &mut Window,
|
|
cx: &mut Context<Self>,
|
|
) -> Self {
|
|
cx.spawn(async move |window, cx| {
|
|
loop {
|
|
Timer::after(Duration::from_millis(500)).await;
|
|
if window
|
|
.update(cx, |window, cx| {
|
|
let model_catalog_changed = window.poll_model_catalog();
|
|
window.retry_model_catalog();
|
|
let application_catalog_changed = window.poll_application_catalog();
|
|
let transcription_changed = window.poll_transcription_download();
|
|
let setup_changed = window.poll_setup(false);
|
|
let command_model_status = if window.preview {
|
|
window.command_model_status
|
|
} else {
|
|
crate::recognition::command_model_status()
|
|
};
|
|
let command_model_changed =
|
|
window.command_model_status != command_model_status;
|
|
window.command_model_status = command_model_status;
|
|
let login_item_changed = window.poll_login_item();
|
|
let personal_commands_changed = window.poll_personal_commands();
|
|
let personal_workspace_changed = window.poll_personal_workspace();
|
|
let history_changed = window.poll_history(cx);
|
|
let update_status = if window.preview {
|
|
window.update_status
|
|
} else {
|
|
crate::sparkle::status()
|
|
};
|
|
let update_status_changed = window.update_status != update_status;
|
|
if update_status_changed {
|
|
window.update_status = update_status;
|
|
window.update_status_changed_at = Instant::now();
|
|
}
|
|
let update_confirmation_expired = window.update_status
|
|
== crate::sparkle::UpdateStatus::UpToDate
|
|
&& window.update_status_changed_at.elapsed() >= Duration::from_secs(4);
|
|
if update_confirmation_expired {
|
|
window.update_status = crate::sparkle::UpdateStatus::Idle;
|
|
crate::sparkle::clear_confirmation();
|
|
}
|
|
if window.settings.meetings.available()
|
|
&& (window.meeting_refresh_started_ms.is_some()
|
|
|| meeting::active(&window.meetings).is_some())
|
|
{
|
|
window.reload_meetings();
|
|
cx.notify();
|
|
}
|
|
if model_catalog_changed
|
|
|| application_catalog_changed
|
|
|| transcription_changed
|
|
|| setup_changed
|
|
|| command_model_changed
|
|
|| login_item_changed
|
|
|| personal_commands_changed
|
|
|| personal_workspace_changed
|
|
|| history_changed
|
|
|| update_status_changed
|
|
|| update_confirmation_expired
|
|
{
|
|
cx.notify();
|
|
}
|
|
})
|
|
.is_err()
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
})
|
|
.detach();
|
|
let preview_mode = preview.is_some();
|
|
let preview_meetings = preview
|
|
.as_ref()
|
|
.filter(|preview| matches!(preview.pane, DeveloperPane::Meetings))
|
|
.map(|preview| MeetingPreview {
|
|
recording: preview.meeting_recording,
|
|
confirm_delete: preview.confirm_meeting_delete,
|
|
open_actions: preview.open_meeting_actions,
|
|
empty: preview.meetings_empty,
|
|
});
|
|
let preview_choices = crate::transcription_models::choices_for_runtime;
|
|
let (settings, settings_load_error) = if let Some(preview) = &preview {
|
|
let mut settings = AppSettings {
|
|
commands_enabled: preview.command_model_missing
|
|
|| preview.confirm_release_microphone,
|
|
..AppSettings::default()
|
|
};
|
|
settings.voice_action.enabled = preview.voice_action_enabled;
|
|
settings.meetings.enabled =
|
|
preview.meetings_enabled || matches!(preview.pane, DeveloperPane::Meetings);
|
|
if let Some((language, _)) = &preview.transcription_picker
|
|
&& let Some(choice) = preview_choices(language).first()
|
|
{
|
|
settings.transcription.model = choice.model.id;
|
|
settings.transcription.language = language.clone();
|
|
}
|
|
if matches!(preview.pane, DeveloperPane::Modes) {
|
|
let mut mode = DictationMode {
|
|
name: "Work notes".into(),
|
|
applications: vec!["Zed".into()],
|
|
browser_hosts: vec!["github.com".into()],
|
|
replacements: vec![TextReplacement {
|
|
matched_phrase: "open code".into(),
|
|
output: "OpenCode".into(),
|
|
}],
|
|
transformations: vec!["smart-punctuation".into(), "normalize-links".into()],
|
|
..DictationMode::default()
|
|
};
|
|
mode.post_processing.enabled = !preview.collapse_mode_processing;
|
|
mode.post_processing.prompt =
|
|
"Tighten prose and preserve technical terminology.".into();
|
|
mode.post_processing.model = Some("anthropic/claude-sonnet-4".into());
|
|
mode.post_processing.variant = Some("medium".into());
|
|
settings.dictation_processing.modes.push(mode);
|
|
}
|
|
(settings, None)
|
|
} else {
|
|
match AppSettings::load() {
|
|
Ok(settings) => (settings, None),
|
|
Err(error) => {
|
|
tracing::error!(%error, "could not load app settings");
|
|
(
|
|
AppSettings::default(),
|
|
Some(format!("Could not load app settings: {error:#}")),
|
|
)
|
|
}
|
|
}
|
|
};
|
|
let transcription_hints =
|
|
Self::transcription_hints_input(&settings.transcription.recognition_hints, cx);
|
|
let mode_editors = Self::mode_editors(&settings, cx);
|
|
let voice_action_inputs = Self::voice_action_inputs(&settings, cx);
|
|
let (model_catalog, model_catalog_receiver) = if preview
|
|
.as_ref()
|
|
.is_some_and(|preview| preview.opencode_unavailable)
|
|
{
|
|
(ModelCatalogState::Missing, None)
|
|
} else if preview_mode {
|
|
(
|
|
ModelCatalogState::Loaded(ModelCatalog {
|
|
models: vec![
|
|
ModelChoice {
|
|
key: "google/gemini-3.1-flash-lite".into(),
|
|
name: "Gemini 3.1 Flash Lite".into(),
|
|
provider: "Google".into(),
|
|
variants: vec![
|
|
"minimal".into(),
|
|
"low".into(),
|
|
"medium".into(),
|
|
"high".into(),
|
|
],
|
|
},
|
|
ModelChoice {
|
|
key: "anthropic/claude-haiku-4-5".into(),
|
|
name: "Claude Haiku 4.5".into(),
|
|
provider: "Anthropic".into(),
|
|
variants: Vec::new(),
|
|
},
|
|
ModelChoice {
|
|
key: "openai/gpt-5.4-nano".into(),
|
|
name: "GPT-5.4 Nano".into(),
|
|
provider: "OpenAI".into(),
|
|
variants: vec!["none".into(), "low".into(), "medium".into()],
|
|
},
|
|
],
|
|
default_key: Some("google/gemini-3.1-flash-lite".into()),
|
|
default_name: Some("Gemini 3.1 Flash Lite".into()),
|
|
default_variant: Some("minimal".into()),
|
|
}),
|
|
None,
|
|
)
|
|
} else {
|
|
(ModelCatalogState::Loading, Some(start_model_catalog_load()))
|
|
};
|
|
let application_catalog = if preview_mode {
|
|
ApplicationCatalogState::Loaded(Vec::new())
|
|
} else {
|
|
ApplicationCatalogState::Loading
|
|
};
|
|
let application_search = Self::application_search_input(cx);
|
|
if !preview_mode {
|
|
crate::app_settings::set_dock_icon_visible(true);
|
|
}
|
|
let window_focus = cx.focus_handle();
|
|
window_focus.focus(native_window);
|
|
let hotkey_focus = cx.focus_handle();
|
|
let hotkey_blur_subscription = cx.on_blur(&hotkey_focus, native_window, |this, _, cx| {
|
|
this.cancel_hotkey_capture(cx)
|
|
});
|
|
let activation_subscription =
|
|
cx.observe_window_activation(native_window, |this, window, cx| {
|
|
if window.is_window_active() {
|
|
this.permission_refresh_at = Instant::now();
|
|
if this.poll_setup(true) {
|
|
cx.notify();
|
|
}
|
|
}
|
|
});
|
|
let compiled_commands = commands
|
|
.catalog()
|
|
.into_iter()
|
|
.map(|command| CatalogCommand {
|
|
task: command_task(&command),
|
|
scope: command.scope,
|
|
phrase: command.phrase,
|
|
aliases: command.aliases,
|
|
description: command.description,
|
|
id: command.id,
|
|
})
|
|
.collect::<Vec<_>>();
|
|
let personal_workspace = if preview_mode {
|
|
PathBuf::from("~/.config/hex")
|
|
} else {
|
|
crate::app_paths::personal_commands_workspace()
|
|
.unwrap_or_else(|_| PathBuf::from("~/.config/hex"))
|
|
};
|
|
let mut personal_commands_status = if preview_mode {
|
|
StatusSnapshot {
|
|
transformations: vec![
|
|
StatusTransformation {
|
|
id: "smart-punctuation".into(),
|
|
name: "Smart punctuation".into(),
|
|
description: None,
|
|
},
|
|
StatusTransformation {
|
|
id: "normalize-links".into(),
|
|
name: "Normalize links".into(),
|
|
description: None,
|
|
},
|
|
],
|
|
..StatusSnapshot::default()
|
|
}
|
|
} else {
|
|
crate::personal_commands::load_status().unwrap_or_else(|error| StatusSnapshot {
|
|
host_state: HostState::Unavailable,
|
|
last_reload_error: Some(error.to_string()),
|
|
..StatusSnapshot::default()
|
|
})
|
|
};
|
|
crate::personal_commands::include_builtin_transformations(&mut personal_commands_status);
|
|
let commands = merged_catalog(&compiled_commands, &personal_commands_status);
|
|
let preview_picker = preview
|
|
.as_ref()
|
|
.and_then(|preview| preview.transcription_picker.as_ref());
|
|
let preview_model_missing = preview
|
|
.as_ref()
|
|
.is_some_and(|preview| preview.model_missing);
|
|
let preview_model_state = preview_picker.map(|(_, state)| *state);
|
|
let preview_downloading = preview_picker.and_then(|(language, state)| {
|
|
matches!(state, PreviewModelState::Downloading)
|
|
.then(|| preview_choices(language)[0].model.id)
|
|
});
|
|
let selected_model = validate(&settings.transcription).ok();
|
|
let setup_status = if preview.as_ref().is_some_and(|preview| preview.onboarding) {
|
|
SetupStatus {
|
|
microphone: PermissionState::NeedsRequest,
|
|
input_monitoring: PermissionState::NeedsRequest,
|
|
accessibility: PermissionState::NeedsRequest,
|
|
transcription_model: false,
|
|
}
|
|
} else if preview
|
|
.as_ref()
|
|
.is_some_and(|preview| preview.permissions_missing)
|
|
{
|
|
SetupStatus {
|
|
microphone: PermissionState::NeedsRequest,
|
|
input_monitoring: PermissionState::NeedsSettings,
|
|
accessibility: PermissionState::NeedsSettings,
|
|
transcription_model: !preview_model_missing,
|
|
}
|
|
} else if preview_mode {
|
|
SetupStatus {
|
|
microphone: PermissionState::Ready,
|
|
input_monitoring: PermissionState::Ready,
|
|
accessibility: PermissionState::Ready,
|
|
transcription_model: !preview_model_missing,
|
|
}
|
|
} else {
|
|
crate::onboarding::status_with_transcription_model(selected_model.is_some_and(
|
|
|model| {
|
|
crate::transcription_models::is_installed(
|
|
model,
|
|
&settings.transcription.language,
|
|
)
|
|
},
|
|
))
|
|
};
|
|
let onboarding_completed = preview_mode || crate::onboarding::completion_recorded();
|
|
let setup_visible = preview.as_ref().is_some_and(|preview| preview.onboarding)
|
|
|| !onboarding_completed && !setup_status.ready();
|
|
let microphone_devices = if preview_mode {
|
|
vec!["Built-in Microphone".into()]
|
|
} else {
|
|
crate::audio::input_device_names().unwrap_or_else(|error| {
|
|
tracing::warn!(%error, "could not list microphones for settings");
|
|
Vec::new()
|
|
})
|
|
};
|
|
let launch_at_login_status = preview_mode.then_some(LoginItemStatus::Disabled);
|
|
let (login_item_worker, launch_at_login_error) = if preview_mode {
|
|
(None, None)
|
|
} else {
|
|
match LoginItemWorker::new() {
|
|
Ok(worker) => (Some(worker), None),
|
|
Err(error) => (None, Some(error)),
|
|
}
|
|
};
|
|
let history = if preview_mode {
|
|
preview
|
|
.as_ref()
|
|
.is_some_and(|preview| matches!(preview.pane, DeveloperPane::History))
|
|
.then(preview_history)
|
|
.flatten()
|
|
} else {
|
|
history
|
|
};
|
|
let history_search = Self::history_search_input(cx);
|
|
let meeting_search = Self::meeting_search_input(cx);
|
|
let command_search = Self::command_search_input(cx);
|
|
let mut window = Self {
|
|
preview: preview_mode,
|
|
pane: preview.as_ref().map_or(Pane::default(), |preview| {
|
|
Pane::from_developer(preview.pane)
|
|
}),
|
|
event_reader: EventReader::open(event_path),
|
|
activity: DesktopActivity::default(),
|
|
meeting_requests,
|
|
indicator,
|
|
hud_tuning: HudTuning::default(),
|
|
hud_demo: HudDemoState::Transcribing,
|
|
hud_queued: 1,
|
|
hud_dragging: None,
|
|
hud_copied: false,
|
|
recognition_start,
|
|
setup_status,
|
|
setup_visible,
|
|
onboarding_completed,
|
|
permission_refresh_at: Instant::now() + PERMISSION_REFRESH_INTERVAL,
|
|
microphone_devices,
|
|
microphone_picker_open: false,
|
|
microphone_picker_error: None,
|
|
launch_at_login_status,
|
|
login_item_worker,
|
|
launch_at_login_error,
|
|
launch_at_login_toggle: ToggleSpring::new(
|
|
launch_at_login_status == Some(LoginItemStatus::Enabled),
|
|
),
|
|
update_status: if let Some(preview) = &preview {
|
|
if preview.update_available {
|
|
crate::sparkle::UpdateStatus::UpdateAvailable
|
|
} else {
|
|
crate::sparkle::UpdateStatus::Idle
|
|
}
|
|
} else {
|
|
crate::sparkle::status()
|
|
},
|
|
update_status_changed_at: Instant::now(),
|
|
commands_toggle: ToggleSpring::new(settings.commands_enabled),
|
|
command_model_status: if preview
|
|
.as_ref()
|
|
.is_some_and(|preview| preview.command_model_missing)
|
|
{
|
|
CommandModelStatus::Failed
|
|
} else if preview_mode {
|
|
CommandModelStatus::Disabled
|
|
} else {
|
|
crate::recognition::command_model_status()
|
|
},
|
|
release_microphone_toggle: ToggleSpring::new(settings.release_microphone_while_idle),
|
|
pending_microphone_policy: preview
|
|
.as_ref()
|
|
.filter(|preview| preview.confirm_release_microphone)
|
|
.map(|_| MicrophonePolicyChange::DisableCommandsAndRelease),
|
|
double_tap_toggle: ToggleSpring::new(settings.double_tap_lock),
|
|
double_tap_only_visibility: ToggleSpring::new(
|
|
settings.double_tap_lock && settings.dictation_hotkey.key.is_some(),
|
|
),
|
|
dock_icon_toggle: ToggleSpring::new(settings.show_dock_icon),
|
|
incremental_toggle: ToggleSpring::new(settings.incremental_transcription),
|
|
meetings_toggle: ToggleSpring::new(settings.meetings.enabled),
|
|
meeting_notes_toggle: ToggleSpring::new(
|
|
settings.meetings.summarize_with_apple_intelligence,
|
|
),
|
|
screen_recording_permitted: match &preview {
|
|
Some(preview) => !preview.screen_recording_missing,
|
|
None => crate::meeting::screen_recording_permitted(),
|
|
},
|
|
meeting_folder_error: None,
|
|
sound_volume_spring: ToggleSpring::at(sound_volume_index(&settings) as f32),
|
|
recording_audio_spring: ToggleSpring::at(recording_audio_index(
|
|
settings.recording_audio_behavior,
|
|
) as f32),
|
|
variant_picker_open: None,
|
|
transcription_hints,
|
|
transcription_picker_language: preview_picker.map(|(language, _)| language.clone()),
|
|
transcription_status: PreparationStatus {
|
|
model: preview_downloading,
|
|
downloaded_bytes: preview_downloading
|
|
.and_then(|model| definition(model).download_bytes())
|
|
.map_or(0, |bytes| bytes * 37 / 100),
|
|
error: matches!(preview_model_state, Some(PreviewModelState::Error))
|
|
.then(|| "Preview download failed while verifying the model checksum.".into()),
|
|
..Default::default()
|
|
},
|
|
transcription_preparation: if preview.is_some() {
|
|
TranscriptionPreparation::default()
|
|
} else {
|
|
cx.default_global::<TranscriptionPreparation>().clone()
|
|
},
|
|
transcription_preview_installed: match preview_model_state {
|
|
Some(PreviewModelState::Installed) => Some(true),
|
|
Some(
|
|
PreviewModelState::Missing
|
|
| PreviewModelState::Downloading
|
|
| PreviewModelState::Error,
|
|
) => Some(false),
|
|
Some(PreviewModelState::Actual) | None => preview_model_missing.then_some(false),
|
|
},
|
|
transcription_deletion: preview_picker
|
|
.filter(|_| {
|
|
preview
|
|
.as_ref()
|
|
.is_some_and(|preview| preview.confirm_model_deletion)
|
|
})
|
|
.and_then(|(language, _)| {
|
|
crate::transcription_models::choices_for_runtime(language)
|
|
.into_iter()
|
|
.map(|choice| choice.model)
|
|
.find(|model| {
|
|
matches!(model.runtime, ModelRuntime::Gguf(_))
|
|
&& model.id != settings.transcription.model
|
|
})
|
|
.map(|model| model.id)
|
|
}),
|
|
transcription_deletion_error: None,
|
|
mode_editors,
|
|
voice_action_inputs,
|
|
selected_mode: if preview
|
|
.as_ref()
|
|
.is_some_and(|preview| preview.select_global_mode)
|
|
{
|
|
ModeSelection::Default
|
|
} else if preview
|
|
.as_ref()
|
|
.is_some_and(|preview| matches!(preview.pane, DeveloperPane::Modes))
|
|
{
|
|
ModeSelection::Custom(0)
|
|
} else {
|
|
ModeSelection::Default
|
|
},
|
|
model_catalog,
|
|
model_catalog_receiver,
|
|
model_catalog_retry_at: Instant::now() + OPENCODE_INSTALL_RETRY_INTERVAL,
|
|
application_catalog,
|
|
application_catalog_receiver: None,
|
|
application_search,
|
|
application_picker_open: false,
|
|
application_picker_error: None,
|
|
transformation_picker_open: preview
|
|
.as_ref()
|
|
.is_some_and(|preview| preview.open_transformation_picker),
|
|
application_picker_highlight: 0,
|
|
model_picker_highlight: 0,
|
|
mode_delete_armed: false,
|
|
mode_context_menu: None,
|
|
settings_save_generation: 0,
|
|
settings_dirty: false,
|
|
hotkey_capture: HotkeyCaptureState::Idle,
|
|
hotkey_capture_animation: ToggleSpring::new(false),
|
|
hotkey_width_spring: ToggleSpring::at(HOTKEY_MIN_WIDTH),
|
|
hotkey_side_animations: [
|
|
HotkeyKind::Dictation,
|
|
HotkeyKind::Edit,
|
|
HotkeyKind::PasteLast,
|
|
]
|
|
.map(|kind| {
|
|
ToggleSpring::new(
|
|
hotkey_binding(&settings, kind)
|
|
.and_then(standalone_modifier_side)
|
|
.is_some(),
|
|
)
|
|
}),
|
|
hotkey_side_selection_springs: [
|
|
HotkeyKind::Dictation,
|
|
HotkeyKind::Edit,
|
|
HotkeyKind::PasteLast,
|
|
]
|
|
.map(|kind| {
|
|
ToggleSpring::at(hotkey_side_index(
|
|
hotkey_binding(&settings, kind)
|
|
.and_then(standalone_modifier_side)
|
|
.unwrap_or(ModifierSide::Either),
|
|
) as f32)
|
|
}),
|
|
window_focus,
|
|
hotkey_focus,
|
|
_hotkey_blur_subscription: hotkey_blur_subscription,
|
|
_activation_subscription: activation_subscription,
|
|
settings,
|
|
settings_load_error,
|
|
#[cfg(test)]
|
|
settings_save_override: None,
|
|
meetings: Vec::new(),
|
|
meetings_error: None,
|
|
meeting_runtime_error: None,
|
|
meeting_refresh_started_ms: None,
|
|
meeting_stop_pending: false,
|
|
selected_meeting: None,
|
|
meeting_transcript: MeetingTranscript::Empty,
|
|
meeting_transcript_id: None,
|
|
meeting_transcript_reader: meeting::TranscriptReader::default(),
|
|
meeting_transcript_scroll: ScrollHandle::new(),
|
|
meeting_turns: Vec::new(),
|
|
meeting_search,
|
|
meeting_search_text: HashMap::new(),
|
|
meeting_rename: None,
|
|
meeting_delete_armed: None,
|
|
meeting_actions_open: false,
|
|
meeting_action_error: None,
|
|
meeting_copied: None,
|
|
meeting_preview_transcripts: None,
|
|
compiled_commands,
|
|
commands,
|
|
personal_commands_status,
|
|
personal_workspace,
|
|
personal_workspace_receiver: None,
|
|
personal_workspace_error: None,
|
|
personal_commands_prompt_copied: false,
|
|
command_search,
|
|
selected_command: None,
|
|
events: Vec::new(),
|
|
current_context: (None, None),
|
|
selected_event: None,
|
|
history,
|
|
history_search,
|
|
history_entries: Vec::new(),
|
|
selected_history: None,
|
|
history_error: None,
|
|
history_clear_armed: false,
|
|
history_retention_open: preview
|
|
.as_ref()
|
|
.is_some_and(|preview| preview.open_history_retention),
|
|
history_copied: None,
|
|
};
|
|
if !window.preview {
|
|
if window.settings.meetings.available() {
|
|
window.reload_meetings();
|
|
if meeting::active(&window.meetings).is_some() {
|
|
window.pane = Pane::Meetings;
|
|
}
|
|
}
|
|
window.reload_events();
|
|
}
|
|
window.reload_history(cx);
|
|
if window.preview {
|
|
window.selected_history = window.history_entries.first().map(|entry| entry.id);
|
|
}
|
|
if let Some(preview) = preview_meetings.as_ref()
|
|
&& window.pane == Pane::Meetings
|
|
{
|
|
window.load_meeting_preview(preview);
|
|
}
|
|
if window.pane == Pane::Modes {
|
|
window.ensure_application_catalog_load();
|
|
}
|
|
if window.pane == Pane::HudLab {
|
|
window.apply_hud_lab();
|
|
}
|
|
window
|
|
}
|
|
|
|
/// Refreshes disk-backed meeting and activity data while retaining valid
|
|
/// selections. This is also called whenever an existing shell is reopened.
|
|
pub fn refresh(&mut self, cx: &mut Context<Self>) {
|
|
if !self.preview {
|
|
if self.settings.meetings.available() {
|
|
self.reload_meetings();
|
|
}
|
|
self.reload_events();
|
|
}
|
|
self.reload_history(cx);
|
|
if self.pane == Pane::Modes {
|
|
self.ensure_application_catalog_load();
|
|
}
|
|
self.permission_refresh_at = Instant::now();
|
|
self.poll_setup(true);
|
|
let pane = self.pane.on_reopen(self.setup_status);
|
|
if pane != self.pane {
|
|
self.select_pane(pane, cx);
|
|
}
|
|
cx.notify();
|
|
}
|
|
|
|
fn select_pane(&mut self, pane: Pane, cx: &mut Context<Self>) {
|
|
self.pane = pane;
|
|
self.mode_context_menu = None;
|
|
self.history_retention_open = false;
|
|
self.pending_microphone_policy = None;
|
|
match pane {
|
|
Pane::HudLab => self.apply_hud_lab(),
|
|
Pane::Meetings => self.reload_meetings(),
|
|
Pane::Commands | Pane::Activity => self.reload_events(),
|
|
Pane::History => self.reload_history(cx),
|
|
Pane::Modes => self.ensure_application_catalog_load(),
|
|
Pane::VoiceAction => {}
|
|
Pane::Settings => self.permission_refresh_at = Instant::now(),
|
|
}
|
|
cx.notify();
|
|
}
|
|
|
|
pub(crate) fn show_settings(&mut self, cx: &mut Context<Self>) {
|
|
self.select_pane(Pane::Settings, cx);
|
|
}
|
|
|
|
pub(crate) fn show_meetings(&mut self, cx: &mut Context<Self>) {
|
|
if self.settings.meetings.available() {
|
|
self.select_pane(Pane::Meetings, cx);
|
|
} else {
|
|
self.show_settings(cx);
|
|
}
|
|
}
|
|
|
|
pub(crate) fn show_transcription_models(&mut self, cx: &mut Context<Self>) {
|
|
self.show_settings(cx);
|
|
self.transcription_picker_language = Some(self.settings.transcription.language.clone());
|
|
self.poll_transcription_download();
|
|
cx.notify();
|
|
}
|
|
|
|
pub(crate) fn developer_select_pane(&mut self, pane: DeveloperPane, cx: &mut Context<Self>) {
|
|
self.select_pane(Pane::from_developer(pane), cx);
|
|
}
|
|
|
|
pub(crate) fn developer_pane(&self) -> DeveloperPane {
|
|
self.pane.developer()
|
|
}
|
|
|
|
pub(crate) fn developer_set_commands_enabled(
|
|
&mut self,
|
|
enabled: bool,
|
|
cx: &mut Context<Self>,
|
|
) -> Result<(), String> {
|
|
self.update_microphone_policy(MicrophonePolicyChange::SetCommands(enabled), cx)
|
|
.map_err(|error| error.to_string())
|
|
}
|
|
|
|
fn update_microphone_policy(
|
|
&mut self,
|
|
change: MicrophonePolicyChange,
|
|
cx: &mut Context<Self>,
|
|
) -> color_eyre::Result<()> {
|
|
let mut candidate = self.settings_candidate();
|
|
match change {
|
|
MicrophonePolicyChange::SetCommands(enabled) => {
|
|
candidate.set_commands_enabled(enabled)?
|
|
}
|
|
MicrophonePolicyChange::SetReleaseWhileIdle(enabled) => {
|
|
candidate.set_release_microphone_while_idle(enabled)?
|
|
}
|
|
MicrophonePolicyChange::KeepReadyAndEnableCommands => {
|
|
candidate.keep_microphone_ready_and_enable_commands()
|
|
}
|
|
MicrophonePolicyChange::DisableCommandsAndRelease => {
|
|
candidate.disable_commands_and_release_microphone()
|
|
}
|
|
}
|
|
let result = self.commit_settings(candidate);
|
|
cx.notify();
|
|
result?;
|
|
self.commands_toggle
|
|
.set_enabled(self.settings.commands_enabled);
|
|
self.release_microphone_toggle
|
|
.set_enabled(self.settings.release_microphone_while_idle);
|
|
self.pending_microphone_policy = None;
|
|
cx.notify();
|
|
Ok(())
|
|
}
|
|
|
|
fn poll_model_catalog(&mut self) -> bool {
|
|
let Some(receiver) = &self.model_catalog_receiver else {
|
|
return false;
|
|
};
|
|
let Ok(result) = receiver.try_recv() else {
|
|
return false;
|
|
};
|
|
self.model_catalog = result;
|
|
self.model_catalog_receiver = None;
|
|
true
|
|
}
|
|
|
|
fn retry_model_catalog(&mut self) {
|
|
if !matches!(&self.model_catalog, ModelCatalogState::Missing)
|
|
|| self.model_catalog_receiver.is_some()
|
|
|| Instant::now() < self.model_catalog_retry_at
|
|
{
|
|
return;
|
|
}
|
|
self.model_catalog_retry_at = Instant::now() + OPENCODE_INSTALL_RETRY_INTERVAL;
|
|
self.model_catalog_receiver = Some(start_model_catalog_load());
|
|
}
|
|
|
|
fn reload_model_catalog(&mut self) {
|
|
if self.preview || self.model_catalog_receiver.is_some() {
|
|
return;
|
|
}
|
|
self.model_catalog = ModelCatalogState::Loading;
|
|
self.model_catalog_retry_at = Instant::now() + OPENCODE_INSTALL_RETRY_INTERVAL;
|
|
self.model_catalog_receiver = Some(start_model_catalog_load());
|
|
}
|
|
|
|
fn opencode_available(&self) -> bool {
|
|
matches!(&self.model_catalog, ModelCatalogState::Loaded(_))
|
|
}
|
|
|
|
fn poll_application_catalog(&mut self) -> bool {
|
|
let Some(receiver) = &self.application_catalog_receiver else {
|
|
return false;
|
|
};
|
|
let Ok(result) = receiver.try_recv() else {
|
|
return false;
|
|
};
|
|
let mut applications = result;
|
|
if let ApplicationCatalogState::Loaded(existing) = &self.application_catalog {
|
|
for application in existing.iter().cloned() {
|
|
crate::application_catalog::insert(&mut applications, application);
|
|
}
|
|
}
|
|
self.application_catalog = ApplicationCatalogState::Loaded(applications);
|
|
self.application_catalog_receiver = None;
|
|
true
|
|
}
|
|
|
|
fn ensure_application_catalog_load(&mut self) {
|
|
if !application_catalog_load_needed(
|
|
self.preview,
|
|
&self.application_catalog,
|
|
self.application_catalog_receiver.is_some(),
|
|
) {
|
|
return;
|
|
}
|
|
let (sender, receiver) = sync_channel(1);
|
|
thread::spawn(move || {
|
|
let _ = sender.send(crate::application_catalog::discover());
|
|
});
|
|
self.application_catalog_receiver = Some(receiver);
|
|
}
|
|
|
|
fn poll_transcription_download(&mut self) -> bool {
|
|
if self.preview {
|
|
return false;
|
|
}
|
|
let status = self.transcription_preparation.status();
|
|
let changed = self.transcription_status != status;
|
|
self.transcription_status = status;
|
|
changed || self.transcription_status.model.is_some()
|
|
}
|
|
|
|
fn poll_setup(&mut self, force: bool) -> bool {
|
|
if self.preview
|
|
|| !force
|
|
&& (Instant::now() < self.permission_refresh_at
|
|
|| !self.setup_visible
|
|
&& self.recognition_start.is_none()
|
|
&& self.pane != Pane::Settings
|
|
&& self.setup_status.transcription_model)
|
|
{
|
|
return false;
|
|
}
|
|
self.permission_refresh_at = Instant::now() + PERMISSION_REFRESH_INTERVAL;
|
|
let mut changed = false;
|
|
let transcription_model = validate(&self.settings.transcription).is_ok_and(|model| {
|
|
crate::transcription_models::is_installed(model, &self.settings.transcription.language)
|
|
});
|
|
let status = crate::onboarding::status_with_transcription_model(transcription_model);
|
|
if status != self.setup_status {
|
|
self.setup_status = status;
|
|
changed = true;
|
|
}
|
|
if self.setup_status.ready() {
|
|
if !self.onboarding_completed {
|
|
if let Err(error) = crate::onboarding::record_completion() {
|
|
tracing::warn!(%error, "could not record onboarding completion");
|
|
}
|
|
self.onboarding_completed = true;
|
|
}
|
|
if let Some(start) = self.recognition_start.take() {
|
|
let _ = start.try_send(());
|
|
}
|
|
if self.setup_visible {
|
|
self.setup_visible = false;
|
|
changed = true;
|
|
}
|
|
}
|
|
if self.settings.meetings.available() {
|
|
let permitted = crate::meeting::screen_recording_permitted();
|
|
if permitted != self.screen_recording_permitted {
|
|
self.screen_recording_permitted = permitted;
|
|
changed = true;
|
|
}
|
|
}
|
|
changed
|
|
}
|
|
|
|
fn poll_login_item(&mut self) -> bool {
|
|
let Some(worker) = &mut self.login_item_worker else {
|
|
return false;
|
|
};
|
|
let response = worker.poll();
|
|
let changed = match response {
|
|
Ok(Some(response)) => self.apply_login_item_response(response),
|
|
Ok(None) => false,
|
|
Err(error) => {
|
|
self.login_item_worker_failed(error);
|
|
return true;
|
|
}
|
|
};
|
|
let request_changed = self.request_login_item(LoginItemRequest::Status);
|
|
changed || request_changed
|
|
}
|
|
|
|
fn apply_login_item_response(&mut self, response: LoginItemResponse) -> bool {
|
|
let before = (
|
|
self.launch_at_login_status,
|
|
self.launch_at_login_toggle.enabled(),
|
|
);
|
|
let error_changed = match response.result {
|
|
Ok(status) => {
|
|
let clear_error = self.launch_at_login_status.is_none()
|
|
|| matches!(response.request, LoginItemRequest::SetEnabled(_))
|
|
|| self.launch_at_login_status != Some(status)
|
|
&& status == LoginItemStatus::Enabled;
|
|
self.launch_at_login_status = Some(status);
|
|
clear_error && self.launch_at_login_error.take().is_some()
|
|
}
|
|
Err(error) => {
|
|
if let Some(status) = error.status {
|
|
self.launch_at_login_status = Some(status);
|
|
}
|
|
let changed = self.launch_at_login_error.as_deref() != Some(error.message.as_str());
|
|
self.launch_at_login_error = Some(error.message);
|
|
changed
|
|
}
|
|
};
|
|
let enabled = self
|
|
.login_item_worker
|
|
.as_ref()
|
|
.and_then(LoginItemWorker::desired_enabled)
|
|
.unwrap_or(self.launch_at_login_status == Some(LoginItemStatus::Enabled));
|
|
self.launch_at_login_toggle.set_enabled(enabled);
|
|
error_changed
|
|
|| before
|
|
!= (
|
|
self.launch_at_login_status,
|
|
self.launch_at_login_toggle.enabled(),
|
|
)
|
|
}
|
|
|
|
fn request_login_item(&mut self, request: LoginItemRequest) -> bool {
|
|
let Some(worker) = &mut self.login_item_worker else {
|
|
return false;
|
|
};
|
|
if let Err(error) = worker.request(request) {
|
|
self.login_item_worker_failed(error);
|
|
return true;
|
|
}
|
|
false
|
|
}
|
|
|
|
fn login_item_worker_failed(&mut self, error: String) {
|
|
self.login_item_worker = None;
|
|
self.launch_at_login_error = Some(error);
|
|
self.launch_at_login_toggle
|
|
.set_enabled(self.launch_at_login_status == Some(LoginItemStatus::Enabled));
|
|
}
|
|
|
|
fn poll_personal_commands(&mut self) -> bool {
|
|
if self.preview {
|
|
return false;
|
|
}
|
|
let Ok(mut status) = crate::personal_commands::load_status() else {
|
|
return false;
|
|
};
|
|
crate::personal_commands::include_builtin_transformations(&mut status);
|
|
if status == self.personal_commands_status {
|
|
return false;
|
|
}
|
|
self.personal_commands_status = status;
|
|
self.commands = merged_catalog(&self.compiled_commands, &self.personal_commands_status);
|
|
if self
|
|
.selected_command
|
|
.as_ref()
|
|
.is_some_and(|id| !self.commands.iter().any(|command| &command.id == id))
|
|
{
|
|
self.selected_command = None;
|
|
}
|
|
true
|
|
}
|
|
|
|
fn poll_personal_workspace(&mut self) -> bool {
|
|
let Some(receiver) = &self.personal_workspace_receiver else {
|
|
return false;
|
|
};
|
|
let Ok(result) = receiver.try_recv() else {
|
|
return false;
|
|
};
|
|
self.personal_workspace_receiver = None;
|
|
match result {
|
|
Ok(workspace) => {
|
|
self.personal_workspace = workspace;
|
|
self.personal_workspace_error = None;
|
|
}
|
|
Err(error) => self.personal_workspace_error = Some(error),
|
|
}
|
|
true
|
|
}
|
|
|
|
fn provision_personal_workspace(&mut self) {
|
|
if self.preview || self.personal_workspace_receiver.is_some() {
|
|
return;
|
|
}
|
|
let (sender, receiver) = sync_channel(1);
|
|
thread::spawn(move || {
|
|
let result =
|
|
crate::personal_commands::initialize_workspace().map_err(|error| error.to_string());
|
|
let _ = sender.send(result);
|
|
});
|
|
self.personal_workspace_error = None;
|
|
self.personal_workspace_receiver = Some(receiver);
|
|
}
|
|
|
|
fn apply_transcription_selection(
|
|
&mut self,
|
|
selection: TranscriptionSelection,
|
|
cx: &mut Context<Self>,
|
|
) -> Result<(), String> {
|
|
validate(&selection).map_err(|error| error.to_string())?;
|
|
let mut candidate = self.settings_candidate();
|
|
candidate.remember_transcription(selection);
|
|
self.commit_settings(candidate)
|
|
.map_err(|error| error.to_string())?;
|
|
if self.preview {
|
|
self.transcription_preview_installed = Some(true);
|
|
self.setup_status.transcription_model = true;
|
|
}
|
|
self.transcription_hints.entity.update(cx, |input, cx| {
|
|
input.set_text(&self.settings.transcription.recognition_hints, cx);
|
|
});
|
|
self.permission_refresh_at = Instant::now();
|
|
self.transcription_picker_language = None;
|
|
self.clear_transcription_error();
|
|
Ok(())
|
|
}
|
|
|
|
fn choose_transcription_model(
|
|
&mut self,
|
|
model: &'static ModelDefinition,
|
|
language: String,
|
|
cx: &mut Context<Self>,
|
|
) {
|
|
self.cancel_transcription_download();
|
|
let selection = TranscriptionSelection {
|
|
model: model.id,
|
|
language,
|
|
recognition_hints: if model.supports_recognition_hints {
|
|
self.transcription_hints.entity.read(cx).text().to_string()
|
|
} else {
|
|
String::new()
|
|
},
|
|
};
|
|
self.clear_transcription_error();
|
|
if self.preview {
|
|
self.apply_transcription_selection(selection, cx)
|
|
.expect("preview selections do not write settings");
|
|
return;
|
|
}
|
|
if transcription_selection_is_active(
|
|
&self.settings.transcription,
|
|
model,
|
|
&selection.language,
|
|
self.transcription_model_installed(model, &selection.language),
|
|
) {
|
|
self.transcription_picker_language = None;
|
|
return;
|
|
}
|
|
self.transcription_preparation.start(selection, false);
|
|
self.poll_transcription_download();
|
|
}
|
|
|
|
fn cancel_transcription_download(&mut self) {
|
|
self.transcription_preparation.cancel();
|
|
self.transcription_status = self.transcription_preparation.status();
|
|
}
|
|
|
|
fn clear_transcription_error(&mut self) {
|
|
self.transcription_preparation.set_error(None);
|
|
self.transcription_status = self.transcription_preparation.status();
|
|
self.transcription_deletion = None;
|
|
self.transcription_deletion_error = None;
|
|
}
|
|
|
|
/// Downloaded local models other than the dictation model can be deleted,
|
|
/// whatever language the picker shows, unless they are being prepared.
|
|
fn transcription_model_deletion(
|
|
&self,
|
|
model: &ModelDefinition,
|
|
installed: bool,
|
|
) -> ModelDeletion {
|
|
if !installed
|
|
|| !matches!(model.runtime, ModelRuntime::Gguf(_))
|
|
|| self.settings.transcription.model == model.id
|
|
|| self.transcription_status.model == Some(model.id)
|
|
{
|
|
ModelDeletion::Unavailable
|
|
} else if self.transcription_deletion == Some(model.id) {
|
|
ModelDeletion::Confirming
|
|
} else {
|
|
ModelDeletion::Offered
|
|
}
|
|
}
|
|
|
|
fn delete_transcription_model(&mut self, model: &'static ModelDefinition) {
|
|
self.transcription_deletion_error = None;
|
|
let language = self
|
|
.transcription_picker_language
|
|
.clone()
|
|
.unwrap_or_default();
|
|
let installed = self.transcription_model_installed(model, &language);
|
|
match self.transcription_model_deletion(model, installed) {
|
|
ModelDeletion::Unavailable => self.transcription_deletion = None,
|
|
ModelDeletion::Offered => self.transcription_deletion = Some(model.id),
|
|
ModelDeletion::Confirming => {
|
|
self.transcription_deletion = None;
|
|
if self.preview {
|
|
return;
|
|
}
|
|
match crate::transcription_models::remove_installed(model) {
|
|
Ok(()) => tracing::info!(model = ?model.id, "deleted transcription model"),
|
|
Err(error) => {
|
|
tracing::warn!(model = ?model.id, %error, "could not delete transcription model");
|
|
self.transcription_deletion_error = Some(error.to_string());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn transcription_model_installed(&self, model: &ModelDefinition, language: &str) -> bool {
|
|
self.transcription_preview_installed
|
|
.unwrap_or_else(|| crate::transcription_models::is_installed(model, language))
|
|
}
|
|
|
|
pub fn meeting_starting(&mut self, cx: &mut Context<Self>) {
|
|
self.meeting_runtime_error = None;
|
|
self.meeting_refresh_started_ms = Some(now_ms());
|
|
self.meeting_stop_pending = false;
|
|
self.pane = Pane::Meetings;
|
|
self.reload_meetings();
|
|
cx.notify();
|
|
}
|
|
|
|
pub fn meeting_started(&mut self, cx: &mut Context<Self>) {
|
|
self.meeting_refresh_started_ms = None;
|
|
self.reload_meetings();
|
|
cx.notify();
|
|
}
|
|
|
|
pub fn meeting_updated(&mut self, cx: &mut Context<Self>) {
|
|
self.meeting_stop_pending = true;
|
|
self.reload_meetings();
|
|
cx.notify();
|
|
}
|
|
|
|
pub fn meeting_updated_notes(&mut self, cx: &mut Context<Self>) {
|
|
self.reload_meetings();
|
|
cx.notify();
|
|
}
|
|
|
|
fn apple_intelligence_availability(&self) -> crate::apple_intelligence::Availability {
|
|
if self.preview {
|
|
crate::apple_intelligence::Availability::Available
|
|
} else {
|
|
crate::apple_intelligence::availability()
|
|
}
|
|
}
|
|
|
|
pub fn meeting_finished(&mut self, cx: &mut Context<Self>) {
|
|
self.meeting_refresh_started_ms = None;
|
|
self.meeting_stop_pending = false;
|
|
self.reload_meetings();
|
|
cx.notify();
|
|
}
|
|
|
|
pub fn meeting_failed(&mut self, title: String, error: String, cx: &mut Context<Self>) {
|
|
self.meeting_runtime_error = Some(format!("{title}: {error}"));
|
|
self.meeting_refresh_started_ms = None;
|
|
self.meeting_stop_pending = false;
|
|
self.pane = Pane::Meetings;
|
|
self.reload_meetings();
|
|
if let Some(failed) = self
|
|
.meetings
|
|
.iter()
|
|
.find(|meeting| meeting.status == MeetingStatus::Failed && meeting.title == title)
|
|
{
|
|
self.selected_meeting = Some(failed.id.clone());
|
|
self.load_selected_meeting();
|
|
}
|
|
cx.notify();
|
|
}
|
|
|
|
fn reload_meetings(&mut self) {
|
|
if self.meeting_preview_transcripts.is_some() {
|
|
return;
|
|
}
|
|
match meeting::list() {
|
|
Ok(meetings) => {
|
|
let previous_active = meeting::active(&self.meetings).map(|meeting| &meeting.id);
|
|
let next_active = meeting::active(&meetings).map(|meeting| meeting.id.clone());
|
|
if next_active.as_deref() != previous_active.map(String::as_str)
|
|
&& next_active.is_some()
|
|
{
|
|
self.selected_meeting = next_active;
|
|
}
|
|
if meeting::active(&meetings).is_none()
|
|
&& (previous_active.is_some()
|
|
|| self.meeting_refresh_started_ms.is_some_and(|started| {
|
|
meetings.iter().any(|meeting| {
|
|
meeting.created_at_ms >= started
|
|
&& matches!(
|
|
meeting.status,
|
|
MeetingStatus::Complete
|
|
| MeetingStatus::Interrupted
|
|
| MeetingStatus::Failed
|
|
)
|
|
})
|
|
}))
|
|
{
|
|
self.meeting_refresh_started_ms = None;
|
|
}
|
|
self.meetings = meetings;
|
|
let indexed = &self.meetings;
|
|
self.meeting_search_text.retain(|id, _| {
|
|
indexed
|
|
.iter()
|
|
.any(|manifest| &manifest.id == id && !manifest.status.is_active())
|
|
});
|
|
if meeting::active(&self.meetings)
|
|
.is_none_or(|meeting| meeting.status == MeetingStatus::Transcribing)
|
|
{
|
|
self.meeting_stop_pending = false;
|
|
}
|
|
self.meetings_error = None;
|
|
if self
|
|
.selected_meeting
|
|
.as_ref()
|
|
.is_some_and(|selected| !self.meetings.iter().any(|item| &item.id == selected))
|
|
{
|
|
self.selected_meeting = None;
|
|
self.meeting_transcript = MeetingTranscript::Empty;
|
|
} else if self.selected_meeting.is_some() {
|
|
self.load_selected_meeting();
|
|
}
|
|
}
|
|
Err(error) => {
|
|
tracing::error!(%error, "could not list meetings");
|
|
self.meetings_error = Some(error.to_string());
|
|
}
|
|
}
|
|
}
|
|
|
|
fn load_selected_meeting(&mut self) {
|
|
let Some(id) = self.selected_meeting.clone() else {
|
|
self.meeting_transcript = MeetingTranscript::Empty;
|
|
self.meeting_transcript_id = None;
|
|
return;
|
|
};
|
|
let selection_changed = self.meeting_transcript_id.as_deref() != Some(&id);
|
|
if selection_changed {
|
|
self.meeting_transcript_id = Some(id.clone());
|
|
self.meeting_transcript_scroll = ScrollHandle::new();
|
|
}
|
|
let previous_lines = match &self.meeting_transcript {
|
|
MeetingTranscript::Loaded(lines) if !selection_changed => Some(lines.clone()),
|
|
MeetingTranscript::Empty
|
|
| MeetingTranscript::Loaded(_)
|
|
| MeetingTranscript::Unavailable(_) => None,
|
|
};
|
|
let was_following = previous_lines.as_ref().is_none_or(|lines| {
|
|
lines.is_empty()
|
|
|| self.meeting_transcript_scroll.max_offset().height
|
|
+ self.meeting_transcript_scroll.offset().y
|
|
<= px(48.0)
|
|
});
|
|
let entries = match &self.meeting_preview_transcripts {
|
|
Some(fixtures) => Ok(fixtures.get(&id).cloned().unwrap_or_default()),
|
|
None => self.meeting_transcript_reader.read(&id),
|
|
};
|
|
self.meeting_transcript = match entries {
|
|
Ok(entries) => {
|
|
self.meeting_turns = meeting::coalesce_transcript(entries);
|
|
MeetingTranscript::Loaded(transcript_lines(&self.meeting_turns))
|
|
}
|
|
Err(error) => {
|
|
self.meeting_turns.clear();
|
|
MeetingTranscript::Unavailable(error.to_string())
|
|
}
|
|
};
|
|
if !selection_changed
|
|
&& matches!(
|
|
&self.meeting_transcript,
|
|
MeetingTranscript::Loaded(lines) if was_following && previous_lines.as_ref() != Some(lines)
|
|
)
|
|
{
|
|
self.meeting_transcript_scroll.scroll_to_bottom();
|
|
}
|
|
}
|
|
|
|
fn meeting_search_input(cx: &mut Context<Self>) -> ProcessingInput {
|
|
let entity = cx.new(|cx| TextInput::picker(cx, "Search meetings", ""));
|
|
let changed = cx.subscribe(&entity, |this, _, _: &TextChanged, cx| {
|
|
this.refresh_meeting_search(cx);
|
|
cx.notify();
|
|
});
|
|
ProcessingInput {
|
|
entity,
|
|
_subscriptions: vec![changed],
|
|
}
|
|
}
|
|
|
|
fn meeting_query(&self, cx: &App) -> String {
|
|
self.meeting_search
|
|
.entity
|
|
.read(cx)
|
|
.text()
|
|
.trim()
|
|
.to_lowercase()
|
|
}
|
|
|
|
/// Loads searchable text for meetings not yet indexed. Runs only while
|
|
/// a query is entered, so idle panes never read transcripts.
|
|
fn refresh_meeting_search(&mut self, cx: &App) {
|
|
if self.meeting_query(cx).is_empty() {
|
|
return;
|
|
}
|
|
for manifest in &self.meetings {
|
|
if !self.meeting_search_text.contains_key(&manifest.id) {
|
|
let text = match &self.meeting_preview_transcripts {
|
|
Some(fixtures) => format!(
|
|
"{} {}",
|
|
meeting::display_title(manifest),
|
|
fixtures
|
|
.get(&manifest.id)
|
|
.into_iter()
|
|
.flatten()
|
|
.map(|entry| entry.text.as_str())
|
|
.collect::<Vec<_>>()
|
|
.join(" ")
|
|
)
|
|
.to_lowercase(),
|
|
None => meeting::search_text(manifest),
|
|
};
|
|
self.meeting_search_text.insert(manifest.id.clone(), text);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn visible_meetings(&self, cx: &App) -> Vec<&MeetingManifest> {
|
|
let query = self.meeting_query(cx);
|
|
self.meetings
|
|
.iter()
|
|
.filter(|manifest| {
|
|
query.is_empty()
|
|
|| manifest.status.is_active()
|
|
|| self
|
|
.meeting_search_text
|
|
.get(&manifest.id)
|
|
.is_none_or(|text| query.split_whitespace().all(|word| text.contains(word)))
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
fn select_meeting(&mut self, id: String) {
|
|
if self.selected_meeting.as_deref() != Some(id.as_str()) {
|
|
self.meeting_rename = None;
|
|
self.meeting_delete_armed = None;
|
|
self.meeting_actions_open = false;
|
|
self.meeting_action_error = None;
|
|
self.meeting_copied = None;
|
|
}
|
|
self.selected_meeting = Some(id);
|
|
self.load_selected_meeting();
|
|
}
|
|
|
|
fn copy_meeting_text(
|
|
&mut self,
|
|
id: String,
|
|
what: &'static str,
|
|
text: String,
|
|
cx: &mut Context<Self>,
|
|
) {
|
|
match arboard::Clipboard::new().and_then(|mut clipboard| clipboard.set_text(text)) {
|
|
Ok(()) => {
|
|
self.meeting_copied = Some((id, what));
|
|
self.meeting_action_error = None;
|
|
}
|
|
Err(error) => self.meeting_action_error = Some(error.to_string()),
|
|
}
|
|
cx.notify();
|
|
}
|
|
|
|
fn trash_meeting(&mut self, id: String, cx: &mut Context<Self>) {
|
|
if self.meeting_delete_armed.as_deref() != Some(id.as_str()) {
|
|
self.meeting_delete_armed = Some(id);
|
|
self.meeting_rename = None;
|
|
cx.notify();
|
|
return;
|
|
}
|
|
self.meeting_delete_armed = None;
|
|
let result = if self.preview {
|
|
Ok(())
|
|
} else {
|
|
meeting::trash(&id)
|
|
};
|
|
match result {
|
|
Ok(()) => {
|
|
self.meeting_action_error = None;
|
|
self.meeting_search_text.remove(&id);
|
|
if self.preview {
|
|
self.meetings.retain(|manifest| manifest.id != id);
|
|
} else {
|
|
self.reload_meetings();
|
|
}
|
|
let next = self.meetings.first().map(|manifest| manifest.id.clone());
|
|
self.selected_meeting = None;
|
|
if let Some(next) = next {
|
|
self.select_meeting(next);
|
|
} else {
|
|
self.load_selected_meeting();
|
|
}
|
|
}
|
|
Err(error) => self.meeting_action_error = Some(error.to_string()),
|
|
}
|
|
cx.notify();
|
|
}
|
|
|
|
fn start_meeting_rename(
|
|
&mut self,
|
|
id: String,
|
|
title: String,
|
|
window: &mut Window,
|
|
cx: &mut Context<Self>,
|
|
) {
|
|
let entity = cx.new(|cx| TextInput::new(cx, "Meeting title", &title));
|
|
let submitted = cx.subscribe(&entity, |this, _, _: &TextSubmitted, cx| {
|
|
this.finish_meeting_rename(cx);
|
|
});
|
|
let dismissed = cx.subscribe(&entity, |this, _, _: &TextDismissed, cx| {
|
|
this.meeting_rename = None;
|
|
cx.notify();
|
|
});
|
|
entity.focus_handle(cx).focus(window);
|
|
self.meeting_delete_armed = None;
|
|
self.meeting_rename = Some((
|
|
id,
|
|
ProcessingInput {
|
|
entity,
|
|
_subscriptions: vec![submitted, dismissed],
|
|
},
|
|
));
|
|
cx.notify();
|
|
}
|
|
|
|
fn finish_meeting_rename(&mut self, cx: &mut Context<Self>) {
|
|
let Some((id, input)) = self.meeting_rename.take() else {
|
|
return;
|
|
};
|
|
let title = input.entity.read(cx).text().to_string();
|
|
let result = if self.preview {
|
|
let title = title.split_whitespace().collect::<Vec<_>>().join(" ");
|
|
match self.meetings.iter_mut().find(|manifest| manifest.id == id) {
|
|
Some(manifest) if !title.is_empty() => {
|
|
manifest.title = title;
|
|
Ok(())
|
|
}
|
|
_ => Err(color_eyre::eyre::eyre!("The title is empty")),
|
|
}
|
|
} else {
|
|
meeting::rename(&id, &title).map(|_| ())
|
|
};
|
|
match result {
|
|
Ok(()) => self.meeting_action_error = None,
|
|
Err(error) => self.meeting_action_error = Some(format!("{error:#}")),
|
|
}
|
|
self.meeting_search_text.remove(&id);
|
|
if !self.preview {
|
|
self.reload_meetings();
|
|
}
|
|
cx.notify();
|
|
}
|
|
|
|
fn load_meeting_preview(&mut self, preview: &MeetingPreview) {
|
|
let (meetings, transcripts) = preview_meetings(preview.empty);
|
|
self.meetings = meetings;
|
|
self.meeting_preview_transcripts = Some(transcripts);
|
|
let selected = if preview.recording {
|
|
meeting::active(&self.meetings)
|
|
} else {
|
|
self.meetings
|
|
.iter()
|
|
.find(|manifest| manifest.status == MeetingStatus::Complete)
|
|
}
|
|
.map(|manifest| manifest.id.clone());
|
|
if let Some(id) = selected {
|
|
self.select_meeting(id.clone());
|
|
if preview.confirm_delete {
|
|
self.meeting_delete_armed = Some(id);
|
|
}
|
|
self.meeting_actions_open = preview.open_actions;
|
|
}
|
|
}
|
|
|
|
fn reload_events(&mut self) {
|
|
if !matches!(self.pane, Pane::Commands | Pane::Activity) {
|
|
return;
|
|
}
|
|
let selected = self
|
|
.selected_event
|
|
.and_then(|index| self.events.get(index))
|
|
.cloned();
|
|
self.activity.refresh(&mut self.event_reader);
|
|
if self.activity.error.is_some() {
|
|
return;
|
|
}
|
|
self.events = self.event_reader.recent(ACTIVITY_LIMIT);
|
|
self.current_context = activity_context(&self.event_reader);
|
|
self.selected_event =
|
|
selected.and_then(|selected| self.events.iter().position(|event| event == &selected));
|
|
}
|
|
|
|
fn history_search_input(cx: &mut Context<Self>) -> ProcessingInput {
|
|
let entity = cx.new(|cx| TextInput::picker(cx, "Search history", ""));
|
|
let changed = cx.subscribe(&entity, |this, _, _: &TextChanged, cx| {
|
|
this.reload_history(cx);
|
|
cx.notify();
|
|
});
|
|
ProcessingInput {
|
|
entity,
|
|
_subscriptions: vec![changed],
|
|
}
|
|
}
|
|
|
|
/// Refresh the bounded history snapshot for the current search query.
|
|
fn reload_history(&mut self, cx: &App) {
|
|
let Some(history) = &self.history else {
|
|
self.history_entries.clear();
|
|
self.selected_history = None;
|
|
return;
|
|
};
|
|
let query = self.history_search.entity.read(cx).text().to_string();
|
|
self.history_entries = history.search(&query);
|
|
if self
|
|
.selected_history
|
|
.is_some_and(|id| !self.history_entries.iter().any(|entry| entry.id == id))
|
|
{
|
|
self.selected_history = None;
|
|
}
|
|
}
|
|
|
|
/// Refresh the visible history while the pane is open so entries recorded
|
|
/// by the recognition side appear without reopening the pane.
|
|
fn poll_history(&mut self, cx: &App) -> bool {
|
|
if self.preview || self.pane != Pane::History || self.history.is_none() {
|
|
return false;
|
|
}
|
|
let previous = std::mem::take(&mut self.history_entries);
|
|
self.reload_history(cx);
|
|
self.history_entries != previous
|
|
}
|
|
|
|
fn set_history_retention(&mut self, retention: HistoryRetention, cx: &mut Context<Self>) {
|
|
if self.settings.history_retention == retention {
|
|
return;
|
|
}
|
|
if !self.update_settings(cx, |settings| settings.history_retention = retention) {
|
|
return;
|
|
}
|
|
if let Some(history) = &self.history
|
|
&& let Err(error) = history.set_retention(retention)
|
|
{
|
|
self.history_error = Some(error.to_string());
|
|
}
|
|
self.reload_history(cx);
|
|
cx.notify();
|
|
}
|
|
|
|
fn copy_history_entry(&mut self, id: u64, cx: &mut Context<Self>) {
|
|
let Some(entry) = self.history_entries.iter().find(|entry| entry.id == id) else {
|
|
return;
|
|
};
|
|
match arboard::Clipboard::new()
|
|
.and_then(|mut clipboard| clipboard.set_text(entry.final_text.clone()))
|
|
{
|
|
Ok(()) => {
|
|
self.history_copied = Some(id);
|
|
self.history_error = None;
|
|
}
|
|
Err(error) => self.history_error = Some(error.to_string()),
|
|
}
|
|
cx.notify();
|
|
}
|
|
|
|
fn delete_history_entry(&mut self, id: u64, cx: &mut Context<Self>) {
|
|
if let Some(history) = &self.history {
|
|
if let Err(error) = history.delete(id) {
|
|
self.history_error = Some(error.to_string());
|
|
}
|
|
self.reload_history(cx);
|
|
}
|
|
cx.notify();
|
|
}
|
|
|
|
fn clear_history(&mut self, cx: &mut Context<Self>) {
|
|
if !self.history_clear_armed {
|
|
self.history_clear_armed = true;
|
|
cx.notify();
|
|
return;
|
|
}
|
|
self.history_clear_armed = false;
|
|
if let Some(history) = &self.history {
|
|
if let Err(error) = history.clear() {
|
|
self.history_error = Some(error.to_string());
|
|
}
|
|
self.reload_history(cx);
|
|
}
|
|
cx.notify();
|
|
}
|
|
|
|
fn render_history(&mut self, cx: &mut Context<Self>) -> AnyElement {
|
|
let retention = self.settings.history_retention;
|
|
let search = div()
|
|
.w(px(SEARCH_FIELD_WIDTH))
|
|
.child(self.history_search.entity.clone());
|
|
let retention_control = button(
|
|
ButtonKind::Secondary,
|
|
format!("Keep: {}", retention.label()),
|
|
)
|
|
.id("history-retention")
|
|
.child(icon(Icon::ChevronDown, TEXT_TERTIARY))
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.history_retention_open = true;
|
|
cx.notify();
|
|
}));
|
|
let retention_control = div().relative().child(retention_control).when(
|
|
self.history_retention_open,
|
|
|control| {
|
|
control.child(deferred(
|
|
dropdown_menu()
|
|
.id("history-retention-menu")
|
|
.right_0()
|
|
.w(px(MENU_WIDTH))
|
|
.on_mouse_down_out(cx.listener(|this, _, _, cx| {
|
|
this.history_retention_open = false;
|
|
cx.notify();
|
|
}))
|
|
.children(HistoryRetention::ALL.into_iter().enumerate().map(
|
|
|(index, choice)| {
|
|
menu_item(choice == retention)
|
|
.id(("history-retention-choice", index))
|
|
.child(choice.label())
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
cx.stop_propagation();
|
|
this.history_retention_open = false;
|
|
this.set_history_retention(choice, cx);
|
|
cx.notify();
|
|
}))
|
|
},
|
|
)),
|
|
))
|
|
},
|
|
);
|
|
let clear = if self.history_clear_armed {
|
|
button(ButtonKind::Danger, "Really clear all?")
|
|
} else {
|
|
button(ButtonKind::Secondary, "Clear all")
|
|
}
|
|
.id("history-clear")
|
|
.on_click(cx.listener(|this, _, _, cx| this.clear_history(cx)))
|
|
.into_any_element();
|
|
let header_action = div()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.child(search)
|
|
.child(retention_control)
|
|
.child(clear)
|
|
.into_any_element();
|
|
let rows: Vec<AnyElement> = self
|
|
.history_entries
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(index, entry)| {
|
|
let id = entry.id;
|
|
let selected = self.selected_history == Some(id);
|
|
let age = event_age(entry.timestamp_ms);
|
|
let preview = entry.final_text.replace('\n', " ");
|
|
let mut meta = entry.kind.label().to_string();
|
|
if let Some(application) = &entry.application {
|
|
meta.push_str(" · ");
|
|
meta.push_str(application);
|
|
}
|
|
timestamped_list_row(
|
|
("history-entry", index),
|
|
selected,
|
|
age,
|
|
div()
|
|
.flex_1()
|
|
.min_w(px(0.0))
|
|
.flex()
|
|
.flex_col()
|
|
.gap_0p5()
|
|
.child(list_row_title(preview, selected))
|
|
.child(list_row_meta(meta, selected)),
|
|
)
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
this.selected_history = Some(id);
|
|
this.history_clear_armed = false;
|
|
cx.notify();
|
|
}))
|
|
.into_any_element()
|
|
})
|
|
.collect();
|
|
let retention_off = retention.is_off();
|
|
div()
|
|
.size_full()
|
|
.flex()
|
|
.flex_col()
|
|
.child(pane_header_with_action("History", Some(header_action)))
|
|
.child(
|
|
pane_body().child(
|
|
pane_content()
|
|
.flex_row()
|
|
.gap_5()
|
|
.child(pane_list(
|
|
"history-list",
|
|
PANE_LIST_WIDTH,
|
|
if retention_off {
|
|
Some("History is off. New dictations are not retained.")
|
|
} else if self.history_entries.is_empty()
|
|
&& self.history_error.is_none()
|
|
{
|
|
Some("No dictations retained yet.")
|
|
} else {
|
|
None
|
|
},
|
|
"History could not be loaded.",
|
|
self.history_error.clone(),
|
|
rows,
|
|
))
|
|
.child(pane_detail(self.render_history_detail(cx))),
|
|
),
|
|
)
|
|
.into_any_element()
|
|
}
|
|
|
|
fn render_history_detail(&self, cx: &mut Context<Self>) -> AnyElement {
|
|
let Some(entry) = self
|
|
.selected_history
|
|
.and_then(|id| self.history_entries.iter().find(|entry| entry.id == id))
|
|
else {
|
|
return detail_placeholder("Select a history entry.");
|
|
};
|
|
let id = entry.id;
|
|
let copied = self.history_copied == Some(id);
|
|
let show_raw = entry.raw_text.trim() != entry.final_text.trim();
|
|
let action_button = |label: &'static str, id_suffix: &'static str| {
|
|
button(ButtonKind::Secondary, label)
|
|
.id(SharedString::from(format!("history-action-{id_suffix}")))
|
|
};
|
|
let mut latency = format!(
|
|
"{} ms audio · {} ms inference",
|
|
entry.audio_ms, entry.inference_ms
|
|
);
|
|
if entry.total_ms > 0 {
|
|
latency.push_str(&format!(" · {} ms total", entry.total_ms));
|
|
}
|
|
let section = |label: &'static str, first: bool| {
|
|
div()
|
|
.w_full()
|
|
.when(!first, |section| {
|
|
section.mt_5().pt_5().border_t_1().border_color(rgb(LINE))
|
|
})
|
|
.child(section_label(label))
|
|
};
|
|
div()
|
|
.flex_1()
|
|
.min_w(px(0.0))
|
|
.h_full()
|
|
.flex()
|
|
.flex_col()
|
|
.child(detail_header(
|
|
detail_title(entry.kind.label()),
|
|
vec![event_age(entry.timestamp_ms).into_any_element()],
|
|
vec![
|
|
action_button(if copied { "Copied" } else { "Copy" }, "copy")
|
|
.on_click(
|
|
cx.listener(move |this, _, _, cx| this.copy_history_entry(id, cx)),
|
|
)
|
|
.into_any_element(),
|
|
action_button("Delete", "delete")
|
|
.on_click(
|
|
cx.listener(move |this, _, _, cx| this.delete_history_entry(id, cx)),
|
|
)
|
|
.into_any_element(),
|
|
],
|
|
))
|
|
.child(
|
|
detail_body("history-detail")
|
|
.child(
|
|
section("Final text", true).child(
|
|
div()
|
|
.pt_2()
|
|
.text_body()
|
|
.text_color(rgb(TEXT_PRIMARY))
|
|
.child(entry.final_text.clone()),
|
|
),
|
|
)
|
|
.when(show_raw, |detail| {
|
|
detail.child(
|
|
section("Raw transcript", false).child(
|
|
div()
|
|
.pt_2()
|
|
.text_body()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child(entry.raw_text.clone()),
|
|
),
|
|
)
|
|
})
|
|
.child(
|
|
div()
|
|
.w_full()
|
|
.mt_5()
|
|
.flex()
|
|
.flex_col()
|
|
.border_t_1()
|
|
.border_color(rgb(LINE))
|
|
.when_some(entry.application.clone(), |rows, application| {
|
|
rows.child(detail_row("Application", application))
|
|
})
|
|
.when_some(entry.processing.clone(), |rows, processing| {
|
|
let mut summary = format!(
|
|
"{} · {} ms",
|
|
processing.profile, processing.latency_ms
|
|
);
|
|
if let Some(fallback) = &processing.fallback {
|
|
summary.push_str(&format!(" · fell back: {fallback}"));
|
|
}
|
|
rows.child(detail_row("Processing", summary))
|
|
})
|
|
.child(detail_row("Latency", latency)),
|
|
),
|
|
)
|
|
.into_any_element()
|
|
}
|
|
|
|
fn render_navigation(&mut self, cx: &mut Context<Self>) -> AnyElement {
|
|
let items = Pane::all(
|
|
crate::DEVELOPER_FEATURES_ENABLED,
|
|
self.settings.meetings.available(),
|
|
)
|
|
.into_iter()
|
|
.enumerate()
|
|
.map(|(index, pane)| {
|
|
let selected = self.pane == pane;
|
|
navigation_item(pane.icon(), selected)
|
|
.id(("app-nav", index))
|
|
.child(pane.label())
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
this.select_pane(pane, cx);
|
|
}))
|
|
});
|
|
|
|
sidebar_frame()
|
|
.child(div().flex().flex_col().gap_0p5().children(items))
|
|
.child(div().flex_1())
|
|
.child(
|
|
div()
|
|
.flex_none()
|
|
.flex()
|
|
.items_center()
|
|
.justify_between()
|
|
.gap_2()
|
|
.h(px(CONTROL_HEIGHT))
|
|
.mt_3()
|
|
.child(
|
|
div()
|
|
.flex_none()
|
|
.pl_3()
|
|
.text_caption()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child(format!("Version {}", env!("CARGO_PKG_VERSION"))),
|
|
)
|
|
.children(sidebar_update_button(self.update_status, self.preview)),
|
|
)
|
|
.into_any_element()
|
|
}
|
|
|
|
fn render_hotkey_control(
|
|
&mut self,
|
|
kind: HotkeyKind,
|
|
window: &mut Window,
|
|
cx: &mut Context<Self>,
|
|
) -> AnyElement {
|
|
let binding_keycaps = hotkey_binding(&self.settings, kind)
|
|
.map_or_else(|| vec!["Off".into()], HotkeyBinding::keycaps);
|
|
let idle_width = hotkey_idle_width(binding_keycaps.len());
|
|
if matches!(
|
|
self.hotkey_capture,
|
|
HotkeyCaptureState::Saved { saved_at, .. }
|
|
if saved_at.elapsed() >= Duration::from_millis(700)
|
|
) {
|
|
self.hotkey_capture = HotkeyCaptureState::Idle;
|
|
self.hotkey_capture_animation.set_enabled(false);
|
|
self.hotkey_width_spring.set_target(idle_width);
|
|
} else if matches!(self.hotkey_capture, HotkeyCaptureState::Idle) {
|
|
self.hotkey_width_spring.set_target(idle_width);
|
|
}
|
|
let intensity = self.hotkey_capture_animation.render_position(window);
|
|
let animated_control_width = self.hotkey_width_spring.render_position(window);
|
|
let this_capture = matches!(
|
|
self.hotkey_capture,
|
|
HotkeyCaptureState::Listening { kind: active, .. }
|
|
| HotkeyCaptureState::Saved { kind: active, .. }
|
|
if active == kind
|
|
);
|
|
let control_width = hotkey_control_width(this_capture, idle_width, animated_control_width);
|
|
let capture_active = !matches!(self.hotkey_capture, HotkeyCaptureState::Idle);
|
|
let control_intensity = hotkey_control_intensity(this_capture, intensity);
|
|
let capture_color = if matches!(
|
|
self.hotkey_capture,
|
|
HotkeyCaptureState::Saved { kind: active, .. } if active == kind
|
|
) {
|
|
rgb(SUCCESS_SURFACE)
|
|
} else {
|
|
rgb(DANGER_SURFACE)
|
|
};
|
|
let pulse = match &self.hotkey_capture {
|
|
HotkeyCaptureState::Listening {
|
|
kind: active,
|
|
started_at,
|
|
..
|
|
} if *active == kind => {
|
|
window.request_animation_frame();
|
|
(started_at.elapsed().as_secs_f32() * 4.5).sin() * 0.5 + 0.5
|
|
}
|
|
HotkeyCaptureState::Saved { kind: active, .. } if *active == kind => {
|
|
window.request_animation_frame();
|
|
1.0
|
|
}
|
|
HotkeyCaptureState::Idle
|
|
| HotkeyCaptureState::Listening { .. }
|
|
| HotkeyCaptureState::Saved { .. } => 0.0,
|
|
};
|
|
let content = match &self.hotkey_capture {
|
|
HotkeyCaptureState::Listening {
|
|
kind: active,
|
|
modifiers,
|
|
message,
|
|
..
|
|
} if *active == kind => {
|
|
let label = message.unwrap_or(if modifiers.is_empty() {
|
|
"Press shortcut"
|
|
} else {
|
|
"Release to save or add key"
|
|
});
|
|
div()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.child(
|
|
div()
|
|
.size(px(5.0 + pulse * 3.0))
|
|
.ml_2()
|
|
.rounded_full()
|
|
.bg(rgb(DANGER))
|
|
.opacity(0.6 + pulse * 0.4),
|
|
)
|
|
.when(!modifiers.is_empty() && message.is_none(), |content| {
|
|
content.child(hotkey_keycaps(
|
|
HotkeyBinding {
|
|
modifiers: *modifiers,
|
|
key: None,
|
|
}
|
|
.keycaps(),
|
|
0.85,
|
|
))
|
|
})
|
|
.child(
|
|
div()
|
|
.text_footnote()
|
|
.text_color(rgb(TEXT_SECONDARY))
|
|
.child(label),
|
|
)
|
|
.child(
|
|
small_button(ButtonKind::Secondary, "Cancel")
|
|
.id(match kind {
|
|
HotkeyKind::Dictation => "cancel-dictation-hotkey-capture",
|
|
HotkeyKind::Edit => "cancel-edit-hotkey-capture",
|
|
HotkeyKind::PasteLast => "cancel-paste-last-hotkey-capture",
|
|
})
|
|
.ml_1()
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
cx.stop_propagation();
|
|
this.cancel_hotkey_capture(cx);
|
|
})),
|
|
)
|
|
.into_any_element()
|
|
}
|
|
HotkeyCaptureState::Saved { kind: active, .. } if *active == kind => div()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.child(tag(Tone::Success, "Saved"))
|
|
.child(hotkey_keycaps(binding_keycaps.clone(), 1.0))
|
|
.into_any_element(),
|
|
HotkeyCaptureState::Idle
|
|
| HotkeyCaptureState::Listening { .. }
|
|
| HotkeyCaptureState::Saved { .. } => div()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.child(hotkey_keycaps(binding_keycaps, 1.0))
|
|
.child(
|
|
div()
|
|
.text_footnote()
|
|
.text_color(rgb(TEXT_SECONDARY))
|
|
.child("Change shortcut"),
|
|
)
|
|
.into_any_element(),
|
|
};
|
|
div()
|
|
.id(match kind {
|
|
HotkeyKind::Dictation => "dictation-hotkey-control",
|
|
HotkeyKind::Edit => "edit-hotkey-control",
|
|
HotkeyKind::PasteLast => "paste-last-hotkey-control",
|
|
})
|
|
.track_focus(&self.hotkey_focus)
|
|
.w(px(control_width))
|
|
.min_w(px(HOTKEY_MIN_WIDTH))
|
|
.h(px(CONTROL_HEIGHT))
|
|
.px(px(2.0))
|
|
.flex()
|
|
.items_center()
|
|
.overflow_hidden()
|
|
.rounded(RADIUS_CONTROL)
|
|
.border_1()
|
|
.border_color(mix_color(
|
|
rgb(LINE),
|
|
rgb(TEXT_SECONDARY),
|
|
control_intensity * 0.55,
|
|
))
|
|
.bg(mix_color(
|
|
rgb(CANVAS),
|
|
capture_color,
|
|
control_intensity * (0.55 + pulse * 0.15),
|
|
))
|
|
.when(!capture_active, |control| {
|
|
control.hover(|control| control.bg(rgb(SURFACE_HOVER)))
|
|
})
|
|
.child(content)
|
|
.on_click(cx.listener(move |this, _, window, cx| {
|
|
if this.hotkey_capture.is_listening() && this_capture {
|
|
this.cancel_hotkey_capture(cx);
|
|
} else {
|
|
this.begin_hotkey_capture(kind, window, cx);
|
|
}
|
|
}))
|
|
.on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| {
|
|
this.capture_hotkey_key(event, cx);
|
|
}))
|
|
.on_modifiers_changed(cx.listener(|this, event: &ModifiersChangedEvent, _, cx| {
|
|
this.capture_hotkey_modifiers(event, cx);
|
|
}))
|
|
.into_any_element()
|
|
}
|
|
|
|
fn render_hotkey_setting_control(
|
|
&mut self,
|
|
kind: HotkeyKind,
|
|
window: &mut Window,
|
|
cx: &mut Context<Self>,
|
|
) -> AnyElement {
|
|
let hotkey = self.render_hotkey_control(kind, window, cx);
|
|
let side = hotkey_binding(&self.settings, kind).and_then(standalone_modifier_side);
|
|
let side_animation = &mut self.hotkey_side_animations[hotkey_kind_index(kind)];
|
|
side_animation.set_enabled(side.is_some());
|
|
let side_position = side_animation.render_position(window).clamp(0.0, 1.0);
|
|
let selected = side.unwrap_or(ModifierSide::Either);
|
|
let side_widths = HOTKEY_SIDE_WIDTHS;
|
|
let side_selection_spring =
|
|
&mut self.hotkey_side_selection_springs[hotkey_kind_index(kind)];
|
|
side_selection_spring.set_target(hotkey_side_index(selected) as f32);
|
|
let selection_position = side_selection_spring.render_position(window);
|
|
let side_selector = div()
|
|
.w(px(HOTKEY_SIDE_SELECTOR_WIDTH * side_position))
|
|
.mr(px(8.0 * side_position))
|
|
.flex_none()
|
|
.overflow_hidden()
|
|
.opacity(side_position)
|
|
.child(
|
|
sliding_segmented_control(selection_position, &side_widths)
|
|
.w(px(HOTKEY_SIDE_SELECTOR_WIDTH))
|
|
.children(
|
|
[
|
|
("Left", ModifierSide::Left),
|
|
("Either", ModifierSide::Either),
|
|
("Right", ModifierSide::Right),
|
|
]
|
|
.into_iter()
|
|
.enumerate()
|
|
.map(|(index, (label, side))| {
|
|
let candidate = hotkey_side_binding(&self.settings, kind, side);
|
|
sliding_segmented_item(side_widths[index], selected == side)
|
|
.id(("hotkey-side", hotkey_kind_index(kind) * 3 + index))
|
|
.when(candidate.is_none(), |item| item.opacity(DISABLED_OPACITY))
|
|
.child(label)
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
let Some(candidate) =
|
|
hotkey_side_binding(&this.settings, kind, side)
|
|
else {
|
|
return;
|
|
};
|
|
if !this.update_settings(cx, |settings| {
|
|
set_hotkey_binding(settings, kind, candidate);
|
|
}) {
|
|
return;
|
|
}
|
|
if kind == HotkeyKind::Edit {
|
|
this.voice_action_inputs.error = None;
|
|
}
|
|
this.hotkey_side_selection_springs[hotkey_kind_index(kind)]
|
|
.set_target(index as f32);
|
|
}))
|
|
}),
|
|
),
|
|
);
|
|
div()
|
|
.flex()
|
|
.items_center()
|
|
.child(side_selector)
|
|
.child(hotkey)
|
|
.into_any_element()
|
|
}
|
|
|
|
fn begin_hotkey_capture(
|
|
&mut self,
|
|
kind: HotkeyKind,
|
|
window: &mut Window,
|
|
cx: &mut Context<Self>,
|
|
) {
|
|
if !self.preview {
|
|
crate::app_settings::set_hotkey_capture_active(true);
|
|
}
|
|
self.hotkey_width_spring.set_target(hotkey_capture_width(0));
|
|
self.hotkey_capture = HotkeyCaptureState::Listening {
|
|
kind,
|
|
modifiers: HotkeyModifiers::default(),
|
|
message: None,
|
|
started_at: Instant::now(),
|
|
};
|
|
self.hotkey_capture_animation.set_enabled(true);
|
|
self.hotkey_focus.focus(window);
|
|
cx.notify();
|
|
}
|
|
|
|
fn cancel_hotkey_capture(&mut self, cx: &mut Context<Self>) {
|
|
if !matches!(self.hotkey_capture, HotkeyCaptureState::Idle) {
|
|
if !self.preview {
|
|
crate::app_settings::set_hotkey_capture_active(false);
|
|
}
|
|
self.hotkey_capture = HotkeyCaptureState::Idle;
|
|
self.hotkey_capture_animation.set_enabled(false);
|
|
self.hotkey_width_spring.set_target(HOTKEY_MIN_WIDTH);
|
|
cx.notify();
|
|
}
|
|
}
|
|
|
|
fn capture_hotkey_key(&mut self, event: &KeyDownEvent, cx: &mut Context<Self>) {
|
|
if !self.hotkey_capture.is_listening() {
|
|
return;
|
|
}
|
|
cx.stop_propagation();
|
|
if event.is_held {
|
|
return;
|
|
}
|
|
if event.keystroke.key == "escape" {
|
|
self.cancel_hotkey_capture(cx);
|
|
return;
|
|
}
|
|
let modifiers = hotkey_modifiers(event.keystroke.modifiers).without_side_constraints();
|
|
let key = match hotkey_key(&event.keystroke.key) {
|
|
Ok(key) => key,
|
|
Err(message) => {
|
|
self.set_hotkey_capture_message(message, cx);
|
|
return;
|
|
}
|
|
};
|
|
if modifiers.is_empty() && !is_function_key(&key.label) {
|
|
self.set_hotkey_capture_message("Add a modifier", cx);
|
|
return;
|
|
}
|
|
let binding = HotkeyBinding {
|
|
modifiers,
|
|
key: Some(key),
|
|
};
|
|
self.hotkey_width_spring
|
|
.set_target(hotkey_capture_width(binding.keycaps().len()));
|
|
self.save_hotkey_binding(binding, cx);
|
|
}
|
|
|
|
fn capture_hotkey_modifiers(&mut self, event: &ModifiersChangedEvent, cx: &mut Context<Self>) {
|
|
let current = normalize_captured_modifiers(hotkey_modifiers(event.modifiers));
|
|
let released = {
|
|
let HotkeyCaptureState::Listening {
|
|
modifiers, message, ..
|
|
} = &mut self.hotkey_capture
|
|
else {
|
|
return;
|
|
};
|
|
if !current.is_empty() {
|
|
if current.count() >= modifiers.count() {
|
|
*modifiers = current;
|
|
*message = None;
|
|
}
|
|
let active_modifiers = *modifiers;
|
|
self.hotkey_width_spring.set_target(hotkey_capture_width(
|
|
HotkeyBinding {
|
|
modifiers: active_modifiers,
|
|
key: None,
|
|
}
|
|
.keycaps()
|
|
.len(),
|
|
));
|
|
cx.notify();
|
|
None
|
|
} else if message.is_some() {
|
|
*modifiers = HotkeyModifiers::default();
|
|
*message = None;
|
|
cx.notify();
|
|
None
|
|
} else {
|
|
(!modifiers.is_empty()).then_some(*modifiers)
|
|
}
|
|
};
|
|
if let Some(modifiers) = released {
|
|
self.save_hotkey_binding(
|
|
HotkeyBinding {
|
|
modifiers,
|
|
key: None,
|
|
},
|
|
cx,
|
|
);
|
|
}
|
|
}
|
|
|
|
fn set_hotkey_capture_message(&mut self, next_message: &'static str, cx: &mut Context<Self>) {
|
|
if let HotkeyCaptureState::Listening { message, .. } = &mut self.hotkey_capture {
|
|
*message = Some(next_message);
|
|
cx.notify();
|
|
}
|
|
}
|
|
|
|
fn save_hotkey_binding(&mut self, binding: HotkeyBinding, cx: &mut Context<Self>) {
|
|
if binding.is_empty() {
|
|
self.set_hotkey_capture_message("Press a shortcut", cx);
|
|
return;
|
|
}
|
|
let kind = match self.hotkey_capture {
|
|
HotkeyCaptureState::Listening { kind, .. } => kind,
|
|
HotkeyCaptureState::Idle | HotkeyCaptureState::Saved { .. } => return,
|
|
};
|
|
if hotkey_binding_conflicts(&self.settings, kind, &binding) {
|
|
self.set_hotkey_capture_message("Already in use", cx);
|
|
return;
|
|
}
|
|
let keycap_count = binding.keycaps().len();
|
|
if !self.update_settings(cx, |settings| set_hotkey_binding(settings, kind, binding)) {
|
|
self.set_hotkey_capture_message("Could not save shortcut. Try again.", cx);
|
|
return;
|
|
}
|
|
self.hotkey_width_spring
|
|
.set_target(hotkey_saved_width(keycap_count));
|
|
if kind == HotkeyKind::Edit {
|
|
self.voice_action_inputs.error = None;
|
|
}
|
|
if !self.preview {
|
|
crate::app_settings::set_hotkey_capture_active(false);
|
|
}
|
|
self.hotkey_capture = HotkeyCaptureState::Saved {
|
|
kind,
|
|
saved_at: Instant::now(),
|
|
};
|
|
cx.notify();
|
|
}
|
|
|
|
fn render_mode_replacements(
|
|
&mut self,
|
|
selection: ModeSelection,
|
|
cx: &mut Context<Self>,
|
|
) -> AnyElement {
|
|
let replacement_count = self.mode_inputs_for(selection).replacements.len();
|
|
let replacement_rows = self
|
|
.mode_inputs_for(selection)
|
|
.replacements
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(index, inputs)| {
|
|
div()
|
|
.id(("text-replacement", index))
|
|
.w_full()
|
|
.px_4()
|
|
.py_2()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.when(index + 1 < replacement_count, |row| {
|
|
row.border_b_1().border_color(rgb(LINE))
|
|
})
|
|
.child(
|
|
div()
|
|
.flex_1()
|
|
.min_w(px(0.0))
|
|
.child(inputs.matched_phrase.entity.clone()),
|
|
)
|
|
.child(icon(Icon::ArrowRight, TEXT_TERTIARY))
|
|
.child(
|
|
div()
|
|
.flex_1()
|
|
.min_w(px(0.0))
|
|
.child(inputs.output.entity.clone()),
|
|
)
|
|
.child(
|
|
icon_button(ButtonKind::Ghost, Icon::Close)
|
|
.id(("remove-text-replacement", index))
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
if this.update_mode_settings(selection, cx, |mode| {
|
|
mode.replacements.remove(index);
|
|
}) {
|
|
this.mode_inputs_mut(selection).replacements.remove(index);
|
|
}
|
|
})),
|
|
)
|
|
.into_any_element()
|
|
})
|
|
.collect::<Vec<_>>();
|
|
|
|
let add = icon_button(ButtonKind::Ghost, Icon::Plus)
|
|
.mr(px(-SPACE_2))
|
|
.id("add-mode-replacement")
|
|
.on_click(cx.listener(move |this, _, window, cx| {
|
|
let replacement = TextReplacement::default();
|
|
if this.update_mode_settings(selection, cx, |mode| {
|
|
mode.replacements.push(replacement.clone());
|
|
}) {
|
|
let inputs = Self::replacement_inputs(&replacement, cx);
|
|
let focus = inputs.matched_phrase.entity.focus_handle(cx);
|
|
this.mode_inputs_mut(selection).replacements.push(inputs);
|
|
focus.focus(window);
|
|
}
|
|
}))
|
|
.into_any_element();
|
|
|
|
panel()
|
|
.child(panel_header("Corrections", Some(add)))
|
|
.when(replacement_count == 0, |panel| {
|
|
panel.child(
|
|
div()
|
|
.px_3()
|
|
.py_3()
|
|
.text_footnote()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child("No corrections in this mode."),
|
|
)
|
|
})
|
|
.children(replacement_rows)
|
|
.into_any_element()
|
|
}
|
|
|
|
fn transcription_picker_view(&mut self, selected_language: &str) -> TranscriptionPickerView {
|
|
let models = crate::transcription_models::choices_for_runtime(selected_language)
|
|
.into_iter()
|
|
.map(|choice| {
|
|
let model = choice.model;
|
|
let installed = self.transcription_model_installed(model, selected_language);
|
|
let downloading = self.transcription_status.model == Some(model.id);
|
|
let active = transcription_selection_is_active(
|
|
&self.settings.transcription,
|
|
model,
|
|
selected_language,
|
|
installed,
|
|
);
|
|
let progress = if downloading {
|
|
model.download_bytes().map_or(0.0, |bytes| {
|
|
(self.transcription_status.downloaded_bytes as f32 / bytes as f32)
|
|
.clamp(0.0, 1.0)
|
|
})
|
|
} else {
|
|
0.0
|
|
};
|
|
let status = if downloading {
|
|
if installed {
|
|
let elapsed = self
|
|
.transcription_status
|
|
.started
|
|
.map_or(0, |started| started.elapsed().as_secs());
|
|
let progress = self
|
|
.transcription_status
|
|
.started
|
|
.map_or(0.0, |started| (started.elapsed().as_secs_f32() % 1.6) / 1.6);
|
|
TranscriptionPickerStatus::Preparing {
|
|
label: format!("Loading model · {elapsed}s"),
|
|
progress: Some(TranscriptionPickerProgress::Loading(progress)),
|
|
}
|
|
} else {
|
|
TranscriptionPickerStatus::Preparing {
|
|
label: format!("Downloading {:.0}%", progress * 100.0),
|
|
progress: matches!(model.runtime, ModelRuntime::Gguf(_))
|
|
.then_some(TranscriptionPickerProgress::Downloading(progress)),
|
|
}
|
|
}
|
|
} else if active {
|
|
TranscriptionPickerStatus::Active
|
|
} else {
|
|
TranscriptionPickerStatus::Available {
|
|
installed,
|
|
deletion: self.transcription_model_deletion(model, installed),
|
|
}
|
|
};
|
|
TranscriptionPickerModel { choice, status }
|
|
})
|
|
.collect();
|
|
TranscriptionPickerView {
|
|
error: self.transcription_status.error.clone(),
|
|
deletion_error: self.transcription_deletion_error.clone(),
|
|
language: selected_language.to_string(),
|
|
models,
|
|
}
|
|
}
|
|
|
|
fn render_transcription_picker(
|
|
&mut self,
|
|
selected_language: &str,
|
|
cx: &mut Context<Self>,
|
|
) -> AnyElement {
|
|
render_shared_transcription_picker(self.transcription_picker_view(selected_language), cx)
|
|
}
|
|
|
|
fn dismiss_transcription_picker(&mut self, cx: &mut Context<Self>) {
|
|
self.transcription_picker_language = None;
|
|
self.clear_transcription_error();
|
|
cx.notify();
|
|
}
|
|
|
|
fn render_microphone_picker(&self, cx: &mut Context<Self>) -> AnyElement {
|
|
let choices = std::iter::once(None)
|
|
.chain(self.microphone_devices.iter().cloned().map(Some))
|
|
.collect::<Vec<_>>();
|
|
microphone_picker_menu(
|
|
choices,
|
|
self.settings.microphone.clone(),
|
|
self.microphone_picker_error.clone(),
|
|
cx.listener(|this, device: &Option<String>, _, cx| {
|
|
if this.update_settings(cx, |settings| settings.microphone = device.clone()) {
|
|
this.microphone_picker_open = false;
|
|
this.microphone_picker_error = None;
|
|
}
|
|
}),
|
|
cx.listener(|this, _, _, cx| {
|
|
this.microphone_picker_open = false;
|
|
this.microphone_picker_error = None;
|
|
cx.notify();
|
|
}),
|
|
)
|
|
.into_any_element()
|
|
}
|
|
|
|
fn set_launch_at_login(&mut self, enabled: bool, cx: &mut Context<Self>) {
|
|
if self.preview {
|
|
self.launch_at_login_status = Some(if enabled {
|
|
LoginItemStatus::Enabled
|
|
} else {
|
|
LoginItemStatus::Disabled
|
|
});
|
|
} else if self.launch_at_login_status.is_none() || self.login_item_worker.is_none() {
|
|
return;
|
|
}
|
|
self.launch_at_login_toggle.set_enabled(enabled);
|
|
self.request_login_item(LoginItemRequest::SetEnabled(enabled));
|
|
cx.notify();
|
|
}
|
|
|
|
fn render_permission_warnings(&mut self, cx: &mut Context<Self>) -> Option<AnyElement> {
|
|
let warnings = crate::onboarding::permission_warnings(self.setup_status);
|
|
if self.setup_visible || warnings.is_empty() {
|
|
return None;
|
|
}
|
|
let warning_count = warnings.len();
|
|
Some(
|
|
div()
|
|
.child(settings_section_label("Permissions needed"))
|
|
.child(panel().children(warnings.into_iter().enumerate().map(
|
|
|(index, warning)| {
|
|
let (name, description) = permission_warning_copy(warning.kind);
|
|
let action = button(
|
|
ButtonKind::Secondary,
|
|
permission_action_label(warning.action),
|
|
)
|
|
.id(permission_warning_id(warning.kind))
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
this.perform_permission_action(warning);
|
|
cx.notify();
|
|
}));
|
|
settings_row(name, description, action)
|
|
.when(index + 1 == warning_count, |row| row.border_b_0())
|
|
},
|
|
)))
|
|
.into_any_element(),
|
|
)
|
|
}
|
|
|
|
fn render_model_notice(&mut self, cx: &mut Context<Self>) -> Option<AnyElement> {
|
|
if self.setup_visible {
|
|
return None;
|
|
}
|
|
let dictation_notice =
|
|
dictation_model_notice(self.setup_status, self.transcription_status.model.is_some());
|
|
let (title, description) = dictation_notice.or_else(|| {
|
|
self.settings
|
|
.commands_enabled
|
|
.then(|| command_model_notice(&self.command_model_status))
|
|
.flatten()
|
|
})?;
|
|
let action = if dictation_notice.is_some() {
|
|
button(ButtonKind::Primary, "Choose model")
|
|
.id("choose-required-model")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.transcription_picker_language =
|
|
Some(this.settings.transcription.language.clone());
|
|
cx.notify();
|
|
}))
|
|
.into_any_element()
|
|
} else {
|
|
div()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.when(
|
|
matches!(self.command_model_status, CommandModelStatus::Failed),
|
|
|controls| {
|
|
controls.child(
|
|
button(ButtonKind::Secondary, "Retry")
|
|
.id("retry-command-model")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
if !this.preview {
|
|
cx.dispatch_action(&RetryCommands);
|
|
}
|
|
})),
|
|
)
|
|
},
|
|
)
|
|
.child(
|
|
button(ButtonKind::Secondary, "Turn off commands")
|
|
.id("disable-unavailable-commands")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
if let Err(error) = this.developer_set_commands_enabled(false, cx) {
|
|
tracing::warn!(%error, "could not disable voice commands");
|
|
}
|
|
})),
|
|
)
|
|
.into_any_element()
|
|
};
|
|
Some(
|
|
div()
|
|
.id("dictation-model-notice")
|
|
.w_full()
|
|
.flex()
|
|
.justify_center()
|
|
.flex_shrink_0()
|
|
.px(px(PANE_GUTTER))
|
|
.pt_6()
|
|
.child(
|
|
panel()
|
|
.max_w(px(PANE_CONTENT_WIDTH))
|
|
.px_4()
|
|
.py_3()
|
|
.flex()
|
|
.items_center()
|
|
.gap_4()
|
|
.child(
|
|
div()
|
|
.flex_1()
|
|
.min_w_0()
|
|
.border_l_2()
|
|
.border_color(rgb(ACCENT))
|
|
.pl_3()
|
|
.child(settings_copy(title, description)),
|
|
)
|
|
.child(div().flex_shrink_0().child(action)),
|
|
)
|
|
.into_any_element(),
|
|
)
|
|
}
|
|
|
|
fn perform_permission_action(&mut self, warning: PermissionWarning) {
|
|
match warning.action {
|
|
PermissionAction::RequestMicrophone => crate::onboarding::request_microphone(),
|
|
PermissionAction::OpenMicrophoneSettings => {
|
|
crate::onboarding::open_permission_settings("microphone");
|
|
}
|
|
PermissionAction::OpenInputMonitoringSettings => {
|
|
crate::permission_guide::show_input_monitoring();
|
|
}
|
|
PermissionAction::OpenAccessibilitySettings => {
|
|
crate::permission_guide::show_accessibility();
|
|
}
|
|
}
|
|
self.permission_refresh_at = Instant::now() + PERMISSION_REFRESH_INTERVAL;
|
|
}
|
|
|
|
fn render_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
|
|
let permission_warnings = self.render_permission_warnings(cx);
|
|
let hotkey_control = self.render_hotkey_setting_control(HotkeyKind::Dictation, window, cx);
|
|
let paste_last_control = self.render_hotkey_control(HotkeyKind::PasteLast, window, cx);
|
|
let transcription_model = definition(self.settings.transcription.model);
|
|
let transcription_label = format!(
|
|
"{} · {}",
|
|
language_name(&self.settings.transcription.language),
|
|
transcription_model.name
|
|
);
|
|
let transcription_control = disclosure_button(transcription_label)
|
|
.id("transcription-model-setting")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.transcription_picker_language =
|
|
Some(this.settings.transcription.language.clone());
|
|
this.clear_transcription_error();
|
|
cx.notify();
|
|
}));
|
|
let double_tap_position = self.double_tap_toggle.render_position(window);
|
|
let release_microphone_position = self.release_microphone_toggle.render_position(window);
|
|
self.double_tap_only_visibility.set_enabled(
|
|
self.settings.double_tap_lock && self.settings.dictation_hotkey.key.is_some(),
|
|
);
|
|
let double_tap_only_visibility = self
|
|
.double_tap_only_visibility
|
|
.render_position(window)
|
|
.clamp(0.0, 1.0);
|
|
let dock_icon_position = self.dock_icon_toggle.render_position(window);
|
|
let incremental_position = self.incremental_toggle.render_position(window);
|
|
let meetings_section = self.render_meeting_settings(window, cx);
|
|
let launch_at_login_position = self.launch_at_login_toggle.render_position(window);
|
|
let microphone_label = self
|
|
.settings
|
|
.microphone
|
|
.clone()
|
|
.unwrap_or_else(|| "Automatic".into());
|
|
let microphone_picker = self
|
|
.microphone_picker_open
|
|
.then(|| self.render_microphone_picker(cx));
|
|
let sound_volume_position = self.sound_volume_spring.render_position(window);
|
|
let selected_volume = sound_volume_index(&self.settings);
|
|
let sound_volume = sliding_segmented_control(sound_volume_position, &[34.0; 5]).children(
|
|
crate::desktop_ui::SOUND_VOLUME_STEPS
|
|
.into_iter()
|
|
.enumerate()
|
|
.map(|(index, (label, volume))| {
|
|
sliding_segmented_item(34.0, selected_volume == index)
|
|
.id(("sound-volume", index))
|
|
.child(label)
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
if !this.update_settings(cx, |settings| {
|
|
settings.sound_effects = volume > 0.0;
|
|
if volume > 0.0 {
|
|
settings.sound_effect_volume = volume;
|
|
}
|
|
}) {
|
|
return;
|
|
}
|
|
this.sound_volume_spring.set_target(index as f32);
|
|
if volume > 0.0 && !this.preview {
|
|
crate::feedback::play(crate::feedback::Tone::DictationStart);
|
|
}
|
|
}))
|
|
}),
|
|
);
|
|
let launch_at_login_control = if self.launch_at_login_status.is_none() {
|
|
div()
|
|
.text_footnote()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child(if self.login_item_worker.is_some() {
|
|
"Checking…"
|
|
} else {
|
|
"Unavailable"
|
|
})
|
|
.into_any_element()
|
|
} else if self.launch_at_login_status == Some(LoginItemStatus::RequiresApproval) {
|
|
button(ButtonKind::Secondary, "Open settings")
|
|
.id("launch-at-login-approval")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.request_login_item(LoginItemRequest::OpenSettings);
|
|
cx.notify();
|
|
}))
|
|
.into_any_element()
|
|
} else {
|
|
toggle(launch_at_login_position)
|
|
};
|
|
let recording_audio_position = self.recording_audio_spring.render_position(window);
|
|
let audio_widths = [50.0, 90.0, 80.0];
|
|
let audio_behavior = sliding_segmented_control(recording_audio_position, &audio_widths)
|
|
.children(RecordingAudioBehavior::ALL.into_iter().enumerate().map(
|
|
|(index, behavior)| {
|
|
let selected = self.settings.recording_audio_behavior == behavior;
|
|
sliding_segmented_item(audio_widths[index], selected)
|
|
.id(("recording-audio-behavior", index))
|
|
.child(behavior.label())
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
if this.settings.recording_audio_behavior == behavior {
|
|
return;
|
|
}
|
|
if this.update_settings(cx, |settings| {
|
|
settings.recording_audio_behavior = behavior
|
|
}) {
|
|
this.recording_audio_spring.set_target(index as f32);
|
|
}
|
|
}))
|
|
},
|
|
));
|
|
let microphone_mode = sliding_segmented_control(release_microphone_position, &[114.0; 2])
|
|
.id("microphone-mode")
|
|
.children(
|
|
[("Keep ready (fast)", false), ("Release when idle", true)]
|
|
.into_iter()
|
|
.enumerate()
|
|
.map(|(index, (label, release))| {
|
|
sliding_segmented_item(
|
|
114.0,
|
|
self.settings.release_microphone_while_idle == release,
|
|
)
|
|
.id(("microphone-mode", index))
|
|
.child(label)
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
if release && !this.settings.release_microphone_while_idle {
|
|
this.pending_microphone_policy =
|
|
Some(MicrophonePolicyChange::DisableCommandsAndRelease);
|
|
cx.notify();
|
|
return;
|
|
}
|
|
this.pending_microphone_policy = None;
|
|
if this.settings.release_microphone_while_idle != release
|
|
&& let Err(error) = this.update_microphone_policy(
|
|
MicrophonePolicyChange::SetReleaseWhileIdle(release),
|
|
cx,
|
|
)
|
|
{
|
|
tracing::error!(%error, "could not update microphone policy");
|
|
}
|
|
cx.notify();
|
|
}))
|
|
}),
|
|
);
|
|
let microphone_confirmation = (self.pending_microphone_policy
|
|
== Some(MicrophonePolicyChange::DisableCommandsAndRelease))
|
|
.then(|| {
|
|
div()
|
|
.px_4()
|
|
.py_3()
|
|
.flex()
|
|
.items_center()
|
|
.justify_between()
|
|
.gap_4()
|
|
.border_b_1()
|
|
.border_color(rgb(LINE))
|
|
.bg(rgb(CANVAS))
|
|
.child(
|
|
div().flex_1().min_w_0().child(settings_copy(
|
|
"Release the microphone when idle?",
|
|
if self.settings.commands_enabled {
|
|
"Opens the microphone on shortcut press without pre-roll and turns Commands off."
|
|
} else {
|
|
"Opens the microphone on shortcut press without pre-roll. Commands remain off."
|
|
},
|
|
)),
|
|
)
|
|
.child(
|
|
div()
|
|
.flex_none()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.child(
|
|
button(ButtonKind::Secondary, "Cancel")
|
|
.id("cancel-release-microphone")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.pending_microphone_policy = None;
|
|
cx.notify();
|
|
})),
|
|
)
|
|
.child(
|
|
button(ButtonKind::Primary, "Release microphone")
|
|
.id("confirm-release-microphone")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
if let Err(error) = this.update_microphone_policy(
|
|
MicrophonePolicyChange::DisableCommandsAndRelease,
|
|
cx,
|
|
) {
|
|
tracing::error!(%error, "could not update microphone policy");
|
|
}
|
|
})),
|
|
),
|
|
)
|
|
});
|
|
settings_pane(
|
|
"Settings",
|
|
"settings-scroll",
|
|
div()
|
|
.children(permission_warnings)
|
|
.child(settings_section_label("Dictation"))
|
|
.child(
|
|
panel()
|
|
.child(settings_row(
|
|
"Local transcription",
|
|
"Language and on-device speech model",
|
|
transcription_control,
|
|
))
|
|
.child(settings_row(
|
|
"Microphone",
|
|
"Input device for dictation and commands",
|
|
div()
|
|
.relative()
|
|
.flex_none()
|
|
.child(
|
|
disclosure_button(microphone_label)
|
|
.id("microphone-setting")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.toggle_microphone_picker(cx)
|
|
})),
|
|
)
|
|
.children(microphone_picker.map(deferred)),
|
|
))
|
|
.when(
|
|
transcription_model.supports_recognition_hints,
|
|
|settings| {
|
|
settings.child(settings_row(
|
|
"Recognition hints",
|
|
"Names and terms to prime the speech model",
|
|
div()
|
|
.w(px(320.0))
|
|
.flex_none()
|
|
.child(
|
|
self.transcription_hints.entity.clone(),
|
|
),
|
|
))
|
|
},
|
|
)
|
|
.child(
|
|
settings_row(
|
|
"Dictation shortcut",
|
|
"Hold to dictate, release to transcribe",
|
|
hotkey_control,
|
|
)
|
|
.border_b_0()
|
|
.id("dictation-hotkey-setting"),
|
|
),
|
|
)
|
|
.child(settings_section_label("Behavior"))
|
|
.child(
|
|
panel()
|
|
.child(
|
|
settings_row(
|
|
"While dictating",
|
|
"Mute or pause other audio during dictation",
|
|
audio_behavior,
|
|
)
|
|
.id("recording-audio-setting"),
|
|
)
|
|
.child(settings_row(
|
|
"Microphone mode",
|
|
if self.settings.release_microphone_while_idle {
|
|
"Opens only while holding the shortcut. Disables pre-roll and commands."
|
|
} else {
|
|
"Keeps the microphone open for instant start and pre-roll"
|
|
},
|
|
microphone_mode,
|
|
))
|
|
.children(microphone_confirmation)
|
|
.child(
|
|
settings_row(
|
|
"Double-tap to lock",
|
|
"Double-tap the shortcut for hands-free dictation",
|
|
toggle(double_tap_position),
|
|
)
|
|
.id("double-tap-setting")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
let enabled = !this.settings.double_tap_lock;
|
|
this.set_double_tap_lock(enabled, cx);
|
|
})),
|
|
)
|
|
.child(
|
|
div()
|
|
.h(px(SETTINGS_ROW_MIN_HEIGHT * double_tap_only_visibility))
|
|
.overflow_hidden()
|
|
.opacity(double_tap_only_visibility)
|
|
.child(
|
|
settings_row(
|
|
"Double-tap only",
|
|
"Wait for two complete shortcut taps before recording",
|
|
toggle(if self.settings.double_tap_only { 1.0 } else { 0.0 }),
|
|
)
|
|
.id("double-tap-only-setting")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
let enabled = !this.settings.double_tap_only;
|
|
this.set_double_tap_only(enabled, cx);
|
|
})),
|
|
),
|
|
)
|
|
.child(
|
|
settings_row(
|
|
"Transcribe during pauses",
|
|
"Finish long dictations sooner by transcribing at each pause",
|
|
toggle(incremental_position),
|
|
)
|
|
.id("incremental-transcription-setting")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
let enabled = !this.settings.incremental_transcription;
|
|
if this.update_settings(cx, |settings| {
|
|
settings.incremental_transcription = enabled
|
|
}) {
|
|
this.incremental_toggle.set_enabled(enabled);
|
|
}
|
|
})),
|
|
)
|
|
.child(
|
|
settings_row(
|
|
"Paste last dictation",
|
|
"Re-paste the most recent dictation",
|
|
div()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.child(paste_last_control)
|
|
.when(self.settings.paste_last_hotkey.is_some(), |row| {
|
|
row.child(
|
|
button(ButtonKind::Secondary, "Clear")
|
|
.id("disable-paste-last-hotkey")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.update_settings(cx, |settings| settings.paste_last_hotkey = None);
|
|
})),
|
|
)
|
|
}),
|
|
)
|
|
.border_b_0()
|
|
.id("paste-last-hotkey-setting"),
|
|
)
|
|
)
|
|
.child(settings_section_label("Meetings"))
|
|
.child(meetings_section)
|
|
.child(settings_section_label("Application"))
|
|
.child(
|
|
panel()
|
|
.child(
|
|
settings_row(
|
|
"Launch at login",
|
|
"Start Hex when you log in",
|
|
launch_at_login_control,
|
|
)
|
|
.id("launch-at-login-setting")
|
|
.when(
|
|
matches!(self.launch_at_login_status, Some(LoginItemStatus::Enabled | LoginItemStatus::Disabled))
|
|
&& (self.preview || self.login_item_worker.is_some()),
|
|
|row| {
|
|
row.on_click(cx.listener(
|
|
|this, _, _, cx| {
|
|
let enabled = !this.launch_at_login_toggle.enabled();
|
|
this.set_launch_at_login(enabled, cx);
|
|
},
|
|
))
|
|
},
|
|
),
|
|
)
|
|
.when_some(
|
|
self.launch_at_login_error.clone(),
|
|
|settings, error| {
|
|
settings.child(inline_error(error))
|
|
},
|
|
)
|
|
.child(
|
|
settings_row(
|
|
"Show Dock icon",
|
|
"Keep Hex in the menu bar when Settings is closed",
|
|
toggle(dock_icon_position),
|
|
)
|
|
.id("dock-icon-setting")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
if !this.update_settings(cx, |settings| settings.show_dock_icon = !settings.show_dock_icon) {
|
|
return;
|
|
}
|
|
this.dock_icon_toggle
|
|
.set_enabled(this.settings.show_dock_icon);
|
|
})),
|
|
)
|
|
.child(
|
|
settings_row(
|
|
"Sound volume",
|
|
"Recording, cancellation, and error tones",
|
|
sound_volume,
|
|
)
|
|
.border_b_0()
|
|
.id("sound-effects-setting"),
|
|
),
|
|
),
|
|
)
|
|
}
|
|
|
|
fn render_meeting_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Div {
|
|
let enabled = self.settings.meetings.enabled;
|
|
let position = self.meetings_toggle.render_position(window);
|
|
let notes_position = self.meeting_notes_toggle.render_position(window);
|
|
let folder = self.settings.meetings.resolved_output_folder();
|
|
let folder_label = folder
|
|
.strip_prefix(dirs::home_dir().unwrap_or_default())
|
|
.map(|relative| format!("~/{}", relative.display()))
|
|
.unwrap_or_else(|_| folder.display().to_string());
|
|
let permission_control = if self.screen_recording_permitted {
|
|
tag(Tone::Success, "Ready").into_any_element()
|
|
} else {
|
|
button(ButtonKind::Secondary, "Open settings")
|
|
.id("meeting-screen-recording")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
if !crate::meeting::request_screen_recording() {
|
|
crate::meeting::open_screen_recording_settings();
|
|
}
|
|
this.permission_refresh_at = Instant::now();
|
|
cx.notify();
|
|
}))
|
|
.into_any_element()
|
|
};
|
|
panel()
|
|
.child(
|
|
settings_row(
|
|
"Meetings (beta)",
|
|
"Offer to record calls and save local transcripts",
|
|
toggle(position),
|
|
)
|
|
.when(!enabled, |row| row.border_b_0())
|
|
.id("meetings-setting")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
let enabled = !this.settings.meetings.enabled;
|
|
if this.update_settings(cx, |settings| settings.meetings.enabled = enabled) {
|
|
this.meetings_toggle.set_enabled(enabled);
|
|
if enabled {
|
|
this.screen_recording_permitted =
|
|
this.preview || crate::meeting::screen_recording_permitted();
|
|
if !this.preview {
|
|
this.reload_meetings();
|
|
}
|
|
} else if this.pane == Pane::Meetings {
|
|
this.pane = Pane::Settings;
|
|
}
|
|
}
|
|
})),
|
|
)
|
|
.when(enabled, |panel| {
|
|
panel
|
|
.child(settings_row(
|
|
"Screen & System Audio Recording",
|
|
if self.screen_recording_permitted {
|
|
"Captures the other participants' audio"
|
|
} else {
|
|
"Required to hear the other participants. Allow Hex, then reopen it."
|
|
},
|
|
permission_control,
|
|
))
|
|
.child(settings_row(
|
|
"Transcript folder",
|
|
"Finished meetings are saved here as Markdown",
|
|
div()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.child(
|
|
button(ButtonKind::Secondary, "Reveal")
|
|
.id("reveal-meeting-folder")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
let folder =
|
|
this.settings.meetings.resolved_output_folder();
|
|
match std::fs::create_dir_all(&folder) {
|
|
Ok(()) => crate::meeting::reveal(&folder),
|
|
Err(error) => {
|
|
this.meeting_folder_error = Some(error.to_string());
|
|
}
|
|
}
|
|
cx.notify();
|
|
})),
|
|
)
|
|
.child(
|
|
disclosure_button(folder_label)
|
|
.id("meeting-folder-setting")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.choose_meeting_folder(cx);
|
|
})),
|
|
),
|
|
))
|
|
.child(
|
|
settings_row(
|
|
"Summarize with Apple Intelligence",
|
|
self.apple_intelligence_availability().description(),
|
|
toggle(notes_position),
|
|
)
|
|
.border_b_0()
|
|
.id("meeting-notes-setting")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
let enabled = !this.settings.meetings.summarize_with_apple_intelligence;
|
|
if this.update_settings(cx, |settings| {
|
|
settings.meetings.summarize_with_apple_intelligence = enabled
|
|
}) {
|
|
this.meeting_notes_toggle.set_enabled(enabled);
|
|
}
|
|
})),
|
|
)
|
|
.when_some(self.meeting_folder_error.clone(), |panel, error| {
|
|
panel.child(inline_error(error))
|
|
})
|
|
})
|
|
}
|
|
|
|
fn choose_meeting_folder(&mut self, cx: &mut Context<Self>) {
|
|
let receiver = cx.prompt_for_paths(PathPromptOptions {
|
|
files: false,
|
|
directories: true,
|
|
multiple: false,
|
|
prompt: Some("Use Folder".into()),
|
|
});
|
|
cx.spawn(async move |window, cx| {
|
|
let result = receiver
|
|
.await
|
|
.map_err(|error| error.to_string())
|
|
.and_then(|result| result.map_err(|error| error.to_string()));
|
|
let _ = window.update(cx, |window, cx| match result {
|
|
Ok(Some(paths)) => {
|
|
if let Some(folder) = paths.into_iter().next() {
|
|
window.meeting_folder_error = None;
|
|
window.update_settings(cx, |settings| {
|
|
settings.meetings.output_folder = Some(folder);
|
|
});
|
|
}
|
|
}
|
|
Ok(None) => {}
|
|
Err(error) => {
|
|
window.meeting_folder_error = Some(error);
|
|
cx.notify();
|
|
}
|
|
});
|
|
})
|
|
.detach();
|
|
}
|
|
|
|
fn toggle_microphone_picker(&mut self, cx: &mut Context<Self>) {
|
|
self.microphone_picker_open = !self.microphone_picker_open;
|
|
if self.microphone_picker_open {
|
|
match crate::audio::input_device_names() {
|
|
Ok(devices) => {
|
|
self.microphone_devices = devices;
|
|
self.microphone_picker_error = None;
|
|
}
|
|
Err(error) => self.microphone_picker_error = Some(error.to_string()),
|
|
}
|
|
}
|
|
cx.notify();
|
|
}
|
|
|
|
fn render_setup(&mut self, cx: &mut Context<Self>) -> AnyElement {
|
|
let status = self.setup_status;
|
|
let microphone = match status.microphone {
|
|
PermissionState::Ready => tag(Tone::Success, "Ready").into_any_element(),
|
|
PermissionState::NeedsRequest => button(ButtonKind::Secondary, "Allow")
|
|
.id("setup-microphone")
|
|
.on_click(cx.listener(|_this, _, _, cx| {
|
|
crate::onboarding::request_microphone();
|
|
cx.notify();
|
|
}))
|
|
.into_any_element(),
|
|
PermissionState::NeedsSettings => button(ButtonKind::Secondary, "Open settings")
|
|
.id("setup-microphone")
|
|
.on_click(cx.listener(|_this, _, _, cx| {
|
|
crate::onboarding::open_permission_settings("microphone");
|
|
cx.notify();
|
|
}))
|
|
.into_any_element(),
|
|
};
|
|
let mut permission_items: Vec<(&'static str, &'static str, AnyElement)> = Vec::new();
|
|
if status.microphone != PermissionState::Ready {
|
|
permission_items.push((
|
|
"Microphone",
|
|
if self.settings.commands_enabled {
|
|
"Hear commands and dictation."
|
|
} else {
|
|
"Record dictation while you hold the shortcut"
|
|
},
|
|
microphone,
|
|
));
|
|
}
|
|
if status.input_monitoring != PermissionState::Ready {
|
|
let input_monitoring = button(ButtonKind::Secondary, "Grant access")
|
|
.id("setup-input-monitoring")
|
|
.on_click(cx.listener(|_this, _, _, cx| {
|
|
crate::permission_guide::show_input_monitoring();
|
|
cx.notify();
|
|
}))
|
|
.into_any_element();
|
|
permission_items.push((
|
|
"Input Monitoring",
|
|
"Recognize the dictation shortcut anywhere",
|
|
input_monitoring,
|
|
));
|
|
}
|
|
if status.accessibility != PermissionState::Ready {
|
|
let accessibility = button(ButtonKind::Secondary, "Grant access")
|
|
.id("setup-accessibility")
|
|
.on_click(cx.listener(|_this, _, _, cx| {
|
|
crate::permission_guide::show_accessibility();
|
|
cx.notify();
|
|
}))
|
|
.into_any_element();
|
|
permission_items.push((
|
|
"Accessibility",
|
|
if self.settings.commands_enabled {
|
|
"Paste text and run keyboard commands."
|
|
} else {
|
|
"Paste completed dictation into the foreground app"
|
|
},
|
|
accessibility,
|
|
));
|
|
}
|
|
let permission_count = permission_items.len();
|
|
let permission_rows = permission_items
|
|
.into_iter()
|
|
.enumerate()
|
|
.map(|(index, (title, description, control))| {
|
|
settings_row(title, description, control)
|
|
.when(index + 1 == permission_count, |row| row.border_b_0())
|
|
})
|
|
.collect::<Vec<_>>();
|
|
let models_ready = status.transcription_model;
|
|
let model_notice =
|
|
dictation_model_notice(status, self.transcription_status.model.is_some());
|
|
let models = if models_ready {
|
|
tag(Tone::Success, "Ready").into_any_element()
|
|
} else {
|
|
button(ButtonKind::Primary, "Choose model")
|
|
.id("setup-models")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.transcription_picker_language =
|
|
Some(this.settings.transcription.language.clone());
|
|
this.clear_transcription_error();
|
|
cx.notify();
|
|
}))
|
|
.into_any_element()
|
|
};
|
|
|
|
div()
|
|
.id("setup-backdrop")
|
|
.occlude()
|
|
.absolute()
|
|
.top_0()
|
|
.left_0()
|
|
.size_full()
|
|
.flex()
|
|
.items_center()
|
|
.justify_center()
|
|
.bg(rgba(SCRIM))
|
|
.child(
|
|
div()
|
|
.id("setup")
|
|
.w(px(640.0))
|
|
.p_6()
|
|
.flex()
|
|
.flex_col()
|
|
.gap_4()
|
|
.rounded(RADIUS_MODAL)
|
|
.border_1()
|
|
.border_color(rgb(LINE))
|
|
.bg(rgb(CANVAS))
|
|
.child(
|
|
div()
|
|
.flex()
|
|
.flex_col()
|
|
.gap_1()
|
|
.child(div().text_headline().child("Set up Hex"))
|
|
.child(
|
|
div()
|
|
.text_footnote()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child("Grant permissions and choose a local model to start dictating."),
|
|
),
|
|
)
|
|
.when(!permission_rows.is_empty(), |setup| {
|
|
setup.child(
|
|
div()
|
|
.flex()
|
|
.flex_col()
|
|
.gap_2()
|
|
.child(section_label("Permissions needed").px_4())
|
|
.child(panel().children(permission_rows)),
|
|
)
|
|
})
|
|
.child(
|
|
div()
|
|
.flex()
|
|
.flex_col()
|
|
.gap_2()
|
|
.child(section_label("Local models").px_4())
|
|
.child(
|
|
panel().child(
|
|
settings_row(
|
|
if let Some((title, _)) = model_notice {
|
|
title
|
|
} else {
|
|
"Local dictation model"
|
|
},
|
|
if let Some((_, description)) = model_notice {
|
|
description
|
|
} else {
|
|
"The selected model transcribes speech entirely on this Mac."
|
|
},
|
|
models,
|
|
)
|
|
.border_b_0(),
|
|
),
|
|
),
|
|
)
|
|
.when(crate::DEVELOPER_FEATURES_ENABLED, |setup| {
|
|
setup.child(
|
|
div()
|
|
.text_footnote()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child("Meeting recording requests Screen & System Audio Recording separately when you use it."),
|
|
)
|
|
}),
|
|
)
|
|
.into_any_element()
|
|
}
|
|
|
|
fn render_voice_action(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
|
|
let enabled = self.settings.voice_action.enabled;
|
|
let description = voice_action_description(enabled);
|
|
let position = self
|
|
.voice_action_inputs
|
|
.enabled_toggle
|
|
.render_position(window);
|
|
let enabled_control = div()
|
|
.id("voice-action-enabled")
|
|
.flex()
|
|
.items_center()
|
|
.child(toggle(position))
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.cancel_hotkey_capture(cx);
|
|
let enabled = !this.settings.voice_action.enabled;
|
|
let mut candidate = this.settings_candidate();
|
|
let result = set_voice_action_enabled(&mut candidate, enabled)
|
|
.map_err(str::to_string)
|
|
.and_then(|()| {
|
|
this.commit_settings(candidate)
|
|
.map_err(|error| error.to_string())
|
|
});
|
|
match result {
|
|
Ok(()) => {
|
|
this.voice_action_inputs.enabled_toggle.set_enabled(enabled);
|
|
this.voice_action_inputs.error = None;
|
|
}
|
|
Err(error) => {
|
|
this.voice_action_inputs.error = Some(error);
|
|
}
|
|
}
|
|
cx.notify();
|
|
}));
|
|
let hotkey = self.render_hotkey_setting_control(HotkeyKind::Edit, window, cx);
|
|
let processing = if !enabled {
|
|
None
|
|
} else if let Some(copy) =
|
|
opencode_unavailable_copy(&self.model_catalog, OpenCodeFeature::VoiceAction)
|
|
{
|
|
let show_actions = copy.can_retry || copy.can_open_setup;
|
|
let actions = Self::opencode_unavailable_actions(
|
|
©,
|
|
"retry-opencode",
|
|
"open-opencode-setup",
|
|
"Open OpenCode setup",
|
|
cx,
|
|
)
|
|
.mt_4();
|
|
Some(
|
|
panel()
|
|
.p_4()
|
|
.child(settings_copy(copy.title, copy.description))
|
|
.when_some(copy.error, |card, error| {
|
|
card.child(error_panel("OpenCode reported:", error).mt_3())
|
|
})
|
|
.when(show_actions, |card| card.child(actions))
|
|
.into_any_element(),
|
|
)
|
|
} else {
|
|
Some(self.render_voice_action_processing(window, cx))
|
|
};
|
|
settings_pane(
|
|
"Voice Action",
|
|
"voice-action-scroll",
|
|
div()
|
|
.child(panel().mt_6().child(
|
|
settings_row("Enable Voice Action", description, enabled_control).border_b_0(),
|
|
))
|
|
.when_some(self.voice_action_inputs.error.clone(), |column, error| {
|
|
column.child(error_message("Could not update Voice Action:", error))
|
|
})
|
|
.child(settings_section_label("Capture"))
|
|
.child(
|
|
panel().child(
|
|
settings_row(
|
|
"Shortcut",
|
|
if enabled {
|
|
"Hold to speak; selected text is included automatically"
|
|
} else {
|
|
"Saved for when Voice Action is enabled"
|
|
},
|
|
hotkey,
|
|
)
|
|
.border_b_0()
|
|
.id("voice-action-hotkey-setting"),
|
|
),
|
|
)
|
|
.when_some(processing, |column, processing| {
|
|
column
|
|
.child(settings_section_label("Processing"))
|
|
.child(processing)
|
|
}),
|
|
)
|
|
}
|
|
|
|
fn save_settings(&mut self, cx: &mut Context<Self>) {
|
|
// Modes and text fields are explicit drafts; failed writes remain dirty
|
|
// for retry or the close-time flush.
|
|
self.settings_dirty = true;
|
|
if let Err(error) = self.persist_settings() {
|
|
tracing::error!(%error, "could not save app settings");
|
|
}
|
|
cx.notify();
|
|
}
|
|
|
|
fn persist_settings(&mut self) -> color_eyre::Result<()> {
|
|
self.commit_settings(self.settings_candidate())
|
|
}
|
|
|
|
fn settings_candidate(&self) -> AppSettings {
|
|
let mut candidate = self.settings.clone();
|
|
self.mode_editors.project(&mut candidate);
|
|
candidate
|
|
}
|
|
|
|
/// Saves before assigning so a failed save leaves the live settings
|
|
/// untouched; the generation bump supersedes any pending debounced save.
|
|
fn commit_settings(&mut self, candidate: AppSettings) -> color_eyre::Result<()> {
|
|
#[cfg(test)]
|
|
if let Some(save) = self.settings_save_override {
|
|
return self.commit_settings_with(candidate, save);
|
|
}
|
|
let preview = self.preview;
|
|
self.commit_settings_with(
|
|
candidate,
|
|
|candidate| {
|
|
if preview { Ok(()) } else { candidate.save() }
|
|
},
|
|
)
|
|
}
|
|
|
|
fn commit_settings_with(
|
|
&mut self,
|
|
candidate: AppSettings,
|
|
save: impl FnOnce(&AppSettings) -> color_eyre::Result<()>,
|
|
) -> color_eyre::Result<()> {
|
|
if let Err(error) = self.settings.commit_with(candidate, save) {
|
|
self.settings_load_error = Some(error.to_string());
|
|
return Err(error);
|
|
}
|
|
self.settings_save_generation = self.settings_save_generation.wrapping_add(1);
|
|
self.settings_dirty = false;
|
|
self.settings_load_error = None;
|
|
Ok(())
|
|
}
|
|
|
|
fn update_settings(
|
|
&mut self,
|
|
cx: &mut Context<Self>,
|
|
update: impl FnOnce(&mut AppSettings),
|
|
) -> bool {
|
|
let mut candidate = self.settings_candidate();
|
|
update(&mut candidate);
|
|
let saved = self.commit_settings(candidate).is_ok();
|
|
cx.notify();
|
|
saved
|
|
}
|
|
|
|
fn set_double_tap_lock(&mut self, enabled: bool, cx: &mut Context<Self>) {
|
|
if self.update_settings(cx, |settings| {
|
|
settings.double_tap_lock = enabled;
|
|
if !enabled {
|
|
settings.double_tap_only = false;
|
|
}
|
|
}) {
|
|
self.double_tap_toggle.set_enabled(enabled);
|
|
}
|
|
}
|
|
|
|
fn set_double_tap_only(&mut self, enabled: bool, cx: &mut Context<Self>) {
|
|
self.update_settings(cx, |settings| {
|
|
settings.double_tap_only =
|
|
enabled && settings.double_tap_lock && settings.dictation_hotkey.key.is_some();
|
|
});
|
|
}
|
|
|
|
fn processing_input(
|
|
placeholder: &'static str,
|
|
initial: &str,
|
|
cx: &mut Context<Self>,
|
|
) -> ProcessingInput {
|
|
let entity = cx.new(|cx| TextInput::new(cx, placeholder, initial));
|
|
Self::synchronized_processing_input(entity, cx)
|
|
}
|
|
|
|
fn replacement_inputs(
|
|
replacement: &TextReplacement,
|
|
cx: &mut Context<Self>,
|
|
) -> ReplacementInputs {
|
|
ReplacementInputs {
|
|
matched_phrase: Self::processing_input(
|
|
"Spoken phrase (e.g. open code)",
|
|
&replacement.matched_phrase,
|
|
cx,
|
|
),
|
|
output: Self::processing_input("Replacement (e.g. OpenCode)", &replacement.output, cx),
|
|
}
|
|
}
|
|
|
|
fn transcription_hints_input(initial: &str, cx: &mut Context<Self>) -> ProcessingInput {
|
|
let entity = cx.new(|cx| {
|
|
TextInput::multiline(
|
|
cx,
|
|
"Names and terms Whisper should expect, e.g. OpenCode, Effect…",
|
|
initial,
|
|
)
|
|
});
|
|
let subscription = cx.subscribe(&entity, |this, _, _: &TextChanged, cx| {
|
|
this.settings.transcription.recognition_hints =
|
|
this.transcription_hints.entity.read(cx).text().to_string();
|
|
this.schedule_settings_save(cx);
|
|
});
|
|
ProcessingInput {
|
|
entity,
|
|
_subscriptions: vec![subscription],
|
|
}
|
|
}
|
|
|
|
fn voice_action_inputs(settings: &AppSettings, cx: &mut Context<Self>) -> VoiceActionInputs {
|
|
let model = Self::model_input(
|
|
settings.voice_action.model.as_deref().unwrap_or_default(),
|
|
|_| ModelPickerTarget::VoiceAction,
|
|
cx,
|
|
);
|
|
VoiceActionInputs {
|
|
model,
|
|
enabled_toggle: ToggleSpring::new(settings.voice_action.enabled),
|
|
error: None,
|
|
}
|
|
}
|
|
|
|
fn synchronized_processing_input(
|
|
entity: Entity<TextInput>,
|
|
cx: &mut Context<Self>,
|
|
) -> ProcessingInput {
|
|
let subscription = cx.subscribe(&entity, |this, _, _: &TextChanged, cx| {
|
|
this.sync_processing_settings(cx)
|
|
});
|
|
ProcessingInput {
|
|
entity,
|
|
_subscriptions: vec![subscription],
|
|
}
|
|
}
|
|
|
|
/// `target` is resolved at event time so the Mode picker follows the
|
|
/// currently selected mode rather than the one selected at construction.
|
|
fn model_input(
|
|
initial: &str,
|
|
target: fn(&Self) -> ModelPickerTarget,
|
|
cx: &mut Context<Self>,
|
|
) -> ProcessingInput {
|
|
let entity = cx.new(|cx| TextInput::picker(cx, "Search available models", initial));
|
|
let changed = cx.subscribe(&entity, |this, _, _: &TextChanged, cx| {
|
|
this.model_picker_highlight = 0;
|
|
cx.notify();
|
|
});
|
|
let navigate = cx.subscribe(&entity, move |this, _, event: &TextNavigate, cx| {
|
|
let count = this.model_choice_keys(target(this), cx).len();
|
|
if count > 0 {
|
|
this.model_picker_highlight =
|
|
advance_highlight(this.model_picker_highlight, event.0, count);
|
|
cx.notify();
|
|
}
|
|
});
|
|
let submitted = cx.subscribe(&entity, move |this, _, _: &TextSubmitted, cx| {
|
|
let target = target(this);
|
|
if let Some(model) = this
|
|
.model_choice_keys(target, cx)
|
|
.get(this.model_picker_highlight)
|
|
.cloned()
|
|
{
|
|
this.select_model(target, model, cx);
|
|
}
|
|
});
|
|
ProcessingInput {
|
|
entity,
|
|
_subscriptions: vec![changed, navigate, submitted],
|
|
}
|
|
}
|
|
|
|
fn application_search_input(cx: &mut Context<Self>) -> ProcessingInput {
|
|
let entity = cx.new(|cx| TextInput::picker(cx, "Search applications", ""));
|
|
let changed = cx.subscribe(&entity, |this, _, _: &TextChanged, cx| {
|
|
this.application_picker_highlight = 0;
|
|
cx.notify();
|
|
});
|
|
let navigate = cx.subscribe(&entity, |this, _, event: &TextNavigate, cx| {
|
|
let count = this.application_choice_names(cx).len();
|
|
if count > 0 {
|
|
this.application_picker_highlight =
|
|
advance_highlight(this.application_picker_highlight, event.0, count);
|
|
cx.notify();
|
|
}
|
|
});
|
|
let submitted = cx.subscribe(&entity, |this, _, _: &TextSubmitted, cx| {
|
|
if let Some(name) = this
|
|
.application_choice_names(cx)
|
|
.get(this.application_picker_highlight)
|
|
.cloned()
|
|
{
|
|
this.add_mode_application(this.selected_mode, name, cx);
|
|
}
|
|
});
|
|
let dismissed = cx.subscribe(&entity, |this, _, _: &TextDismissed, cx| {
|
|
this.close_application_picker(cx);
|
|
cx.notify();
|
|
});
|
|
ProcessingInput {
|
|
entity,
|
|
_subscriptions: vec![changed, navigate, submitted, dismissed],
|
|
}
|
|
}
|
|
|
|
fn multiline_processing_input(
|
|
placeholder: &'static str,
|
|
initial: &str,
|
|
cx: &mut Context<Self>,
|
|
) -> ProcessingInput {
|
|
let entity = cx.new(|cx| TextInput::multiline(cx, placeholder, initial));
|
|
Self::synchronized_processing_input(entity, cx)
|
|
}
|
|
|
|
fn mode_inputs(mode: &DictationMode, cx: &mut Context<Self>) -> ModeInputs {
|
|
let processing = &mode.post_processing;
|
|
ModeInputs {
|
|
name: Self::processing_input("Mode name", &mode.name, cx),
|
|
browser_hosts: Self::processing_input(
|
|
"github.com, x.com",
|
|
&mode.browser_hosts.join(", "),
|
|
cx,
|
|
),
|
|
prompt: Self::multiline_processing_input(
|
|
"Describe how OpenCode should rewrite your dictation…",
|
|
&processing.prompt,
|
|
cx,
|
|
),
|
|
model: Self::model_input(
|
|
processing.model.as_deref().unwrap_or_default(),
|
|
|this| ModelPickerTarget::Mode(this.selected_mode),
|
|
cx,
|
|
),
|
|
deadline: Self::processing_input("30", &processing.deadline_seconds.to_string(), cx),
|
|
processing_toggle: ToggleSpring::new(processing.enabled),
|
|
replacements: mode
|
|
.replacements
|
|
.iter()
|
|
.map(|replacement| Self::replacement_inputs(replacement, cx))
|
|
.collect(),
|
|
}
|
|
}
|
|
|
|
fn mode_editor(mode: &DictationMode, cx: &mut Context<Self>) -> ModeEditor {
|
|
ModeEditor {
|
|
settings: mode.clone(),
|
|
inputs: Self::mode_inputs(mode, cx),
|
|
}
|
|
}
|
|
|
|
fn mode_editors(settings: &AppSettings, cx: &mut Context<Self>) -> ModeEditors {
|
|
let processing = &settings.dictation_processing;
|
|
ModeEditors {
|
|
default_mode: Self::mode_editor(&processing.default_mode, cx),
|
|
modes: processing
|
|
.modes
|
|
.iter()
|
|
.map(|mode| Self::mode_editor(mode, cx))
|
|
.collect(),
|
|
}
|
|
}
|
|
|
|
fn sync_processing_settings(&mut self, cx: &mut Context<Self>) {
|
|
let row = &mut self.mode_editors.default_mode;
|
|
apply_mode_inputs(&row.inputs, &mut row.settings, true, cx);
|
|
for row in &mut self.mode_editors.modes {
|
|
apply_mode_inputs(&row.inputs, &mut row.settings, false, cx);
|
|
}
|
|
self.schedule_settings_save(cx);
|
|
}
|
|
|
|
fn update_mode_settings(
|
|
&mut self,
|
|
selection: ModeSelection,
|
|
cx: &mut Context<Self>,
|
|
update: impl FnOnce(&mut DictationMode),
|
|
) -> bool {
|
|
let mut candidate = self.settings_candidate();
|
|
let mode = mode_settings_mut(&mut candidate, selection);
|
|
update(mode);
|
|
let mode = mode.clone();
|
|
let saved = self.commit_settings(candidate).is_ok();
|
|
if saved {
|
|
self.mode_editor_mut(selection).settings = mode;
|
|
}
|
|
cx.notify();
|
|
saved
|
|
}
|
|
|
|
fn add_mode(&mut self, cx: &mut Context<Self>) -> Option<ModeSelection> {
|
|
let mut mode = self.mode_editors.default_mode.settings.clone();
|
|
mode.name = format!("Mode {}", self.mode_editors.modes.len() + 1);
|
|
mode.applications.clear();
|
|
mode.browser_hosts.clear();
|
|
let mut candidate = self.settings_candidate();
|
|
candidate.dictation_processing.modes.push(mode.clone());
|
|
let saved = self.commit_settings(candidate).is_ok();
|
|
cx.notify();
|
|
if !saved {
|
|
return None;
|
|
}
|
|
let selection = ModeSelection::Custom(self.mode_editors.modes.len());
|
|
self.mode_editors.modes.push(Self::mode_editor(&mode, cx));
|
|
Some(selection)
|
|
}
|
|
|
|
fn delete_mode(&mut self, index: usize, cx: &mut Context<Self>) {
|
|
if index >= self.mode_editors.modes.len() {
|
|
return;
|
|
}
|
|
let mut candidate = self.settings_candidate();
|
|
candidate.dictation_processing.modes.remove(index);
|
|
if self.commit_settings(candidate).is_ok() {
|
|
self.mode_editors.modes.remove(index);
|
|
self.selected_mode = ModeSelection::Default;
|
|
self.mode_delete_armed = false;
|
|
self.variant_picker_open = None;
|
|
self.application_picker_open = false;
|
|
self.transformation_picker_open = false;
|
|
}
|
|
cx.notify();
|
|
}
|
|
|
|
fn schedule_settings_save(&mut self, cx: &mut Context<Self>) {
|
|
self.settings_dirty = true;
|
|
self.settings_save_generation = self.settings_save_generation.wrapping_add(1);
|
|
let generation = self.settings_save_generation;
|
|
let delay = cx.background_executor().timer(Duration::from_millis(250));
|
|
cx.spawn(async move |window, cx| {
|
|
delay.await;
|
|
let _ = window.update(cx, |window, cx| {
|
|
if window.settings_save_generation == generation {
|
|
window.save_settings(cx);
|
|
}
|
|
});
|
|
})
|
|
.detach();
|
|
}
|
|
|
|
fn render_modes(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
|
|
let add = icon_button(ButtonKind::Secondary, Icon::Plus)
|
|
.id("add-dictation-mode")
|
|
.on_click(cx.listener(|this, _, window, cx| {
|
|
if let Some(selection) = this.add_mode(cx) {
|
|
this.select_mode(selection, window, cx);
|
|
}
|
|
}));
|
|
let default_selected = self.selected_mode == ModeSelection::Default;
|
|
let mut rows = vec![
|
|
mode_row(
|
|
"Global",
|
|
"Fallback for everything",
|
|
default_selected,
|
|
&[],
|
|
&[],
|
|
&self.application_catalog,
|
|
)
|
|
.id("default-dictation-mode")
|
|
.on_click(cx.listener(|this, _, window, cx| {
|
|
this.select_mode(ModeSelection::Default, window, cx);
|
|
}))
|
|
.into_any_element(),
|
|
];
|
|
rows.extend(
|
|
self.mode_editors
|
|
.modes
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(index, row)| {
|
|
let name = input_text(&row.inputs.name, cx);
|
|
let mode = &row.settings;
|
|
let selected = self.selected_mode == ModeSelection::Custom(index);
|
|
mode_row(
|
|
name,
|
|
"No activation rules",
|
|
selected,
|
|
&mode.applications,
|
|
&mode.browser_hosts,
|
|
&self.application_catalog,
|
|
)
|
|
.id(("dictation-mode", index))
|
|
.on_mouse_down(
|
|
MouseButton::Right,
|
|
cx.listener(move |this, event: &MouseDownEvent, window, cx| {
|
|
this.select_mode(ModeSelection::Custom(index), window, cx);
|
|
this.mode_context_menu = Some(event.position);
|
|
cx.stop_propagation();
|
|
cx.notify();
|
|
}),
|
|
)
|
|
.on_click(cx.listener(move |this, _, window, cx| {
|
|
this.select_mode(ModeSelection::Custom(index), window, cx);
|
|
}))
|
|
.into_any_element()
|
|
})
|
|
.collect::<Vec<_>>(),
|
|
);
|
|
let detail = self.render_mode_detail(window, cx);
|
|
div()
|
|
.size_full()
|
|
.flex()
|
|
.flex_col()
|
|
.child(pane_header_with_action(
|
|
"Modes",
|
|
Some(add.into_any_element()),
|
|
))
|
|
.child(
|
|
pane_body().child(
|
|
pane_content()
|
|
.flex_row()
|
|
.gap_5()
|
|
.child(pane_list(
|
|
"modes-list",
|
|
PANE_LIST_WIDTH_COMPACT,
|
|
None,
|
|
"",
|
|
None,
|
|
rows,
|
|
))
|
|
.child(detail),
|
|
),
|
|
)
|
|
.into_any_element()
|
|
}
|
|
|
|
fn render_mode_context_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
|
|
let position = self.mode_context_menu?;
|
|
Some(
|
|
menu()
|
|
.absolute()
|
|
.left(position.x)
|
|
.top(position.y)
|
|
.w(px(MENU_WIDTH))
|
|
.child(
|
|
danger_menu_item()
|
|
.id("context-delete-mode")
|
|
.child("Delete mode…")
|
|
.on_mouse_down(
|
|
MouseButton::Left,
|
|
cx.listener(move |this, _, _, cx| {
|
|
this.mode_delete_armed = true;
|
|
this.mode_context_menu = None;
|
|
cx.stop_propagation();
|
|
cx.notify();
|
|
}),
|
|
),
|
|
)
|
|
.into_any_element(),
|
|
)
|
|
}
|
|
|
|
fn render_mode_detail(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
|
|
let selection = self.selected_mode;
|
|
let is_default = selection == ModeSelection::Default;
|
|
let (name, browser_hosts, prompt, model, deadline, processing_position) = {
|
|
let inputs = self.selected_mode_inputs_mut();
|
|
(
|
|
inputs.name.entity.clone(),
|
|
inputs.browser_hosts.entity.clone(),
|
|
inputs.prompt.entity.clone(),
|
|
inputs.model.entity.clone(),
|
|
inputs.deadline.entity.clone(),
|
|
inputs.processing_toggle.render_position(window),
|
|
)
|
|
};
|
|
let processing_enabled = self.selected_mode_settings().post_processing.enabled;
|
|
let processing_can_toggle = processing_enabled || self.opencode_available();
|
|
let processing_unavailable =
|
|
opencode_unavailable_copy(&self.model_catalog, OpenCodeFeature::Transformation);
|
|
let corrections = self.render_mode_replacements(selection, cx);
|
|
let transformations = self.render_mode_transformations(selection, cx);
|
|
let application_picker =
|
|
(!is_default).then(|| self.render_application_picker(selection, cx));
|
|
let basics = if is_default {
|
|
panel()
|
|
.child(
|
|
div()
|
|
.min_h(px(SETTINGS_ROW_MIN_HEIGHT))
|
|
.px_4()
|
|
.py_2()
|
|
.flex()
|
|
.flex_col()
|
|
.justify_center()
|
|
.child(settings_copy(
|
|
"Global",
|
|
"Used unless a more specific mode matches.",
|
|
)),
|
|
)
|
|
.into_any_element()
|
|
} else {
|
|
panel()
|
|
.child(
|
|
div()
|
|
.min_h(px(SETTINGS_ROW_MIN_HEIGHT))
|
|
.px_4()
|
|
.py_2()
|
|
.flex()
|
|
.items_center()
|
|
.justify_between()
|
|
.gap_4()
|
|
.border_b_1()
|
|
.border_color(rgb(LINE))
|
|
.child(
|
|
div()
|
|
.text_body()
|
|
.font_weight(FontWeight::MEDIUM)
|
|
.child("Name"),
|
|
)
|
|
.child(div().max_w(px(MODE_FIELD_WIDTH)).flex_1().child(name)),
|
|
)
|
|
.when_some(application_picker, |panel, picker| {
|
|
panel.child(div().border_b_1().border_color(rgb(LINE)).child(picker))
|
|
})
|
|
.child(
|
|
div()
|
|
.min_h(px(SETTINGS_ROW_MIN_HEIGHT))
|
|
.px_4()
|
|
.py_2()
|
|
.flex()
|
|
.items_center()
|
|
.justify_between()
|
|
.gap_4()
|
|
.child(settings_copy(
|
|
"Web pages",
|
|
"Switch when a domain is active in Brave",
|
|
))
|
|
.child(
|
|
div()
|
|
.max_w(px(MODE_FIELD_WIDTH))
|
|
.flex_1()
|
|
.child(browser_hosts),
|
|
),
|
|
)
|
|
.into_any_element()
|
|
};
|
|
|
|
let processing_toggle = div()
|
|
.id("mode-processing-toggle")
|
|
.h(px(CONTROL_HEIGHT))
|
|
.flex()
|
|
.items_center()
|
|
.child(toggle(processing_position))
|
|
.when(!processing_can_toggle, |control| {
|
|
control.opacity(DISABLED_OPACITY)
|
|
})
|
|
.when(processing_can_toggle, |control| {
|
|
control.on_click(cx.listener(move |this, _, _, cx| {
|
|
let enabled = !this.selected_mode_settings().post_processing.enabled;
|
|
if this.update_mode_settings(this.selected_mode, cx, |mode| {
|
|
mode.post_processing.enabled = enabled;
|
|
}) {
|
|
this.selected_mode_inputs_mut()
|
|
.processing_toggle
|
|
.set_enabled(enabled);
|
|
}
|
|
}))
|
|
})
|
|
.into_any_element();
|
|
let processing_settings = processing_enabled.then(|| {
|
|
self.render_processing_settings(
|
|
ModelPickerTarget::Mode(selection),
|
|
prompt,
|
|
model,
|
|
deadline,
|
|
window,
|
|
cx,
|
|
)
|
|
});
|
|
let processing_unavailable = processing_unavailable.map(|copy| {
|
|
let show_actions = copy.can_retry || copy.can_open_setup;
|
|
let actions = Self::opencode_unavailable_actions(
|
|
©,
|
|
"retry-mode-opencode",
|
|
"open-mode-opencode-setup",
|
|
"Open setup",
|
|
cx,
|
|
)
|
|
.items_center();
|
|
div()
|
|
.px_4()
|
|
.py_3()
|
|
.flex()
|
|
.items_start()
|
|
.justify_between()
|
|
.gap_4()
|
|
.border_t_1()
|
|
.border_color(rgb(LINE))
|
|
.child(
|
|
div()
|
|
.min_w(px(0.0))
|
|
.flex_1()
|
|
.flex()
|
|
.flex_col()
|
|
.gap_0p5()
|
|
.child(
|
|
div()
|
|
.text_body()
|
|
.font_weight(FontWeight::MEDIUM)
|
|
.child(copy.title),
|
|
)
|
|
.child(
|
|
div()
|
|
.text_footnote()
|
|
.text_color(rgb(if copy.error.is_some() {
|
|
DANGER
|
|
} else {
|
|
TEXT_TERTIARY
|
|
}))
|
|
.child(copy.error.unwrap_or_else(|| copy.description.into())),
|
|
),
|
|
)
|
|
.when(show_actions, |notice| notice.child(actions))
|
|
});
|
|
let processing = panel()
|
|
.child(
|
|
panel_header("OpenCode transformation", Some(processing_toggle)).when(
|
|
!processing_enabled && processing_unavailable.is_none(),
|
|
|header| header.border_b_0(),
|
|
),
|
|
)
|
|
.when_some(processing_settings, |panel, settings| {
|
|
panel.child(div().px_4().pb_4().child(settings))
|
|
})
|
|
.when_some(processing_unavailable, |panel, unavailable| {
|
|
panel.child(unavailable)
|
|
})
|
|
.into_any_element();
|
|
|
|
let remove = (!is_default).then(|| {
|
|
let action = if self.mode_delete_armed {
|
|
div()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.child(
|
|
button(ButtonKind::Secondary, "Cancel")
|
|
.id("cancel-remove-mode")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.mode_delete_armed = false;
|
|
cx.notify();
|
|
})),
|
|
)
|
|
.child(
|
|
button(ButtonKind::Danger, "Confirm delete")
|
|
.id("confirm-remove-mode")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
let ModeSelection::Custom(index) = this.selected_mode else {
|
|
return;
|
|
};
|
|
this.delete_mode(index, cx);
|
|
})),
|
|
)
|
|
.into_any_element()
|
|
} else {
|
|
button(ButtonKind::Danger, "Delete mode")
|
|
.id("remove-selected-mode")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.mode_delete_armed = true;
|
|
cx.notify();
|
|
}))
|
|
.into_any_element()
|
|
};
|
|
div()
|
|
.pt_2()
|
|
.flex()
|
|
.items_center()
|
|
.justify_end()
|
|
.child(action)
|
|
.into_any_element()
|
|
});
|
|
|
|
div()
|
|
.id("mode-detail")
|
|
.flex_1()
|
|
.min_w(px(0.0))
|
|
.h_full()
|
|
.overflow_y_scroll()
|
|
.child(
|
|
div()
|
|
.w_full()
|
|
.flex()
|
|
.flex_col()
|
|
.gap_2()
|
|
.child(basics)
|
|
.child(section_label("Text processing").pt_2().px_4())
|
|
.child(corrections)
|
|
.child(processing)
|
|
.child(transformations)
|
|
.when_some(remove, |detail, remove| {
|
|
detail.child(div().pt_1().child(remove))
|
|
}),
|
|
)
|
|
.into_any_element()
|
|
}
|
|
|
|
fn render_mode_transformations(
|
|
&self,
|
|
selection: ModeSelection,
|
|
cx: &mut Context<Self>,
|
|
) -> AnyElement {
|
|
let selected = self.mode_settings(selection).transformations.clone();
|
|
let catalog = &self.personal_commands_status.transformations;
|
|
let selected_rows = selected
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(target_index, id)| {
|
|
let name = catalog
|
|
.iter()
|
|
.find(|transformation| &transformation.id == id)
|
|
.map_or_else(|| id.clone(), |transformation| transformation.name.clone());
|
|
let drag = TransformationDrag {
|
|
selection,
|
|
id: id.clone(),
|
|
name: name.clone(),
|
|
position: Point::default(),
|
|
};
|
|
let dragged_id = id.clone();
|
|
let drop_id = id.clone();
|
|
div()
|
|
.id(("mode-transformation", target_index))
|
|
.h(px(CONTROL_HEIGHT + SPACE_2))
|
|
.pl_2()
|
|
.pr_1()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.when(target_index + 1 < selected.len(), |row| {
|
|
row.border_b_1().border_color(rgb(LINE))
|
|
})
|
|
.can_drop(move |value, _, _| {
|
|
value
|
|
.downcast_ref::<TransformationDrag>()
|
|
.is_some_and(|drag| drag.selection == selection && drag.id != drop_id)
|
|
})
|
|
.on_drop(cx.listener(move |this, drag: &TransformationDrag, _, cx| {
|
|
if drag.selection != selection {
|
|
return;
|
|
}
|
|
this.update_mode_settings(selection, cx, |mode| {
|
|
reorder_transformation(
|
|
&mut mode.transformations,
|
|
&drag.id,
|
|
target_index,
|
|
);
|
|
});
|
|
}))
|
|
.child(
|
|
div()
|
|
.id(("drag-mode-transformation", target_index))
|
|
.w_5()
|
|
.h_full()
|
|
.flex_none()
|
|
.flex()
|
|
.items_center()
|
|
.justify_center()
|
|
.cursor_grab()
|
|
.child(icon(Icon::DragHandle, TEXT_DISABLED))
|
|
.on_drag(drag, |drag, position, _, cx| {
|
|
cx.new(|_| drag.clone().at(position))
|
|
}),
|
|
)
|
|
.child(
|
|
truncated_line(BODY, name)
|
|
.flex_1()
|
|
.text_color(rgb(TEXT_SECONDARY)),
|
|
)
|
|
.child(
|
|
icon_button(ButtonKind::Ghost, Icon::Close)
|
|
.id(("remove-mode-transformation", target_index))
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
this.update_mode_settings(selection, cx, |mode| {
|
|
mode.transformations
|
|
.retain(|candidate| candidate != &dragged_id);
|
|
});
|
|
})),
|
|
)
|
|
.into_any_element()
|
|
})
|
|
.collect::<Vec<_>>();
|
|
|
|
let available_rows = if self.transformation_picker_open {
|
|
catalog
|
|
.iter()
|
|
.enumerate()
|
|
.filter(|(_, transformation)| !selected.contains(&transformation.id))
|
|
.map(|(index, transformation)| {
|
|
let id = transformation.id.clone();
|
|
let name = transformation.name.clone();
|
|
let description = transformation.description.clone();
|
|
div()
|
|
.id(("available-mode-transformation", index))
|
|
.min_h(px(SETTINGS_ROW_MIN_HEIGHT))
|
|
.px_4()
|
|
.py_2()
|
|
.flex()
|
|
.items_center()
|
|
.justify_between()
|
|
.gap_3()
|
|
.border_t_1()
|
|
.border_color(rgb(LINE))
|
|
.hover(|row| row.bg(rgb(SURFACE_HOVER)))
|
|
.child(
|
|
div()
|
|
.flex_1()
|
|
.min_w(px(0.0))
|
|
.child(
|
|
div()
|
|
.text_body()
|
|
.font_weight(FontWeight::MEDIUM)
|
|
.text_color(rgb(TEXT_SECONDARY))
|
|
.child(name),
|
|
)
|
|
.when_some(description, |copy, description| {
|
|
copy.child(
|
|
div()
|
|
.pt_0p5()
|
|
.text_footnote()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child(description),
|
|
)
|
|
}),
|
|
)
|
|
.child(small_button(ButtonKind::Secondary, "Add"))
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
this.update_mode_settings(selection, cx, |mode| {
|
|
mode.transformations.push(id.clone());
|
|
});
|
|
}))
|
|
.into_any_element()
|
|
})
|
|
.collect::<Vec<_>>()
|
|
} else {
|
|
Vec::new()
|
|
};
|
|
let available_empty = available_rows.is_empty();
|
|
let catalog_empty = catalog.is_empty();
|
|
let add = (!catalog_empty).then(|| {
|
|
let control = if self.transformation_picker_open {
|
|
small_button(ButtonKind::Secondary, "Done")
|
|
} else {
|
|
icon_button(ButtonKind::Ghost, Icon::Plus).mr(px(-SPACE_2))
|
|
};
|
|
control
|
|
.id("toggle-transformation-picker")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.transformation_picker_open = !this.transformation_picker_open;
|
|
cx.notify();
|
|
}))
|
|
.into_any_element()
|
|
});
|
|
|
|
panel()
|
|
.child(panel_header("Transformations", add).when(
|
|
selected.is_empty() && !self.transformation_picker_open,
|
|
|header| header.border_b_0(),
|
|
))
|
|
.children(selected_rows)
|
|
.when(self.transformation_picker_open && !catalog_empty, |panel| {
|
|
panel
|
|
.when(available_empty, |list| {
|
|
list.child(
|
|
div()
|
|
.border_t_1()
|
|
.border_color(rgb(LINE))
|
|
.px_4()
|
|
.py_3()
|
|
.text_footnote()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child("Every registered transformation is already included."),
|
|
)
|
|
})
|
|
.children(available_rows)
|
|
})
|
|
.into_any_element()
|
|
}
|
|
|
|
fn render_application_picker(
|
|
&self,
|
|
selection: ModeSelection,
|
|
cx: &mut Context<Self>,
|
|
) -> AnyElement {
|
|
let selected = self.mode_settings(selection).applications.clone();
|
|
let selected_rows = selected.iter().enumerate().map(|(index, name)| {
|
|
let application = self.application_named(name);
|
|
let name = name.clone();
|
|
div()
|
|
.id(("selected-application", index))
|
|
.h(px(CONTROL_HEIGHT_SMALL))
|
|
.pl_1()
|
|
.flex()
|
|
.items_center()
|
|
.gap_1p5()
|
|
.rounded(RADIUS_SMALL)
|
|
.bg(rgb(SURFACE_SELECTED))
|
|
.text_caption()
|
|
.font_weight(FontWeight::MEDIUM)
|
|
.text_color(rgb(TEXT_SECONDARY))
|
|
.child(application_icon(
|
|
application,
|
|
Some(name.as_str()),
|
|
ICON_SIZE + 2.0,
|
|
))
|
|
.child(name.clone())
|
|
.child(
|
|
icon_button(ButtonKind::Ghost, Icon::Close)
|
|
.id(("remove-selected-application", index))
|
|
.size(px(CONTROL_HEIGHT_SMALL))
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
this.remove_mode_application(selection, &name, cx);
|
|
})),
|
|
)
|
|
});
|
|
let query = self
|
|
.application_search
|
|
.entity
|
|
.read(cx)
|
|
.text()
|
|
.trim()
|
|
.to_lowercase();
|
|
let available = if self.application_picker_open {
|
|
self.application_choices(selection, cx)
|
|
} else {
|
|
Vec::new()
|
|
};
|
|
let no_matches = available.is_empty();
|
|
let available_rows =
|
|
available
|
|
.into_iter()
|
|
.cloned()
|
|
.enumerate()
|
|
.map(|(index, application)| {
|
|
let name = application.name.clone();
|
|
let location = application
|
|
.path
|
|
.parent()
|
|
.map_or_else(String::new, |path| path.display().to_string());
|
|
list_row(index == self.application_picker_highlight)
|
|
.id(("available-application", index))
|
|
.flex_row()
|
|
.items_center()
|
|
.gap_3()
|
|
.child(application_icon(
|
|
Some(&application),
|
|
Some(&name),
|
|
CONTROL_HEIGHT,
|
|
))
|
|
.child(
|
|
div()
|
|
.flex_1()
|
|
.min_w(px(0.0))
|
|
.flex()
|
|
.flex_col()
|
|
.gap_0p5()
|
|
.child(list_row_title(name.clone(), false))
|
|
.child(list_row_meta(location, false)),
|
|
)
|
|
.on_mouse_down(
|
|
MouseButton::Left,
|
|
cx.listener(move |this, _, _, cx| {
|
|
this.add_mode_application(selection, name.clone(), cx);
|
|
}),
|
|
)
|
|
});
|
|
let picker_status = match &self.application_catalog {
|
|
ApplicationCatalogState::Loading => Some("Finding applications on this Mac…".into()),
|
|
ApplicationCatalogState::Loaded(applications) if applications.is_empty() => {
|
|
Some("No applications found.".into())
|
|
}
|
|
ApplicationCatalogState::Loaded(_) if no_matches && !query.is_empty() => {
|
|
Some(format!("No applications match \"{query}\"."))
|
|
}
|
|
_ => None,
|
|
};
|
|
let tray = self.application_picker_open.then(|| {
|
|
div()
|
|
.mx_4()
|
|
.mb_4()
|
|
.p_2()
|
|
.flex()
|
|
.flex_col()
|
|
.gap_1()
|
|
.rounded(RADIUS_CONTROL)
|
|
.border_1()
|
|
.border_color(rgb(LINE))
|
|
.bg(rgb(CANVAS))
|
|
.child(self.application_search.entity.clone())
|
|
.when_some(picker_status, |tray, status| {
|
|
tray.child(
|
|
div()
|
|
.px_2()
|
|
.py_3()
|
|
.text_footnote()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child(status),
|
|
)
|
|
})
|
|
.child(
|
|
div()
|
|
.id("application-picker-results")
|
|
.max_h(px(300.0))
|
|
.overflow_y_scroll()
|
|
.children(available_rows),
|
|
)
|
|
.child(
|
|
div()
|
|
.pt_2()
|
|
.flex()
|
|
.items_center()
|
|
.justify_between()
|
|
.child(
|
|
small_button(ButtonKind::Secondary, "Choose from Finder…")
|
|
.id("choose-application-bundle")
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
this.choose_application(selection, cx);
|
|
})),
|
|
)
|
|
.child(
|
|
small_button(ButtonKind::Secondary, "Done")
|
|
.id("close-application-picker")
|
|
.on_click(cx.listener(|this, _, window, cx| {
|
|
this.close_application_picker(cx);
|
|
window.blur();
|
|
cx.notify();
|
|
})),
|
|
),
|
|
)
|
|
});
|
|
div()
|
|
.flex()
|
|
.flex_col()
|
|
.child(
|
|
div()
|
|
.min_h(px(SETTINGS_ROW_MIN_HEIGHT))
|
|
.px_4()
|
|
.py_2()
|
|
.flex()
|
|
.items_center()
|
|
.justify_between()
|
|
.gap_4()
|
|
.child(settings_copy(
|
|
"Applications",
|
|
"Switch when an app is frontmost",
|
|
))
|
|
.child(
|
|
div()
|
|
.max_w(px(MODE_FIELD_WIDTH))
|
|
.min_h(px(CONTROL_HEIGHT))
|
|
.flex_1()
|
|
.flex()
|
|
.flex_wrap()
|
|
.items_center()
|
|
.justify_end()
|
|
.gap_1()
|
|
.children(selected_rows)
|
|
.child(
|
|
icon_button(ButtonKind::Secondary, Icon::Plus)
|
|
.id("open-application-picker")
|
|
.on_click(cx.listener(|this, _, window, cx| {
|
|
this.application_picker_highlight = 0;
|
|
this.application_picker_open = true;
|
|
this.application_picker_error = None;
|
|
this.ensure_application_catalog_load();
|
|
this.application_search
|
|
.entity
|
|
.update(cx, |input, cx| input.set_text("", cx));
|
|
this.application_search
|
|
.entity
|
|
.focus_handle(cx)
|
|
.focus(window);
|
|
cx.notify();
|
|
})),
|
|
),
|
|
),
|
|
)
|
|
.when_some(self.application_picker_error.clone(), |picker, error| {
|
|
picker.child(inline_error(error))
|
|
})
|
|
.when_some(tray, |picker, tray| picker.child(tray))
|
|
.into_any_element()
|
|
}
|
|
|
|
fn application_named(&self, name: &str) -> Option<&InstalledApplication> {
|
|
self.application_catalog.application_named(name)
|
|
}
|
|
|
|
fn application_choice_names(&self, cx: &App) -> Vec<String> {
|
|
self.application_choices(self.selected_mode, cx)
|
|
.into_iter()
|
|
.map(|application| application.name.clone())
|
|
.collect()
|
|
}
|
|
|
|
fn application_choices<'a>(
|
|
&'a self,
|
|
selection: ModeSelection,
|
|
cx: &App,
|
|
) -> Vec<&'a InstalledApplication> {
|
|
let ApplicationCatalogState::Loaded(applications) = &self.application_catalog else {
|
|
return Vec::new();
|
|
};
|
|
let selected = &self.mode_settings(selection).applications;
|
|
let query = self
|
|
.application_search
|
|
.entity
|
|
.read(cx)
|
|
.text()
|
|
.trim()
|
|
.to_lowercase();
|
|
applications
|
|
.iter()
|
|
.filter(|application| {
|
|
!selected.contains(&application.name)
|
|
&& (query.is_empty()
|
|
|| application.name.to_lowercase().contains(&query)
|
|
|| application
|
|
.bundle_id
|
|
.as_deref()
|
|
.is_some_and(|bundle| bundle.to_lowercase().contains(&query)))
|
|
})
|
|
.take(10)
|
|
.collect()
|
|
}
|
|
|
|
fn add_mode_application(
|
|
&mut self,
|
|
selection: ModeSelection,
|
|
name: String,
|
|
cx: &mut Context<Self>,
|
|
) {
|
|
if let Some(conflict) = self
|
|
.mode_editors
|
|
.modes
|
|
.iter()
|
|
.enumerate()
|
|
.find(|(index, row)| {
|
|
selection != ModeSelection::Custom(*index)
|
|
&& row.settings.applications.contains(&name)
|
|
})
|
|
.map(|(_, row)| row.settings.name.clone())
|
|
{
|
|
self.application_picker_error = Some(format!(
|
|
"{name} already activates {conflict}. Remove it there before reassigning it."
|
|
));
|
|
cx.notify();
|
|
return;
|
|
}
|
|
if !self.mode_settings(selection).applications.contains(&name)
|
|
&& self.update_mode_settings(selection, cx, |mode| {
|
|
mode.applications.push(name);
|
|
mode.applications.sort_by_key(|name| name.to_lowercase());
|
|
})
|
|
{
|
|
self.application_picker_highlight = 0;
|
|
self.application_search
|
|
.entity
|
|
.update(cx, |input, cx| input.set_text("", cx));
|
|
self.application_picker_error = None;
|
|
}
|
|
}
|
|
|
|
fn remove_mode_application(
|
|
&mut self,
|
|
selection: ModeSelection,
|
|
name: &str,
|
|
cx: &mut Context<Self>,
|
|
) {
|
|
self.update_mode_settings(selection, cx, |mode| {
|
|
mode.applications.retain(|application| application != name);
|
|
});
|
|
}
|
|
|
|
fn choose_application(&mut self, selection: ModeSelection, cx: &mut Context<Self>) {
|
|
let receiver = cx.prompt_for_paths(PathPromptOptions {
|
|
files: true,
|
|
directories: false,
|
|
multiple: false,
|
|
prompt: Some("Add Application".into()),
|
|
});
|
|
cx.spawn(async move |window, cx| {
|
|
let path = match receiver
|
|
.await
|
|
.map_err(|error| error.to_string())
|
|
.and_then(|result| result.map_err(|error| error.to_string()))
|
|
{
|
|
Ok(paths) => paths.and_then(|paths| paths.into_iter().next()),
|
|
Err(error) => {
|
|
let _ = window.update(cx, |window, cx| {
|
|
window.application_picker_error = Some(error);
|
|
cx.notify();
|
|
});
|
|
return;
|
|
}
|
|
};
|
|
let Some(path) = path else {
|
|
return;
|
|
};
|
|
let result = cx
|
|
.background_executor()
|
|
.spawn(async move { crate::application_catalog::metadata(&path) })
|
|
.await;
|
|
let _ = window.update(cx, |window, cx| match result {
|
|
Ok(application) => {
|
|
let name = application.name.clone();
|
|
match &mut window.application_catalog {
|
|
ApplicationCatalogState::Loading => {
|
|
window.application_catalog =
|
|
ApplicationCatalogState::Loaded(vec![application]);
|
|
}
|
|
ApplicationCatalogState::Loaded(applications) => {
|
|
crate::application_catalog::insert(applications, application);
|
|
}
|
|
}
|
|
window.application_picker_error = None;
|
|
window.add_mode_application(selection, name, cx);
|
|
}
|
|
Err(error) => {
|
|
window.application_picker_error = Some(error.to_string());
|
|
cx.notify();
|
|
}
|
|
});
|
|
})
|
|
.detach();
|
|
}
|
|
|
|
/// Build the shared OpenCode model picker: the collapsed selected-model
|
|
/// card, the type-to-filter search input with bounded suggestions, the
|
|
/// catalog status line, and the thinking-variant control. Every surface
|
|
/// that selects a model renders these same parts.
|
|
fn processing_picker(
|
|
&mut self,
|
|
target: ModelPickerTarget,
|
|
model: Entity<TextInput>,
|
|
window: &mut Window,
|
|
cx: &mut Context<Self>,
|
|
) -> ProcessingPicker {
|
|
let focused = model.read(cx).is_focused(window);
|
|
let (selected_model, selected_variant) = self.model_settings_for(target);
|
|
let selected_model_text = selected_model.unwrap_or_default();
|
|
if !focused && model.read(cx).text() != selected_model_text {
|
|
model.update(cx, |input, cx| input.set_text(selected_model_text, cx));
|
|
}
|
|
let query = model.read(cx).text().trim().to_lowercase();
|
|
let presentation = model_presentation(&self.model_catalog, selected_model);
|
|
let (catalog_status, default_label, matches, variants) = match &self.model_catalog {
|
|
ModelCatalogState::Loading => {
|
|
("Loading OpenCode…".into(), None, Vec::new(), Vec::new())
|
|
}
|
|
ModelCatalogState::Missing => (
|
|
"OpenCode beta required".into(),
|
|
None,
|
|
Vec::new(),
|
|
Vec::new(),
|
|
),
|
|
ModelCatalogState::Failed(error) => (
|
|
format!("OpenCode models unavailable: {error}"),
|
|
None,
|
|
Vec::new(),
|
|
Vec::new(),
|
|
),
|
|
ModelCatalogState::Loaded(catalog) => {
|
|
let choice_keys = if focused {
|
|
filtered_model_keys(catalog, &query)
|
|
} else {
|
|
Vec::new()
|
|
};
|
|
let matches = choice_keys
|
|
.iter()
|
|
.filter_map(Option::as_deref)
|
|
.filter_map(|key| catalog.models.iter().find(|choice| choice.key == key))
|
|
.cloned()
|
|
.collect();
|
|
let variants = model_variants(catalog, selected_model);
|
|
let default_label = choice_keys
|
|
.first()
|
|
.is_some_and(Option::is_none)
|
|
.then(|| {
|
|
catalog
|
|
.default_name
|
|
.as_ref()
|
|
.map(|name| match &catalog.default_key {
|
|
Some(key) => format!("OpenCode default: {name} ({key})"),
|
|
None => format!("OpenCode default: {name}"),
|
|
})
|
|
})
|
|
.flatten();
|
|
(
|
|
format!("{} available models", catalog.models.len()),
|
|
default_label,
|
|
matches,
|
|
variants,
|
|
)
|
|
}
|
|
};
|
|
let suggestions =
|
|
(focused && (!matches.is_empty() || default_label.is_some())).then(|| {
|
|
menu()
|
|
.mt_1()
|
|
.when_some(default_label.clone(), |list, label| {
|
|
list.child(
|
|
model_choice_row(
|
|
"Use OpenCode default",
|
|
label,
|
|
self.model_picker_highlight == 0,
|
|
)
|
|
.id("opencode-default")
|
|
.on_mouse_down(
|
|
MouseButton::Left,
|
|
cx.listener(move |this, _, window, cx| {
|
|
this.select_model(target, None, cx);
|
|
window.blur();
|
|
}),
|
|
),
|
|
)
|
|
})
|
|
.children(matches.into_iter().enumerate().map(|(index, choice)| {
|
|
let key = choice.key.clone();
|
|
let row_index = index + usize::from(default_label.is_some());
|
|
model_choice_row(
|
|
choice.name,
|
|
choice.key,
|
|
self.model_picker_highlight == row_index,
|
|
)
|
|
.id(("model-choice", index))
|
|
.on_mouse_down(
|
|
MouseButton::Left,
|
|
cx.listener(move |this, _, window, cx| {
|
|
this.select_model(target, Some(key.clone()), cx);
|
|
window.blur();
|
|
}),
|
|
)
|
|
}))
|
|
});
|
|
let effective_variant = selected_variant.or_else(|| {
|
|
selected_model.is_none().then(|| {
|
|
let ModelCatalogState::Loaded(catalog) = &self.model_catalog else {
|
|
return None;
|
|
};
|
|
catalog.default_variant.as_deref()
|
|
})?
|
|
});
|
|
let has_variants = !variants.is_empty();
|
|
let variant_open = self.variant_picker_open == Some(target);
|
|
let variant_list = (has_variants && variant_open).then(|| {
|
|
let choices = std::iter::once(None)
|
|
.chain(variants.iter().cloned().map(Some))
|
|
.collect::<Vec<_>>();
|
|
menu()
|
|
.mt_1()
|
|
.children(choices.into_iter().enumerate().map(|(index, variant)| {
|
|
let selected = effective_variant == variant.as_deref();
|
|
let label = variant.clone().unwrap_or_else(|| "Default".into());
|
|
menu_item(selected)
|
|
.id(("model-variant", index))
|
|
.child(label)
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
this.variant_picker_open = None;
|
|
this.set_model_variant(target, variant.clone(), cx);
|
|
}))
|
|
}))
|
|
});
|
|
let variant_control = div()
|
|
.w(px(160.0))
|
|
.flex_none()
|
|
.child(
|
|
disclosure_button(effective_variant.unwrap_or("Default").to_string())
|
|
.id("model-variant-trigger")
|
|
.w(px(160.0))
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
this.variant_picker_open = if this.variant_picker_open == Some(target) {
|
|
None
|
|
} else {
|
|
Some(target)
|
|
};
|
|
cx.notify();
|
|
})),
|
|
)
|
|
.when_some(variant_list, |control, list| control.child(list));
|
|
let model_control = if let Some(presentation) = presentation.filter(|_| !focused) {
|
|
let model_input = model.clone();
|
|
disclosure_frame()
|
|
.id("selected-model")
|
|
.w_full()
|
|
.flex_shrink()
|
|
.child(
|
|
truncated_line(FOOTNOTE, presentation.name)
|
|
.flex_1()
|
|
.font_weight(FontWeight::MEDIUM)
|
|
.text_color(rgb(TEXT_PRIMARY)),
|
|
)
|
|
.child(
|
|
div()
|
|
.flex_none()
|
|
.text_caption()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child(presentation.provider),
|
|
)
|
|
.when(presentation.is_default, |control| {
|
|
control.child(tag(Tone::Neutral, "Default"))
|
|
})
|
|
.child(icon(Icon::ChevronDown, TEXT_TERTIARY))
|
|
.on_click(cx.listener(move |_, _, window, cx| {
|
|
model_input.focus_handle(cx).focus(window);
|
|
cx.notify();
|
|
}))
|
|
.into_any_element()
|
|
} else {
|
|
model.clone().into_any_element()
|
|
};
|
|
let refresh_control =
|
|
matches!(&self.model_catalog, ModelCatalogState::Loaded(_)).then(|| {
|
|
button(ButtonKind::Secondary, "Refresh")
|
|
.id("refresh-opencode-models")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.reload_model_catalog();
|
|
cx.notify();
|
|
}))
|
|
.into_any_element()
|
|
});
|
|
ProcessingPicker {
|
|
catalog_status,
|
|
model_control,
|
|
refresh_control,
|
|
suggestions,
|
|
has_variants,
|
|
variant_control,
|
|
}
|
|
}
|
|
|
|
/// The Voice Action processing panel: the shared model and thinking
|
|
/// pickers presented in the pane's setting-row language. The processing
|
|
/// deadline is not configurable here; Voice Action uses the persisted
|
|
/// default.
|
|
fn opencode_unavailable_actions(
|
|
copy: &OpenCodeUnavailableCopy,
|
|
retry_id: &'static str,
|
|
setup_id: &'static str,
|
|
setup_label: &'static str,
|
|
cx: &mut Context<Self>,
|
|
) -> Div {
|
|
div()
|
|
.flex()
|
|
.gap_2()
|
|
.when(copy.can_retry, |actions| {
|
|
actions.child(
|
|
button(ButtonKind::Secondary, copy.retry_label)
|
|
.id(retry_id)
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.reload_model_catalog();
|
|
cx.notify();
|
|
})),
|
|
)
|
|
})
|
|
.when(copy.can_open_setup, |actions| {
|
|
actions.child(
|
|
button(ButtonKind::Secondary, setup_label)
|
|
.id(setup_id)
|
|
.on_click(|_, _, _| open_opencode_beta_docs()),
|
|
)
|
|
})
|
|
}
|
|
|
|
fn render_voice_action_processing(
|
|
&mut self,
|
|
window: &mut Window,
|
|
cx: &mut Context<Self>,
|
|
) -> AnyElement {
|
|
let model = self.voice_action_inputs.model.entity.clone();
|
|
let ProcessingPicker {
|
|
catalog_status,
|
|
model_control,
|
|
refresh_control,
|
|
suggestions,
|
|
has_variants,
|
|
variant_control,
|
|
} = self.processing_picker(ModelPickerTarget::VoiceAction, model, window, cx);
|
|
let model_field = div()
|
|
.w(px(380.0))
|
|
.flex_none()
|
|
.child(
|
|
div()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.child(div().min_w(px(0.0)).flex_1().child(model_control))
|
|
.when_some(refresh_control, |row, refresh| row.child(refresh)),
|
|
)
|
|
.when_some(suggestions, |field, suggestions| field.child(suggestions));
|
|
panel()
|
|
.child(
|
|
settings_row("OpenCode model", catalog_status, model_field)
|
|
.when(!has_variants, |row| row.border_b_0()),
|
|
)
|
|
.when(has_variants, |panel| {
|
|
panel.child(
|
|
settings_row(
|
|
"Thinking",
|
|
"Choose how much reasoning the model should use",
|
|
div().w(px(160.0)).flex_none().child(variant_control),
|
|
)
|
|
.border_b_0(),
|
|
)
|
|
})
|
|
.into_any_element()
|
|
}
|
|
|
|
fn render_processing_settings(
|
|
&mut self,
|
|
target: ModelPickerTarget,
|
|
prompt: Entity<TextInput>,
|
|
model: Entity<TextInput>,
|
|
deadline: Entity<TextInput>,
|
|
window: &mut Window,
|
|
cx: &mut Context<Self>,
|
|
) -> AnyElement {
|
|
let compact = window.viewport_size().width < px(980.0);
|
|
let ProcessingPicker {
|
|
catalog_status,
|
|
model_control,
|
|
refresh_control,
|
|
suggestions,
|
|
has_variants,
|
|
variant_control,
|
|
} = self.processing_picker(target, model, window, cx);
|
|
div()
|
|
.pt_5()
|
|
.flex()
|
|
.flex_col()
|
|
.gap_5()
|
|
.child(
|
|
div()
|
|
.flex()
|
|
.when(compact, |fields| fields.flex_col())
|
|
.gap_3()
|
|
.child(
|
|
div()
|
|
.flex_1()
|
|
.min_w(px(0.0))
|
|
.child(settings_control(
|
|
"Model",
|
|
&catalog_status,
|
|
div()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.child(div().min_w(px(0.0)).flex_1().child(model_control))
|
|
.when_some(refresh_control, |row, refresh| row.child(refresh))
|
|
.into_any_element(),
|
|
))
|
|
.when(
|
|
matches!(&self.model_catalog, ModelCatalogState::Missing),
|
|
|field| {
|
|
field.child(
|
|
button(ButtonKind::Secondary, "Install OpenCode")
|
|
.mt_2()
|
|
.id("install-opencode-beta")
|
|
.on_click(|_, _, _| open_opencode_beta_docs()),
|
|
)
|
|
},
|
|
)
|
|
.when_some(suggestions, |field, suggestions| field.child(suggestions)),
|
|
)
|
|
.child(
|
|
div()
|
|
.when(!compact, |field| field.w(px(150.0)).flex_none())
|
|
.when(compact, |field| field.w_full())
|
|
.child(settings_control("Deadline", "Seconds", deadline)),
|
|
),
|
|
)
|
|
.when(has_variants, |processing| {
|
|
processing.child(
|
|
div()
|
|
.flex()
|
|
.flex_col()
|
|
.gap_2()
|
|
.child(field_label("Thinking"))
|
|
.child(div().flex().child(variant_control)),
|
|
)
|
|
})
|
|
.child(settings_control(
|
|
"Instructions",
|
|
"System instructions for rewriting dictation in this mode",
|
|
prompt,
|
|
))
|
|
.into_any_element()
|
|
}
|
|
|
|
fn model_choice_keys(&self, target: ModelPickerTarget, cx: &App) -> Vec<Option<String>> {
|
|
let ModelCatalogState::Loaded(catalog) = &self.model_catalog else {
|
|
return Vec::new();
|
|
};
|
|
let query = self
|
|
.model_input_for(target)
|
|
.read(cx)
|
|
.text()
|
|
.trim()
|
|
.to_lowercase();
|
|
filtered_model_keys(catalog, &query)
|
|
}
|
|
|
|
fn select_model(
|
|
&mut self,
|
|
target: ModelPickerTarget,
|
|
model: Option<String>,
|
|
cx: &mut Context<Self>,
|
|
) {
|
|
let recommended_variant = model.as_deref().and_then(|key| {
|
|
let ModelCatalogState::Loaded(catalog) = &self.model_catalog else {
|
|
return None;
|
|
};
|
|
catalog.recommended_variant_for(key).map(str::to_owned)
|
|
});
|
|
let text = model.clone().unwrap_or_default();
|
|
let saved = match target {
|
|
ModelPickerTarget::Mode(selection) => {
|
|
self.update_mode_settings(selection, cx, |mode| {
|
|
mode.post_processing.model = model;
|
|
mode.post_processing.variant = recommended_variant;
|
|
})
|
|
}
|
|
ModelPickerTarget::VoiceAction => self.update_settings(cx, |settings| {
|
|
settings.voice_action.model = model;
|
|
settings.voice_action.variant = recommended_variant;
|
|
}),
|
|
};
|
|
if saved {
|
|
self.model_input_for(target)
|
|
.update(cx, |input, cx| input.set_text(text, cx));
|
|
}
|
|
}
|
|
|
|
fn set_model_variant(
|
|
&mut self,
|
|
target: ModelPickerTarget,
|
|
variant: Option<String>,
|
|
cx: &mut Context<Self>,
|
|
) {
|
|
let mut candidate = self.settings_candidate();
|
|
apply_model_variant(&mut candidate, target, variant, &self.model_catalog);
|
|
if self.commit_settings(candidate).is_ok()
|
|
&& let ModelPickerTarget::Mode(selection) = target
|
|
{
|
|
let mode = mode_settings_mut(&mut self.settings, selection).clone();
|
|
self.mode_editor_mut(selection).settings = mode;
|
|
}
|
|
cx.notify();
|
|
}
|
|
|
|
fn model_input_for(&self, target: ModelPickerTarget) -> Entity<TextInput> {
|
|
match target {
|
|
ModelPickerTarget::Mode(selection) => {
|
|
self.mode_inputs_for(selection).model.entity.clone()
|
|
}
|
|
ModelPickerTarget::VoiceAction => self.voice_action_inputs.model.entity.clone(),
|
|
}
|
|
}
|
|
|
|
fn model_settings_for(&self, target: ModelPickerTarget) -> (Option<&str>, Option<&str>) {
|
|
match target {
|
|
ModelPickerTarget::Mode(selection) => {
|
|
let processing = &self.mode_settings(selection).post_processing;
|
|
(processing.model.as_deref(), processing.variant.as_deref())
|
|
}
|
|
ModelPickerTarget::VoiceAction => (
|
|
self.settings.voice_action.model.as_deref(),
|
|
self.settings.voice_action.variant.as_deref(),
|
|
),
|
|
}
|
|
}
|
|
|
|
fn selected_mode_inputs_mut(&mut self) -> &mut ModeInputs {
|
|
self.mode_inputs_mut(self.selected_mode)
|
|
}
|
|
|
|
fn select_mode(
|
|
&mut self,
|
|
selection: ModeSelection,
|
|
window: &mut Window,
|
|
cx: &mut Context<Self>,
|
|
) {
|
|
self.selected_mode = selection;
|
|
self.close_application_picker(cx);
|
|
self.application_picker_error = None;
|
|
self.transformation_picker_open = false;
|
|
self.variant_picker_open = None;
|
|
self.model_picker_highlight = 0;
|
|
self.mode_delete_armed = false;
|
|
self.mode_context_menu = None;
|
|
window.blur();
|
|
cx.notify();
|
|
}
|
|
|
|
fn close_application_picker(&mut self, cx: &mut Context<Self>) {
|
|
self.application_picker_open = false;
|
|
self.application_picker_highlight = 0;
|
|
self.application_search
|
|
.entity
|
|
.update(cx, |input, cx| input.set_text("", cx));
|
|
}
|
|
|
|
fn mode_inputs_mut(&mut self, selection: ModeSelection) -> &mut ModeInputs {
|
|
&mut self.mode_editor_mut(selection).inputs
|
|
}
|
|
|
|
fn mode_inputs_for(&self, selection: ModeSelection) -> &ModeInputs {
|
|
&self.mode_editor_for(selection).inputs
|
|
}
|
|
|
|
fn selected_mode_settings(&self) -> &DictationMode {
|
|
self.mode_settings(self.selected_mode)
|
|
}
|
|
|
|
fn mode_settings(&self, selection: ModeSelection) -> &DictationMode {
|
|
&self.mode_editor_for(selection).settings
|
|
}
|
|
|
|
fn mode_editor_for(&self, selection: ModeSelection) -> &ModeEditor {
|
|
match selection {
|
|
ModeSelection::Default => &self.mode_editors.default_mode,
|
|
ModeSelection::Custom(index) => &self.mode_editors.modes[index],
|
|
}
|
|
}
|
|
|
|
fn mode_editor_mut(&mut self, selection: ModeSelection) -> &mut ModeEditor {
|
|
match selection {
|
|
ModeSelection::Default => &mut self.mode_editors.default_mode,
|
|
ModeSelection::Custom(index) => &mut self.mode_editors.modes[index],
|
|
}
|
|
}
|
|
|
|
fn render_meetings(&mut self, cx: &mut Context<Self>) -> AnyElement {
|
|
let active_meeting = meeting::active(&self.meetings);
|
|
let action = match active_meeting.map(|meeting| meeting.status) {
|
|
_ if self.meeting_stop_pending => busy_label("Finalizing…").into_any_element(),
|
|
Some(MeetingStatus::Transcribing) => busy_label("Finalizing…").into_any_element(),
|
|
Some(MeetingStatus::Starting) => busy_label("Starting…").into_any_element(),
|
|
// Recording is a state, not the screen's main action: a neutral
|
|
// button in the same red-dot language as the Recording tag.
|
|
Some(MeetingStatus::Recording) => button(ButtonKind::Secondary, status_dot(DANGER))
|
|
.child("Stop & transcribe")
|
|
.children(active_meeting.map(|meeting| {
|
|
div()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child(meeting::format_duration(meeting_duration(meeting)))
|
|
}))
|
|
.id("stop-meeting")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.meeting_stop_pending = true;
|
|
if let Err(error) = this.meeting_requests.try_send(MeetingRequest::Stop) {
|
|
this.meeting_stop_pending = false;
|
|
log_meeting_request_error(error);
|
|
}
|
|
cx.notify();
|
|
}))
|
|
.into_any_element(),
|
|
_ if self.meeting_refresh_started_ms.is_some() => {
|
|
busy_label("Starting…").into_any_element()
|
|
}
|
|
_ => button(ButtonKind::Primary, "Start recording")
|
|
.id("start-meeting")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.meeting_refresh_started_ms = Some(now_ms());
|
|
if let Err(error) = this.meeting_requests.try_send(MeetingRequest::Start) {
|
|
this.meeting_refresh_started_ms = None;
|
|
log_meeting_request_error(error);
|
|
}
|
|
cx.notify();
|
|
}))
|
|
.into_any_element(),
|
|
};
|
|
let header_action = div()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.child(
|
|
div()
|
|
.w(px(SEARCH_FIELD_WIDTH))
|
|
.child(self.meeting_search.entity.clone()),
|
|
)
|
|
.child(action)
|
|
.into_any_element();
|
|
|
|
let now = now_ms();
|
|
let visible = self.visible_meetings(cx);
|
|
let searching = !self.meeting_query(cx).is_empty();
|
|
let mut rows: Vec<AnyElement> = Vec::new();
|
|
let mut current_day = None;
|
|
for (index, meeting) in visible.iter().enumerate() {
|
|
let day = meeting::day_label(meeting.created_at_ms, now);
|
|
if current_day.as_ref() != Some(&day) {
|
|
rows.push(list_section_label(day.clone(), rows.is_empty()).into_any_element());
|
|
current_day = Some(day);
|
|
}
|
|
let id = meeting.id.clone();
|
|
let selected = self.selected_meeting.as_deref() == Some(id.as_str());
|
|
let mut meta = vec![
|
|
meeting::clock(meeting.created_at_ms),
|
|
meeting_length(meeting_duration(meeting)),
|
|
];
|
|
meta.extend(meeting.app.clone());
|
|
rows.push(
|
|
list_row(selected)
|
|
.id(("meeting", index))
|
|
.child(
|
|
div()
|
|
.w_full()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.child(
|
|
list_row_title(meeting::display_title(meeting), selected).flex_1(),
|
|
)
|
|
.when_some(
|
|
meeting_status_chip(
|
|
meeting.status,
|
|
self.meeting_stop_pending,
|
|
false,
|
|
),
|
|
|row, chip| row.child(chip),
|
|
),
|
|
)
|
|
.child(list_row_meta(meta.join(" · "), selected))
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
this.select_meeting(id.clone());
|
|
cx.notify();
|
|
}))
|
|
.into_any_element(),
|
|
);
|
|
}
|
|
|
|
let list = pane_list(
|
|
"meetings-list",
|
|
PANE_LIST_WIDTH,
|
|
(visible.is_empty() && self.meetings_error.is_none()).then_some(if searching {
|
|
"No meetings match."
|
|
} else {
|
|
"No meetings yet."
|
|
}),
|
|
"Meetings could not be loaded.",
|
|
self.meetings_error.clone(),
|
|
rows,
|
|
);
|
|
|
|
div()
|
|
.size_full()
|
|
.flex()
|
|
.flex_col()
|
|
.child(pane_header_with_action("Meetings", Some(header_action)))
|
|
.child(
|
|
pane_body().child(
|
|
pane_content()
|
|
.id("meetings-workspace")
|
|
.gap_3()
|
|
.when_some(self.meeting_runtime_error.clone(), |column, error| {
|
|
column.child(
|
|
error_panel("Meeting could not be recorded.", error).flex_none(),
|
|
)
|
|
})
|
|
.child(
|
|
div()
|
|
.flex_1()
|
|
.min_h(px(0.0))
|
|
.flex()
|
|
.gap_5()
|
|
.child(list)
|
|
.child(pane_detail(self.render_meeting_detail(cx))),
|
|
),
|
|
),
|
|
)
|
|
.into_any_element()
|
|
}
|
|
|
|
fn render_meeting_detail(&self, cx: &mut Context<Self>) -> AnyElement {
|
|
let Some(meeting) = self
|
|
.selected_meeting
|
|
.as_deref()
|
|
.and_then(|id| self.meetings.iter().find(|meeting| meeting.id == id))
|
|
.cloned()
|
|
else {
|
|
return detail_placeholder(if self.meetings.is_empty() {
|
|
"Record a call to see its notes and transcript here."
|
|
} else {
|
|
"Select a meeting."
|
|
});
|
|
};
|
|
let id = meeting.id.clone();
|
|
let active = meeting.status.is_active();
|
|
let recording = meeting.status == MeetingStatus::Recording && !self.meeting_stop_pending;
|
|
let title = meeting::display_title(&meeting);
|
|
let copied = |what: &'static str| {
|
|
self.meeting_copied
|
|
.as_ref()
|
|
.is_some_and(|(copied_id, copied)| copied_id == &id && *copied == what)
|
|
};
|
|
let action_of = |kind: ButtonKind, key: &'static str, label: &'static str| {
|
|
button(kind, label).id(SharedString::from(format!("meeting-action-{key}")))
|
|
};
|
|
let action =
|
|
|key: &'static str, label: &'static str| action_of(ButtonKind::Secondary, key, label);
|
|
let menu_action = |key: &'static str, item: Div| {
|
|
item.id(SharedString::from(format!("meeting-action-{key}")))
|
|
};
|
|
|
|
// Copy transcript and Rename stay visible; the rest live in the
|
|
// overflow menu, with Delete last.
|
|
let mut actions: Vec<AnyElement> = Vec::new();
|
|
let mut menu_items: Vec<AnyElement> = Vec::new();
|
|
if let Some(notes) = meeting.notes.clone() {
|
|
let id = id.clone();
|
|
menu_items.push(
|
|
menu_action(
|
|
"copy-notes",
|
|
menu_item(false).child(if copied("notes") {
|
|
"Copied"
|
|
} else {
|
|
"Copy summary"
|
|
}),
|
|
)
|
|
// Stays open so "Copied" confirms the copy.
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
cx.stop_propagation();
|
|
this.copy_meeting_text(id.clone(), "notes", meeting::notes_markdown(¬es), cx)
|
|
}))
|
|
.into_any_element(),
|
|
);
|
|
}
|
|
if !self.meeting_turns.is_empty() {
|
|
let id = id.clone();
|
|
let turns = self.meeting_turns.clone();
|
|
actions.push(
|
|
action(
|
|
"copy-transcript",
|
|
if copied("transcript") {
|
|
"Copied"
|
|
} else {
|
|
"Copy transcript"
|
|
},
|
|
)
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
this.copy_meeting_text(
|
|
id.clone(),
|
|
"transcript",
|
|
meeting::transcript_markdown(&turns),
|
|
cx,
|
|
)
|
|
}))
|
|
.into_any_element(),
|
|
);
|
|
}
|
|
if !active && self.meeting_rename.is_none() {
|
|
let (id, title) = (id.clone(), title.clone());
|
|
actions.push(
|
|
action("rename", "Rename")
|
|
.on_click(cx.listener(move |this, _, window, cx| {
|
|
this.start_meeting_rename(id.clone(), title.clone(), window, cx)
|
|
}))
|
|
.into_any_element(),
|
|
);
|
|
}
|
|
if !active {
|
|
let export_path = meeting.export_path.clone().filter(|path| path.exists());
|
|
let reveal_id = id.clone();
|
|
menu_items.push(
|
|
menu_action(
|
|
"reveal",
|
|
menu_item(false).child(if export_path.is_some() {
|
|
"Reveal Markdown"
|
|
} else {
|
|
"Reveal files"
|
|
}),
|
|
)
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
this.meeting_actions_open = false;
|
|
reveal_meeting(&reveal_id, export_path.as_deref());
|
|
cx.notify();
|
|
}))
|
|
.into_any_element(),
|
|
);
|
|
}
|
|
let notes_running = meeting::notes_in_progress(&meeting.id);
|
|
if meeting.status == MeetingStatus::Complete
|
|
&& self.apple_intelligence_availability().is_available()
|
|
{
|
|
if notes_running {
|
|
menu_items.push(
|
|
disabled_menu_item()
|
|
.child("Summarizing…")
|
|
.into_any_element(),
|
|
);
|
|
} else {
|
|
let id = id.clone();
|
|
menu_items.push(
|
|
menu_action(
|
|
"notes",
|
|
menu_item(false).child(if meeting.notes.is_some() {
|
|
"Regenerate summary"
|
|
} else {
|
|
"Summarize"
|
|
}),
|
|
)
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
this.meeting_actions_open = false;
|
|
if let Err(error) = this
|
|
.meeting_requests
|
|
.try_send(MeetingRequest::Summarize(id.clone()))
|
|
{
|
|
log_meeting_request_error(error);
|
|
}
|
|
cx.notify();
|
|
}))
|
|
.into_any_element(),
|
|
);
|
|
}
|
|
}
|
|
let armed = self.meeting_delete_armed.as_deref() == Some(id.as_str());
|
|
if !active && !notes_running && !armed {
|
|
let delete_id = id.clone();
|
|
if !menu_items.is_empty() {
|
|
menu_items.push(menu_separator().into_any_element());
|
|
}
|
|
menu_items.push(
|
|
menu_action("delete", danger_menu_item().child("Delete…"))
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
this.meeting_actions_open = false;
|
|
this.trash_meeting(delete_id.clone(), cx)
|
|
}))
|
|
.into_any_element(),
|
|
);
|
|
}
|
|
if !menu_items.is_empty() {
|
|
let trigger = icon_button(ButtonKind::Secondary, Icon::Ellipsis)
|
|
.id("meeting-action-more")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.meeting_actions_open = true;
|
|
cx.notify();
|
|
}));
|
|
actions.push(
|
|
div()
|
|
.relative()
|
|
.child(trigger)
|
|
.when(self.meeting_actions_open, |more| {
|
|
more.child(deferred(
|
|
dropdown_menu()
|
|
.id("meeting-actions-menu")
|
|
.debug_selector(|| "meeting-actions-menu".into())
|
|
.left_0()
|
|
.w(px(MENU_WIDTH))
|
|
.on_mouse_down_out(cx.listener(|this, _, _, cx| {
|
|
this.meeting_actions_open = false;
|
|
cx.notify();
|
|
}))
|
|
.children(menu_items),
|
|
))
|
|
})
|
|
.into_any_element(),
|
|
);
|
|
}
|
|
if !active && !notes_running && armed {
|
|
// The confirmation takes the whole row until it is answered.
|
|
actions.clear();
|
|
let delete_id = id.clone();
|
|
actions.push(
|
|
action_of(
|
|
ButtonKind::Danger,
|
|
"delete",
|
|
if meeting
|
|
.export_path
|
|
.as_ref()
|
|
.is_some_and(|path| path.exists())
|
|
{
|
|
"Trash recording & Markdown"
|
|
} else {
|
|
"Trash recording"
|
|
},
|
|
)
|
|
.on_click(
|
|
cx.listener(move |this, _, _, cx| this.trash_meeting(delete_id.clone(), cx)),
|
|
)
|
|
.into_any_element(),
|
|
);
|
|
actions.push(
|
|
action("cancel-delete", "Cancel")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.meeting_delete_armed = None;
|
|
cx.notify();
|
|
}))
|
|
.into_any_element(),
|
|
);
|
|
}
|
|
|
|
let title_row: AnyElement = match &self.meeting_rename {
|
|
Some((rename_id, input)) if rename_id == &id => div()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.child(div().flex_1().min_w(px(0.0)).child(input.entity.clone()))
|
|
.child(
|
|
action("save-title", "Save")
|
|
.on_click(cx.listener(|this, _, _, cx| this.finish_meeting_rename(cx))),
|
|
)
|
|
.child(
|
|
action("cancel-title", "Cancel").on_click(cx.listener(|this, _, _, cx| {
|
|
this.meeting_rename = None;
|
|
cx.notify();
|
|
})),
|
|
)
|
|
.into_any_element(),
|
|
_ => detail_title(title).into_any_element(),
|
|
};
|
|
|
|
let mut meta = vec![
|
|
meeting::day_label(meeting.created_at_ms, now_ms()),
|
|
meeting::clock(meeting.created_at_ms),
|
|
meeting::format_duration(meeting_duration(&meeting)),
|
|
];
|
|
meta.extend(meeting.app.clone());
|
|
|
|
let errors = [
|
|
self.meeting_action_error
|
|
.clone()
|
|
.map(|error| ("Meeting could not be updated.", error)),
|
|
meeting
|
|
.error
|
|
.clone()
|
|
.map(|error| ("Recording failed.", error)),
|
|
meeting
|
|
.export_error
|
|
.clone()
|
|
.map(|error| ("Markdown not saved.", error)),
|
|
meeting
|
|
.notes_error
|
|
.clone()
|
|
.filter(|_| !notes_running)
|
|
.map(|error| ("Notes could not be written.", error)),
|
|
meeting
|
|
.live_transcription_error
|
|
.clone()
|
|
.filter(|_| active)
|
|
.map(|error| ("Live draft unavailable.", error)),
|
|
]
|
|
.into_iter()
|
|
.flatten();
|
|
|
|
let notes = meeting.notes.clone().map(render_meeting_notes).or_else(|| {
|
|
notes_running.then(|| {
|
|
div()
|
|
.pb_5()
|
|
.text_footnote()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child("Writing a title and summary with Apple Intelligence…")
|
|
})
|
|
});
|
|
|
|
let transcript = match &self.meeting_transcript {
|
|
MeetingTranscript::Empty => empty_state("No transcript selected."),
|
|
MeetingTranscript::Loaded(lines) if lines.is_empty() => {
|
|
empty_state(match meeting.status {
|
|
MeetingStatus::Starting => "Preparing local audio capture…",
|
|
MeetingStatus::Recording if meeting.live_transcription_error.is_some() => {
|
|
"Live transcription is unavailable. Audio is still recording safely."
|
|
}
|
|
MeetingStatus::Recording if self.meeting_stop_pending => {
|
|
"Building the final transcript…"
|
|
}
|
|
MeetingStatus::Recording => "Listening for speech…",
|
|
MeetingStatus::Transcribing => "Building the final transcript…",
|
|
MeetingStatus::Complete => "No speech was transcribed.",
|
|
MeetingStatus::Interrupted | MeetingStatus::Failed => {
|
|
"No recoverable transcript is available."
|
|
}
|
|
})
|
|
}
|
|
MeetingTranscript::Loaded(lines) => div()
|
|
.w_full()
|
|
.flex()
|
|
.flex_col()
|
|
.gap_3()
|
|
.children(
|
|
lines
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(index, line)| transcript_turn(index, line)),
|
|
)
|
|
.when(recording, |turns| {
|
|
turns.child(
|
|
div()
|
|
.pt_1()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.text_caption()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child(status_dot(DANGER))
|
|
.child("Listening…"),
|
|
)
|
|
})
|
|
.into_any_element(),
|
|
MeetingTranscript::Unavailable(error) => {
|
|
error_message("Transcript unavailable.", error.clone())
|
|
}
|
|
};
|
|
let transcript_label = match meeting.status {
|
|
MeetingStatus::Starting | MeetingStatus::Recording if !self.meeting_stop_pending => {
|
|
"Live transcript"
|
|
}
|
|
MeetingStatus::Starting | MeetingStatus::Recording | MeetingStatus::Transcribing => {
|
|
"Draft transcript"
|
|
}
|
|
MeetingStatus::Complete => "Transcript",
|
|
MeetingStatus::Interrupted | MeetingStatus::Failed => "Recovered draft",
|
|
};
|
|
|
|
div()
|
|
.debug_selector(|| "meeting-detail".into())
|
|
.flex_1()
|
|
.min_w(px(0.0))
|
|
.h_full()
|
|
.overflow_hidden()
|
|
.flex()
|
|
.flex_col()
|
|
.child(detail_header(
|
|
title_row,
|
|
meeting_status_chip(meeting.status, self.meeting_stop_pending, true)
|
|
.map(IntoElement::into_any_element)
|
|
.into_iter()
|
|
.chain([truncated_line(FOOTNOTE, meta.join(" · "))
|
|
.flex_1()
|
|
.into_any_element()])
|
|
.collect(),
|
|
actions,
|
|
))
|
|
.child(
|
|
detail_body("meeting-transcript")
|
|
.track_scroll(&self.meeting_transcript_scroll)
|
|
.children(errors.map(|(message, error)| error_panel(message, error).mb_4()))
|
|
.when_some(notes, |content, notes| content.child(notes))
|
|
.child(
|
|
div()
|
|
.pb_3()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.child(section_label(transcript_label))
|
|
.when(recording, |label| label.child(status_dot(DANGER))),
|
|
)
|
|
.child(transcript),
|
|
)
|
|
.into_any_element()
|
|
}
|
|
|
|
fn render_commands(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
|
|
let config_path = self.personal_workspace.join("hex.config.ts");
|
|
let workspace_state = personal_workspace_state(
|
|
!self.preview && config_path.is_file(),
|
|
self.personal_workspace_receiver.is_some(),
|
|
&self.personal_commands_status,
|
|
);
|
|
let last_error = self
|
|
.personal_workspace_error
|
|
.clone()
|
|
.or_else(|| self.personal_commands_status.last_reload_error.clone());
|
|
let open_config = config_path.clone();
|
|
let config_control = match workspace_state {
|
|
PersonalWorkspaceState::Missing => button(ButtonKind::Secondary, "Create config")
|
|
.id("personal-commands-create")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.provision_personal_workspace();
|
|
cx.notify();
|
|
}))
|
|
.into_any_element(),
|
|
PersonalWorkspaceState::Creating => busy_label("Creating config…").into_any_element(),
|
|
PersonalWorkspaceState::Ready | PersonalWorkspaceState::Error => {
|
|
button(ButtonKind::Secondary, "Edit config")
|
|
.id("personal-commands-open-config")
|
|
.on_click(move |_, _, _| open_path(&open_config))
|
|
.into_any_element()
|
|
}
|
|
};
|
|
let copy_prompt = matches!(
|
|
workspace_state,
|
|
PersonalWorkspaceState::Ready | PersonalWorkspaceState::Error
|
|
)
|
|
.then(|| {
|
|
let copied = self.personal_commands_prompt_copied;
|
|
let workspace = self.personal_workspace.display();
|
|
let config = config_path.display();
|
|
let prompt = format!(
|
|
"Help me configure my Hex custom voice commands.\n\n\
|
|
Workspace: {workspace}\n\
|
|
Config: {config}\n\n\
|
|
Read AGENTS.md and .agents/skills/personal-commands/SKILL.md in the workspace \
|
|
before editing. Ask me what commands or dictation phrases I want, update \
|
|
hex.config.ts, and run `bun run check` from the workspace when finished. You \
|
|
may add npm packages when a command needs them."
|
|
);
|
|
button(
|
|
ButtonKind::Secondary,
|
|
if copied {
|
|
"Copied"
|
|
} else {
|
|
"Copy agent prompt"
|
|
},
|
|
)
|
|
.id("personal-commands-copy-prompt")
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
match arboard::Clipboard::new()
|
|
.and_then(|mut clipboard| clipboard.set_text(prompt.clone()))
|
|
{
|
|
Ok(()) => {
|
|
this.personal_commands_prompt_copied = true;
|
|
cx.notify();
|
|
}
|
|
Err(error) => {
|
|
tracing::warn!(%error, "could not copy personal command agent prompt")
|
|
}
|
|
}
|
|
}))
|
|
});
|
|
let commands_position = self.commands_toggle.render_position(window);
|
|
let commands_toggle_control = if self.pending_microphone_policy
|
|
== Some(MicrophonePolicyChange::KeepReadyAndEnableCommands)
|
|
{
|
|
button(
|
|
ButtonKind::Primary,
|
|
"Keep microphone ready & enable commands",
|
|
)
|
|
.id("confirm-enable-commands")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
cx.stop_propagation();
|
|
if let Err(error) = this.update_microphone_policy(
|
|
MicrophonePolicyChange::KeepReadyAndEnableCommands,
|
|
cx,
|
|
) {
|
|
tracing::error!(%error, "could not update microphone policy");
|
|
}
|
|
}))
|
|
.into_any_element()
|
|
} else {
|
|
div()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.child(
|
|
div()
|
|
.text_footnote()
|
|
.text_color(rgb(TEXT_SECONDARY))
|
|
.child("Voice commands"),
|
|
)
|
|
.child(toggle(commands_position))
|
|
.into_any_element()
|
|
};
|
|
let commands_control = div()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.child(config_control)
|
|
.when_some(copy_prompt, |controls, prompt| controls.child(prompt))
|
|
.child(div().mx_1().w(px(1.0)).h_5().bg(rgb(LINE)))
|
|
.child(
|
|
div()
|
|
.id("commands-enabled")
|
|
.flex()
|
|
.items_center()
|
|
.child(commands_toggle_control)
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
let enabled = !this.settings.commands_enabled;
|
|
if enabled && this.settings.release_microphone_while_idle {
|
|
this.pending_microphone_policy =
|
|
Some(MicrophonePolicyChange::KeepReadyAndEnableCommands);
|
|
cx.notify();
|
|
return;
|
|
}
|
|
if let Err(error) = this.developer_set_commands_enabled(enabled, cx) {
|
|
tracing::error!(%error, "could not save app settings");
|
|
}
|
|
})),
|
|
)
|
|
.into_any_element();
|
|
let context_label = self.current_context_label();
|
|
let query = self
|
|
.command_search
|
|
.entity
|
|
.read(cx)
|
|
.text()
|
|
.trim()
|
|
.to_lowercase();
|
|
let visible: Vec<usize> = self
|
|
.commands
|
|
.iter()
|
|
.enumerate()
|
|
.filter_map(|(index, command)| Self::command_matches(command, &query).then_some(index))
|
|
.collect();
|
|
let mut tasks = Vec::new();
|
|
for index in &visible {
|
|
let task = self.commands[*index].task.clone();
|
|
if !tasks.contains(&task) {
|
|
tasks.push(task);
|
|
}
|
|
}
|
|
let effective_selected = self
|
|
.selected_command
|
|
.clone()
|
|
.filter(|id| visible.iter().any(|index| self.commands[*index].id == *id))
|
|
.or_else(|| {
|
|
visible
|
|
.first()
|
|
.map(|index| self.commands[*index].id.clone())
|
|
});
|
|
let mut groups: Vec<AnyElement> = Vec::new();
|
|
for task in tasks {
|
|
groups.push(list_section_label(task.clone(), groups.is_empty()).into_any_element());
|
|
groups.extend(
|
|
visible
|
|
.iter()
|
|
.copied()
|
|
.filter(|index| self.commands[*index].task == task)
|
|
.map(|index| {
|
|
let command = self.commands[index].clone();
|
|
let command_id = command.id.clone();
|
|
let selected = effective_selected.as_deref() == Some(command_id.as_str());
|
|
list_row(selected)
|
|
.id(("command", index))
|
|
.gap_0p5()
|
|
.child(list_row_title(command.phrase, selected))
|
|
.child(list_row_meta(command.description, selected))
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
this.selected_command = Some(command_id.clone());
|
|
cx.notify();
|
|
}))
|
|
.into_any_element()
|
|
}),
|
|
);
|
|
}
|
|
|
|
let no_commands = groups.is_empty();
|
|
div()
|
|
.size_full()
|
|
.flex()
|
|
.flex_col()
|
|
.child(pane_header_with_action("Commands", Some(commands_control)))
|
|
.child(
|
|
pane_body().child(
|
|
pane_content()
|
|
.gap_3()
|
|
.when_some(last_error, |column, error| {
|
|
column.child(
|
|
error_panel("Personal commands are not loading.", error)
|
|
.flex_none(),
|
|
)
|
|
})
|
|
.child(
|
|
div()
|
|
.flex_1()
|
|
.min_h(px(0.0))
|
|
.flex()
|
|
.gap_5()
|
|
.child(
|
|
div()
|
|
.w(px(PANE_LIST_WIDTH))
|
|
.h_full()
|
|
.flex_none()
|
|
.flex()
|
|
.flex_col()
|
|
.gap_2()
|
|
.child(
|
|
div()
|
|
.flex_none()
|
|
.child(self.command_search.entity.clone()),
|
|
)
|
|
.child(
|
|
pane_list(
|
|
"commands-list",
|
|
PANE_LIST_WIDTH,
|
|
no_commands.then_some(if query.is_empty() {
|
|
"No commands yet."
|
|
} else {
|
|
"No matching commands."
|
|
}),
|
|
"",
|
|
None,
|
|
groups,
|
|
)
|
|
.flex_1()
|
|
.min_h(px(0.0)),
|
|
),
|
|
)
|
|
.child(
|
|
pane_detail(self.render_command_detail(
|
|
effective_selected.as_deref(),
|
|
&context_label,
|
|
))
|
|
.id("command-detail"),
|
|
),
|
|
),
|
|
),
|
|
)
|
|
.into_any_element()
|
|
}
|
|
|
|
fn render_command_detail(&self, selected: Option<&str>, context_label: &str) -> AnyElement {
|
|
let Some(command) =
|
|
selected.and_then(|id| self.commands.iter().find(|command| command.id == id))
|
|
else {
|
|
return detail_placeholder("Select a command.");
|
|
};
|
|
let aliases = if command.aliases.is_empty() {
|
|
"None".into()
|
|
} else {
|
|
command.aliases.join("\n")
|
|
};
|
|
div()
|
|
.size_full()
|
|
.flex()
|
|
.flex_col()
|
|
.child(detail_header(
|
|
detail_title(command.phrase.clone()),
|
|
vec![command.description.clone().into_any_element()],
|
|
Vec::new(),
|
|
))
|
|
.child(
|
|
detail_body("command-detail-body")
|
|
.pt_1()
|
|
.child(detail_row("Task", command.task.clone()))
|
|
.child(detail_row("Context", command_scope(&command.scope)))
|
|
.child(detail_row("Aliases", aliases))
|
|
.child(detail_row("Current context", context_label.to_string())),
|
|
)
|
|
.into_any_element()
|
|
}
|
|
|
|
fn command_search_input(cx: &mut Context<Self>) -> ProcessingInput {
|
|
let entity = cx.new(|cx| TextInput::picker(cx, "Search commands", ""));
|
|
let changed = cx.subscribe(&entity, |_, _, _: &TextChanged, cx| {
|
|
cx.notify();
|
|
});
|
|
ProcessingInput {
|
|
entity,
|
|
_subscriptions: vec![changed],
|
|
}
|
|
}
|
|
|
|
/// Case-insensitive match over everything a person might remember about a
|
|
/// command: its phrase, aliases, description, and group.
|
|
fn command_matches(command: &CatalogCommand, query: &str) -> bool {
|
|
if query.is_empty() {
|
|
return true;
|
|
}
|
|
let scope = match &command.scope {
|
|
CommandScope::Sleeping | CommandScope::Global => "global",
|
|
CommandScope::Application(name) => name,
|
|
CommandScope::Browser(host) => host,
|
|
};
|
|
command.phrase.to_lowercase().contains(query)
|
|
|| command.description.to_lowercase().contains(query)
|
|
|| command.task.to_lowercase().contains(query)
|
|
|| scope.to_lowercase().contains(query)
|
|
|| command
|
|
.aliases
|
|
.iter()
|
|
.any(|alias| alias.to_lowercase().contains(query))
|
|
}
|
|
|
|
fn current_context(&self) -> (Option<String>, Option<String>) {
|
|
self.current_context.clone()
|
|
}
|
|
|
|
fn current_context_label(&self) -> String {
|
|
let (application, browser_host) = self.current_context();
|
|
match (application, browser_host) {
|
|
(Some(application), Some(host)) => format!("{application} / {host}"),
|
|
(Some(application), None) => application,
|
|
_ => "Unavailable".into(),
|
|
}
|
|
}
|
|
|
|
fn render_activity(&mut self, cx: &mut Context<Self>) -> AnyElement {
|
|
let refresh = button(ButtonKind::Secondary, "Refresh")
|
|
.id("refresh-activity")
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.reload_events();
|
|
cx.notify();
|
|
}))
|
|
.into_any_element();
|
|
let header_action = div()
|
|
.flex()
|
|
.items_center()
|
|
.gap_4()
|
|
.when_some(self.activity.state_label(), |actions, status| {
|
|
let active = self.activity.state != Some(VoiceState::Stopping);
|
|
actions.child(listener_status(
|
|
status,
|
|
self.activity.device.clone().unwrap_or_default(),
|
|
active,
|
|
))
|
|
})
|
|
.child(refresh)
|
|
.into_any_element();
|
|
let rows: Vec<AnyElement> = self
|
|
.events
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(index, event)| {
|
|
let selected = self.selected_event == Some(index);
|
|
let summary = event_summary(event);
|
|
let age = event_age(event.timestamp_ms());
|
|
let boundary = matches!(event, VoiceEvent::SessionStarted { .. });
|
|
timestamped_list_row(
|
|
("activity-event", index),
|
|
selected,
|
|
age,
|
|
div()
|
|
.flex_1()
|
|
.map(|text| {
|
|
if boundary {
|
|
text.text_caption()
|
|
.font_weight(FontWeight::SEMIBOLD)
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
} else {
|
|
text.text_body().text_color(rgb(TEXT_SECONDARY))
|
|
}
|
|
})
|
|
.child(summary),
|
|
)
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
this.selected_event = Some(index);
|
|
cx.notify();
|
|
}))
|
|
.into_any_element()
|
|
})
|
|
.collect();
|
|
|
|
div()
|
|
.size_full()
|
|
.flex()
|
|
.flex_col()
|
|
.child(pane_header_with_action("Activity", Some(header_action)))
|
|
.child(
|
|
pane_body().child(
|
|
pane_content()
|
|
.flex_row()
|
|
.gap_5()
|
|
.child(pane_list(
|
|
"activity-list",
|
|
PANE_LIST_WIDTH,
|
|
(self.events.is_empty() && self.activity.error.is_none())
|
|
.then_some("No activity yet."),
|
|
"Activity could not be loaded.",
|
|
self.activity.error.clone(),
|
|
rows,
|
|
))
|
|
.child(pane_detail(self.render_event_detail())),
|
|
),
|
|
)
|
|
.into_any_element()
|
|
}
|
|
|
|
fn render_event_detail(&self) -> AnyElement {
|
|
let Some(event) = self.selected_event.and_then(|index| self.events.get(index)) else {
|
|
return detail_placeholder("Select an activity row.");
|
|
};
|
|
let raw = serde_json::to_string(event).unwrap_or_else(|error| error.to_string());
|
|
div()
|
|
.id("activity-detail")
|
|
.flex_1()
|
|
.min_w(px(0.0))
|
|
.h_full()
|
|
.overflow_y_scroll()
|
|
.px_6()
|
|
.py_6()
|
|
.child(div().text_headline().child(event_summary(event)))
|
|
.child(
|
|
div()
|
|
.pt_6()
|
|
.child(detail_row("Event", event.kind()))
|
|
.child(detail_row(
|
|
"Timestamp",
|
|
format!("{} ms", event.timestamp_ms()),
|
|
)),
|
|
)
|
|
.child(
|
|
div()
|
|
.mt_6()
|
|
.pt_5()
|
|
.border_t_1()
|
|
.border_color(rgb(LINE))
|
|
.child(section_label("Raw event"))
|
|
.child(
|
|
div()
|
|
.pt_2()
|
|
.text_footnote()
|
|
.text_monospace()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child(raw),
|
|
),
|
|
)
|
|
.into_any_element()
|
|
}
|
|
fn apply_hud_lab(&self) {
|
|
self.indicator
|
|
.send(DictationIndicatorEvent::Configure(self.hud_tuning));
|
|
self.indicator.send(DictationIndicatorEvent::Reset);
|
|
match self.hud_demo {
|
|
HudDemoState::Recording => {
|
|
for job_id in 0..self.hud_queued as u64 {
|
|
self.indicator
|
|
.send(DictationIndicatorEvent::Submitted { job_id });
|
|
self.indicator
|
|
.send(DictationIndicatorEvent::Transcribing { job_id });
|
|
}
|
|
self.indicator.send(DictationIndicatorEvent::Started);
|
|
self.indicator.send(DictationIndicatorEvent::Meter {
|
|
average: 0.08,
|
|
peak: 0.42,
|
|
});
|
|
}
|
|
HudDemoState::Transcribing | HudDemoState::Processing => {
|
|
self.indicator
|
|
.send(DictationIndicatorEvent::Submitted { job_id: 0 });
|
|
self.indicator.send(match self.hud_demo {
|
|
HudDemoState::Transcribing => {
|
|
DictationIndicatorEvent::Transcribing { job_id: 0 }
|
|
}
|
|
HudDemoState::Processing => DictationIndicatorEvent::Processing { job_id: 0 },
|
|
HudDemoState::Recording => unreachable!(),
|
|
});
|
|
for job_id in 1..=self.hud_queued as u64 {
|
|
self.indicator
|
|
.send(DictationIndicatorEvent::Submitted { job_id });
|
|
self.indicator
|
|
.send(DictationIndicatorEvent::Transcribing { job_id });
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn hud_control_value(&self, control: HudControl) -> f32 {
|
|
match control {
|
|
HudControl::LineCount => (self.hud_tuning.line_count - 1.0) / 5.0,
|
|
HudControl::Curvature => self.hud_tuning.curvature,
|
|
HudControl::Speed => self.hud_tuning.speed / HUD_MAX_SPEED,
|
|
HudControl::Blur => 1.0 - self.hud_tuning.sharpness,
|
|
HudControl::Glow => self.hud_tuning.glow,
|
|
HudControl::Depth => self.hud_tuning.depth,
|
|
HudControl::LightAngle => self.hud_tuning.light_angle,
|
|
HudControl::Outline => self.hud_tuning.outline,
|
|
}
|
|
.clamp(0.0, 1.0)
|
|
}
|
|
|
|
fn set_hud_control(&mut self, control: HudControl, value: f32, cx: &mut Context<Self>) {
|
|
let value = value.clamp(0.0, 1.0);
|
|
match control {
|
|
HudControl::LineCount => self.hud_tuning.line_count = (1.0 + value * 5.0).round(),
|
|
HudControl::Curvature => self.hud_tuning.curvature = value,
|
|
HudControl::Speed => self.hud_tuning.speed = value * HUD_MAX_SPEED,
|
|
HudControl::Blur => self.hud_tuning.sharpness = 1.0 - value,
|
|
HudControl::Glow => self.hud_tuning.glow = value,
|
|
HudControl::Depth => self.hud_tuning.depth = value,
|
|
HudControl::LightAngle => self.hud_tuning.light_angle = value,
|
|
HudControl::Outline => self.hud_tuning.outline = value,
|
|
}
|
|
self.hud_copied = false;
|
|
self.indicator
|
|
.send(DictationIndicatorEvent::Configure(self.hud_tuning));
|
|
cx.notify();
|
|
}
|
|
|
|
fn update_hud_from_pointer(
|
|
&mut self,
|
|
control: HudControl,
|
|
pointer_x: f32,
|
|
window: &Window,
|
|
cx: &mut Context<Self>,
|
|
) {
|
|
const SLIDER_WIDTH: f32 = 360.0;
|
|
let available = (f32::from(window.viewport_size().width) - SIDEBAR_WIDTH - 64.0).max(0.0);
|
|
let content_width = available.min(PANE_CONTENT_WIDTH);
|
|
let slider_left = SIDEBAR_WIDTH + 32.0 + (available - content_width) / 2.0;
|
|
self.set_hud_control(control, (pointer_x - slider_left) / SLIDER_WIDTH, cx);
|
|
}
|
|
|
|
fn select_hud_style(&mut self, style: usize, cx: &mut Context<Self>) {
|
|
self.hud_tuning = match style {
|
|
0 => HudTuning {
|
|
style: 0.0,
|
|
line_count: 1.0,
|
|
curvature: 0.5,
|
|
speed: 0.7,
|
|
sharpness: 0.42,
|
|
glow: 0.4,
|
|
depth: 0.75,
|
|
light_angle: 0.35,
|
|
outline: 0.25,
|
|
},
|
|
1 => HudTuning::default(),
|
|
_ => HudTuning {
|
|
style: 2.0,
|
|
line_count: 3.0,
|
|
curvature: 0.7,
|
|
speed: 0.9,
|
|
sharpness: 0.64,
|
|
glow: 0.28,
|
|
depth: 0.74,
|
|
light_angle: 0.35,
|
|
outline: 0.3,
|
|
},
|
|
};
|
|
self.hud_copied = false;
|
|
self.apply_hud_lab();
|
|
cx.notify();
|
|
}
|
|
|
|
fn hud_preset(&self) -> String {
|
|
format!(
|
|
"hud-v1 style={} lines={:.0} curvature={:.2} speed={:.2} blur={:.2} glow={:.2} depth={:.2} light={:.2} outline={:.2}",
|
|
self.hud_tuning.style as usize,
|
|
self.hud_tuning.line_count,
|
|
self.hud_tuning.curvature,
|
|
self.hud_tuning.speed,
|
|
1.0 - self.hud_tuning.sharpness,
|
|
self.hud_tuning.glow,
|
|
self.hud_tuning.depth,
|
|
self.hud_tuning.light_angle,
|
|
self.hud_tuning.outline,
|
|
)
|
|
}
|
|
|
|
fn render_hud_slider(
|
|
&self,
|
|
control: HudControl,
|
|
label: &'static str,
|
|
cx: &mut Context<Self>,
|
|
) -> AnyElement {
|
|
let value = self.hud_control_value(control);
|
|
let display = match control {
|
|
HudControl::LineCount => format!("{:.0}", self.hud_tuning.line_count),
|
|
HudControl::Speed => format!("{:.2}x", self.hud_tuning.speed),
|
|
HudControl::LightAngle => format!("{:.0}°", self.hud_tuning.light_angle * 360.0),
|
|
_ => format!("{:.2}", value),
|
|
};
|
|
div()
|
|
.w(px(360.0))
|
|
.flex()
|
|
.flex_col()
|
|
.gap_2()
|
|
.child(
|
|
div()
|
|
.flex()
|
|
.justify_between()
|
|
.text_footnote()
|
|
.child(label)
|
|
.child(div().text_color(rgb(TEXT_TERTIARY)).child(display)),
|
|
)
|
|
.child(
|
|
div()
|
|
.id(("hud-slider", control as usize))
|
|
.relative()
|
|
.w_full()
|
|
.h(px(18.0))
|
|
.child(
|
|
div()
|
|
.absolute()
|
|
.left_0()
|
|
.right_0()
|
|
.top(px(7.0))
|
|
.h(px(4.0))
|
|
.rounded_full()
|
|
.bg(rgb(SURFACE_SELECTED)),
|
|
)
|
|
.child(
|
|
div()
|
|
.absolute()
|
|
.left_0()
|
|
.top(px(7.0))
|
|
.w(relative(value))
|
|
.h(px(4.0))
|
|
.rounded_full()
|
|
.bg(rgb(ACCENT)),
|
|
)
|
|
.child(
|
|
div()
|
|
.absolute()
|
|
.left(relative(value))
|
|
.top(px(2.0))
|
|
.ml(px(-7.0))
|
|
.size(px(14.0))
|
|
.rounded_full()
|
|
.border_2()
|
|
.border_color(rgb(TEXT_PRIMARY))
|
|
.bg(rgb(SURFACE_SELECTED)),
|
|
)
|
|
.on_mouse_down(
|
|
MouseButton::Left,
|
|
cx.listener(move |this, event: &MouseDownEvent, window, cx| {
|
|
this.hud_dragging = Some(control);
|
|
this.update_hud_from_pointer(
|
|
control,
|
|
f32::from(event.position.x),
|
|
window,
|
|
cx,
|
|
);
|
|
}),
|
|
)
|
|
.on_mouse_move(
|
|
cx.listener(move |this, event: &MouseMoveEvent, window, cx| {
|
|
if event.dragging() && this.hud_dragging == Some(control) {
|
|
this.update_hud_from_pointer(
|
|
control,
|
|
f32::from(event.position.x),
|
|
window,
|
|
cx,
|
|
);
|
|
}
|
|
}),
|
|
),
|
|
)
|
|
.into_any_element()
|
|
}
|
|
|
|
fn render_hud_lab(&mut self, cx: &mut Context<Self>) -> AnyElement {
|
|
let styles = [
|
|
(
|
|
"A",
|
|
"Moving light",
|
|
"A line-free area light travels around the orb.",
|
|
),
|
|
(
|
|
"B",
|
|
"Meridians",
|
|
"Highlights wrap around the sphere instead of crossing it.",
|
|
),
|
|
(
|
|
"C",
|
|
"Ribbons",
|
|
"Curved bands retained for comparison and tuning.",
|
|
),
|
|
];
|
|
let style_cards =
|
|
styles
|
|
.into_iter()
|
|
.enumerate()
|
|
.map(|(index, (key, name, description))| {
|
|
let selected = self.hud_tuning.style as usize == index;
|
|
div()
|
|
.id(("hud-style", index))
|
|
.w(px(190.0))
|
|
.p_3()
|
|
.flex()
|
|
.flex_col()
|
|
.gap_1()
|
|
.rounded(RADIUS_PANEL)
|
|
.border_1()
|
|
.border_color(rgb(if selected { ACCENT } else { LINE }))
|
|
.bg(rgb(if selected { ACCENT_SURFACE } else { SURFACE }))
|
|
.hover(|card| card.bg(rgb(SURFACE_HOVER)))
|
|
.child(div().text_caption().text_color(rgb(ACCENT_TEXT)).child(key))
|
|
.child(
|
|
div()
|
|
.text_body()
|
|
.font_weight(FontWeight::MEDIUM)
|
|
.child(name),
|
|
)
|
|
.child(
|
|
div()
|
|
.text_caption()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child(description),
|
|
)
|
|
.on_click(
|
|
cx.listener(move |this, _, _, cx| this.select_hud_style(index, cx)),
|
|
)
|
|
});
|
|
let state_button = |state, label: &'static str, index: usize| {
|
|
segmented_item(self.hud_demo == state)
|
|
.id(("hud-state", index))
|
|
.child(label)
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
this.hud_demo = state;
|
|
this.apply_hud_lab();
|
|
cx.notify();
|
|
}))
|
|
};
|
|
let queue_buttons = (0..=3).map(|count| {
|
|
segmented_item(self.hud_queued == count)
|
|
.id(("hud-queue", count))
|
|
.child(count.to_string())
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
this.hud_queued = count;
|
|
this.apply_hud_lab();
|
|
cx.notify();
|
|
}))
|
|
});
|
|
let preset = self.hud_preset();
|
|
let copied = self.hud_copied;
|
|
|
|
div()
|
|
.size_full()
|
|
.flex()
|
|
.flex_col()
|
|
.on_mouse_up(
|
|
MouseButton::Left,
|
|
cx.listener(|this, _, _, _| {
|
|
this.hud_dragging = None;
|
|
}),
|
|
)
|
|
.child(pane_header_with_action(
|
|
"HUD Lab",
|
|
Some(
|
|
button(
|
|
ButtonKind::Secondary,
|
|
if copied { "Copied" } else { "Copy preset" },
|
|
)
|
|
.id("copy-hud-preset")
|
|
.on_click(cx.listener(move |this, _, _, cx| {
|
|
if let Ok(mut clipboard) = arboard::Clipboard::new() {
|
|
let _ = clipboard.set_text(this.hud_preset());
|
|
this.hud_copied = true;
|
|
cx.notify();
|
|
}
|
|
}))
|
|
.into_any_element(),
|
|
),
|
|
))
|
|
.child(pane_scroll_body(
|
|
"hud-lab-scroll",
|
|
pane_content()
|
|
.pt_6()
|
|
.gap_6()
|
|
.child(
|
|
div()
|
|
.flex()
|
|
.items_center()
|
|
.gap_4()
|
|
.child(segmented_control().children([
|
|
state_button(HudDemoState::Recording, "Recording", 0),
|
|
state_button(HudDemoState::Transcribing, "Transcribing", 1),
|
|
state_button(HudDemoState::Processing, "Processing", 2),
|
|
]))
|
|
.child(
|
|
div()
|
|
.flex()
|
|
.items_center()
|
|
.gap_2()
|
|
.child(
|
|
div()
|
|
.text_caption()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child("Queued"),
|
|
)
|
|
.child(segmented_control().children(queue_buttons)),
|
|
),
|
|
)
|
|
.child(div().flex().gap_3().children(style_cards))
|
|
.child(
|
|
div()
|
|
.flex()
|
|
.child(div().flex().flex_col().gap_4().children([
|
|
self.render_hud_slider(HudControl::LineCount, "Line count", cx),
|
|
self.render_hud_slider(HudControl::Curvature, "Curvature", cx),
|
|
self.render_hud_slider(HudControl::Speed, "Speed", cx),
|
|
self.render_hud_slider(HudControl::Blur, "Highlight blur", cx),
|
|
self.render_hud_slider(HudControl::Glow, "Line glow", cx),
|
|
self.render_hud_slider(HudControl::Depth, "Sphere depth", cx),
|
|
self.render_hud_slider(HudControl::LightAngle, "Light angle", cx),
|
|
self.render_hud_slider(HudControl::Outline, "Sphere outline", cx),
|
|
])),
|
|
)
|
|
.child(
|
|
div()
|
|
.p_3()
|
|
.rounded(RADIUS_PANEL)
|
|
.border_1()
|
|
.border_color(rgb(LINE))
|
|
.bg(rgb(SURFACE))
|
|
.text_monospace()
|
|
.text_caption()
|
|
.text_color(rgb(TEXT_SECONDARY))
|
|
.child(preset),
|
|
),
|
|
))
|
|
.into_any_element()
|
|
}
|
|
}
|
|
|
|
fn application_catalog_load_needed(
|
|
preview: bool,
|
|
catalog: &ApplicationCatalogState,
|
|
receiver_pending: bool,
|
|
) -> bool {
|
|
!preview && matches!(catalog, ApplicationCatalogState::Loading) && !receiver_pending
|
|
}
|
|
|
|
impl Drop for AppWindow {
|
|
fn drop(&mut self) {
|
|
if !self.preview
|
|
&& self.settings_dirty
|
|
&& let Err(error) = self.settings_candidate().save()
|
|
{
|
|
tracing::error!(%error, "could not flush app settings while closing window");
|
|
}
|
|
if !self.preview {
|
|
crate::app_settings::set_hotkey_capture_active(false);
|
|
crate::app_settings::set_dock_icon_visible(crate::app_settings::dock_icon_visible(
|
|
self.settings.show_dock_icon,
|
|
crate::status_item::installed(),
|
|
));
|
|
}
|
|
}
|
|
}
|
|
|
|
impl TranscriptionPickerDelegate for AppWindow {
|
|
fn cancel_transcription_preparation(&mut self) {
|
|
self.cancel_transcription_download();
|
|
}
|
|
|
|
fn choose_transcription_model(
|
|
&mut self,
|
|
model: TranscriptionModelId,
|
|
language: String,
|
|
cx: &mut Context<Self>,
|
|
) {
|
|
AppWindow::choose_transcription_model(self, definition(model), language, cx);
|
|
}
|
|
|
|
fn delete_transcription_model(&mut self, model: TranscriptionModelId, _cx: &mut Context<Self>) {
|
|
AppWindow::delete_transcription_model(self, definition(model));
|
|
}
|
|
|
|
fn dismiss_transcription_picker(&mut self, cx: &mut Context<Self>) {
|
|
AppWindow::dismiss_transcription_picker(self, cx);
|
|
}
|
|
|
|
fn select_transcription_language(&mut self, language: String, cx: &mut Context<Self>) {
|
|
if self.transcription_picker_language.as_deref() != Some(&language) {
|
|
self.cancel_transcription_download();
|
|
self.transcription_picker_language = Some(language);
|
|
self.clear_transcription_error();
|
|
cx.notify();
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Render for AppWindow {
|
|
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
|
let model_notice = self.render_model_notice(cx);
|
|
let content = match self.pane {
|
|
Pane::HudLab => self.render_hud_lab(cx),
|
|
Pane::Meetings => self.render_meetings(cx),
|
|
Pane::Commands => self.render_commands(window, cx),
|
|
Pane::Activity => self.render_activity(cx),
|
|
Pane::History => self.render_history(cx),
|
|
Pane::Modes => self.render_modes(window, cx),
|
|
Pane::VoiceAction => self.render_voice_action(window, cx),
|
|
Pane::Settings => self.render_settings(window, cx),
|
|
};
|
|
let transcription_picker = self
|
|
.transcription_picker_language
|
|
.clone()
|
|
.map(|language| self.render_transcription_picker(&language, cx));
|
|
let setup = self.setup_visible.then(|| self.render_setup(cx));
|
|
let mode_context_menu = (self.pane == Pane::Modes)
|
|
.then(|| self.render_mode_context_menu(cx))
|
|
.flatten();
|
|
window_frame()
|
|
.track_focus(&self.window_focus)
|
|
.on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| {
|
|
if event.keystroke.key != "escape" {
|
|
return;
|
|
}
|
|
if this.history_retention_open {
|
|
this.history_retention_open = false;
|
|
cx.stop_propagation();
|
|
cx.notify();
|
|
} else if this.mode_context_menu.take().is_some()
|
|
|| this.pending_microphone_policy.take().is_some()
|
|
{
|
|
cx.stop_propagation();
|
|
cx.notify();
|
|
} else if this.transcription_picker_language.is_some() {
|
|
cx.stop_propagation();
|
|
this.dismiss_transcription_picker(cx);
|
|
}
|
|
}))
|
|
.on_mouse_down(
|
|
MouseButton::Left,
|
|
cx.listener(|this, _, _, cx| {
|
|
if this.mode_context_menu.take().is_some() {
|
|
cx.notify();
|
|
}
|
|
}),
|
|
)
|
|
.on_action(|_: &CloseWindow, window, _| window.remove_window())
|
|
.on_action(|_: &MinimizeWindow, window, _| window.minimize_window())
|
|
.on_action(|_: &ToggleFullscreen, window, _| window.toggle_fullscreen())
|
|
.on_action(cx.listener(|this, _: &ShowSettings, window, cx| {
|
|
this.select_pane(Pane::Settings, cx);
|
|
window.activate_window();
|
|
}))
|
|
.on_action(cx.listener(|this, _: &ShowModes, window, cx| {
|
|
this.select_pane(Pane::Modes, cx);
|
|
window.activate_window();
|
|
}))
|
|
.on_action(cx.listener(|this, _: &ShowVoiceAction, window, cx| {
|
|
this.select_pane(Pane::VoiceAction, cx);
|
|
window.activate_window();
|
|
}))
|
|
.on_action(cx.listener(|this, _: &ShowCommands, window, cx| {
|
|
this.select_pane(Pane::Commands, cx);
|
|
window.activate_window();
|
|
}))
|
|
.on_action(cx.listener(|this, _: &ShowHistory, window, cx| {
|
|
this.select_pane(Pane::History, cx);
|
|
window.activate_window();
|
|
}))
|
|
.child(self.render_navigation(cx))
|
|
.child(
|
|
div()
|
|
.flex_1()
|
|
.min_w_0()
|
|
.h_full()
|
|
.flex()
|
|
.flex_col()
|
|
.overflow_hidden()
|
|
.children(model_notice)
|
|
.when_some(self.settings_load_error.clone(), |column, error| {
|
|
column.child(
|
|
div()
|
|
.px(px(PANE_GUTTER))
|
|
.py_2()
|
|
.debug_selector(|| "settings-error".into())
|
|
.child(error_message("Settings error:", error)),
|
|
)
|
|
})
|
|
.child(div().flex_1().min_h_0().child(content)),
|
|
)
|
|
.children(setup)
|
|
.children(transcription_picker)
|
|
.children(mode_context_menu)
|
|
}
|
|
}
|
|
|
|
/// Deterministic retained-history fixtures for the History pane preview.
|
|
fn preview_history() -> Option<History> {
|
|
use crate::history::{HistoryDraft, HistoryProcessing, HistoryStore, now_ms};
|
|
let directory =
|
|
std::env::temp_dir().join(format!("hex-history-preview-{}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&directory);
|
|
std::fs::create_dir_all(&directory).ok()?;
|
|
let mut store = HistoryStore::open(
|
|
directory.join("history.json"),
|
|
HistoryRetention::Week,
|
|
now_ms(),
|
|
);
|
|
let now = now_ms();
|
|
let fixtures = [
|
|
(
|
|
26 * 60 * 60 * 1_000,
|
|
HistoryKind::Dictation,
|
|
"so um the parser needs a retry when the socket drops",
|
|
"The parser needs a retry when the socket drops.",
|
|
Some("Zed"),
|
|
Some(("Work notes", 940)),
|
|
),
|
|
(
|
|
3 * 60 * 60 * 1_000,
|
|
HistoryKind::Send,
|
|
"sounds good shipping it after lunch",
|
|
"Sounds good — shipping it after lunch.",
|
|
Some("Slack"),
|
|
Some(("Messages", 610)),
|
|
),
|
|
(
|
|
42 * 60 * 1_000,
|
|
HistoryKind::VoiceAction,
|
|
"write a haiku about warm tea",
|
|
"Steam curls from the cup—\nafternoon light through the glass,\nthe first sip of calm.",
|
|
Some("Brave Browser"),
|
|
None,
|
|
),
|
|
(
|
|
4 * 60 * 1_000,
|
|
HistoryKind::Dictation,
|
|
"so um remember to publish the appcast after validating the artifact and uh \
|
|
double check that the release notes mention the new capture placeholders \
|
|
before anyone downloads it",
|
|
"Remember to publish the appcast after validating the artifact, and double-check \
|
|
that the release notes mention the new capture placeholders before anyone \
|
|
downloads it.",
|
|
Some("Messages"),
|
|
None,
|
|
),
|
|
];
|
|
for (age_ms, kind, raw, final_text, application, processing) in fixtures {
|
|
let _ = store.record(
|
|
HistoryDraft {
|
|
kind,
|
|
raw_text: raw.into(),
|
|
final_text: final_text.into(),
|
|
application: application.map(Into::into),
|
|
processing: processing.map(|(profile, latency_ms)| HistoryProcessing {
|
|
profile: profile.into(),
|
|
latency_ms,
|
|
fallback: None,
|
|
}),
|
|
audio_ms: 2_800,
|
|
inference_ms: 96,
|
|
total_ms: 3_400,
|
|
},
|
|
now.saturating_sub(age_ms),
|
|
);
|
|
}
|
|
Some(History::new(store))
|
|
}
|
|
|
|
fn voice_action_description(enabled: bool) -> &'static str {
|
|
if enabled {
|
|
"Use the shortcut below with OpenCode to run spoken instructions"
|
|
} else {
|
|
"Off by default. Its saved shortcut is not reserved until you enable Voice Action."
|
|
}
|
|
}
|
|
|
|
fn set_voice_action_enabled(settings: &mut AppSettings, enabled: bool) -> Result<(), &'static str> {
|
|
if enabled && hotkey_binding_conflicts(settings, HotkeyKind::Edit, &settings.edit_hotkey) {
|
|
return Err(
|
|
"The Voice Action shortcut is already in use. Change it below or change the other shortcut before enabling Voice Action.",
|
|
);
|
|
}
|
|
settings.voice_action.enabled = enabled;
|
|
Ok(())
|
|
}
|
|
|
|
fn hotkey_idle_width(keycap_count: usize) -> f32 {
|
|
(112.0 + hotkey_keycaps_width(keycap_count)).max(HOTKEY_MIN_WIDTH)
|
|
}
|
|
|
|
const fn hotkey_kind_index(kind: HotkeyKind) -> usize {
|
|
match kind {
|
|
HotkeyKind::Dictation => 0,
|
|
HotkeyKind::Edit => 1,
|
|
HotkeyKind::PasteLast => 2,
|
|
}
|
|
}
|
|
|
|
const fn hotkey_side_index(side: ModifierSide) -> usize {
|
|
match side {
|
|
ModifierSide::Left => 0,
|
|
ModifierSide::Either => 1,
|
|
ModifierSide::Right => 2,
|
|
}
|
|
}
|
|
|
|
fn normalize_captured_modifiers(modifiers: HotkeyModifiers) -> HotkeyModifiers {
|
|
let mut sides = [
|
|
modifiers.control,
|
|
modifiers.option,
|
|
modifiers.shift,
|
|
modifiers.command,
|
|
]
|
|
.into_iter()
|
|
.flatten();
|
|
let Some(first) = sides.next() else {
|
|
return modifiers;
|
|
};
|
|
if sides.all(|side| side == first) {
|
|
modifiers
|
|
} else {
|
|
modifiers.without_side_constraints()
|
|
}
|
|
}
|
|
|
|
fn standalone_modifier_side(binding: &HotkeyBinding) -> Option<ModifierSide> {
|
|
if binding.key.is_some() {
|
|
return None;
|
|
}
|
|
let mut sides = [
|
|
binding.modifiers.control,
|
|
binding.modifiers.option,
|
|
binding.modifiers.shift,
|
|
binding.modifiers.command,
|
|
]
|
|
.into_iter()
|
|
.flatten();
|
|
let first = sides.next()?;
|
|
sides.all(|side| side == first).then_some(first)
|
|
}
|
|
|
|
fn set_standalone_modifier_side(binding: &mut HotkeyBinding, side: ModifierSide) {
|
|
if standalone_modifier_side(binding).is_none() {
|
|
return;
|
|
}
|
|
for current in [
|
|
&mut binding.modifiers.control,
|
|
&mut binding.modifiers.option,
|
|
&mut binding.modifiers.shift,
|
|
&mut binding.modifiers.command,
|
|
] {
|
|
if current.is_some() {
|
|
*current = Some(side);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn hotkey_binding_conflicts(
|
|
settings: &AppSettings,
|
|
kind: HotkeyKind,
|
|
binding: &HotkeyBinding,
|
|
) -> bool {
|
|
let mut others = match kind {
|
|
HotkeyKind::Dictation => Vec::new(),
|
|
HotkeyKind::Edit | HotkeyKind::PasteLast => vec![settings.dictation_hotkey.clone()],
|
|
};
|
|
if kind != HotkeyKind::Edit && settings.voice_action.enabled {
|
|
others.push(settings.edit_hotkey.clone());
|
|
}
|
|
if kind != HotkeyKind::PasteLast
|
|
&& let Some(paste) = &settings.paste_last_hotkey
|
|
{
|
|
others.push(paste.clone());
|
|
}
|
|
if settings.meetings.available() {
|
|
others.push(HotkeyBinding::paste_meeting_default());
|
|
}
|
|
crate::app_settings::hotkey_conflicts(binding, others)
|
|
}
|
|
|
|
fn hotkey_binding(settings: &AppSettings, kind: HotkeyKind) -> Option<&HotkeyBinding> {
|
|
match kind {
|
|
HotkeyKind::Dictation => Some(&settings.dictation_hotkey),
|
|
HotkeyKind::Edit => Some(&settings.edit_hotkey),
|
|
HotkeyKind::PasteLast => settings.paste_last_hotkey.as_ref(),
|
|
}
|
|
}
|
|
|
|
fn hotkey_side_binding(
|
|
settings: &AppSettings,
|
|
kind: HotkeyKind,
|
|
side: ModifierSide,
|
|
) -> Option<HotkeyBinding> {
|
|
let mut binding = hotkey_binding(settings, kind)?.clone();
|
|
standalone_modifier_side(&binding)?;
|
|
set_standalone_modifier_side(&mut binding, side);
|
|
(!hotkey_binding_conflicts(settings, kind, &binding)).then_some(binding)
|
|
}
|
|
|
|
fn hotkey_control_width(active: bool, idle_width: f32, animated_width: f32) -> f32 {
|
|
if active { animated_width } else { idle_width }
|
|
}
|
|
|
|
fn hotkey_control_intensity(active: bool, intensity: f32) -> f32 {
|
|
if active { intensity } else { 0.0 }
|
|
}
|
|
|
|
fn hotkey_capture_width(keycap_count: usize) -> f32 {
|
|
if keycap_count == 0 {
|
|
180.0
|
|
} else {
|
|
236.0 + hotkey_keycaps_width(keycap_count)
|
|
}
|
|
}
|
|
|
|
fn hotkey_saved_width(keycap_count: usize) -> f32 {
|
|
(53.0 + hotkey_keycaps_width(keycap_count)).max(HOTKEY_MIN_WIDTH)
|
|
}
|
|
|
|
fn hotkey_keycaps_width(keycap_count: usize) -> f32 {
|
|
if keycap_count == 0 {
|
|
0.0
|
|
} else {
|
|
KEYCAP_WIDTH * keycap_count as f32 + 3.0 * keycap_count.saturating_sub(1) as f32
|
|
}
|
|
}
|
|
|
|
fn recording_audio_index(behavior: RecordingAudioBehavior) -> usize {
|
|
match behavior {
|
|
RecordingAudioBehavior::Mute => 0,
|
|
RecordingAudioBehavior::PauseMedia => 1,
|
|
RecordingAudioBehavior::DoNothing => 2,
|
|
}
|
|
}
|
|
|
|
fn sound_volume_index(settings: &AppSettings) -> usize {
|
|
if !settings.sound_effects {
|
|
return 0;
|
|
}
|
|
crate::desktop_ui::SOUND_VOLUME_STEPS[1..]
|
|
.iter()
|
|
.enumerate()
|
|
.min_by(|(_, (_, left)), (_, (_, right))| {
|
|
(settings.sound_effect_volume - *left)
|
|
.abs()
|
|
.total_cmp(&(settings.sound_effect_volume - *right).abs())
|
|
})
|
|
.map_or(0, |(index, _)| index + 1)
|
|
}
|
|
|
|
fn open_opencode_beta_docs() {
|
|
if let Err(error) = crate::commands::execute(crate::commands::Action::OpenUrl(
|
|
OPENCODE_BETA_DOCS_URL.into(),
|
|
)) {
|
|
tracing::error!(%error, "could not open the OpenCode beta documentation");
|
|
}
|
|
}
|
|
|
|
fn advance_highlight(current: usize, direction: i32, count: usize) -> usize {
|
|
if direction < 0 {
|
|
current.saturating_sub(1)
|
|
} else {
|
|
(current + 1).min(count - 1)
|
|
}
|
|
}
|
|
|
|
fn mode_row(
|
|
title: impl Into<String>,
|
|
subtitle: impl Into<String>,
|
|
selected: bool,
|
|
applications: &[String],
|
|
browser_hosts: &[String],
|
|
catalog: &ApplicationCatalogState,
|
|
) -> Div {
|
|
let title = title.into();
|
|
let subtitle = subtitle.into();
|
|
let has_activations = !applications.is_empty() || !browser_hosts.is_empty();
|
|
list_row(selected)
|
|
.gap_1()
|
|
.child(list_row_title(title, selected))
|
|
.when(has_activations, |row| {
|
|
row.child(mode_activation_icons(applications, browser_hosts, catalog))
|
|
})
|
|
.when(!has_activations, |row| {
|
|
row.child(list_row_meta(subtitle, selected))
|
|
})
|
|
}
|
|
|
|
const ACTIVATION_ICON_SIZE: f32 = 18.0;
|
|
|
|
fn mode_activation_icons(
|
|
applications: &[String],
|
|
browser_hosts: &[String],
|
|
catalog: &ApplicationCatalogState,
|
|
) -> AnyElement {
|
|
let total = applications.len() + browser_hosts.len();
|
|
let visible = total.min(5);
|
|
let mut icons = Vec::with_capacity(visible + usize::from(total > visible));
|
|
for name in applications.iter().take(visible) {
|
|
let application = catalog.application_named(name);
|
|
icons.push(application_icon(
|
|
application,
|
|
Some(name),
|
|
ACTIVATION_ICON_SIZE,
|
|
));
|
|
}
|
|
for _ in browser_hosts
|
|
.iter()
|
|
.take(visible.saturating_sub(icons.len()))
|
|
{
|
|
icons.push(
|
|
div()
|
|
.size(px(ACTIVATION_ICON_SIZE))
|
|
.flex_none()
|
|
.flex()
|
|
.items_center()
|
|
.justify_center()
|
|
.rounded(icon_radius(ACTIVATION_ICON_SIZE))
|
|
.bg(rgb(SURFACE_SELECTED))
|
|
.child(icon(Icon::Globe, TEXT_SECONDARY))
|
|
.into_any_element(),
|
|
);
|
|
}
|
|
if total > visible {
|
|
icons.push(tag(Tone::Neutral, format!("+{}", total - visible)).into_any_element());
|
|
}
|
|
div()
|
|
.h(px(ACTIVATION_ICON_SIZE))
|
|
.flex()
|
|
.items_center()
|
|
.gap_1()
|
|
.children(icons)
|
|
.into_any_element()
|
|
}
|
|
|
|
fn application_icon(
|
|
application: Option<&InstalledApplication>,
|
|
fallback_name: Option<&str>,
|
|
size: f32,
|
|
) -> AnyElement {
|
|
if let Some(icon) = application.and_then(|application| application.icon.as_ref()) {
|
|
return img(icon.clone())
|
|
.size(px(size))
|
|
.rounded(icon_radius(size))
|
|
.into_any_element();
|
|
}
|
|
let initial = fallback_name
|
|
.and_then(|name| name.chars().find(|character| character.is_alphanumeric()))
|
|
.map(|character| character.to_uppercase().to_string())
|
|
.unwrap_or_else(|| "?".into());
|
|
div()
|
|
.size(px(size))
|
|
.flex_none()
|
|
.flex()
|
|
.items_center()
|
|
.justify_center()
|
|
.rounded(icon_radius(size))
|
|
.bg(rgb(SURFACE_SELECTED))
|
|
.map(|monogram| {
|
|
if size >= CONTROL_HEIGHT {
|
|
monogram.text_body()
|
|
} else {
|
|
monogram.text_caption()
|
|
}
|
|
})
|
|
.font_weight(FontWeight::SEMIBOLD)
|
|
.text_color(rgb(TEXT_SECONDARY))
|
|
.child(initial)
|
|
.into_any_element()
|
|
}
|
|
|
|
fn filtered_model_keys(catalog: &ModelCatalog, query: &str) -> Vec<Option<String>> {
|
|
let mut choices = Vec::new();
|
|
if query.is_empty() && catalog.default_name.is_some() {
|
|
choices.push(None);
|
|
}
|
|
choices.extend(
|
|
catalog
|
|
.models
|
|
.iter()
|
|
.filter(|choice| {
|
|
query.is_empty()
|
|
|| choice.key.to_lowercase().contains(query)
|
|
|| choice.name.to_lowercase().contains(query)
|
|
|| choice.provider.to_lowercase().contains(query)
|
|
})
|
|
.take(8)
|
|
.map(|choice| Some(choice.key.clone())),
|
|
);
|
|
choices
|
|
}
|
|
|
|
fn model_presentation(
|
|
catalog: &ModelCatalogState,
|
|
selected_key: Option<&str>,
|
|
) -> Option<ModelPresentation> {
|
|
let ModelCatalogState::Loaded(catalog) = catalog else {
|
|
return selected_key.map(fallback_model_presentation);
|
|
};
|
|
let is_default = selected_key.is_none();
|
|
let key = selected_key.or(catalog.default_key.as_deref())?;
|
|
let choice = catalog.models.iter().find(|choice| choice.key == key);
|
|
let name = choice
|
|
.map(|choice| choice.name.clone())
|
|
.or_else(|| is_default.then(|| catalog.default_name.clone()).flatten())
|
|
.unwrap_or_else(|| model_id(key).to_owned());
|
|
let provider = choice
|
|
.map(|choice| provider_label(&choice.provider))
|
|
.unwrap_or_else(|| {
|
|
provider_label(key.split_once('/').map_or(key, |(provider, _)| provider))
|
|
});
|
|
Some(ModelPresentation {
|
|
name,
|
|
provider,
|
|
#[cfg(test)]
|
|
key: key.to_owned(),
|
|
is_default,
|
|
})
|
|
}
|
|
|
|
fn mode_settings_mut(settings: &mut AppSettings, selection: ModeSelection) -> &mut DictationMode {
|
|
match selection {
|
|
ModeSelection::Default => &mut settings.dictation_processing.default_mode,
|
|
ModeSelection::Custom(index) => &mut settings.dictation_processing.modes[index],
|
|
}
|
|
}
|
|
|
|
fn apply_model_variant(
|
|
settings: &mut AppSettings,
|
|
target: ModelPickerTarget,
|
|
variant: Option<String>,
|
|
catalog: &ModelCatalogState,
|
|
) {
|
|
let (model, selected_variant) = match target {
|
|
ModelPickerTarget::Mode(selection) => {
|
|
let processing = &mut mode_settings_mut(settings, selection).post_processing;
|
|
(&mut processing.model, &mut processing.variant)
|
|
}
|
|
ModelPickerTarget::VoiceAction => (
|
|
&mut settings.voice_action.model,
|
|
&mut settings.voice_action.variant,
|
|
),
|
|
};
|
|
if variant.is_some()
|
|
&& model.is_none()
|
|
&& let ModelCatalogState::Loaded(catalog) = catalog
|
|
{
|
|
// V2 variants belong to an explicit catalog model, not the floating default.
|
|
*model = catalog.default_key.clone();
|
|
}
|
|
*selected_variant = variant;
|
|
}
|
|
|
|
fn model_variants(catalog: &ModelCatalog, selected_key: Option<&str>) -> Vec<String> {
|
|
selected_key
|
|
.or(catalog.default_key.as_deref())
|
|
.and_then(|key| catalog.models.iter().find(|choice| choice.key == key))
|
|
.map_or_else(Vec::new, |choice| choice.variants.clone())
|
|
}
|
|
|
|
fn fallback_model_presentation(key: &str) -> ModelPresentation {
|
|
let provider = key.split_once('/').map_or(key, |(provider, _)| provider);
|
|
ModelPresentation {
|
|
name: model_id(key).to_owned(),
|
|
provider: provider_label(provider),
|
|
#[cfg(test)]
|
|
key: key.to_owned(),
|
|
is_default: false,
|
|
}
|
|
}
|
|
|
|
fn model_id(key: &str) -> &str {
|
|
key.split_once('/').map_or(key, |(_, model)| model)
|
|
}
|
|
|
|
fn provider_label(provider: &str) -> String {
|
|
if provider.eq_ignore_ascii_case("opencode") {
|
|
return "OpenCode".into();
|
|
}
|
|
provider
|
|
.split(['-', '_'])
|
|
.filter(|part| !part.is_empty())
|
|
.map(|part| {
|
|
let mut characters = part.chars();
|
|
characters.next().map_or_else(String::new, |first| {
|
|
first.to_uppercase().chain(characters).collect()
|
|
})
|
|
})
|
|
.collect::<Vec<_>>()
|
|
.join(" ")
|
|
}
|
|
|
|
fn model_choice_row(
|
|
title: impl Into<String>,
|
|
subtitle: impl Into<String>,
|
|
highlighted: bool,
|
|
) -> Div {
|
|
menu_item(highlighted)
|
|
.child(truncated_line(FOOTNOTE, title.into()).flex_1())
|
|
.child(
|
|
div()
|
|
.flex_none()
|
|
.text_caption()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child(subtitle.into()),
|
|
)
|
|
}
|
|
|
|
fn settings_control(
|
|
label: &'static str,
|
|
description: impl Into<String>,
|
|
control: impl IntoElement,
|
|
) -> AnyElement {
|
|
div()
|
|
.flex_1()
|
|
.min_w(px(0.0))
|
|
.flex()
|
|
.flex_col()
|
|
.gap_2()
|
|
.child(
|
|
div()
|
|
.flex()
|
|
.items_center()
|
|
.justify_between()
|
|
.gap_2()
|
|
.child(field_label(label))
|
|
.child(
|
|
div()
|
|
.text_caption()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child(description.into()),
|
|
),
|
|
)
|
|
.child(control)
|
|
.into_any_element()
|
|
}
|
|
|
|
/// The label above a stacked form field.
|
|
fn field_label(label: &'static str) -> Div {
|
|
div()
|
|
.text_footnote()
|
|
.font_weight(FontWeight::MEDIUM)
|
|
.text_color(rgb(TEXT_SECONDARY))
|
|
.child(label)
|
|
}
|
|
|
|
fn input_text(input: &ProcessingInput, cx: &App) -> String {
|
|
input.entity.read(cx).text().trim().to_string()
|
|
}
|
|
|
|
fn browser_hosts(value: &str) -> Vec<String> {
|
|
let mut hosts: Vec<_> = value
|
|
.split(',')
|
|
.map(str::trim)
|
|
.filter(|value| !value.is_empty())
|
|
.filter_map(|value| {
|
|
let candidate = if value.contains("://") {
|
|
value.to_owned()
|
|
} else {
|
|
format!("https://{value}")
|
|
};
|
|
url::Url::parse(&candidate)
|
|
.ok()?
|
|
.host_str()
|
|
.map(str::to_lowercase)
|
|
})
|
|
.collect();
|
|
hosts.sort();
|
|
hosts.dedup();
|
|
hosts
|
|
}
|
|
|
|
fn reorder_transformation(values: &mut Vec<String>, id: &str, target_index: usize) -> bool {
|
|
let Some(from) = values.iter().position(|candidate| candidate == id) else {
|
|
return false;
|
|
};
|
|
if from == target_index {
|
|
return false;
|
|
}
|
|
let value = values.remove(from);
|
|
let target = target_index.min(values.len());
|
|
values.insert(target, value);
|
|
true
|
|
}
|
|
|
|
fn apply_mode_inputs(inputs: &ModeInputs, mode: &mut DictationMode, is_default: bool, cx: &App) {
|
|
mode.name = if is_default {
|
|
"Global".into()
|
|
} else {
|
|
input_text(&inputs.name, cx)
|
|
};
|
|
mode.browser_hosts = if is_default {
|
|
Vec::new()
|
|
} else {
|
|
browser_hosts(&input_text(&inputs.browser_hosts, cx))
|
|
};
|
|
mode.replacements = inputs
|
|
.replacements
|
|
.iter()
|
|
.map(|inputs| TextReplacement {
|
|
matched_phrase: inputs.matched_phrase.entity.read(cx).text().to_string(),
|
|
output: inputs.output.entity.read(cx).text().to_string(),
|
|
})
|
|
.collect();
|
|
mode.post_processing.enabled = inputs.processing_toggle.enabled();
|
|
mode.post_processing.prompt = input_text(&inputs.prompt, cx);
|
|
mode.post_processing.deadline_seconds = input_text(&inputs.deadline, cx)
|
|
.parse::<u64>()
|
|
.unwrap_or(mode.post_processing.deadline_seconds)
|
|
.max(1);
|
|
}
|
|
|
|
fn dictation_model_notice(
|
|
status: SetupStatus,
|
|
preparing: bool,
|
|
) -> Option<(&'static str, &'static str)> {
|
|
if status.transcription_model {
|
|
return None;
|
|
}
|
|
Some(if preparing {
|
|
(
|
|
"Preparing speech model",
|
|
"Dictation will be available once your local speech model is ready.",
|
|
)
|
|
} else {
|
|
(
|
|
"Download a speech model to start dictating",
|
|
"The dictation shortcut needs a local speech model. Choose one to download first.",
|
|
)
|
|
})
|
|
}
|
|
|
|
fn command_model_notice(status: &CommandModelStatus) -> Option<(&'static str, &'static str)> {
|
|
match status {
|
|
CommandModelStatus::Disabled | CommandModelStatus::Ready => None,
|
|
CommandModelStatus::Loading => Some((
|
|
"Preparing voice commands",
|
|
"The command model is loading. Hotkey dictation does not require it.",
|
|
)),
|
|
CommandModelStatus::Failed => Some((
|
|
"Voice commands are unavailable",
|
|
"The command model could not load. Retry or turn off commands; hotkey dictation is unaffected.",
|
|
)),
|
|
}
|
|
}
|
|
|
|
const fn permission_warning_copy(kind: PermissionKind) -> (&'static str, &'static str) {
|
|
match kind {
|
|
PermissionKind::Microphone => (
|
|
"Microphone access is off",
|
|
"Hex cannot record dictation until microphone access is restored.",
|
|
),
|
|
PermissionKind::InputMonitoring => (
|
|
"Input Monitoring is off",
|
|
"Hex cannot recognize the dictation shortcut in other apps.",
|
|
),
|
|
PermissionKind::Accessibility => (
|
|
"Accessibility is off",
|
|
"Hex cannot paste completed dictation into the foreground app.",
|
|
),
|
|
}
|
|
}
|
|
|
|
const fn permission_action_label(action: PermissionAction) -> &'static str {
|
|
match action {
|
|
PermissionAction::RequestMicrophone => "Allow",
|
|
PermissionAction::OpenMicrophoneSettings => "Open settings",
|
|
PermissionAction::OpenInputMonitoringSettings
|
|
| PermissionAction::OpenAccessibilitySettings => "Grant access",
|
|
}
|
|
}
|
|
|
|
const fn permission_warning_id(kind: PermissionKind) -> &'static str {
|
|
match kind {
|
|
PermissionKind::Microphone => "permission-warning-microphone",
|
|
PermissionKind::InputMonitoring => "permission-warning-input-monitoring",
|
|
PermissionKind::Accessibility => "permission-warning-accessibility",
|
|
}
|
|
}
|
|
|
|
fn hotkey_modifiers(modifiers: GpuiModifiers) -> HotkeyModifiers {
|
|
hotkey_modifiers_with_flags(modifiers, crate::suppression::physical_modifier_flags())
|
|
}
|
|
|
|
fn hotkey_modifiers_with_flags(modifiers: GpuiModifiers, flags: u64) -> HotkeyModifiers {
|
|
let physical = crate::app_settings::modifiers_from_flags(flags);
|
|
if !physical.is_empty() {
|
|
return physical;
|
|
}
|
|
HotkeyModifiers {
|
|
control: modifiers.control.then_some(Default::default()),
|
|
option: modifiers.alt.then_some(Default::default()),
|
|
shift: modifiers.shift.then_some(Default::default()),
|
|
command: modifiers.platform.then_some(Default::default()),
|
|
function: modifiers.function,
|
|
}
|
|
}
|
|
|
|
fn hotkey_key(key: &str) -> std::result::Result<HotkeyKey, &'static str> {
|
|
let special = match key {
|
|
"space" => Some((49, "Space")),
|
|
"tab" => Some((48, "Tab")),
|
|
"enter" => Some((36, "Return")),
|
|
"backspace" => Some((51, "Delete")),
|
|
"up" => Some((126, "Up")),
|
|
"down" => Some((125, "Down")),
|
|
"left" => Some((123, "Left")),
|
|
"right" => Some((124, "Right")),
|
|
"pageup" => Some((116, "Page Up")),
|
|
"pagedown" => Some((121, "Page Down")),
|
|
"home" => Some((115, "Home")),
|
|
"end" => Some((119, "End")),
|
|
"delete" => Some((117, "Forward Delete")),
|
|
"insert" => Some((114, "Help")),
|
|
"f1" => Some((122, "F1")),
|
|
"f2" => Some((120, "F2")),
|
|
"f3" => Some((99, "F3")),
|
|
"f4" => Some((118, "F4")),
|
|
"f5" => Some((96, "F5")),
|
|
"f6" => Some((97, "F6")),
|
|
"f7" => Some((98, "F7")),
|
|
"f8" => Some((100, "F8")),
|
|
"f9" => Some((101, "F9")),
|
|
"f10" => Some((109, "F10")),
|
|
"f11" => Some((103, "F11")),
|
|
"f12" => Some((111, "F12")),
|
|
"f13" => Some((105, "F13")),
|
|
"f14" => Some((107, "F14")),
|
|
"f15" => Some((113, "F15")),
|
|
"f16" => Some((106, "F16")),
|
|
"f17" => Some((64, "F17")),
|
|
"f18" => Some((79, "F18")),
|
|
"f19" => Some((80, "F19")),
|
|
"f20" => Some((90, "F20")),
|
|
_ => None,
|
|
};
|
|
if let Some((code, label)) = special {
|
|
return Ok(HotkeyKey {
|
|
code,
|
|
label: label.into(),
|
|
});
|
|
}
|
|
let mut characters = key.chars();
|
|
let Some(character) = characters.next() else {
|
|
return Err("Unsupported key");
|
|
};
|
|
if characters.next().is_some() {
|
|
return Err("Unsupported key");
|
|
}
|
|
let code = crate::keyboard::key_code_for(character).map_err(|_| "Unsupported key")?;
|
|
Ok(HotkeyKey {
|
|
code,
|
|
label: character.to_uppercase().collect(),
|
|
})
|
|
}
|
|
|
|
fn is_function_key(label: &str) -> bool {
|
|
label
|
|
.strip_prefix('F')
|
|
.and_then(|number| number.parse::<u8>().ok())
|
|
.is_some_and(|number| (1..=20).contains(&number))
|
|
}
|
|
|
|
fn command_task(command: &CommandInfo) -> String {
|
|
if let Some(group) = &command.group {
|
|
return group.clone();
|
|
}
|
|
if command.id.starts_with("mode.") {
|
|
"Voice control".into()
|
|
} else if command.id.starts_with("dictation.") {
|
|
"Dictation".into()
|
|
} else if command.id.starts_with("meeting.") {
|
|
"Meetings".into()
|
|
} else {
|
|
match command.description.as_str() {
|
|
"Open application" => "Open applications",
|
|
"Open website" => "Open websites",
|
|
"Navigate active tab" => "Browser navigation",
|
|
"Use keyboard shortcut" => "Keyboard",
|
|
"Use application shortcut" | "Open application destination" => "Application navigation",
|
|
_ => "Other",
|
|
}
|
|
.into()
|
|
}
|
|
}
|
|
|
|
fn merged_catalog(compiled: &[CatalogCommand], personal: &StatusSnapshot) -> Vec<CatalogCommand> {
|
|
let mut commands = compiled.to_vec();
|
|
commands.extend(personal.catalog.iter().filter_map(|command| {
|
|
let (phrase, aliases) = command.phrases.split_first()?;
|
|
Some(CatalogCommand {
|
|
task: command.group.clone(),
|
|
scope: match &command.context {
|
|
StatusContext::Global => CommandScope::Global,
|
|
StatusContext::Application { application } => {
|
|
CommandScope::Application(application.clone())
|
|
}
|
|
StatusContext::BrowserHost { browser_host } => {
|
|
CommandScope::Browser(browser_host.clone())
|
|
}
|
|
},
|
|
phrase: phrase.clone(),
|
|
aliases: aliases.to_vec(),
|
|
description: command.description.clone(),
|
|
id: command.id.clone(),
|
|
})
|
|
}));
|
|
commands
|
|
}
|
|
|
|
fn open_path(path: &std::path::Path) {
|
|
if let Err(error) = ProcessCommand::new("/usr/bin/open").arg(path).spawn() {
|
|
tracing::error!(%error, path = %path.display(), "could not open personal command path");
|
|
}
|
|
}
|
|
|
|
fn command_scope(scope: &CommandScope) -> String {
|
|
match scope {
|
|
CommandScope::Sleeping | CommandScope::Global => "Global".into(),
|
|
CommandScope::Application(application) => application.clone(),
|
|
CommandScope::Browser(host) => host.clone(),
|
|
}
|
|
}
|
|
|
|
fn timestamped_list_row(
|
|
id: (&'static str, usize),
|
|
selected: bool,
|
|
age: String,
|
|
body: Div,
|
|
) -> gpui::Stateful<Div> {
|
|
list_row(selected)
|
|
.id(id)
|
|
.flex_row()
|
|
.items_start()
|
|
.justify_between()
|
|
.gap_3()
|
|
.child(body.min_w(px(0.0)))
|
|
.child(
|
|
div()
|
|
.flex_none()
|
|
.pt(px(baseline_offset(BODY, CAPTION)))
|
|
.text_caption()
|
|
.text_color(rgb(if selected {
|
|
TEXT_SECONDARY
|
|
} else {
|
|
TEXT_TERTIARY
|
|
}))
|
|
.child(age),
|
|
)
|
|
}
|
|
|
|
fn render_meeting_notes(notes: meeting::MeetingNotes) -> Div {
|
|
let summary = notes.summary.trim().to_string();
|
|
div()
|
|
.mb_5()
|
|
.pb_5()
|
|
.flex()
|
|
.flex_col()
|
|
.gap(px(6.0))
|
|
.border_b_1()
|
|
.border_color(rgb(LINE))
|
|
.child(section_label("Summary"))
|
|
.child(
|
|
div()
|
|
.text_body()
|
|
.text_color(rgb(if summary.is_empty() {
|
|
TEXT_TERTIARY
|
|
} else {
|
|
TEXT_SECONDARY
|
|
}))
|
|
.child(if summary.is_empty() {
|
|
"Nothing to summarize.".to_string()
|
|
} else {
|
|
summary
|
|
}),
|
|
)
|
|
}
|
|
|
|
/// A compact status tag; `Ready` appears only in the detail header, so the
|
|
/// list stays quiet for finished meetings.
|
|
fn meeting_status_chip(status: MeetingStatus, stop_pending: bool, show_ready: bool) -> Option<Div> {
|
|
let (label, tone) = match status {
|
|
MeetingStatus::Recording if stop_pending => ("Transcribing", Tone::Accent),
|
|
MeetingStatus::Starting | MeetingStatus::Recording => ("Recording", Tone::Danger),
|
|
MeetingStatus::Transcribing => ("Transcribing", Tone::Accent),
|
|
MeetingStatus::Complete if show_ready => ("Ready", Tone::Success),
|
|
MeetingStatus::Complete => return None,
|
|
MeetingStatus::Interrupted => ("Interrupted", Tone::Neutral),
|
|
MeetingStatus::Failed => ("Failed", Tone::Danger),
|
|
};
|
|
let live =
|
|
matches!(status, MeetingStatus::Starting | MeetingStatus::Recording) && !stop_pending;
|
|
Some(tag(tone, label).when(live, |chip| {
|
|
chip.child(status_dot(DANGER).size(px(5.0)))
|
|
.flex_row_reverse()
|
|
}))
|
|
}
|
|
|
|
/// `42 min`, `1 h 05 min`, or `< 1 min`.
|
|
fn meeting_length(milliseconds: u64) -> String {
|
|
let minutes = milliseconds / 60_000;
|
|
match minutes {
|
|
0 => "< 1 min".into(),
|
|
1..=59 => format!("{minutes} min"),
|
|
_ => format!("{} h {:02} min", minutes / 60, minutes % 60),
|
|
}
|
|
}
|
|
|
|
fn transcript_lines(turns: &[TranscriptEntry]) -> Vec<TranscriptLine> {
|
|
turns
|
|
.iter()
|
|
.scan(None, |previous_end: &mut Option<u64>, turn| {
|
|
let pause_before_ms = previous_end
|
|
.map(|end| turn.start_ms.saturating_sub(end))
|
|
.filter(|pause| *pause >= 30_000);
|
|
*previous_end = Some(previous_end.map_or(turn.end_ms, |end| end.max(turn.end_ms)));
|
|
Some(TranscriptLine {
|
|
source: turn.source,
|
|
clock: meeting::format_duration(turn.start_ms),
|
|
text: turn.text.clone(),
|
|
pause_before_ms,
|
|
})
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// One conversational turn: the other side on the left, the user on the
|
|
/// right in the accent color.
|
|
fn transcript_turn(index: usize, line: &TranscriptLine) -> AnyElement {
|
|
let mine = line.source == MeetingSource::Microphone;
|
|
div()
|
|
.id(("transcript-line", index))
|
|
.flex()
|
|
.flex_col()
|
|
.when_some(line.pause_before_ms, |row, pause| {
|
|
row.child(
|
|
div()
|
|
.py_2()
|
|
.flex()
|
|
.items_center()
|
|
.gap_3()
|
|
.text_caption()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child(div().h(px(1.0)).flex_1().bg(rgb(LINE)))
|
|
.child(format!("{} pause", meeting_length(pause)))
|
|
.child(div().h(px(1.0)).flex_1().bg(rgb(LINE))),
|
|
)
|
|
})
|
|
.child(
|
|
div()
|
|
.flex()
|
|
.flex_col()
|
|
.gap_1()
|
|
.when(mine, |turn| turn.items_end())
|
|
.when(!mine, |turn| turn.items_start())
|
|
.child(
|
|
// Inset to the bubble's text, not its rounded edge.
|
|
div()
|
|
.px_3()
|
|
.flex()
|
|
.gap_2()
|
|
.text_caption()
|
|
.text_color(rgb(TEXT_TERTIARY))
|
|
.child(
|
|
div()
|
|
.font_weight(FontWeight::SEMIBOLD)
|
|
.text_color(rgb(if mine { ACCENT_TEXT } else { TEXT_TERTIARY }))
|
|
.child(line.source.label()),
|
|
)
|
|
.child(line.clock.clone()),
|
|
)
|
|
.child(
|
|
div()
|
|
.debug_selector(move || format!("meeting-bubble-{index}"))
|
|
.max_w(relative(0.82))
|
|
.px_3()
|
|
.py_2()
|
|
.rounded(RADIUS_PANEL)
|
|
.border_1()
|
|
.when(mine, |bubble| {
|
|
bubble
|
|
.border_color(rgb(ACCENT_BORDER))
|
|
.bg(rgb(ACCENT_SURFACE))
|
|
.text_color(rgb(TEXT_PRIMARY))
|
|
})
|
|
.when(!mine, |bubble| {
|
|
bubble
|
|
.border_color(rgb(LINE))
|
|
.bg(rgb(CANVAS))
|
|
.text_color(rgb(TEXT_SECONDARY))
|
|
})
|
|
.text_body()
|
|
.child(line.text.clone()),
|
|
),
|
|
)
|
|
.into_any_element()
|
|
}
|
|
|
|
fn reveal_meeting(id: &str, export_path: Option<&std::path::Path>) {
|
|
if let Some(path) = export_path {
|
|
meeting::reveal(path);
|
|
return;
|
|
}
|
|
match meeting::root() {
|
|
Ok(root) => match ProcessCommand::new("/usr/bin/open")
|
|
.arg(root.join(id))
|
|
.status()
|
|
{
|
|
Ok(status) if status.success() => {}
|
|
Ok(status) => tracing::error!(%status, "could not reveal meeting files"),
|
|
Err(error) => tracing::error!(%error, "could not reveal meeting files"),
|
|
},
|
|
Err(error) => tracing::error!(%error, "could not locate meeting files"),
|
|
}
|
|
}
|
|
|
|
/// Deterministic meetings for the Meetings preview: one recording, one with
|
|
/// notes, one without, and one that failed.
|
|
fn preview_meetings(empty: bool) -> (Vec<MeetingManifest>, HashMap<String, Vec<TranscriptEntry>>) {
|
|
if empty {
|
|
return (Vec::new(), HashMap::new());
|
|
}
|
|
let now = now_ms();
|
|
let minute = 60_000;
|
|
let manifest =
|
|
|id: &str, title: &str, status, started: u64, duration: u64, app: Option<&str>| {
|
|
MeetingManifest {
|
|
schema_version: 1,
|
|
id: id.into(),
|
|
title: title.into(),
|
|
status,
|
|
created_at_ms: started,
|
|
ended_at_ms: (status != MeetingStatus::Recording).then_some(started + duration),
|
|
duration_ms: (status != MeetingStatus::Recording).then_some(duration),
|
|
system: Default::default(),
|
|
microphone: Default::default(),
|
|
live_dropped_packets: 0,
|
|
live_transcription_error: None,
|
|
error: None,
|
|
app: app.map(Into::into),
|
|
export_path: None,
|
|
export_error: None,
|
|
echo_suppressed_utterances: 0,
|
|
provisional_title: None,
|
|
notes: None,
|
|
notes_error: None,
|
|
}
|
|
};
|
|
let recording_start = now - 7 * minute - 12_000;
|
|
let mut live = manifest(
|
|
"preview-live",
|
|
&meeting::default_title(Some("Zoom"), recording_start),
|
|
MeetingStatus::Recording,
|
|
recording_start,
|
|
0,
|
|
Some("Zoom"),
|
|
);
|
|
live.created_at_ms = recording_start;
|
|
let synced_start = now - 3 * 60 * minute;
|
|
let mut synced = manifest(
|
|
"preview-notes",
|
|
&meeting::default_title(Some("Zoom"), synced_start),
|
|
MeetingStatus::Complete,
|
|
synced_start,
|
|
38 * minute + 20_000,
|
|
Some("Zoom"),
|
|
);
|
|
synced.notes = Some(meeting::MeetingNotes {
|
|
title: "Arcade launch plan".into(),
|
|
summary: "One login for every Anomaly Arcade game, aiming for twenty to thirty games \
|
|
over the next couple of months. The build screen needs a proposal before more polish."
|
|
.into(),
|
|
generated_at_ms: synced_start + 39 * minute,
|
|
elapsed_ms: 4_000,
|
|
..Default::default()
|
|
});
|
|
let design_start = now - 27 * 60 * minute;
|
|
let design = manifest(
|
|
"preview-design",
|
|
"Design review",
|
|
MeetingStatus::Complete,
|
|
design_start,
|
|
24 * minute,
|
|
Some("FaceTime"),
|
|
);
|
|
let failed_start = now - 29 * 60 * minute;
|
|
let mut failed = manifest(
|
|
"preview-failed",
|
|
&meeting::default_title(None, failed_start),
|
|
MeetingStatus::Failed,
|
|
failed_start,
|
|
2 * minute,
|
|
None,
|
|
);
|
|
failed.error = Some("ScreenCaptureKit stopped the capture.".into());
|
|
|
|
let turn = |source, seconds: u64, text: &str| TranscriptEntry {
|
|
source,
|
|
start_ms: seconds * 1_000,
|
|
end_ms: seconds * 1_000 + 2_500,
|
|
text: text.into(),
|
|
};
|
|
use MeetingSource::{Microphone as You, System as Them};
|
|
let conversation = vec![
|
|
turn(
|
|
Them,
|
|
1,
|
|
"Basically, I want Anomaly Arcade to be one login where you add friends and jump into any game.",
|
|
),
|
|
turn(Them, 4, "I need to finish my StarCraft game, too."),
|
|
turn(You, 9, "Oh nice. How far along is it?"),
|
|
turn(
|
|
Them,
|
|
13,
|
|
"Close. I feel like over a couple of months we could make twenty to thirty games.",
|
|
),
|
|
turn(You, 20, "That's basically a new version of Steam."),
|
|
turn(
|
|
Them,
|
|
24,
|
|
"If we're seeing Roblox, the idea should be to become Roblox.",
|
|
),
|
|
turn(
|
|
You,
|
|
31,
|
|
"Apple has a new thing where you hold two phones together and there's this pulse and gravity well.",
|
|
),
|
|
turn(
|
|
You,
|
|
34,
|
|
"Could be a nice mini gravity well for the transitions.",
|
|
),
|
|
turn(Them, 40, "Prototype it in WebGPU, whatever's faster."),
|
|
turn(
|
|
You,
|
|
95,
|
|
"The build screen looks rough, by the way. We need a proposal for it.",
|
|
),
|
|
turn(
|
|
Them,
|
|
101,
|
|
"Agreed. Write it up and I'll review it tomorrow.",
|
|
),
|
|
];
|
|
let transcripts = HashMap::from([
|
|
("preview-live".to_string(), conversation[..7].to_vec()),
|
|
("preview-notes".to_string(), conversation.clone()),
|
|
("preview-design".to_string(), conversation[2..6].to_vec()),
|
|
]);
|
|
(vec![live, synced, design, failed], transcripts)
|
|
}
|
|
|
|
fn log_meeting_request_error(error: TrySendError<MeetingRequest>) {
|
|
match error {
|
|
TrySendError::Full(_) => tracing::warn!("meeting controller is busy"),
|
|
TrySendError::Disconnected(_) => tracing::error!("meeting controller is unavailable"),
|
|
}
|
|
}
|
|
|
|
fn meeting_duration(meeting: &MeetingManifest) -> u64 {
|
|
meeting.duration_ms.unwrap_or_else(|| {
|
|
if matches!(
|
|
meeting.status,
|
|
MeetingStatus::Starting | MeetingStatus::Recording
|
|
) {
|
|
now_ms().saturating_sub(meeting.created_at_ms)
|
|
} else {
|
|
meeting
|
|
.ended_at_ms
|
|
.map_or(0, |ended| ended.saturating_sub(meeting.created_at_ms))
|
|
}
|
|
})
|
|
}
|
|
|
|
fn activity_context(reader: &EventReader) -> (Option<String>, Option<String>) {
|
|
reader
|
|
.current_context()
|
|
.map(|(application, browser_url)| {
|
|
(
|
|
application.clone(),
|
|
browser_url
|
|
.as_deref()
|
|
.and_then(|url| url::Url::parse(url).ok())
|
|
.and_then(|url| url.host_str().map(str::to_owned)),
|
|
)
|
|
})
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
fn event_age(timestamp_ms: u64) -> String {
|
|
let seconds = now_ms().saturating_sub(timestamp_ms) / 1_000;
|
|
match seconds {
|
|
0..=59 => format!("{seconds}s ago"),
|
|
60..=3_599 => format!("{}m ago", seconds / 60),
|
|
3_600..=86_399 => format!("{}h ago", seconds / 3_600),
|
|
_ => format!("{}d ago", seconds / 86_400),
|
|
}
|
|
}
|
|
|
|
fn event_summary(event: &VoiceEvent) -> String {
|
|
match event {
|
|
VoiceEvent::SessionStarted { .. } => "Hex session started".into(),
|
|
VoiceEvent::State { state, device, .. } => match state {
|
|
VoiceState::Sleeping => "Voice commands went to sleep".into(),
|
|
VoiceState::Listening => format!("Voice commands resumed on {device}"),
|
|
VoiceState::Dictating => format!("Dictation started on {device}"),
|
|
VoiceState::Transcribing => "Dictation is being transcribed".into(),
|
|
VoiceState::Stopping => "Hex is stopping".into(),
|
|
},
|
|
VoiceEvent::Transcript {
|
|
phase,
|
|
latency_ms,
|
|
text,
|
|
..
|
|
} => match phase {
|
|
TranscriptPhase::Started => "Speech recognition started".into(),
|
|
TranscriptPhase::Updated => format!("Heard \"{text}\" so far"),
|
|
TranscriptPhase::Completed => format!("Heard \"{text}\" in {latency_ms} ms"),
|
|
},
|
|
VoiceEvent::Command {
|
|
heard,
|
|
command,
|
|
outcome,
|
|
..
|
|
} => {
|
|
let command = command.as_deref().unwrap_or("an unmatched command");
|
|
match outcome {
|
|
CommandOutcome::Ignored => format!("Ignored \"{heard}\""),
|
|
CommandOutcome::Woke => format!("\"{heard}\" woke Hex"),
|
|
CommandOutcome::Slept => format!("\"{heard}\" put voice commands to sleep"),
|
|
CommandOutcome::Submitted => format!("Sent {command} for \"{heard}\""),
|
|
CommandOutcome::Executed => format!("Ran {command} for \"{heard}\""),
|
|
CommandOutcome::Failed(error) => format!("Could not run {command}: {error}"),
|
|
}
|
|
}
|
|
VoiceEvent::Dictation {
|
|
phase,
|
|
text,
|
|
processing,
|
|
..
|
|
} => {
|
|
let description = match phase {
|
|
DictationPhase::Started => "Dictation started".into(),
|
|
DictationPhase::Discarded => "A brief dictation was discarded".into(),
|
|
DictationPhase::Cancelled => "Dictation was cancelled".into(),
|
|
DictationPhase::Transcribing => "Dictation is being transcribed".into(),
|
|
DictationPhase::Pasted => text_or("Dictation was pasted", text),
|
|
DictationPhase::Edited => text_or("Selected text was edited", text),
|
|
DictationPhase::VoiceAction => text_or("Voice Action completed", text),
|
|
DictationPhase::Logged => text_or("Journal entry was saved", text),
|
|
DictationPhase::Repasted => text_or("The last dictation was pasted again", text),
|
|
DictationPhase::MeetingPasted => text_or("New meeting transcript was pasted", text),
|
|
DictationPhase::Failed(error) => format!("Dictation failed: {error}"),
|
|
};
|
|
processing
|
|
.as_ref()
|
|
.map_or(description.clone(), |processing| {
|
|
processing.fallback.as_ref().map_or_else(
|
|
|| {
|
|
format!(
|
|
"{description} · {} profile · {} ms",
|
|
processing.profile, processing.latency_ms
|
|
)
|
|
},
|
|
|error| {
|
|
format!(
|
|
"{description} · {} profile fell back to raw after {} ms: {}",
|
|
processing.profile, processing.latency_ms, error
|
|
)
|
|
},
|
|
)
|
|
})
|
|
}
|
|
VoiceEvent::Context {
|
|
application,
|
|
browser_url,
|
|
..
|
|
} => match (application, browser_url) {
|
|
(Some(application), Some(url)) => format!("Context changed to {application} / {url}"),
|
|
(Some(application), None) => format!("Context changed to {application}"),
|
|
_ => "Foreground context became unavailable".into(),
|
|
},
|
|
VoiceEvent::ApiServerStarted { port, .. } => {
|
|
format!("Local API started on port {port}")
|
|
}
|
|
VoiceEvent::ApiServerStopped { .. } => "Local API stopped".into(),
|
|
VoiceEvent::ApiAuthFailed { method, path, .. } => {
|
|
format!("Rejected unauthenticated {method} {path}")
|
|
}
|
|
}
|
|
}
|
|
|
|
fn text_or(prefix: &str, text: &str) -> String {
|
|
if text.is_empty() {
|
|
prefix.into()
|
|
} else {
|
|
format!("{prefix}: \"{text}\"")
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use std::fs;
|
|
|
|
use super::*;
|
|
use crate::personal_commands::StatusExecution;
|
|
|
|
fn preview_fixture(
|
|
preview: AppWindowPreview,
|
|
window: &mut Window,
|
|
cx: &mut Context<AppWindow>,
|
|
) -> AppWindow {
|
|
AppWindow::new(
|
|
PathBuf::from("unused-preview-events.ndjson"),
|
|
crate::config::voice_control(),
|
|
sync_channel(1).0,
|
|
crate::dictation_indicator::channel().0,
|
|
None,
|
|
None,
|
|
Some(preview),
|
|
window,
|
|
cx,
|
|
)
|
|
}
|
|
|
|
fn pane_preview(pane: DeveloperPane) -> AppWindowPreview {
|
|
AppWindowPreview {
|
|
pane,
|
|
transcription_picker: None,
|
|
onboarding: false,
|
|
confirm_model_deletion: false,
|
|
collapse_mode_processing: false,
|
|
open_transformation_picker: false,
|
|
select_global_mode: false,
|
|
voice_action_enabled: false,
|
|
opencode_unavailable: false,
|
|
permissions_missing: false,
|
|
model_missing: false,
|
|
command_model_missing: false,
|
|
open_history_retention: false,
|
|
confirm_release_microphone: false,
|
|
update_available: false,
|
|
meetings_enabled: true,
|
|
screen_recording_missing: false,
|
|
meeting_recording: false,
|
|
confirm_meeting_delete: false,
|
|
open_meeting_actions: false,
|
|
meetings_empty: false,
|
|
}
|
|
}
|
|
|
|
fn editor_fixture(window: &mut Window, cx: &mut Context<AppWindow>) -> AppWindow {
|
|
preview_fixture(
|
|
AppWindowPreview {
|
|
collapse_mode_processing: true,
|
|
select_global_mode: true,
|
|
opencode_unavailable: true,
|
|
meetings_enabled: false,
|
|
..pane_preview(DeveloperPane::Modes)
|
|
},
|
|
window,
|
|
cx,
|
|
)
|
|
}
|
|
|
|
fn meetings_fixture(window: &mut Window, cx: &mut Context<AppWindow>) -> AppWindow {
|
|
preview_fixture(pane_preview(DeveloperPane::Meetings), window, cx)
|
|
}
|
|
|
|
fn history_fixture(window: &mut Window, cx: &mut Context<AppWindow>) -> AppWindow {
|
|
preview_fixture(pane_preview(DeveloperPane::History), window, cx)
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn history_detail_rows_keep_their_values_on_one_line(cx: &mut gpui::TestAppContext) {
|
|
let (_, cx) = cx.add_window_view(history_fixture);
|
|
cx.simulate_resize(size(px(WINDOW_WIDTH), px(MINIMUM_HEIGHT)));
|
|
cx.update(|window, _| window.refresh());
|
|
cx.run_until_parked();
|
|
let value = cx.debug_bounds("detail-row-value").expect("detail row");
|
|
assert!(value.size.width > px(200.0), "{value:?}");
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn meeting_turns_alternate_sides_inside_the_detail(cx: &mut gpui::TestAppContext) {
|
|
let (_, cx) = cx.add_window_view(meetings_fixture);
|
|
for width in [MINIMUM_WIDTH, WINDOW_WIDTH, 1400.0] {
|
|
cx.simulate_resize(size(px(width), px(MINIMUM_HEIGHT)));
|
|
cx.update(|window, _| window.refresh());
|
|
cx.run_until_parked();
|
|
let detail = cx.debug_bounds("meeting-detail").expect("detail rendered");
|
|
let them = cx.debug_bounds("meeting-bubble-0").expect("first turn");
|
|
let you = cx.debug_bounds("meeting-bubble-1").expect("second turn");
|
|
let actions = cx.debug_bounds("detail-actions").expect("actions");
|
|
for bounds in [them, you, actions] {
|
|
assert!(
|
|
bounds.left() >= detail.left() && bounds.right() <= detail.right(),
|
|
"{width}: {bounds:?} outside {detail:?}"
|
|
);
|
|
}
|
|
assert!(them.left() < you.left(), "{width}: Them sits left of You");
|
|
assert!(you.right() > them.right(), "{width}: You sits right");
|
|
assert!(
|
|
detail.right() - you.right() <= px(25.0),
|
|
"{width}: You is right-aligned"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn meeting_overflow_menu_opens_beside_the_visible_actions(cx: &mut gpui::TestAppContext) {
|
|
let (view, cx) = cx.add_window_view(meetings_fixture);
|
|
cx.update(|window, cx| {
|
|
view.update(cx, |view, _| view.meeting_actions_open = true);
|
|
window.refresh();
|
|
});
|
|
cx.run_until_parked();
|
|
let actions = cx.debug_bounds("detail-actions").expect("actions");
|
|
let menu = cx.debug_bounds("meeting-actions-menu").expect("menu");
|
|
assert!(menu.top() >= actions.bottom() - px(CONTROL_HEIGHT));
|
|
assert_eq!(menu.size.width, px(MENU_WIDTH));
|
|
cx.update(|_, cx| {
|
|
view.update(cx, |view, _| {
|
|
view.select_meeting("preview-design".into());
|
|
assert!(
|
|
!view.meeting_actions_open,
|
|
"a new selection closes the menu"
|
|
);
|
|
})
|
|
});
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn meeting_search_delete_and_rename_work_on_the_selected_meeting(
|
|
cx: &mut gpui::TestAppContext,
|
|
) {
|
|
let (view, cx) = cx.add_window_view(meetings_fixture);
|
|
cx.update(|window, cx| {
|
|
view.update(cx, |view, cx| {
|
|
assert_eq!(view.selected_meeting.as_deref(), Some("preview-notes"));
|
|
view.meeting_search
|
|
.entity
|
|
.update(cx, |input, cx| input.set_text("gravity", cx));
|
|
view.refresh_meeting_search(cx);
|
|
let visible = view
|
|
.visible_meetings(cx)
|
|
.into_iter()
|
|
.map(|meeting| meeting.id.as_str())
|
|
.collect::<Vec<_>>();
|
|
assert_eq!(visible, ["preview-live", "preview-notes"]);
|
|
view.meeting_search
|
|
.entity
|
|
.update(cx, |input, cx| input.set_text("", cx));
|
|
|
|
view.start_meeting_rename(
|
|
"preview-design".into(),
|
|
"Design review".into(),
|
|
window,
|
|
cx,
|
|
);
|
|
let (_, input) = view.meeting_rename.as_ref().unwrap();
|
|
input
|
|
.entity
|
|
.update(cx, |input, cx| input.set_text(" Motion review ", cx));
|
|
view.finish_meeting_rename(cx);
|
|
assert!(view.meeting_rename.is_none());
|
|
let design = view
|
|
.meetings
|
|
.iter()
|
|
.find(|m| m.id == "preview-design")
|
|
.unwrap();
|
|
assert_eq!(meeting::display_title(design), "Motion review");
|
|
|
|
view.trash_meeting("preview-notes".into(), cx);
|
|
assert_eq!(view.meeting_delete_armed.as_deref(), Some("preview-notes"));
|
|
assert_eq!(view.meetings.len(), 4, "the first click only asks");
|
|
view.trash_meeting("preview-notes".into(), cx);
|
|
assert_eq!(view.meetings.len(), 3);
|
|
assert!(view.meetings.iter().all(|m| m.id != "preview-notes"));
|
|
assert_eq!(view.selected_meeting.as_deref(), Some("preview-live"));
|
|
});
|
|
});
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn login_item_response_reconciles_optimistic_toggle_and_unknown_state(
|
|
cx: &mut gpui::TestAppContext,
|
|
) {
|
|
let (view, cx) = cx.add_window_view(editor_fixture);
|
|
cx.update(|_, cx| {
|
|
view.update(cx, |view, _| {
|
|
view.launch_at_login_status = None;
|
|
assert!(view.apply_login_item_response(LoginItemResponse {
|
|
request: LoginItemRequest::Status,
|
|
result: Ok(LoginItemStatus::Disabled),
|
|
}));
|
|
assert_eq!(view.launch_at_login_status, Some(LoginItemStatus::Disabled));
|
|
view.launch_at_login_toggle.set_enabled(true);
|
|
view.launch_at_login_error = Some("Registration failed".into());
|
|
// Even with unchanged confirmed status and error, rollback needs a redraw.
|
|
assert!(view.apply_login_item_response(LoginItemResponse {
|
|
request: LoginItemRequest::SetEnabled(true),
|
|
result: Err(crate::login_item::LoginItemFailure {
|
|
status: Some(LoginItemStatus::Disabled),
|
|
message: "Registration failed".into(),
|
|
}),
|
|
}));
|
|
assert!(!view.launch_at_login_toggle.enabled());
|
|
assert!(!view.apply_login_item_response(LoginItemResponse {
|
|
request: LoginItemRequest::SetEnabled(true),
|
|
result: Err(crate::login_item::LoginItemFailure {
|
|
status: Some(LoginItemStatus::Disabled),
|
|
message: "Registration failed".into(),
|
|
}),
|
|
}));
|
|
// Clearing only the error still needs a redraw.
|
|
assert!(view.apply_login_item_response(LoginItemResponse {
|
|
request: LoginItemRequest::SetEnabled(false),
|
|
result: Ok(LoginItemStatus::Disabled),
|
|
}));
|
|
assert!(view.launch_at_login_error.is_none());
|
|
assert!(view.apply_login_item_response(LoginItemResponse {
|
|
request: LoginItemRequest::SetEnabled(true),
|
|
result: Ok(LoginItemStatus::RequiresApproval),
|
|
}));
|
|
assert_eq!(
|
|
view.launch_at_login_status,
|
|
Some(LoginItemStatus::RequiresApproval)
|
|
);
|
|
assert!(view.launch_at_login_error.is_none());
|
|
assert!(view.apply_login_item_response(LoginItemResponse {
|
|
request: LoginItemRequest::Status,
|
|
result: Ok(LoginItemStatus::Enabled),
|
|
}));
|
|
assert!(view.launch_at_login_toggle.enabled());
|
|
assert!(!view.apply_login_item_response(LoginItemResponse {
|
|
request: LoginItemRequest::Status,
|
|
result: Ok(LoginItemStatus::Enabled),
|
|
}));
|
|
});
|
|
});
|
|
}
|
|
|
|
fn reject_settings_save(_: &AppSettings) -> color_eyre::Result<()> {
|
|
Err(color_eyre::eyre::eyre!("fixture persistence failure"))
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn model_deletion_confirms_first_and_spares_the_dictation_model(cx: &mut gpui::TestAppContext) {
|
|
let (view, cx) = cx.add_window_view(editor_fixture);
|
|
cx.update(|_, cx| {
|
|
view.update(cx, |view, _| {
|
|
view.transcription_preview_installed = Some(true);
|
|
view.transcription_picker_language = Some("en".into());
|
|
let current = definition(view.settings.transcription.model);
|
|
let other = crate::transcription_models::choices_for_runtime("en")
|
|
.into_iter()
|
|
.map(|choice| choice.model)
|
|
.find(|model| {
|
|
matches!(model.runtime, ModelRuntime::Gguf(_)) && model.id != current.id
|
|
})
|
|
.unwrap();
|
|
|
|
assert_eq!(
|
|
view.transcription_model_deletion(current, true),
|
|
ModelDeletion::Unavailable
|
|
);
|
|
assert_eq!(
|
|
view.transcription_model_deletion(other, false),
|
|
ModelDeletion::Unavailable
|
|
);
|
|
assert_eq!(
|
|
view.transcription_model_deletion(other, true),
|
|
ModelDeletion::Offered
|
|
);
|
|
|
|
view.delete_transcription_model(other);
|
|
assert_eq!(
|
|
view.transcription_model_deletion(other, true),
|
|
ModelDeletion::Confirming
|
|
);
|
|
view.clear_transcription_error();
|
|
assert_eq!(
|
|
view.transcription_model_deletion(other, true),
|
|
ModelDeletion::Offered
|
|
);
|
|
|
|
view.delete_transcription_model(other);
|
|
view.delete_transcription_model(other);
|
|
assert_eq!(view.transcription_deletion, None);
|
|
assert_eq!(view.transcription_deletion_error, None);
|
|
|
|
view.transcription_status.model = Some(other.id);
|
|
assert_eq!(
|
|
view.transcription_model_deletion(other, true),
|
|
ModelDeletion::Unavailable
|
|
);
|
|
});
|
|
});
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn activity_log_is_only_read_when_an_observing_pane_needs_it(cx: &mut gpui::TestAppContext) {
|
|
let path = std::env::temp_dir().join(format!(
|
|
"hex-lazy-activity-{}-{}.ndjson",
|
|
std::process::id(),
|
|
now_ms()
|
|
));
|
|
std::fs::write(&path, b"{\"kind\":\"context\",\"timestamp_ms\":1,\"application\":\"Fixture\",\"browser_url\":null}\n").unwrap();
|
|
let (view, cx) = cx.add_window_view(editor_fixture);
|
|
cx.update(|_, cx| {
|
|
view.update(cx, |view, cx| {
|
|
view.event_reader = EventReader::open(&path);
|
|
view.pane = Pane::Settings;
|
|
view.reload_events();
|
|
assert!(view.event_reader.events().is_empty());
|
|
view.select_pane(Pane::Commands, cx);
|
|
assert_eq!(view.current_context.0.as_deref(), Some("Fixture"));
|
|
|
|
std::fs::write(
|
|
&path,
|
|
b"{\"kind\":\"session_started\",\"timestamp_ms\":2}\n",
|
|
)
|
|
.unwrap();
|
|
view.select_pane(Pane::Settings, cx);
|
|
view.reload_events();
|
|
assert_eq!(view.current_context.0.as_deref(), Some("Fixture"));
|
|
view.select_pane(Pane::Activity, cx);
|
|
assert_eq!(view.current_context, (None, None));
|
|
assert_eq!(view.activity.session_started_at, Some(2));
|
|
});
|
|
});
|
|
std::fs::remove_file(path).unwrap();
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn failed_shortcut_save_stays_in_capture_and_preserves_pending_edits(
|
|
cx: &mut gpui::TestAppContext,
|
|
) {
|
|
let (view, cx) = cx.add_window_view(editor_fixture);
|
|
cx.update(|_, cx| {
|
|
view.update(cx, |view, cx| {
|
|
view.settings.transcription.recognition_hints = "Unsaved vocabulary".into();
|
|
view.schedule_settings_save(cx);
|
|
let generation = view.settings_save_generation;
|
|
let before = serde_json::to_value(&view.settings).unwrap();
|
|
view.settings_save_override = Some(reject_settings_save);
|
|
view.hotkey_capture = HotkeyCaptureState::Listening {
|
|
kind: HotkeyKind::Dictation,
|
|
modifiers: HotkeyModifiers::default(),
|
|
message: None,
|
|
started_at: Instant::now(),
|
|
};
|
|
let binding = HotkeyBinding {
|
|
modifiers: HotkeyModifiers {
|
|
control: Some(ModifierSide::Either),
|
|
..Default::default()
|
|
},
|
|
key: None,
|
|
};
|
|
view.save_hotkey_binding(binding.clone(), cx);
|
|
assert!(view.hotkey_capture.is_listening());
|
|
assert_eq!(serde_json::to_value(&view.settings).unwrap(), before);
|
|
assert!(view.settings_dirty);
|
|
assert_eq!(view.settings_save_generation, generation);
|
|
assert_eq!(
|
|
view.settings_load_error.as_deref(),
|
|
Some("fixture persistence failure")
|
|
);
|
|
|
|
// An immediate retry commits the unrelated draft as well, and only
|
|
// then ends capture and invalidates the earlier debounce.
|
|
view.settings_save_override = None;
|
|
view.save_hotkey_binding(binding.clone(), cx);
|
|
assert!(matches!(
|
|
view.hotkey_capture,
|
|
HotkeyCaptureState::Saved { .. }
|
|
));
|
|
assert_eq!(view.settings.dictation_hotkey, binding);
|
|
assert_eq!(
|
|
view.settings.transcription.recognition_hints,
|
|
"Unsaved vocabulary"
|
|
);
|
|
assert!(!view.settings_dirty);
|
|
assert_ne!(view.settings_save_generation, generation);
|
|
assert!(view.settings_load_error.is_none());
|
|
})
|
|
});
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn failed_retention_save_keeps_previous_choice_and_reports_the_error(
|
|
cx: &mut gpui::TestAppContext,
|
|
) {
|
|
let (view, cx) = cx.add_window_view(editor_fixture);
|
|
cx.update(|_, cx| {
|
|
view.update(cx, |view, cx| {
|
|
view.settings_save_override = Some(reject_settings_save);
|
|
view.set_history_retention(HistoryRetention::Off, cx);
|
|
assert_eq!(view.settings.history_retention, HistoryRetention::Week);
|
|
assert_eq!(
|
|
view.settings_load_error.as_deref(),
|
|
Some("fixture persistence failure")
|
|
);
|
|
})
|
|
});
|
|
cx.run_until_parked();
|
|
assert!(cx.debug_bounds("settings-error").is_some());
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn mode_rows_preserve_edits_across_add_delete_and_supersede_old_debounces(
|
|
cx: &mut gpui::TestAppContext,
|
|
) {
|
|
let (view, cx) = cx.add_window_view(editor_fixture);
|
|
cx.update(|_, cx| {
|
|
view.update(cx, |view, cx| {
|
|
let name = view
|
|
.mode_inputs_for(ModeSelection::Custom(0))
|
|
.name
|
|
.entity
|
|
.clone();
|
|
name.update(cx, |input, cx| input.set_text("Pending mode name", cx));
|
|
view.sync_processing_settings(cx);
|
|
assert!(view.settings_dirty);
|
|
let pending_generation = view.settings_save_generation;
|
|
|
|
view.settings_save_override = Some(reject_settings_save);
|
|
assert!(view.add_mode(cx).is_none());
|
|
view.delete_mode(0, cx);
|
|
assert_eq!(view.mode_editors.modes.len(), 1);
|
|
assert_eq!(
|
|
view.settings_candidate().dictation_processing.modes[0].name,
|
|
"Pending mode name"
|
|
);
|
|
assert_eq!(
|
|
view.settings.dictation_processing.modes[0].name,
|
|
"Work notes"
|
|
);
|
|
assert_eq!(view.settings_save_generation, pending_generation);
|
|
|
|
view.settings_save_override = None;
|
|
assert!(view.add_mode(cx) == Some(ModeSelection::Custom(1)));
|
|
assert_eq!(view.mode_editors.modes.len(), 2);
|
|
assert_eq!(
|
|
view.settings.dictation_processing.modes[0].name,
|
|
"Pending mode name"
|
|
);
|
|
let second_name = view
|
|
.mode_inputs_for(ModeSelection::Custom(1))
|
|
.name
|
|
.entity
|
|
.clone();
|
|
second_name.update(cx, |input, cx| input.set_text("Survivor", cx));
|
|
view.sync_processing_settings(cx);
|
|
view.delete_mode(0, cx);
|
|
assert_eq!(view.mode_editors.modes.len(), 1);
|
|
assert_eq!(
|
|
view.mode_settings(ModeSelection::Custom(0)).name,
|
|
"Survivor"
|
|
);
|
|
assert_eq!(view.settings.dictation_processing.modes[0].name, "Survivor");
|
|
assert!(!view.settings_dirty);
|
|
view.select_model(
|
|
ModelPickerTarget::Mode(ModeSelection::Custom(0)),
|
|
Some("example/writer".into()),
|
|
cx,
|
|
);
|
|
|
|
// If either obsolete debounce writes, the injected failure becomes
|
|
// visible and makes the assertions below fail.
|
|
view.settings_save_override = Some(reject_settings_save);
|
|
})
|
|
});
|
|
cx.run_until_parked();
|
|
cx.background_executor
|
|
.advance_clock(Duration::from_millis(300));
|
|
cx.run_until_parked();
|
|
cx.update(|_, cx| {
|
|
view.update(cx, |view, cx| {
|
|
assert!(view.settings_load_error.is_none());
|
|
assert!(!view.settings_dirty);
|
|
let name = view
|
|
.mode_inputs_for(ModeSelection::Custom(0))
|
|
.name
|
|
.entity
|
|
.clone();
|
|
name.update(cx, |input, cx| input.set_text("Later draft", cx));
|
|
view.sync_processing_settings(cx);
|
|
})
|
|
});
|
|
cx.run_until_parked();
|
|
cx.background_executor
|
|
.advance_clock(Duration::from_millis(300));
|
|
cx.run_until_parked();
|
|
cx.update(|_, cx| {
|
|
view.update(cx, |view, _| {
|
|
assert!(view.settings_dirty);
|
|
assert_eq!(
|
|
view.settings_load_error.as_deref(),
|
|
Some("fixture persistence failure")
|
|
);
|
|
assert_eq!(
|
|
view.settings_candidate().dictation_processing.modes[0].name,
|
|
"Later draft"
|
|
);
|
|
assert_eq!(view.settings.dictation_processing.modes[0].name, "Survivor");
|
|
assert_eq!(
|
|
view.settings.dictation_processing.modes[0]
|
|
.post_processing
|
|
.model
|
|
.as_deref(),
|
|
Some("example/writer")
|
|
);
|
|
})
|
|
});
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn settings_content_stays_inside_the_pane_at_supported_widths(cx: &mut gpui::TestAppContext) {
|
|
struct SettingsLayout;
|
|
|
|
impl Render for SettingsLayout {
|
|
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
|
|
window_frame()
|
|
.child(sidebar_frame())
|
|
.child(
|
|
div().flex_1().min_w_0().h_full().child(settings_pane(
|
|
"Settings",
|
|
"settings-scroll",
|
|
div()
|
|
.child(panel().child(settings_row(
|
|
"Microphone",
|
|
"Automatically chooses the preferred available input",
|
|
disclosure_button("Automatic"),
|
|
)))
|
|
.child(settings_copy(
|
|
"Release the microphone when idle?",
|
|
"Hex will open the microphone when you press the shortcut. This adds a start-up delay and removes pre-roll, so the beginning of speech may be missed if you speak right away.",
|
|
)),
|
|
)),
|
|
)
|
|
}
|
|
}
|
|
|
|
let (_, cx) = cx.add_window_view(|_, _| SettingsLayout);
|
|
for width in [MINIMUM_WIDTH, WINDOW_WIDTH, 1400.0] {
|
|
cx.simulate_resize(size(px(width), px(MINIMUM_HEIGHT)));
|
|
cx.update(|window, _| window.refresh());
|
|
cx.run_until_parked();
|
|
let column = cx
|
|
.debug_bounds("settings-content")
|
|
.expect("content was rendered");
|
|
let available = width - SIDEBAR_WIDTH - 64.0;
|
|
let expected_width = available.min(PANE_CONTENT_WIDTH);
|
|
assert_eq!(column.size.width, px(expected_width));
|
|
assert_eq!(
|
|
column.origin.x,
|
|
px(SIDEBAR_WIDTH + 32.0 + (available - expected_width) / 2.0)
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn command_model_failure_has_recovery_without_blocking_dictation() {
|
|
assert!(command_model_notice(&CommandModelStatus::Ready).is_none());
|
|
assert!(command_model_notice(&CommandModelStatus::Disabled).is_none());
|
|
assert_eq!(
|
|
command_model_notice(&CommandModelStatus::Loading)
|
|
.unwrap()
|
|
.0,
|
|
"Preparing voice commands"
|
|
);
|
|
let (_, description) = command_model_notice(&CommandModelStatus::Failed).unwrap();
|
|
assert!(description.contains("Retry"));
|
|
assert!(description.contains("dictation is unaffected"));
|
|
}
|
|
|
|
#[test]
|
|
fn opening_the_app_prioritizes_settings_and_missing_permissions() {
|
|
assert_eq!(Pane::default(), Pane::Settings);
|
|
let ready = SetupStatus {
|
|
microphone: PermissionState::Ready,
|
|
input_monitoring: PermissionState::Ready,
|
|
accessibility: PermissionState::Ready,
|
|
transcription_model: true,
|
|
};
|
|
assert_eq!(Pane::Modes.on_reopen(ready), Pane::Modes);
|
|
for status in [
|
|
SetupStatus {
|
|
microphone: PermissionState::NeedsRequest,
|
|
..ready
|
|
},
|
|
SetupStatus {
|
|
input_monitoring: PermissionState::NeedsSettings,
|
|
..ready
|
|
},
|
|
SetupStatus {
|
|
accessibility: PermissionState::NeedsSettings,
|
|
..ready
|
|
},
|
|
] {
|
|
assert_eq!(Pane::Modes.on_reopen(status), Pane::Settings);
|
|
assert_eq!(Pane::VoiceAction.on_reopen(status), Pane::Settings);
|
|
assert_eq!(Pane::Settings.on_reopen(status), Pane::Settings);
|
|
}
|
|
assert_eq!(
|
|
Pane::from_developer(
|
|
serde_json::from_str::<DeveloperPane>(r#""replacements""#).unwrap()
|
|
),
|
|
Pane::Modes
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn missing_dictation_model_has_a_notice_even_with_all_permissions_granted() {
|
|
let mut status = SetupStatus {
|
|
microphone: PermissionState::Ready,
|
|
input_monitoring: PermissionState::Ready,
|
|
accessibility: PermissionState::Ready,
|
|
transcription_model: false,
|
|
};
|
|
let (title, description) = dictation_model_notice(status, false).unwrap();
|
|
assert_eq!(title, "Download a speech model to start dictating");
|
|
assert!(description.contains("dictation shortcut"));
|
|
assert!(!status.ready());
|
|
|
|
assert_eq!(
|
|
dictation_model_notice(status, true).unwrap().0,
|
|
"Preparing speech model"
|
|
);
|
|
// A failed or cancelled preparation must expose the download action again.
|
|
assert_eq!(dictation_model_notice(status, false).unwrap().0, title);
|
|
|
|
status.transcription_model = true;
|
|
assert!(dictation_model_notice(status, false).is_none());
|
|
assert!(dictation_model_notice(status, true).is_none());
|
|
|
|
// Permission failures have their own setup UI.
|
|
status.microphone = PermissionState::NeedsRequest;
|
|
assert!(dictation_model_notice(status, false).is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn sidebar_update_button_only_appears_for_an_available_update() {
|
|
use crate::sparkle::UpdateStatus;
|
|
|
|
for (status, visible) in [
|
|
(UpdateStatus::Unavailable, false),
|
|
(UpdateStatus::Idle, false),
|
|
(UpdateStatus::Checking, false),
|
|
(UpdateStatus::UpToDate, false),
|
|
(UpdateStatus::UpdateAvailable, true),
|
|
] {
|
|
assert_eq!(sidebar_update_button(status, false).is_some(), visible);
|
|
}
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn sidebar_update_click_dispatches_only_outside_preview(cx: &mut gpui::TestAppContext) {
|
|
struct UpdateButton {
|
|
preview: bool,
|
|
}
|
|
|
|
impl Render for UpdateButton {
|
|
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
|
|
sidebar_update_button(crate::sparkle::UpdateStatus::UpdateAvailable, self.preview)
|
|
.unwrap()
|
|
.debug_selector(|| "sidebar-update".into())
|
|
}
|
|
}
|
|
|
|
let calls = Rc::new(std::cell::Cell::new(0));
|
|
cx.update(|cx| {
|
|
let calls = calls.clone();
|
|
cx.on_action(move |_: &CheckForUpdates, _| calls.set(calls.get() + 1));
|
|
});
|
|
|
|
for preview in [true, false] {
|
|
let (_, cx) = cx.add_window_view(|_, _| UpdateButton { preview });
|
|
cx.update(|window, cx| {
|
|
// Test windows do not activate automatically; an inactive window masks the bug.
|
|
window.activate_window();
|
|
assert!(cx.active_window() == Some(window.window_handle()));
|
|
});
|
|
cx.run_until_parked();
|
|
let button = cx.debug_bounds("sidebar-update").unwrap();
|
|
cx.simulate_click(button.center(), GpuiModifiers::default());
|
|
assert_eq!(calls.get(), usize::from(!preview), "preview={preview}");
|
|
}
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn microphone_picker_occludes_the_controls_beneath_it(cx: &mut gpui::TestAppContext) {
|
|
#[derive(Default)]
|
|
struct Observed {
|
|
beneath_clicks: usize,
|
|
beneath_hovered: bool,
|
|
chosen: Option<Option<String>>,
|
|
dismissed: usize,
|
|
}
|
|
|
|
struct PickerOverControl {
|
|
observed: Rc<RefCell<Observed>>,
|
|
}
|
|
|
|
impl Render for PickerOverControl {
|
|
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
|
|
let observed = self.observed.clone();
|
|
let hovered = self.observed.clone();
|
|
let chosen = self.observed.clone();
|
|
let dismissed = self.observed.clone();
|
|
div()
|
|
.size_full()
|
|
.flex()
|
|
.flex_col()
|
|
.child(
|
|
div()
|
|
.relative()
|
|
.w(px(220.0))
|
|
.child(disclosure_button("Automatic").id("anchor"))
|
|
.child(deferred(microphone_picker_menu(
|
|
vec![None, Some("Studio Microphone".into())],
|
|
None,
|
|
None,
|
|
move |device, _, _| {
|
|
chosen.borrow_mut().chosen = Some(device.clone());
|
|
},
|
|
move |_, _, _| dismissed.borrow_mut().dismissed += 1,
|
|
)))
|
|
.child(
|
|
div()
|
|
.id("beneath")
|
|
.debug_selector(|| "beneath".into())
|
|
.w(px(220.0))
|
|
.h(px(120.0))
|
|
.on_hover(move |is_hovered, _, _| {
|
|
if *is_hovered {
|
|
hovered.borrow_mut().beneath_hovered = true;
|
|
}
|
|
})
|
|
.on_click(move |_, _, _| {
|
|
observed.borrow_mut().beneath_clicks += 1;
|
|
}),
|
|
),
|
|
)
|
|
.child(
|
|
div()
|
|
.id("outside")
|
|
.debug_selector(|| "outside".into())
|
|
.w(px(220.0))
|
|
.h(px(200.0)),
|
|
)
|
|
}
|
|
}
|
|
|
|
let observed = Rc::new(RefCell::new(Observed::default()));
|
|
let (_, cx) = cx.add_window_view(|_, _| PickerOverControl {
|
|
observed: observed.clone(),
|
|
});
|
|
cx.update(|window, cx| {
|
|
window.activate_window();
|
|
assert!(cx.active_window() == Some(window.window_handle()));
|
|
});
|
|
cx.run_until_parked();
|
|
let beneath = cx.debug_bounds("beneath").unwrap();
|
|
let menu = cx.debug_bounds("microphone-picker").unwrap();
|
|
let second_choice = cx.debug_bounds("microphone-choice-1").unwrap();
|
|
assert!(
|
|
menu.contains(&second_choice.center()) && beneath.contains(&second_choice.center()),
|
|
"fixture must place a menu choice over the control beneath"
|
|
);
|
|
|
|
cx.simulate_mouse_move(second_choice.center(), None, GpuiModifiers::default());
|
|
cx.run_until_parked();
|
|
assert!(
|
|
!observed.borrow().beneath_hovered,
|
|
"hover leaked beneath the menu"
|
|
);
|
|
|
|
cx.simulate_click(second_choice.center(), GpuiModifiers::default());
|
|
cx.run_until_parked();
|
|
{
|
|
let observed = observed.borrow();
|
|
assert_eq!(observed.beneath_clicks, 0, "click leaked beneath the menu");
|
|
assert_eq!(observed.chosen, Some(Some("Studio Microphone".into())));
|
|
assert_eq!(
|
|
observed.dismissed, 0,
|
|
"choosing must not also count as dismissal"
|
|
);
|
|
}
|
|
|
|
let outside = cx.debug_bounds("outside").unwrap();
|
|
cx.simulate_click(outside.center(), GpuiModifiers::default());
|
|
cx.run_until_parked();
|
|
assert_eq!(observed.borrow().dismissed, 1);
|
|
}
|
|
|
|
#[test]
|
|
fn inactive_hotkey_controls_keep_their_idle_width() {
|
|
assert_eq!(hotkey_control_width(false, 146.0, 270.0), 146.0);
|
|
assert_eq!(hotkey_control_width(true, 146.0, 270.0), 270.0);
|
|
assert_eq!(hotkey_control_intensity(false, 0.8), 0.0);
|
|
assert_eq!(hotkey_control_intensity(true, 0.8), 0.8);
|
|
}
|
|
|
|
#[test]
|
|
fn voice_action_defaults_off_and_explains_its_inactive_shortcut() {
|
|
let settings = AppSettings::default();
|
|
assert!(!settings.voice_action.enabled);
|
|
let description = voice_action_description(settings.voice_action.enabled);
|
|
assert!(description.contains("Off by default"));
|
|
assert!(description.contains("not reserved"));
|
|
|
|
let description = voice_action_description(true);
|
|
assert!(description.contains("OpenCode"));
|
|
assert!(!description.contains("not reserved"));
|
|
}
|
|
|
|
#[test]
|
|
fn disabled_voice_action_does_not_reserve_its_shortcut() {
|
|
let mut settings = AppSettings::default();
|
|
for enabled in [false, true] {
|
|
settings.voice_action.enabled = enabled;
|
|
for kind in [HotkeyKind::Dictation, HotkeyKind::PasteLast] {
|
|
assert_eq!(
|
|
hotkey_binding_conflicts(&settings, kind, &settings.edit_hotkey),
|
|
enabled,
|
|
);
|
|
}
|
|
}
|
|
settings.voice_action.enabled = false;
|
|
assert!(hotkey_binding_conflicts(
|
|
&settings,
|
|
HotkeyKind::Edit,
|
|
&settings.dictation_hotkey,
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn voice_action_opt_in_rejects_active_conflicts_without_rebinding() {
|
|
let defaults = AppSettings::default();
|
|
let mut active = vec![
|
|
defaults.dictation_hotkey,
|
|
defaults.paste_last_hotkey.unwrap(),
|
|
];
|
|
if crate::DEVELOPER_FEATURES_ENABLED {
|
|
active.push(HotkeyBinding::paste_meeting_default());
|
|
}
|
|
for binding in active {
|
|
let mut settings = AppSettings {
|
|
edit_hotkey: binding,
|
|
..AppSettings::default()
|
|
};
|
|
let before = serde_json::to_value(&settings).unwrap();
|
|
let error = set_voice_action_enabled(&mut settings, true).unwrap_err();
|
|
|
|
assert!(error.contains("already in use"));
|
|
assert!(error.contains("Change it below"));
|
|
assert_eq!(serde_json::to_value(&settings).unwrap(), before);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn voice_action_toggle_preserves_configuration_and_can_always_disable() {
|
|
let mut settings: AppSettings = serde_json::from_value(serde_json::json!({
|
|
"voice_action": {
|
|
"model": "example/saved-model",
|
|
"variant": "high",
|
|
"deadline_seconds": 45
|
|
},
|
|
"edit_hotkey": {
|
|
"modifiers": { "control": "left" }
|
|
}
|
|
}))
|
|
.unwrap();
|
|
assert!(!settings.voice_action.enabled);
|
|
let mut expected = serde_json::to_value(&settings).unwrap();
|
|
for enabled in [true, false] {
|
|
set_voice_action_enabled(&mut settings, enabled).unwrap();
|
|
expected["voice_action"]["enabled"] = serde_json::json!(enabled);
|
|
assert_eq!(serde_json::to_value(&settings).unwrap(), expected);
|
|
}
|
|
|
|
set_voice_action_enabled(&mut settings, true).unwrap();
|
|
settings.dictation_hotkey = settings.edit_hotkey.clone();
|
|
set_voice_action_enabled(&mut settings, false).unwrap();
|
|
assert!(!settings.voice_action.enabled);
|
|
}
|
|
|
|
#[test]
|
|
fn shortcut_side_changes_reject_overlap_without_changing_the_saved_binding() {
|
|
let mut settings = AppSettings::default();
|
|
settings.voice_action.enabled = true;
|
|
settings.dictation_hotkey.modifiers.option = Some(ModifierSide::Left);
|
|
settings.edit_hotkey = HotkeyBinding {
|
|
modifiers: HotkeyModifiers {
|
|
option: Some(ModifierSide::Right),
|
|
..Default::default()
|
|
},
|
|
key: None,
|
|
};
|
|
let original = settings.dictation_hotkey.clone();
|
|
|
|
assert!(
|
|
hotkey_side_binding(&settings, HotkeyKind::Dictation, ModifierSide::Right).is_none()
|
|
);
|
|
assert!(
|
|
hotkey_side_binding(&settings, HotkeyKind::Dictation, ModifierSide::Either).is_none()
|
|
);
|
|
assert_eq!(settings.dictation_hotkey, original);
|
|
assert_eq!(
|
|
hotkey_side_binding(&settings, HotkeyKind::Dictation, ModifierSide::Left),
|
|
Some(original)
|
|
);
|
|
|
|
settings.edit_hotkey = HotkeyBinding::edit_default();
|
|
let candidate =
|
|
hotkey_side_binding(&settings, HotkeyKind::Dictation, ModifierSide::Right).unwrap();
|
|
assert_eq!(
|
|
standalone_modifier_side(&candidate),
|
|
Some(ModifierSide::Right)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn side_selection_changes_modifier_only_bindings_and_ignores_key_chords() {
|
|
let mut standalone = HotkeyBinding {
|
|
modifiers: HotkeyModifiers {
|
|
option: Some(ModifierSide::Left),
|
|
..Default::default()
|
|
},
|
|
key: None,
|
|
};
|
|
set_standalone_modifier_side(&mut standalone, ModifierSide::Either);
|
|
assert_eq!(
|
|
standalone_modifier_side(&standalone),
|
|
Some(ModifierSide::Either)
|
|
);
|
|
|
|
let mut modifier_chord = HotkeyBinding {
|
|
modifiers: normalize_captured_modifiers(HotkeyModifiers {
|
|
option: Some(ModifierSide::Right),
|
|
command: Some(ModifierSide::Right),
|
|
..Default::default()
|
|
}),
|
|
key: None,
|
|
};
|
|
assert_eq!(
|
|
standalone_modifier_side(&modifier_chord),
|
|
Some(ModifierSide::Right)
|
|
);
|
|
assert_eq!(modifier_chord.keycaps(), vec!["R⌥", "R⌘"]);
|
|
set_standalone_modifier_side(&mut modifier_chord, ModifierSide::Left);
|
|
assert_eq!(
|
|
modifier_chord.modifiers,
|
|
HotkeyModifiers {
|
|
option: Some(ModifierSide::Left),
|
|
command: Some(ModifierSide::Left),
|
|
..Default::default()
|
|
}
|
|
);
|
|
|
|
let mixed = normalize_captured_modifiers(HotkeyModifiers {
|
|
option: Some(ModifierSide::Left),
|
|
command: Some(ModifierSide::Right),
|
|
..Default::default()
|
|
});
|
|
assert_eq!(
|
|
mixed,
|
|
HotkeyModifiers {
|
|
option: Some(ModifierSide::Either),
|
|
command: Some(ModifierSide::Either),
|
|
..Default::default()
|
|
}
|
|
);
|
|
|
|
let mut chord = HotkeyBinding {
|
|
modifiers: HotkeyModifiers {
|
|
option: Some(ModifierSide::Left),
|
|
..Default::default()
|
|
},
|
|
key: Some(HotkeyKey {
|
|
code: 0,
|
|
label: "A".into(),
|
|
}),
|
|
};
|
|
set_standalone_modifier_side(&mut chord, ModifierSide::Right);
|
|
assert_eq!(chord.modifiers.option, Some(ModifierSide::Left));
|
|
}
|
|
|
|
#[test]
|
|
fn production_navigation_keeps_commands_available_as_an_opt_in() {
|
|
assert_eq!(
|
|
Pane::all(false, false),
|
|
vec![
|
|
Pane::Settings,
|
|
Pane::Modes,
|
|
Pane::Commands,
|
|
Pane::VoiceAction,
|
|
Pane::History,
|
|
]
|
|
);
|
|
assert_eq!(
|
|
Pane::all(false, true),
|
|
vec![
|
|
Pane::Settings,
|
|
Pane::Modes,
|
|
Pane::Commands,
|
|
Pane::VoiceAction,
|
|
Pane::History,
|
|
Pane::Meetings,
|
|
],
|
|
"the meetings opt-in adds only the Meetings pane"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn developer_navigation_appends_developer_panes_in_order() {
|
|
assert_eq!(
|
|
Pane::all(true, false),
|
|
vec![
|
|
Pane::Settings,
|
|
Pane::Modes,
|
|
Pane::Commands,
|
|
Pane::VoiceAction,
|
|
Pane::History,
|
|
Pane::HudLab,
|
|
Pane::Meetings,
|
|
Pane::Activity,
|
|
]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn application_catalog_loads_only_when_explicitly_requested() {
|
|
let loading = ApplicationCatalogState::Loading;
|
|
let loaded = ApplicationCatalogState::Loaded(Vec::new());
|
|
|
|
assert!(application_catalog_load_needed(false, &loading, false));
|
|
assert!(!application_catalog_load_needed(false, &loading, true));
|
|
assert!(!application_catalog_load_needed(false, &loaded, false));
|
|
assert!(!application_catalog_load_needed(true, &loading, false));
|
|
}
|
|
|
|
#[test]
|
|
fn hotkey_capture_preserves_the_function_modifier() {
|
|
let modifiers = hotkey_modifiers_with_flags(
|
|
GpuiModifiers {
|
|
function: true,
|
|
..Default::default()
|
|
},
|
|
0,
|
|
);
|
|
|
|
assert!(modifiers.function);
|
|
assert_eq!(modifiers.count(), 1);
|
|
}
|
|
|
|
#[test]
|
|
fn toggle_spring_is_frame_rate_independent_and_settles() {
|
|
let simulate = |frame_rate: u32| {
|
|
let mut spring = ToggleSpring::new(false);
|
|
spring.set_enabled(true);
|
|
for _ in 0..frame_rate {
|
|
spring.advance(Duration::from_secs_f32(1.0 / frame_rate as f32));
|
|
}
|
|
spring
|
|
};
|
|
|
|
let at_60_hz = simulate(60);
|
|
let at_120_hz = simulate(120);
|
|
assert!(at_60_hz.is_settled());
|
|
assert!(at_120_hz.is_settled());
|
|
assert!((at_60_hz.position - at_120_hz.position).abs() < 0.001);
|
|
assert_eq!(at_60_hz.position, 1.0);
|
|
}
|
|
|
|
#[test]
|
|
fn recent_activity_keeps_context_older_than_the_visible_window() {
|
|
let path = std::env::temp_dir().join(format!(
|
|
"voice-control-app-window-{}-{}.ndjson",
|
|
std::process::id(),
|
|
crate::events::now_ms()
|
|
));
|
|
let mut lines = vec![
|
|
serde_json::to_string(&VoiceEvent::Context {
|
|
timestamp_ms: 1,
|
|
application: Some("Brave Browser".into()),
|
|
browser_url: Some("https://meet.google.com/example".into()),
|
|
})
|
|
.unwrap(),
|
|
];
|
|
lines.extend((0..=ACTIVITY_LIMIT).map(|timestamp_ms| {
|
|
serde_json::to_string(&VoiceEvent::State {
|
|
timestamp_ms: timestamp_ms as u64 + 2,
|
|
state: VoiceState::Listening,
|
|
device: "Test microphone".into(),
|
|
})
|
|
.unwrap()
|
|
}));
|
|
fs::write(&path, lines.join("\n")).unwrap();
|
|
|
|
let mut reader = EventReader::open(&path);
|
|
reader.refresh().unwrap();
|
|
|
|
assert_eq!(reader.recent(ACTIVITY_LIMIT).len(), ACTIVITY_LIMIT);
|
|
assert_eq!(
|
|
activity_context(&reader),
|
|
(Some("Brave Browser".into()), Some("meet.google.com".into()))
|
|
);
|
|
fs::remove_file(path).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn browser_hosts_are_canonicalized_and_deduplicated() {
|
|
assert_eq!(
|
|
browser_hosts(" https://www.Reddit.com/r/rust, , reddit.com, github.com/path"),
|
|
["github.com", "reddit.com", "www.reddit.com"]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn transformations_reorder_in_both_directions() {
|
|
let mut transformations = vec!["one".into(), "two".into(), "three".into()];
|
|
|
|
assert!(reorder_transformation(&mut transformations, "one", 2));
|
|
assert_eq!(transformations, ["two", "three", "one"]);
|
|
assert!(reorder_transformation(&mut transformations, "one", 0));
|
|
assert_eq!(transformations, ["one", "two", "three"]);
|
|
}
|
|
|
|
#[test]
|
|
fn transformation_reorder_ignores_same_position_and_missing_ids() {
|
|
let mut transformations = vec!["one".into(), "two".into()];
|
|
|
|
assert!(!reorder_transformation(&mut transformations, "one", 0));
|
|
assert!(!reorder_transformation(&mut transformations, "missing", 1));
|
|
assert_eq!(transformations, ["one", "two"]);
|
|
}
|
|
|
|
#[test]
|
|
fn picker_arrows_stop_at_the_ends() {
|
|
assert_eq!(advance_highlight(0, -1, 4), 0);
|
|
assert_eq!(advance_highlight(2, 1, 4), 3);
|
|
assert_eq!(advance_highlight(3, 1, 4), 3);
|
|
}
|
|
|
|
#[test]
|
|
fn selected_transcription_model_is_not_active_until_installed() {
|
|
let selection = TranscriptionSelection::default();
|
|
let model = definition(selection.model);
|
|
|
|
assert!(!transcription_selection_is_active(
|
|
&selection,
|
|
model,
|
|
&selection.language,
|
|
false
|
|
));
|
|
assert!(transcription_selection_is_active(
|
|
&selection,
|
|
model,
|
|
&selection.language,
|
|
true
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn selected_model_presents_provider_name_and_resolved_key() {
|
|
let catalog = ModelCatalogState::Loaded(ModelCatalog {
|
|
models: vec![crate::dictation_processor::ModelChoice {
|
|
key: "opencode/example-rewrite".into(),
|
|
name: "Example Rewrite".into(),
|
|
provider: "opencode".into(),
|
|
variants: Vec::new(),
|
|
}],
|
|
default_key: Some("opencode/example-rewrite".into()),
|
|
default_name: Some("Example Rewrite".into()),
|
|
default_variant: None,
|
|
});
|
|
|
|
let selected = model_presentation(&catalog, Some("opencode/example-rewrite")).unwrap();
|
|
assert_eq!(selected.name, "Example Rewrite");
|
|
assert_eq!(selected.provider, "OpenCode");
|
|
assert_eq!(selected.key, "opencode/example-rewrite");
|
|
assert!(!selected.is_default);
|
|
|
|
let default = model_presentation(&catalog, None).unwrap();
|
|
assert!(default.is_default);
|
|
}
|
|
|
|
#[test]
|
|
fn model_search_finds_provider_models_with_nested_ids() {
|
|
let catalog = ModelCatalog {
|
|
models: vec![crate::dictation_processor::ModelChoice {
|
|
key: "console-groq/openai/gpt-oss-120b".into(),
|
|
name: "GPT OSS 120B".into(),
|
|
provider: "console-groq".into(),
|
|
variants: Vec::new(),
|
|
}],
|
|
default_key: None,
|
|
default_name: None,
|
|
default_variant: None,
|
|
};
|
|
|
|
assert_eq!(
|
|
filtered_model_keys(&catalog, "gpt oss"),
|
|
[Some("console-groq/openai/gpt-oss-120b".into())]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn opencode_failure_copy_preserves_the_actionable_error() {
|
|
let state = ModelCatalogState::Failed(
|
|
"OpenCode /api/model failed: config.providers was invalid".into(),
|
|
);
|
|
|
|
let copy = opencode_unavailable_copy(&state, OpenCodeFeature::VoiceAction).unwrap();
|
|
|
|
assert_eq!(copy.title, "OpenCode is unavailable");
|
|
assert_eq!(
|
|
copy.description,
|
|
"Hex could not load the OpenCode model catalog."
|
|
);
|
|
assert_eq!(
|
|
copy.error.as_deref(),
|
|
Some("OpenCode /api/model failed: config.providers was invalid")
|
|
);
|
|
assert!(copy.can_retry);
|
|
assert!(!copy.can_open_setup);
|
|
}
|
|
|
|
#[test]
|
|
fn opencode_missing_copy_offers_setup_without_an_error() {
|
|
let copy =
|
|
opencode_unavailable_copy(&ModelCatalogState::Missing, OpenCodeFeature::VoiceAction)
|
|
.unwrap();
|
|
|
|
assert_eq!(copy.title, "Voice Action requires OpenCode");
|
|
assert_eq!(copy.error, None);
|
|
assert!(copy.can_retry);
|
|
assert!(copy.can_open_setup);
|
|
}
|
|
|
|
#[test]
|
|
fn opencode_transformation_copy_describes_modes_without_changing_actions() {
|
|
let loading =
|
|
opencode_unavailable_copy(&ModelCatalogState::Loading, OpenCodeFeature::Transformation)
|
|
.unwrap();
|
|
assert_eq!(loading.title, "Checking for OpenCode");
|
|
assert_eq!(
|
|
loading.description,
|
|
"OpenCode transformation will be available after Hex connects to OpenCode."
|
|
);
|
|
assert!(!loading.can_retry);
|
|
assert!(!loading.can_open_setup);
|
|
|
|
let missing =
|
|
opencode_unavailable_copy(&ModelCatalogState::Missing, OpenCodeFeature::Transformation)
|
|
.unwrap();
|
|
assert_eq!(missing.title, "Transformation requires OpenCode");
|
|
assert_eq!(
|
|
missing.description,
|
|
"Install and configure OpenCode to transform dictated text."
|
|
);
|
|
assert_eq!(missing.error, None);
|
|
assert!(missing.can_retry);
|
|
assert_eq!(missing.retry_label, "Check again");
|
|
assert!(missing.can_open_setup);
|
|
|
|
let failed = ModelCatalogState::Failed("catalog failure".into());
|
|
let error = opencode_unavailable_copy(&failed, OpenCodeFeature::Transformation).unwrap();
|
|
assert_eq!(error.title, "OpenCode is unavailable");
|
|
assert_eq!(error.error.as_deref(), Some("catalog failure"));
|
|
assert!(error.can_retry);
|
|
assert!(!error.can_open_setup);
|
|
let loaded = ModelCatalogState::Loaded(ModelCatalog {
|
|
models: Vec::new(),
|
|
default_key: None,
|
|
default_name: None,
|
|
default_variant: None,
|
|
});
|
|
for feature in [
|
|
OpenCodeFeature::VoiceAction,
|
|
OpenCodeFeature::Transformation,
|
|
] {
|
|
assert!(opencode_unavailable_copy(&loaded, feature).is_none());
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn opencode_errors_are_bounded_without_splitting_utf8() {
|
|
let error = "é".repeat(MAX_OPENCODE_ERROR_BYTES);
|
|
let bounded = bounded_opencode_error(&error);
|
|
|
|
assert!(bounded.ends_with('…'));
|
|
assert!(bounded.is_char_boundary(bounded.len()));
|
|
assert!(bounded.len() <= MAX_OPENCODE_ERROR_BYTES + '…'.len_utf8());
|
|
}
|
|
|
|
#[test]
|
|
fn default_model_exposes_its_thinking_variants() {
|
|
let catalog = ModelCatalog {
|
|
models: vec![crate::dictation_processor::ModelChoice {
|
|
key: "opencode/example-rewrite".into(),
|
|
name: "Example Rewrite".into(),
|
|
provider: "opencode".into(),
|
|
variants: vec!["low".into(), "high".into()],
|
|
}],
|
|
default_key: Some("opencode/example-rewrite".into()),
|
|
default_name: Some("Example Rewrite".into()),
|
|
default_variant: None,
|
|
};
|
|
|
|
assert_eq!(model_variants(&catalog, None), ["low", "high"]);
|
|
}
|
|
|
|
#[test]
|
|
fn model_variant_selection_resolves_defaults_without_replacing_explicit_models() {
|
|
let catalog = ModelCatalogState::Loaded(ModelCatalog {
|
|
models: Vec::new(),
|
|
default_key: Some("example/rewrite-default".into()),
|
|
default_name: Some("Example Rewrite".into()),
|
|
default_variant: None,
|
|
});
|
|
for (target, path) in [
|
|
(
|
|
ModelPickerTarget::Mode(ModeSelection::Default),
|
|
"/dictation_processing/default_mode/post_processing",
|
|
),
|
|
(
|
|
ModelPickerTarget::Mode(ModeSelection::Custom(0)),
|
|
"/dictation_processing/modes/0/post_processing",
|
|
),
|
|
(ModelPickerTarget::VoiceAction, "/voice_action"),
|
|
] {
|
|
for model in [None, Some("example/explicit-selection")] {
|
|
for variant in [None, Some("high")] {
|
|
let mut settings: AppSettings = serde_json::from_value(serde_json::json!({
|
|
"dictation_processing": {
|
|
"default_mode": { "post_processing": { "model": model, "variant": "low" } },
|
|
"modes": [{ "post_processing": { "model": model, "variant": "low" } }]
|
|
},
|
|
"voice_action": { "model": model, "variant": "low" }
|
|
}))
|
|
.unwrap();
|
|
let mut expected = serde_json::to_value(&settings).unwrap();
|
|
let selection = expected.pointer_mut(path).unwrap();
|
|
selection["model"] =
|
|
serde_json::json!(model.or(variant.map(|_| "example/rewrite-default")));
|
|
selection["variant"] = serde_json::json!(variant);
|
|
|
|
apply_model_variant(
|
|
&mut settings,
|
|
target,
|
|
variant.map(str::to_owned),
|
|
&catalog,
|
|
);
|
|
|
|
assert_eq!(serde_json::to_value(&settings).unwrap(), expected);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn custom_catalog_preserves_groups() {
|
|
let compiled = vec![CatalogCommand {
|
|
task: "Built in".into(),
|
|
scope: CommandScope::Global,
|
|
phrase: "built in".into(),
|
|
aliases: Vec::new(),
|
|
description: "Compiled command".into(),
|
|
id: "compiled".into(),
|
|
}];
|
|
let status = StatusSnapshot {
|
|
catalog: vec![
|
|
crate::personal_commands::StatusCommand {
|
|
id: "default".into(),
|
|
phrases: vec!["default custom".into()],
|
|
group: "Other".into(),
|
|
description: "Custom command".into(),
|
|
context: StatusContext::Global,
|
|
execution: StatusExecution::Handler,
|
|
},
|
|
crate::personal_commands::StatusCommand {
|
|
id: "work".into(),
|
|
phrases: vec!["do work".into()],
|
|
group: "Work".into(),
|
|
description: "Do work".into(),
|
|
context: StatusContext::Global,
|
|
execution: StatusExecution::Handler,
|
|
},
|
|
],
|
|
..StatusSnapshot::default()
|
|
};
|
|
|
|
let merged = merged_catalog(&compiled, &status);
|
|
assert_eq!(merged[0].task, "Built in");
|
|
assert_eq!(merged[1].task, "Other");
|
|
assert_eq!(merged[2].task, "Work");
|
|
}
|
|
|
|
#[test]
|
|
fn personal_workspace_states_cover_setup_and_runtime_failures() {
|
|
let mut status = StatusSnapshot::default();
|
|
assert_eq!(
|
|
personal_workspace_state(false, false, &status),
|
|
PersonalWorkspaceState::Missing
|
|
);
|
|
assert_eq!(
|
|
personal_workspace_state(false, true, &status),
|
|
PersonalWorkspaceState::Creating
|
|
);
|
|
assert_eq!(
|
|
personal_workspace_state(true, false, &status),
|
|
PersonalWorkspaceState::Ready
|
|
);
|
|
status.host_state = HostState::Unavailable;
|
|
assert_eq!(
|
|
personal_workspace_state(true, false, &status),
|
|
PersonalWorkspaceState::Error
|
|
);
|
|
status.active_generation = Some(3);
|
|
assert_eq!(
|
|
personal_workspace_state(true, false, &status),
|
|
PersonalWorkspaceState::Ready
|
|
);
|
|
}
|
|
}
|