Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
//! The settings window: sidebar, General page, Tauri-compatible store.
//!
//! Transcribed from `apps/desktop/src/routes/(window-chrome)/settings.tsx`
//! (the shell), `settings/general.tsx` (the page), `settings/Setting.tsx` (the
//! section/card/row primitives) and the `[data-macos-native-material="settings"]`
//! block of `apps/desktop/src/styles/theme.css`, which is what actually sizes
//! this window's chrome -- most of the Tailwind on the elements is overridden
//! there, so the CSS wins wherever the two disagree and the quoted rule next to
//! each metric says which one it is.
//!
//! Every value the General page writes goes into the same tauri-plugin-store
//! file the shipping app uses, one key at a time, through
//! [`crate::store::set_store_setting`].
use std::{
cell::Cell,
path::{Path, PathBuf},
rc::Rc,
sync::Arc,
time::Duration,
};
use gpui::{
AppContext as _, Bounds, Context, Entity, FocusHandle, FontWeight, Hsla, InteractiveElement,
IntoElement, MouseButton, ParentElement, Pixels, Point, Render, RenderImage, ScrollAnchor,
ScrollHandle, SharedString, StatefulInteractiveElement, Styled, Window, div, img,
prelude::FluentBuilder, px, rgb, svg,
};
use serde_json::Value;
use crate::theme::LocaleFont as _;
use crate::{
devices::WindowOption,
i18n::{self, tr},
library::{self, RecordingItem, RecordingMode, ScreenshotItem},
main_window::Mode,
sign_in::{SignIn, SignInEvent, SignInOrigin, SignInOutcome},
store::{
self, AppTheme, DEFAULT_PROJECT_NAME_TEMPLATE, DEFAULT_SERVER_URL, GENERAL_SETTINGS,
GeneralSettings, MainWindowStartBehaviour, PostDeletionBehaviour, RECORDING_START_SAFETY,
SettingsEnum, StudioQuality, UpdateChannel, UpdateDownloadPolicy, WindowCaptureStyle,
WindowExclusion,
},
theme::Theme,
ui,
};
/// `.inner_size(782.0, 775.0)` / `.min_inner_size(780.0, 560.0)` on the
/// `ShowCapWindow::Settings` builder in `windows.rs`.
pub const SETTINGS_WIDTH: f32 = 782.;
pub const SETTINGS_HEIGHT: f32 = 775.;
pub const SETTINGS_MIN_WIDTH: f32 = 780.;
pub const SETTINGS_MIN_HEIGHT: f32 = 560.;
const MAX_PROFILE_IMAGE_BYTES: usize = 5 * 1024 * 1024;
/// `CapWindowId::Settings::traffic_lights_position` -- `Some(Some(
/// LogicalPosition::new(22.0, 22.0)))`. Unlike the main window these are the
/// *real* AppKit buttons, repositioned; `(window-chrome).tsx` returns `null`
/// for its own header on the settings route, so there is nothing hand-drawn to
/// mirror here. The Tauri inset resolves to a top-left of
/// `(inset.x, inset.y / 2 + 4)` (see `editor_window::TRAFFIC_LIGHTS` for the
/// `position_window_controls` derivation), and gpui takes the literal
/// top-left: (22, 22) -> (22, 15).
pub const TRAFFIC_LIGHTS: Point<Pixels> = Point {
x: px(22.),
y: px(15.),
};
/// AppKit's titled-window shadow uses a 16px contour; a larger content mask
/// leaves a transparent crescent between the settings window and its shadow.
pub const SETTINGS_MATERIAL_RADIUS: f64 = 16.;
// -- Sidebar/content metrics, all `:root` custom properties -----------------
/// `--macos-settings-sidebar-width: 227px`.
const SIDEBAR_WIDTH: f32 = 227.;
/// `--macos-settings-sidebar-padding-x: 10px`.
const SIDEBAR_PADDING_X: f32 = 10.;
/// `--macos-settings-content-padding-x: 16px`.
const CONTENT_PADDING_X: f32 = 16.;
/// `.cap-settings-window-spacer { height: calc(
/// var(--macos-settings-window-header-height) -
/// var(--macos-settings-sidebar-wrapper-padding)) }` -- 52 - 8. The strip the
/// repositioned traffic lights sit in.
const SIDEBAR_SPACER: f32 = 44.;
/// The sidebar list, in `settingsItems` order. `href` is the route segment,
/// which is also what `showWindow({ Settings: { page } })` takes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Page {
General,
Quality,
Shortcuts,
Cli,
Recordings,
Screenshots,
Automations,
Transcription,
Integrations,
License,
Experimental,
Feedback,
Changelog,
}
impl Page {
pub const ALL: &'static [Page] = &[
Page::General,
Page::Quality,
Page::Shortcuts,
Page::Cli,
Page::Recordings,
Page::Screenshots,
Page::Automations,
Page::Transcription,
Page::Integrations,
Page::License,
Page::Experimental,
Page::Feedback,
Page::Changelog,
];
/// The `name` field. Note "Shortcuts" for the `hotkeys` route -- the label
/// and the route disagree in the shipping app.
fn label(self) -> &'static str {
match self {
Self::General => tr::settings::nav::general(),
Self::Quality => tr::settings::nav::quality(),
Self::Shortcuts => tr::settings::nav::shortcuts(),
Self::Cli => tr::settings::nav::cli(),
Self::Recordings => tr::settings::nav::recordings(),
Self::Screenshots => tr::settings::nav::screenshots(),
Self::Automations => tr::settings::nav::automations(),
Self::Transcription => tr::settings::nav::transcription(),
Self::Integrations => tr::settings::nav::integrations(),
Self::License => tr::settings::nav::license(),
Self::Experimental => tr::settings::nav::experimental(),
Self::Feedback => tr::settings::nav::feedback(),
Self::Changelog => tr::settings::nav::changelog(),
}
}
/// The `href`, i.e. the `page` argument of `showWindow`.
pub fn slug(self) -> &'static str {
match self {
Self::General => "general",
Self::Quality => "quality",
Self::Shortcuts => "hotkeys",
Self::Cli => "cli",
Self::Recordings => "recordings",
Self::Screenshots => "screenshots",
Self::Automations => "automations",
Self::Transcription => "transcription",
Self::Integrations => "integrations",
Self::License => "license",
Self::Experimental => "experimental",
Self::Feedback => "feedback",
Self::Changelog => "changelog",
}
}
/// The `icon` field. Cap's own icon set where the TSX uses `IconCap*`,
/// Lucide's where it uses `IconLucide*` -- except Screenshots, whose
/// `IconLucideImage` is served by the Cap picture glyph already embedded
/// for the main window's screenshots button.
fn icon(self) -> &'static str {
match self {
Self::General => "icons/settings.svg",
Self::Experimental => "icons/settings-2.svg",
Self::Shortcuts => "icons/hotkeys.svg",
Self::Cli => "icons/terminal.svg",
Self::Quality => "icons/gauge.svg",
Self::Recordings => "icons/square-play.svg",
Self::Screenshots => "icons/image.svg",
Self::Automations => "icons/zap.svg",
Self::Transcription => "icons/captions.svg",
Self::Integrations => "icons/unplug.svg",
Self::License => "icons/gift.svg",
Self::Feedback => "icons/message-square-plus.svg",
Self::Changelog => "icons/bell.svg",
}
}
pub fn from_slug(slug: &str) -> Option<Self> {
Self::ALL.iter().copied().find(|page| page.slug() == slug)
}
}
/// A popup list standing in for the native `Menu.popup()` the selects use.
///
/// The variants from `S3Provider` down belong to the pages in
/// `settings_pages.rs`, whose option lists and commits live there
/// (`pages_menu_items` / `pages_choose`); the `usize` payloads are the rule
/// index and, where present, the condition/action index within it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MenuKind {
Countdown,
MainWindowStart,
WindowCapture,
PostDeletion,
MaxFps,
Language,
/// The excluded-windows card's Add button, whose menu is the live window
/// list rather than a fixed option set.
AddWindow,
/// The S3 config page's Storage Provider select.
S3Provider,
AutomationTrigger(usize),
AutomationMatchMode(usize),
AutomationConditionType(usize, usize),
AutomationConditionTarget(usize, usize),
AutomationConditionMode(usize, usize),
AutomationActionType(usize, usize),
AutomationClipboardSource(usize, usize),
AutomationWebhookMethod(usize, usize),
AutomationExportFormat(usize, usize),
AutomationExportResolution(usize, usize),
AutomationExportFps(usize, usize),
AutomationExportCompression(usize, usize),
AutomationPreset(usize, usize),
}
struct OpenMenu {
kind: MenuKind,
return_focus: Option<FocusHandle>,
/// Anchor, row count and keyboard highlight. `Menu.popup()` with no
/// position argument opens at the pointer, so the origin is the faithful
/// anchor; the highlight is what makes arrows and Enter work.
state: ui::MenuState,
}
/// `MAX_FPS_OPTIONS` in general.tsx.
const MAX_FPS_OPTIONS: &[(u32, fn() -> &'static str)] = &[
(24, tr::settings::general::recording::max_fps::fps_24),
(25, tr::settings::general::recording::max_fps::fps_25),
(30, tr::settings::general::recording::max_fps::fps_30),
(60, tr::settings::general::recording::max_fps::fps_60),
(120, tr::settings::general::recording::max_fps::fps_120),
];
/// The Countdown select's options.
const COUNTDOWN_OPTIONS: &[(u32, fn() -> &'static str)] = &[
(0, tr::settings::general::recording::countdown::off),
(3, tr::settings::general::recording::countdown::seconds_3),
(5, tr::settings::general::recording::countdown::seconds_5),
(10, tr::settings::general::recording::countdown::seconds_10),
];
type Label = fn() -> &'static str;
const STUDIO_QUALITY_TIERS: &[(StudioQuality, Label, Label)] = &[
(
StudioQuality::Balanced,
tr::settings::quality::studio::balanced,
tr::settings::quality::studio::balanced_description,
),
(
StudioQuality::Compatibility,
tr::settings::quality::studio::compatibility,
tr::settings::quality::studio::compatibility_description,
),
(
StudioQuality::Ultra,
tr::settings::quality::studio::ultra,
tr::settings::quality::studio::ultra_description,
),
];
const INSTANT_RESOLUTION_TIERS: &[(u32, &str, Label)] = &[
(1280, "720p", tr::settings::quality::instant::res_720p),
(1920, "1080p", tr::settings::quality::instant::res_1080p),
(2560, "1440p", tr::settings::quality::instant::res_1440p),
(3840, "4K", tr::settings::quality::instant::res_4k),
];
/// `FREE_INSTANT_MODE_MAX_RESOLUTION`.
const FREE_INSTANT_MODE_MAX_RESOLUTION: u32 = 1280;
#[derive(Clone, Copy)]
enum InstantQualityNotice {
SaveFailed,
}
/// `UPDATE_CHANNEL_OPTIONS`.
const UPDATE_CHANNEL_DESCRIPTIONS: &[(UpdateChannel, fn() -> &'static str)] = &[
(
UpdateChannel::Stable,
tr::settings::general::updates::stable_description,
),
(
UpdateChannel::Nightly,
tr::settings::general::updates::nightly_description,
),
];
/// The three theme previews (`~/assets/theme-previews/*.jpg`), keyed the way
/// `AppearanceSection`'s `previews` map is.
fn theme_preview(theme: AppTheme) -> &'static str {
match theme {
AppTheme::System => "images/auto.jpg",
AppTheme::Light => "images/light.jpg",
AppTheme::Dark => "images/dark.jpg",
}
}
/// Which text field an event came from, so one handler can serve all three.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Field {
ProjectName,
ServerUrl,
/// The Recordings page's filter.
RecordingsSearch,
ScreenshotsSearch,
}
// ---------------------------------------------------------------------------
// The Recordings page (`settings/recordings.tsx`)
// ---------------------------------------------------------------------------
/// `PAGE_SIZE` (`recordings.tsx:64`).
const RECORDINGS_PAGE_SIZE: usize = 20;
/// `hasActiveRecording`'s poll: `refetchInterval` returns 2000 while anything
/// in the list is still being written.
const RECORDINGS_POLL: Duration = Duration::from_millis(2000);
/// `Tabs` (`recordings.tsx:47-62`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RecordingsTab {
All,
Instant,
Studio,
}
impl RecordingsTab {
const ALL: &'static [RecordingsTab] = &[Self::All, Self::Instant, Self::Studio];
/// The tab's `id`, which for the two mode tabs is the mode's own
/// serialized name -- `emptyMessage()` interpolates it directly.
fn id(self) -> &'static str {
match self.mode() {
Some(mode) => mode.slug(),
None => "all",
}
}
fn label(self) -> &'static str {
match self {
Self::All => tr::settings::recordings::show_all(),
Self::Instant => "Instant",
Self::Studio => "Studio",
}
}
/// `Show all` has no glyph; the other two carry the mode's own.
fn icon(self) -> Option<&'static str> {
self.mode().map(RecordingMode::icon)
}
/// What `data.filter(r => r.meta.mode === activeTab())` compares against;
/// `None` for the tab that filters nothing.
fn mode(self) -> Option<RecordingMode> {
match self {
Self::All => None,
Self::Instant => Some(RecordingMode::Instant),
Self::Studio => Some(RecordingMode::Studio),
}
}
}
/// One row: the scanned recording, plus its thumbnail once the background
/// decode lands -- the Recents shape, for the same reason (the bundle's
/// `display.jpg` is a native-resolution JPEG and must not be decoded on the UI
/// thread).
struct RecordingRow {
item: RecordingItem,
thumbnail: Option<Arc<RenderImage>>,
thumbnail_stale: bool,
}
impl RecordingRow {
fn pending_thumbnail(&self) -> Option<&Path> {
self.item
.thumbnail
.as_deref()
.filter(|_| self.thumbnail_stale)
}
}
/// Everything the page owns. The Solid route keeps this in a `createQuery` plus
/// three signals; the lifetimes are the same, they just live on the window here.
struct Recordings {
/// The scan. `None` until the first one lands -- which the page draws the
/// same as an empty library, because `recordings.data && length > 0` is
/// false for both and the route has no loading branch.
items: Option<Vec<RecordingRow>>,
tab: RecordingsTab,
/// The filter field. `search()` is mirrored here so the filter math reads a
/// plain `String`.
search_input: Entity<ui::TextInputState>,
search: String,
/// `visibleCount`, reset to `PAGE_SIZE` by a tab or search change.
visible_count: usize,
/// The scan task. Dropping it cancels, so a refresh that arrives mid-scan
/// replaces the old one rather than racing it.
scan: Option<gpui::Task<()>>,
/// The thumbnail decode for the rows on screen, replaced whenever more of
/// them come into view.
decode: Option<gpui::Task<()>>,
/// The 2s poll, armed only while something in the list is still being
/// written (`refetchInterval`).
tick: Option<gpui::Task<()>>,
}
impl Recordings {
fn new(search_input: Entity<ui::TextInputState>) -> Self {
Self {
items: None,
tab: RecordingsTab::All,
search_input,
search: String::new(),
visible_count: RECORDINGS_PAGE_SIZE,
scan: None,
decode: None,
tick: None,
}
}
/// `trimmedSearch()`.
fn trimmed_search(&self) -> &str {
self.search.trim()
}
/// `visibleRecordings()` over `filteredRecordings()`: the tab, then the
/// case-insensitive substring.
fn visible_rows(&self) -> VisibleRows {
let query = self.trimmed_search().to_lowercase();
visible_rows(
self.items
.iter()
.flatten()
.map(|row| matches_recording_filters(&row.item, self.tab, &query)),
!query.is_empty(),
self.visible_count,
)
}
fn pending_thumbnails(&self) -> Vec<(usize, PathBuf)> {
pending_thumbnail_decodes(
self.items.as_deref().unwrap_or_default(),
&self.visible_rows().indices,
RecordingRow::pending_thumbnail,
)
}
}
/// One row against the tab and the already-lowercased, already-trimmed query.
fn matches_recording_filters(item: &RecordingItem, tab: RecordingsTab, query: &str) -> bool {
if let Some(mode) = tab.mode()
&& item.mode != mode
{
return false;
}
query.is_empty() || item.pretty_name.to_lowercase().contains(query)
}
struct ScreenshotRow {
item: ScreenshotItem,
thumbnail: Option<Arc<RenderImage>>,
}
impl ScreenshotRow {
fn pending_thumbnail(&self) -> Option<&Path> {
self.item
.thumbnail
.as_deref()
.filter(|_| self.thumbnail.is_none())
}
}
struct Screenshots {
items: Option<Vec<ScreenshotRow>>,
search_input: Entity<ui::TextInputState>,
search: String,
visible_count: usize,
scan: Option<gpui::Task<()>>,
decode: Option<gpui::Task<()>>,
}
impl Screenshots {
fn new(search_input: Entity<ui::TextInputState>) -> Self {
Self {
items: None,
search_input,
search: String::new(),
visible_count: RECORDINGS_PAGE_SIZE,
scan: None,
decode: None,
}
}
fn trimmed_search(&self) -> &str {
self.search.trim()
}
fn visible_rows(&self) -> VisibleRows {
let query = self.trimmed_search().to_lowercase();
visible_rows(
self.items.iter().flatten().map(|row| {
query.is_empty() || row.item.pretty_name.to_lowercase().contains(&query)
}),
!query.is_empty(),
self.visible_count,
)
}
fn pending_thumbnails(&self) -> Vec<(usize, PathBuf)> {
pending_thumbnail_decodes(
self.items.as_deref().unwrap_or_default(),
&self.visible_rows().indices,
ScreenshotRow::pending_thumbnail,
)
}
}
/// The rows a list paints, as indices into the unfiltered scan, so the list and
/// its thumbnail decode agree on what is on screen.
struct VisibleRows {
indices: Vec<usize>,
/// `filteredRecordings().length`, which the empty state and "Load more"
/// read.
matching: usize,
}
fn visible_rows(
matches: impl IntoIterator<Item = bool>,
has_search: bool,
visible_count: usize,
) -> VisibleRows {
let mut indices: Vec<usize> = matches
.into_iter()
.enumerate()
.filter_map(|(index, matched)| matched.then_some(index))
.collect();
let matching = indices.len();
indices.truncate(visible_recordings_len(matching, has_search, visible_count));
VisibleRows { indices, matching }
}
/// The `(row, thumbnail)` decode jobs for the visible rows only. A library can
/// hold thousands of items while the page paints twenty; rows further down are
/// queued when "Load more", a tab, or a search brings them on screen.
fn pending_thumbnail_decodes<R>(
rows: &[R],
visible: &[usize],
pending: impl Fn(&R) -> Option<&Path>,
) -> Vec<(usize, PathBuf)> {
visible
.iter()
.filter_map(|&index| pending(rows.get(index)?).map(|path| (index, path.to_path_buf())))
.collect()
}
/// `visibleRecordings()`: an active search shows every match, unpaginated.
fn visible_recordings_len(total: usize, has_search: bool, visible_count: usize) -> usize {
if has_search {
total
} else {
total.min(visible_count)
}
}
/// `hasMoreRecordings()`.
fn has_more_recordings(total: usize, has_search: bool, visible_count: usize) -> bool {
!has_search && total > visible_count
}
/// `setVisibleCount(count => Math.min(count + PAGE_SIZE, filtered.length))`.
fn load_more_count(visible_count: usize, total: usize) -> usize {
(visible_count + RECORDINGS_PAGE_SIZE).min(total)
}
fn search_may_have_changed(event: &ui::TextInputEvent) -> bool {
matches!(
event,
ui::TextInputEvent::Changed | ui::TextInputEvent::Cancelled
)
}
/// `emptyMessage()`.
fn recordings_empty_message(tab: RecordingsTab, trimmed_search: &str) -> &'static str {
match (tab, trimmed_search.is_empty()) {
(RecordingsTab::All, true) => tr::settings::recordings::empty::all(),
(RecordingsTab::All, false) => tr::settings::recordings::empty::all_matching(),
(RecordingsTab::Instant, true) => tr::settings::recordings::empty::instant(),
(RecordingsTab::Instant, false) => tr::settings::recordings::empty::instant_matching(),
(RecordingsTab::Studio, true) => tr::settings::recordings::empty::studio(),
(RecordingsTab::Studio, false) => tr::settings::recordings::empty::studio_matching(),
}
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct UserProfile {
name: Option<String>,
email: Option<String>,
image_url: Option<String>,
}
fn signed_in_profile_session() -> Option<(Option<String>, String, String)> {
let token = store::auth_snapshot().token?;
let user_id = store::store_section("auth")
.get("user_id")
.and_then(Value::as_str)
.map(str::to_string);
Some((user_id, token, crate::auth::server_url()))
}
fn cached_user_profile(
user_id: Option<&str>,
cached: &serde_json::Map<String, Value>,
) -> Option<UserProfile> {
let cached_user_id = match cached.get("userId")? {
Value::Null => None,
Value::String(value) => Some(value.as_str()),
_ => return None,
};
if cached_user_id != user_id {
return None;
}
serde_json::from_value(cached.get("profile")?.clone()).ok()
}
fn account_name(signed_in: bool, profile: Option<&UserProfile>) -> String {
if !signed_in {
return tr::settings::sidebar::click_to_sign_in().to_string();
}
profile
.and_then(|profile| {
[&profile.name, &profile.email]
.into_iter()
.filter_map(Option::as_deref)
.map(str::trim)
.find(|value| !value.is_empty())
})
.unwrap_or(tr::settings::sidebar::signed_in())
.to_string()
}
async fn fetch_user_profile() -> Result<UserProfile, crate::auth::AuthApiError> {
let response =
crate::auth::authed_request(reqwest::Method::GET, "/api/desktop/user/profile", None)
.await?;
if !response.status().is_success() {
return Err(crate::auth::AuthApiError::Other(format!(
"Profile fetch returned {}",
response.status()
)));
}
response
.json::<UserProfile>()
.await
.map_err(|error| crate::auth::AuthApiError::Other(error.to_string()))
}
async fn fetch_profile_image() -> Result<Arc<RenderImage>, crate::auth::AuthApiError> {
let response = crate::auth::authed_request(
reqwest::Method::GET,
"/api/desktop/user/profile/image",
None,
)
.await?;
if !response.status().is_success() {
return Err(crate::auth::AuthApiError::Other(format!(
"Profile image fetch returned {}",
response.status()
)));
}
if response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.is_some_and(|value| {
value.to_str().map_or(true, |value| {
!value.to_ascii_lowercase().starts_with("image/")
})
})
{
return Err(crate::auth::AuthApiError::Other(
"Invalid profile image response".to_string(),
));
}
if response
.content_length()
.is_some_and(|length| length > MAX_PROFILE_IMAGE_BYTES as u64)
{
return Err(crate::auth::AuthApiError::Other(
"Profile image is too large".to_string(),
));
}
let bytes = response
.bytes()
.await
.map_err(|error| crate::auth::AuthApiError::Other(error.to_string()))?;
if bytes.len() > MAX_PROFILE_IMAGE_BYTES {
return Err(crate::auth::AuthApiError::Other(
"Profile image is too large".to_string(),
));
}
let image = image::load_from_memory(&bytes)
.map_err(|error| crate::auth::AuthApiError::Other(error.to_string()))?;
Ok(library::rgba_to_render_image(image.into_rgba8()))
}
pub struct SettingsWindow {
pub(crate) theme: Theme,
pub(crate) page: Page,
pub(crate) settings: GeneralSettings,
menu: Option<OpenMenu>,
page_scroll: ScrollHandle,
instant_quality_anchor: ScrollAnchor,
studio_quality_anchor: ScrollAnchor,
quality_scroll_request: Option<Mode>,
has_cap_pro: bool,
pub(crate) plan_refresh_pending: bool,
pub(crate) plan_refresh_failed: bool,
instant_quality_notice: Option<InstantQualityNotice>,
studio_quality_save_failed: bool,
/// Everything the pages in `settings_pages.rs` own -- their fetch state,
/// drafts and text-input entities.
pub(crate) pages: crate::settings_pages::PagesState,
/// Drafts for the two text fields. Both are Save/Update-committed in the
/// shipping page too, so the store only sees them on the button.
project_name: String,
server_url: String,
/// The real fields. `ui::TextInputState` owns the caret, the selection,
/// the clipboard and the field-scoped undo; the drafts above stay because
/// Save/Update are the commit, not Return.
project_name_input: Entity<ui::TextInputState>,
server_url_input: Entity<ui::TextInputState>,
_field_events: [gpui::Subscription; 4],
/// The Recordings page.
recordings: Recordings,
screenshots: Screenshots,
/// `Collapsible` under the project-name input, with the content's measured
/// height so the reveal animates a real layout property.
placeholders: ui::CollapsibleState,
/// Keeps the collapsible repainting while its height animates. Dropping it
/// cancels, so a re-toggle mid-flight replaces the ticker rather than
/// racing it -- the main window's resize rule.
placeholders_task: Option<gpui::Task<()>>,
/// The zoom slider's track rect, captured during prepaint -- the row is
/// inside a resizable pane, so it cannot be computed.
slider_track: Rc<Cell<Option<Bounds<Pixels>>>>,
slider_dragging: bool,
/// `commands.listCaptureWindows()`, for the excluded-windows menu.
windows: Vec<WindowOption>,
/// Key handling for Cmd-W lives on the root, which needs a focus handle of
/// its own so the window has something focused when nothing else does.
pub(crate) focus: FocusHandle,
_sign_in_subscriptions: [gpui::Subscription; 2],
user_profile: Option<UserProfile>,
profile_image: Option<Arc<RenderImage>>,
keyboard_nav: bool,
_keyboard_nav: gpui::Subscription,
}
impl SettingsWindow {
pub fn new(page: Page, window: &mut Window, cx: &mut Context<Self>) -> Self {
crate::theme::bind_window(window, cx);
let theme = Theme::for_window(window, cx, true);
let settings = GeneralSettings::load();
let user_profile = signed_in_profile_session().and_then(|(user_id, _, _)| {
cached_user_profile(user_id.as_deref(), &store::store_section("user_profile"))
});
// The Tauri app's close button and Cmd-W both go through the window's
// own close, and `CapWindowId::Settings`'s `Destroyed` arm calls
// `restore_main_and_target_select_windows`. Same here: whichever way
// the window goes away, the main window comes back.
window.on_window_should_close(cx, |_window, cx| {
cx.defer(crate::app_windows::settings_closed);
true
});
// Both fields are built up front so their focus handles outlive a page
// change, and because `TextInputState`'s blur listener needs a window.
let project_name_input = cx.new(|cx| {
let mut input = ui::TextInputState::single_line(window, cx);
input.set_text(
settings
.default_project_name_template
.clone()
.unwrap_or_else(|| DEFAULT_PROJECT_NAME_TEMPLATE.to_string()),
cx,
);
input
});
let server_url_input = cx.new(|cx| {
let mut input = ui::TextInputState::single_line(window, cx);
input.set_text(settings.server_url.clone(), cx);
input
});
let recordings_search = cx.new(|cx| ui::TextInputState::single_line(window, cx));
let screenshots_search = cx.new(|cx| ui::TextInputState::single_line(window, cx));
let field_events = [
cx.subscribe(&project_name_input, |this, input, event, cx| {
this.on_field_event(Field::ProjectName, input, event, cx)
}),
cx.subscribe(&server_url_input, |this, input, event, cx| {
this.on_field_event(Field::ServerUrl, input, event, cx)
}),
cx.subscribe_in(
&recordings_search,
window,
|this, input, event, window, cx| {
this.on_field_event(Field::RecordingsSearch, input.clone(), event, cx);
if search_may_have_changed(event) {
this.decode_visible_recordings(window, cx);
}
},
),
cx.subscribe_in(
&screenshots_search,
window,
|this, input, event, window, cx| {
this.on_field_event(Field::ScreenshotsSearch, input.clone(), event, cx);
if search_may_have_changed(event) {
this.decode_visible_screenshots(window, cx);
}
},
),
];
let sign_in = SignIn::global(cx);
let sign_in_subscriptions = [
cx.observe_in(&sign_in, window, |_, _, window, cx| {
cx.notify();
window.refresh();
}),
cx.subscribe_in(&sign_in, window, |this, _, event, window, cx| match event {
SignInEvent::Finished {
outcome: SignInOutcome::SignedIn,
..
} => this.refresh_user_profile(window, cx),
SignInEvent::AccountRefreshed => {
this.has_cap_pro = store::auth_snapshot().is_upgraded();
cx.notify();
window.refresh();
}
SignInEvent::Finished { .. } => {}
}),
];
let pages = crate::settings_pages::PagesState::new(window, cx);
let page_scroll = ScrollHandle::new();
let keyboard_nav = ui::keyboard_nav::install(window, cx, |this: &Self, _| {
this.menu.is_some() || this.shortcut_listening() || this.switch_back_running()
});
Self {
theme,
page,
pages,
project_name: settings
.default_project_name_template
.clone()
.unwrap_or_else(|| DEFAULT_PROJECT_NAME_TEMPLATE.to_string()),
server_url: settings.server_url.clone(),
settings,
menu: None,
instant_quality_anchor: ScrollAnchor::for_handle(page_scroll.clone()),
studio_quality_anchor: ScrollAnchor::for_handle(page_scroll.clone()),
page_scroll,
quality_scroll_request: None,
has_cap_pro: store::auth_snapshot().is_upgraded(),
plan_refresh_pending: false,
plan_refresh_failed: false,
instant_quality_notice: None,
studio_quality_save_failed: false,
project_name_input,
server_url_input,
_field_events: field_events,
recordings: Recordings::new(recordings_search),
screenshots: Screenshots::new(screenshots_search),
placeholders: ui::CollapsibleState::new(false),
placeholders_task: None,
slider_track: Rc::new(Cell::new(None)),
slider_dragging: false,
windows: Vec::new(),
focus: cx.focus_handle(),
_sign_in_subscriptions: sign_in_subscriptions,
user_profile,
profile_image: None,
keyboard_nav: false,
_keyboard_nav: keyboard_nav,
}
}
/// Enumerate capture windows for the excluded-windows menu.
///
/// Same reason `MainWindow::start_enumeration` is not called from `new`:
/// a task spawned inside `open_window`'s builder closure updates the model
/// without ever scheduling a frame.
pub fn start_enumeration(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.refresh_user_profile(window, cx);
cx.spawn_in(window, async move |this, cx| {
let windows = cx
.background_executor()
.spawn(async { crate::devices::DeviceSnapshot::enumerate().windows })
.await;
this.update(cx, |this, cx| {
this.windows = windows;
cx.notify();
})
.ok();
})
.detach();
}
pub fn focus_root(&self, window: &mut Window, cx: &mut Context<Self>) {
window.focus(&self.focus, cx);
}
/// Re-target an already-open window, the way `showWindow({ Settings: {
/// page } })` navigates a live one.
pub fn set_page(&mut self, page: Page, window: &mut Window, cx: &mut Context<Self>) {
if self.page != page {
self.page_scroll = ScrollHandle::new();
self.instant_quality_anchor = ScrollAnchor::for_handle(self.page_scroll.clone());
self.studio_quality_anchor = ScrollAnchor::for_handle(self.page_scroll.clone());
}
self.quality_scroll_request = None;
self.instant_quality_notice = None;
self.studio_quality_save_failed = false;
self.has_cap_pro = store::auth_snapshot().is_upgraded();
self.shortcuts_cancel(cx);
self.page = page;
self.menu = None;
// The store may have changed under us while the window was in the
// background (the Tauri app writing, or a recording updating a
// window position).
self.settings = GeneralSettings::load();
self.page_shown(window, cx);
cx.notify();
}
pub fn show_quality_settings(
&mut self,
mode: Mode,
window: &mut Window,
cx: &mut Context<Self>,
) {
if mode == Mode::Screenshot {
return;
}
if self.page != Page::Quality {
self.set_page(Page::Quality, window, cx);
}
self.quality_scroll_request = Some(mode);
cx.notify();
}
/// Whatever the newly shown page has to fetch.
///
/// The Recordings page's `createQuery` runs on mount and again on every
/// remount, which is what navigating to it is. Leaving the page drops the
/// scan and the poll -- `@tanstack/solid-query` stops refetching for an
/// unmounted observer, and a poll running behind a page nobody is looking
/// at is filesystem work for nothing.
///
/// Called from the window's own open path rather than from `new` for the
/// [`Self::start_enumeration`] reason: a task spawned inside
/// `open_window`'s builder closure updates the model without ever
/// scheduling a frame.
pub fn page_shown(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.pages_shown(window, cx);
if matches!(self.page, Page::Quality | Page::License) {
self.refresh_plan(window, cx);
}
if self.page == Page::Recordings {
self.screenshots.scan = None;
self.screenshots.decode = None;
self.refresh_recordings(window, cx);
return;
}
if self.page == Page::Screenshots {
self.recordings.scan = None;
self.recordings.decode = None;
self.recordings.tick = None;
self.refresh_screenshots(window, cx);
return;
}
self.recordings.scan = None;
self.recordings.decode = None;
self.recordings.tick = None;
self.screenshots.scan = None;
self.screenshots.decode = None;
}
/// The `recordings` query: scan the library on the background executor,
/// then decode the visible rows' thumbnails there through
/// [`library::spawn_decode_pool`].
///
/// Same two-stage shape as the main window's Recents (`refresh_recents`):
/// the list lands first so the rows can paint with their grey placeholder,
/// and each thumbnail replaces its own row's as it arrives. A library with
/// several hundred bundles is several hundred `read_dir` + JSON parses and
/// as many native-resolution JPEG decodes; none of it may happen on the UI
/// thread.
pub fn refresh_recordings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.page != Page::Recordings {
return;
}
self.recordings.scan = Some(cx.spawn_in(window, async move |this, cx| {
let items = cx
.background_executor()
.spawn(async { library::list_recordings() })
.await;
tracing::info!(count = items.len(), "scanned the recordings library");
this.update_in(cx, |this, window, cx| {
this.set_recordings(items, window, cx);
let pending = this.recordings.pending_thumbnails();
this.decode_recording_thumbnails(pending, window, cx);
})
.ok();
}));
}
/// After "Load more", a tab, or a search: decode whatever just came on
/// screen. With nothing new the running batch, and the poll it arms when it
/// finishes, are left alone.
fn decode_visible_recordings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let pending = self.recordings.pending_thumbnails();
if !pending.is_empty() {
self.decode_recording_thumbnails(pending, window, cx);
}
}
/// Replaces the running batch rather than adding a second pool: its
/// unfinished rows are still pending, so `pending` re-queues the ones that
/// are still on screen.
fn decode_recording_thumbnails(
&mut self,
pending: Vec<(usize, PathBuf)>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.recordings.decode = Some(cx.spawn_in(window, async move |this, cx| {
let (_decodes, results) =
library::spawn_decode_pool(cx.background_executor(), pending, |(index, path)| {
library::decode_thumbnail(&path).map(|image| (index, path, image))
});
while let Ok(first) = results.recv_async().await {
let mut batch = vec![first];
batch.extend(results.try_iter());
if this
.update_in(cx, |this, window, cx| {
for (index, path, image) in batch {
let Some(row) = this
.recordings
.items
.as_mut()
.and_then(|rows| rows.get_mut(index))
else {
continue;
};
// A refresh may have landed while this decode was in
// flight, and the row at this index may now be a
// different recording.
if row.item.thumbnail.as_deref() != Some(path.as_path()) {
continue;
}
if let Some(old) = row.thumbnail.replace(image) {
let _ = window.drop_image(old);
}
row.thumbnail_stale = false;
}
cx.notify();
// An unfocused window only repaints when asked.
window.refresh();
})
.is_err()
{
return;
}
}
this.update_in(cx, |this, window, cx| this.arm_recordings_poll(window, cx))
.ok();
}));
}
/// Install a scan result. A row whose thumbnail still has to be decoded is
/// left `thumbnail_stale` until it is on screen.
///
/// `reconcile: "path"` on the query is doing real work here: the 2s poll
/// re-runs the whole scan, and a row that is still in the library must keep
/// the image it already has. Without that every tick blanked all five
/// thumbnails and re-decoded them one by one, which is visible as a flicker
/// (found on the first fixture run). A row that has gone away releases its
/// image from the sprite atlas, the same explicit drop `set_recents` does.
///
fn set_recordings(
&mut self,
items: Vec<RecordingItem>,
window: &mut Window,
cx: &mut Context<Self>,
) {
let mut cached: std::collections::HashMap<_, _> = self
.recordings
.items
.take()
.into_iter()
.flatten()
.map(|row| (row.item.path.clone(), row))
.collect();
let rows: Vec<RecordingRow> = items
.into_iter()
.map(|item| {
let previous = cached.remove(&item.path);
let changed = previous.as_ref().is_none_or(|row| {
row.item.thumbnail != item.thumbnail
|| row.item.thumbnail_version != item.thumbnail_version
|| row.thumbnail_stale
|| row.thumbnail.is_none()
});
let thumbnail = previous.and_then(|row| row.thumbnail);
RecordingRow {
item,
thumbnail,
thumbnail_stale: changed,
}
})
.collect();
for (_, row) in cached {
if let Some(image) = row.thumbnail {
let _ = window.drop_image(image);
}
}
self.recordings.items = Some(rows);
cx.notify();
// The settings window is not necessarily the active one while a
// recording is being written into the library, and an inactive gpui
// window does not repaint from a background-driven model update.
window.refresh();
}
/// `refetchInterval: data.some(hasActiveRecording) ? 2000 : false` -- armed
/// at the end of a scan, so a recording that finishes stops the poll and a
/// recording that starts restarts it.
fn arm_recordings_poll(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let active = self
.recordings
.items
.iter()
.flatten()
.any(|row| row.item.is_active());
if !active || self.page != Page::Recordings {
self.recordings.tick = None;
return;
}
self.recordings.tick = Some(cx.spawn_in(window, async move |this, cx| {
cx.background_executor().timer(RECORDINGS_POLL).await;
this.update_in(cx, |this, window, cx| this.refresh_recordings(window, cx))
.ok();
}));
}
/// The row's own delete: `ask(..)`, then the guarded recursive delete, then
/// a refetch.
///
/// The alert runs in a spawned task rather than in the click handler: it
/// spins AppKit's modal run loop, which re-enters gpui's window callbacks
/// for as long as it is up, and doing that with the App RefCell held is the
/// `place_overlay_panel` failure. gpui's foreground executor is the main
/// thread, which is where `NSAlert` has to run, so the task is both the
/// right thread and the right borrow state.
fn delete_recording(&mut self, path: PathBuf, window: &mut Window, cx: &mut Context<Self>) {
cx.spawn_in(window, async move |_, cx| {
let confirmed = crate::platform::confirm_dialog(
"Cap",
tr::main::delete_recording_confirm(),
tr::common::yes(),
tr::common::no(),
false,
);
if !confirmed {
return;
}
let Ok(task) = cx.update(|_, cx| {
gpui_tokio::Tokio::spawn(cx, crate::upload::queue::delete_recording(path.clone()))
}) else {
return;
};
let deleted = task.await.unwrap_or_else(|error| Err(error.to_string()));
if let Err(error) = deleted {
tracing::error!(path = %path.display(), "deleting the recording failed: {error}");
return;
}
tracing::info!(path = %path.display(), "deleted a recording");
cx.update(|_, cx| cx.defer(crate::app_windows::refresh_library_after_delete))
.ok();
})
.detach();
}
pub fn refresh_screenshots(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.page != Page::Screenshots {
return;
}
self.screenshots.scan = Some(cx.spawn_in(window, async move |this, cx| {
let items = cx
.background_executor()
.spawn(async { library::list_screenshots() })
.await;
tracing::info!(count = items.len(), "scanned the screenshots library");
this.update_in(cx, |this, window, cx| {
this.set_screenshots(items, window, cx);
let pending = this.screenshots.pending_thumbnails();
this.decode_screenshot_thumbnails(pending, window, cx);
})
.ok();
}));
}
fn decode_visible_screenshots(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let pending = self.screenshots.pending_thumbnails();
if !pending.is_empty() {
self.decode_screenshot_thumbnails(pending, window, cx);
}
}
fn decode_screenshot_thumbnails(
&mut self,
pending: Vec<(usize, PathBuf)>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.screenshots.decode = Some(cx.spawn_in(window, async move |this, cx| {
let (_decodes, results) =
library::spawn_decode_pool(cx.background_executor(), pending, |(index, path)| {
library::decode_thumbnail(&path).map(|image| (index, path, image))
});
while let Ok(first) = results.recv_async().await {
let mut batch = vec![first];
batch.extend(results.try_iter());
if this
.update_in(cx, |this, window, cx| {
for (index, path, image) in batch {
let Some(row) = this
.screenshots
.items
.as_mut()
.and_then(|rows| rows.get_mut(index))
else {
continue;
};
if row.item.thumbnail.as_deref() != Some(path.as_path()) {
continue;
}
if let Some(old) = row.thumbnail.replace(image) {
let _ = window.drop_image(old);
}
}
cx.notify();
window.refresh();
})
.is_err()
{
return;
}
}
}));
}
fn set_screenshots(
&mut self,
items: Vec<ScreenshotItem>,
window: &mut Window,
cx: &mut Context<Self>,
) {
let mut cached: std::collections::HashMap<PathBuf, Arc<RenderImage>> = self
.screenshots
.items
.take()
.into_iter()
.flatten()
.filter_map(|row| row.thumbnail.map(|image| (row.item.path, image)))
.collect();
let rows: Vec<ScreenshotRow> = items
.into_iter()
.map(|item| {
let thumbnail = cached.remove(&item.path);
ScreenshotRow { item, thumbnail }
})
.collect();
for (_, image) in cached {
let _ = window.drop_image(image);
}
self.screenshots.items = Some(rows);
cx.notify();
window.refresh();
}
fn delete_screenshot(&mut self, path: PathBuf, window: &mut Window, cx: &mut Context<Self>) {
cx.spawn_in(window, async move |this, cx| {
let confirmed = crate::platform::confirm_dialog(
"Cap",
tr::main::delete_screenshot_confirm(),
tr::common::yes(),
tr::common::no(),
false,
);
if !confirmed {
return;
}
let deleted = cx
.background_executor()
.spawn({
let path = path.clone();
async move { library::delete_screenshot(&path) }
})
.await;
if let Err(error) = deleted {
tracing::error!(path = %path.display(), "deleting the screenshot failed: {error}");
return;
}
this.update_in(cx, |this, window, cx| this.refresh_screenshots(window, cx))
.ok();
})
.detach();
}
fn save_screenshot(
&mut self,
src: PathBuf,
name: String,
window: &mut Window,
cx: &mut Context<Self>,
) {
cx.spawn_in(window, async move |this, cx| {
let dest =
crate::platform::save_file_panel_async(&format!("{name}.png"), &["png"], cx).await;
if this.update_in(cx, |_, _, _| ()).is_err() {
return;
}
let Some(dest) = dest else {
return;
};
if let Err(error) = library::copy_file_to_path(&src, &dest) {
tracing::error!("saving screenshot failed: {error}");
}
})
.detach();
}
/// The Edit button on a `Failed` studio recording, which asks first.
fn open_editor_confirmed(
&mut self,
path: PathBuf,
confirm: bool,
window: &mut Window,
cx: &mut Context<Self>,
) {
if !confirm {
// Deferred: opening a window paints it synchronously, which would
// double-lease the app from inside this update.
cx.defer(move |cx| crate::app_windows::open_editor(path, cx));
return;
}
cx.spawn_in(window, async move |_this, cx| {
let confirmed = crate::platform::confirm_dialog(
tr::settings::recordings::corrupted_title(),
tr::settings::recordings::corrupted_body(),
tr::settings::prompt::ok(),
tr::common::cancel(),
true,
);
if !confirmed {
return;
}
// Deferred inside the update for the same reason the direct arm
// defers: `open_window` paints synchronously.
cx.update(|_window, cx| cx.defer(move |cx| crate::app_windows::open_editor(path, cx)))
.ok();
})
.detach();
}
fn sync_appearance(&mut self, window: &Window, cx: &gpui::App) {
self.theme.refresh(window, cx, true);
}
// -- Writes ------------------------------------------------------------
/// `handleChange` in general.tsx: update the in-memory copy, then the
/// store. Written synchronously on the main thread -- the store is a few
/// kilobytes and the write is a read-modify-write, so pushing it to the
/// background executor would let two quick toggles interleave and lose
/// one.
pub(crate) fn write(&mut self, key: &'static str, value: Value, cx: &mut Context<Self>) {
if !store::set_store_setting(GENERAL_SETTINGS, key, value) {
// The store refused (unparseable file); reload so the UI shows
// what is actually on disk rather than the change that did not
// land.
self.settings = GeneralSettings::load();
}
cx.notify();
}
pub(crate) fn write_bool(&mut self, key: &'static str, value: bool, cx: &mut Context<Self>) {
self.write(key, Value::Bool(value), cx);
}
fn write_u32(&mut self, key: &'static str, value: u32, cx: &mut Context<Self>) {
self.write(key, Value::from(value), cx);
}
pub(crate) fn write_enum<T: SettingsEnum>(
&mut self,
key: &'static str,
value: T,
cx: &mut Context<Self>,
) {
self.write(key, Value::String(value.as_json().to_string()), cx);
}
fn write_excluded(&mut self, windows: Vec<WindowExclusion>, cx: &mut Context<Self>) {
self.settings.excluded_windows = windows;
let json = store::excluded_windows_to_json(&self.settings.excluded_windows);
self.write("excludedWindows", json, cx);
}
/// The `Collapsible` under the project-name input.
///
/// The height animates over the content's *measured* height, which is what
/// Kobalte's `--kb-collapsible-content-height` is, so a ticker has to keep
/// the window repainting for the 200ms the keyframe runs -- gpui only
/// renders on invalidation. Assigning over the previous task drops it,
/// cancelling a toggle still in flight.
fn toggle_placeholders(&mut self, cx: &mut Context<Self>) {
self.placeholders.toggle();
self.placeholders_task = Some(cx.spawn(async move |this, cx| {
loop {
let more = this
.update(cx, |this, cx| {
cx.notify();
this.placeholders.is_animating()
})
.unwrap_or(false);
if !more {
return;
}
cx.background_executor()
.timer(std::time::Duration::from_millis(8))
.await;
}
}));
cx.notify();
}
// -- Menus -------------------------------------------------------------
pub(crate) fn open_menu(
&mut self,
kind: MenuKind,
origin: Point<Pixels>,
window: &mut Window,
cx: &mut Context<Self>,
) {
// The menu's arrows / Home / End / Enter / Escape are handled by the
// root's `on_key_down`, and a focused text field would consume all of
// them first -- its bindings sit deeper in the dispatch path. Opening
// a menu therefore takes focus back, which is also what clicking a
// `<button>` does to a focused `<input>` in the webview.
let return_focus = ui::keyboard_nav::active(window, cx)
.then(|| window.focused(cx))
.flatten();
let focus = self.focus.clone();
window.focus(&focus, cx);
let items = self.menu_items(kind);
self.menu = Some(OpenMenu {
kind,
return_focus,
state: ui::MenuState::new(origin, &items),
});
cx.notify();
}
/// Arrows / Home / End / Enter / Escape on an open menu -- the Kobalte
/// `Select` contract. Returns whether the key was consumed.
fn menu_key(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) -> bool {
let Some(menu) = self.menu.as_mut() else {
return false;
};
let kind = menu.kind;
match menu.state.on_key(key) {
ui::MenuKey::Moved => {
cx.notify();
true
}
ui::MenuKey::Commit(index) => {
self.choose(kind, index, window, cx);
true
}
ui::MenuKey::Dismiss => {
self.close_menu(window, cx);
cx.notify();
true
}
ui::MenuKey::Ignored => false,
}
}
fn close_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if let Some(menu) = self.menu.take()
&& ui::keyboard_nav::active(window, cx)
&& self.focus.is_focused(window)
&& let Some(focus) = menu.return_focus
{
window.focus(&focus, cx);
}
}
/// One row per option, check-marked when it is the value in force.
fn menu_items(&self, kind: MenuKind) -> Vec<ui::MenuItem> {
match kind {
MenuKind::Countdown => {
let current = self.settings.recording_countdown.unwrap_or(0);
COUNTDOWN_OPTIONS
.iter()
.map(|(value, label)| ui::MenuItem::new(label(), *value == current))
.collect()
}
MenuKind::MaxFps => MAX_FPS_OPTIONS
.iter()
.map(|(value, label)| ui::MenuItem::new(label(), *value == self.settings.max_fps))
.collect(),
MenuKind::Language => {
let current = self.language_preference();
i18n::Preference::options()
.map(|option| ui::MenuItem::new(language_label(option), option == current))
.collect()
}
MenuKind::MainWindowStart => {
enum_items(self.settings.main_window_recording_start_behaviour)
}
MenuKind::WindowCapture => enum_items(self.settings.window_capture_style),
MenuKind::PostDeletion => enum_items(self.settings.post_deletion_behaviour),
MenuKind::AddWindow => self
.available_windows()
.into_iter()
.map(|window| ui::MenuItem::new(window_option_label(&window), false))
.collect(),
kind => self.pages_menu_items(kind),
}
}
fn choose(
&mut self,
kind: MenuKind,
index: usize,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.close_menu(window, cx);
match kind {
MenuKind::Countdown => {
if let Some((value, _)) = COUNTDOWN_OPTIONS.get(index) {
self.settings.recording_countdown = Some(*value);
self.write_u32("recordingCountdown", *value, cx);
}
}
MenuKind::MaxFps => {
if let Some((value, _)) = MAX_FPS_OPTIONS.get(index) {
self.settings.max_fps = *value;
self.write_u32("maxFps", *value, cx);
}
}
MenuKind::Language => {
if let Some(option) = i18n::Preference::options().nth(index) {
self.settings.ui_language = Some(option.setting().to_string());
self.write(i18n::SETTING_KEY, Value::from(option.setting()), cx);
let preference = self.language_preference();
cx.defer(move |cx: &mut gpui::App| i18n::apply(preference, cx));
}
}
MenuKind::MainWindowStart => {
if let Some(value) = MainWindowStartBehaviour::ALL.get(index) {
self.settings.main_window_recording_start_behaviour = *value;
self.write_enum("mainWindowRecordingStartBehaviour", *value, cx);
}
}
MenuKind::WindowCapture => {
if let Some(value) = WindowCaptureStyle::ALL.get(index) {
self.settings.window_capture_style = *value;
self.write_enum("windowCaptureStyle", *value, cx);
}
}
MenuKind::PostDeletion => {
if let Some(value) = PostDeletionBehaviour::ALL.get(index) {
self.settings.post_deletion_behaviour = *value;
self.write_enum("postDeletionBehaviour", *value, cx);
}
}
MenuKind::AddWindow => {
let Some(option) = self.available_windows().get(index).cloned() else {
return;
};
// `handleAddWindow`: the title is only recorded when there is
// no bundle id to match on.
let mut next = self.settings.excluded_windows.clone();
next.push(WindowExclusion {
bundle_identifier: None,
owner_name: Some(option.app.clone()),
window_title: Some(option.label.clone()),
});
self.write_excluded(next, cx);
}
kind => self.pages_choose(kind, index, window, cx),
}
cx.notify();
}
/// `availableWindows`: everything not already covered by an exclusion.
/// The `ostype === "windows"` narrowing is not reproduced -- this app is
/// macOS-only so far.
fn available_windows(&self) -> Vec<WindowOption> {
self.windows
.iter()
.filter(|window| {
!self
.settings
.excluded_windows
.iter()
.any(|exclusion| matches_exclusion(exclusion, window))
})
.cloned()
.collect()
}
/// `missingDefaultExclusions`, which drives the amber warning.
fn missing_default_exclusions(&self) -> Vec<WindowExclusion> {
store::default_excluded_windows()
.into_iter()
.filter(|default| {
!self
.settings
.excluded_windows
.iter()
.any(|entry| covers_default_exclusion(entry, default))
})
.collect()
}
}
/// Each catalog under its own name; System default names the language it
/// resolves to, in that language.
fn language_label(option: i18n::Preference) -> SharedString {
match option {
i18n::Preference::System => {
tr::settings::general::language::system_default(i18n::system().endonym()).into()
}
i18n::Preference::Fixed(locale) => SharedString::new_static(locale.endonym()),
}
}
fn enum_items<T: SettingsEnum>(current: T) -> Vec<ui::MenuItem> {
T::ALL
.iter()
.map(|value| ui::MenuItem::new(value.label(), *value == current))
.collect()
}
/// `getWindowOptionLabel`: `owner • title`, title dropped when it repeats the
/// owner.
fn window_option_label(window: &WindowOption) -> String {
if window.label.is_empty() || window.label == window.app {
window.app.clone()
} else {
format!("{} • {}", window.app, window.label)
}
}
/// `matchesExclusion` in general.tsx.
fn matches_exclusion(exclusion: &WindowExclusion, window: &WindowOption) -> bool {
// Nothing here carries a bundle identifier yet (`scap-targets` reports the
// owning app's name), so the bundle branch can only ever miss.
let owner_match = exclusion
.owner_name
.as_ref()
.is_some_and(|owner| *owner == window.app);
if let (Some(_), Some(title)) = (&exclusion.owner_name, &exclusion.window_title) {
return owner_match && *title == window.label;
}
if owner_match {
return true;
}
exclusion
.window_title
.as_ref()
.is_some_and(|title| *title == window.label)
}
/// `coversDefaultExclusion`.
fn covers_default_exclusion(entry: &WindowExclusion, default: &WindowExclusion) -> bool {
if entry == default {
return true;
}
if default.window_title.is_some() && entry.window_title == default.window_title {
return true;
}
if default.bundle_identifier.is_some() && entry.bundle_identifier == default.bundle_identifier {
return true;
}
if default.owner_name.is_some() && entry.owner_name == default.owner_name {
return entry.window_title.is_none() || entry.window_title == default.window_title;
}
false
}
impl Render for SettingsWindow {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.sync_appearance(window, cx);
if self.switch_back_running() {
ui::keyboard_nav::leave(window, cx);
}
self.keyboard_nav = ui::keyboard_nav::active(window, cx);
let theme = self.theme;
if self.page == Page::Quality
&& let Some(mode) = self.quality_scroll_request.take()
{
match mode {
Mode::Instant => self.instant_quality_anchor.scroll_to(window, cx),
Mode::Studio => self.studio_quality_anchor.scroll_to(window, cx),
Mode::Screenshot => {}
}
window.request_animation_frame();
}
let shell = div()
.track_focus(&self.focus)
.child(ui::keyboard_nav::pointer_watcher())
// `(window-chrome).tsx` binds Cmd-W to `getCurrentWindow().close()`
// for every chrome window. Escape is not bound there and is not
// bound here.
.on_key_down(cx.listener(|this, event: &gpui::KeyDownEvent, window, cx| {
let keystroke = &event.keystroke;
// An open menu takes arrows, Home/End, Enter and Escape first
// -- the Kobalte `Select` contract. Everything else, and every
// key at all when no menu is open, falls through.
if this.menu_key(&keystroke.key, window, cx) {
return;
}
// The Shortcuts page's listen mode eats every key while it
// is armed (hotkeys.tsx's window keydown listener).
if this.shortcuts_capture_key(keystroke, cx) {
return;
}
// Ctrl+W on Linux, where the platform modifier is Super.
let close = if cfg!(target_os = "linux") {
keystroke.modifiers.control
} else {
keystroke.modifiers.platform
};
if close && keystroke.key == "w" {
cx.defer(crate::app_windows::close_settings);
}
}))
.on_modifiers_changed(cx.listener(
|this, event: &gpui::ModifiersChangedEvent, _window, cx| {
this.shortcuts_modifiers_changed(event.modifiers, cx);
},
))
.size_full()
.flex()
.flex_row()
.overflow_hidden()
.rounded(px(theme
.settings_window_radius()
.min(SETTINGS_MATERIAL_RADIUS as f32)))
.font_family(crate::theme::UI_FONT)
.locale_font()
.font_weight(FontWeight::NORMAL)
.text_color(theme.settings_text());
#[cfg(target_os = "windows")]
let shell = shell
.flex_col()
.child(
div()
.h(px(36.))
.w_full()
.flex_shrink_0()
.flex()
.justify_end()
.bg(theme.header_bg())
.border_b_1()
.border_color(theme.header_border())
.window_control_area(gpui::WindowControlArea::Drag)
.child(ui::windows_caption_controls(
theme,
window.is_window_active(),
window.is_maximized(),
true,
true,
)),
)
.child(
div()
.flex()
.flex_row()
.flex_1()
.min_h_0()
.w_full()
.child(self.render_sidebar(cx))
.child(self.render_content(window, cx)),
);
#[cfg(not(target_os = "windows"))]
let shell = shell
.child(self.render_sidebar(cx))
.child(self.render_content(window, cx));
// GNOME and other compositors without server-side decorations leave
// the frame to the app; without this the window had no way to close.
#[cfg(target_os = "linux")]
let shell = shell.when(
matches!(
window.window_decorations(),
gpui::Decorations::Client { .. }
),
|shell| shell.child(linux_close_button(theme)),
);
shell
// Painted last so it lands over the page: the select menus, and
// the drag layer the zoom slider needs while the button is held.
.children(self.render_menu(cx))
.children(self.render_slider_drag_layer(cx))
// Over everything, including the menus: the Experimental page's
// hand-back takes the whole window while it counts down.
.children(self.render_switch_overlay(cx))
}
}
#[cfg(target_os = "linux")]
fn linux_close_button(theme: Theme) -> impl IntoElement {
div()
.id("settings-close")
.absolute()
.top(px(10.))
.right(px(10.))
.size(px(28.))
.flex()
.items_center()
.justify_center()
.rounded(px(6.))
.cursor_pointer()
.occlude()
.hover(move |style| style.bg(theme.settings_sidebar_bg()))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(|_, _, cx| cx.defer(crate::app_windows::close_settings))
.child(
svg()
.path("icons/x.svg")
.size(px(14.))
.text_color(theme.settings_text()),
)
}
impl SettingsWindow {
// -- Sidebar -----------------------------------------------------------
fn render_sidebar(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
div()
.flex()
.flex_col()
.h_full()
// `width/min-width/max-width: var(--macos-settings-sidebar-width)`.
.w(px(SIDEBAR_WIDTH))
.flex_shrink_0()
.bg(theme.settings_sidebar_bg())
.child(
// `.cap-settings-window-spacer`, the strip the traffic lights
// sit in. `data-tauri-drag-region` on the sidebar makes it a
// drag handle; AppKit already drags the top ~28pt of a
// transparent titlebar, this covers the rest of the strip.
div()
.id("settings-drag")
.h(px(SIDEBAR_SPACER))
.flex_shrink_0()
.w_full()
.on_mouse_down(MouseButton::Left, |_, window, _| {
window.start_window_move();
}),
)
.child(self.render_profile(cx))
.child(self.render_nav(cx))
.child(self.render_account(cx))
}
fn render_profile(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
let signed_in = store::auth_snapshot().signed_in();
let avatar = match self.profile_image.clone() {
Some(image) if signed_in => {
use gpui::StyledImage as _;
img(image)
.size(px(32.))
.flex_shrink_0()
.object_fit(gpui::ObjectFit::Cover)
.rounded_full()
.into_any_element()
}
_ => div()
.flex()
.items_center()
.justify_center()
.size(px(32.))
.flex_shrink_0()
.rounded_full()
.bg(theme.settings_fill())
.child(
svg()
.path("icons/user-round.svg")
.size(px(16.))
.text_color(theme.settings_muted()),
)
.into_any_element(),
};
div()
.id("settings-profile")
.flex()
.flex_row()
.items_center()
// `.cap-settings-profile { gap: 8px; min-height: 44px; margin: 0
// var(--macos-settings-sidebar-padding-x) 16px; padding: 6px 4px;
// border-radius: 8px }`
.gap(px(8.))
.min_h(px(44.))
.mx(px(SIDEBAR_PADDING_X))
.mb(px(16.))
.px(px(4.))
.py(px(6.))
.rounded(px(8.))
.cursor_pointer()
.hover(move |style| style.bg(theme.settings_hover()))
.active(move |style| style.bg(theme.settings_selection()))
.child(avatar)
.child(
div()
.flex()
.flex_col()
.flex_1()
.min_w_0()
.justify_center()
// `.cap-settings-profile-copy { gap: 2px }`
.gap(px(2.))
.child(
div()
.truncate()
.text_size(px(13.))
.line_height(px(15.))
.child(account_name(signed_in, self.user_profile.as_ref())),
)
.child(
// `text-[11px] leading-[13px] text-gray-10`
div()
.truncate()
.text_size(px(11.))
.line_height(px(13.))
.text_color(theme.settings_muted())
.child(tr::settings::sidebar::account()),
),
)
.on_click(cx.listener(|this, _, window, cx| {
if store::auth_snapshot().signed_in() {
cx.open_url(&format!("{}/dashboard", crate::auth::server_url()));
} else {
this.toggle_sign_in(window, cx);
}
}))
}
fn render_nav(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
div()
.id("settings-nav")
.role(gpui::Role::TabList)
.flex()
.flex_col()
// `.cap-settings-nav { padding: 0 var(--sidebar-padding-x)
// var(--sidebar-padding-x); overflow-y: auto }`, `space-y-1`.
.px(px(SIDEBAR_PADDING_X))
.pb(px(SIDEBAR_PADDING_X))
.gap(px(2.))
.flex_1()
.min_h_0()
.overflow_y_scroll()
.children(Page::ALL.iter().copied().map(|page| {
let selected = page == self.page;
div()
.id(SharedString::from(page.slug()))
.when(self.keyboard_nav, ui::keyboard_nav::stop)
.role(gpui::Role::Tab)
.aria_label(page.label())
.aria_selected(selected)
.flex()
.flex_row()
.items_center()
// `.cap-settings-nav-item { height: 32px; padding: 6px;
// border-radius: 8px }`, `gap-1.5 text-[13px]`.
.h(px(30.))
.px(px(6.))
.gap(px(8.))
.rounded(px(8.))
.text_size(px(13.))
.when(selected, |this| {
this.bg(Theme::with_alpha(
rgb(Theme::SETTINGS_ACCENT),
if theme.is_dark() { 0.22 } else { 0.12 },
))
.font_weight(FontWeight::MEDIUM)
})
.when(!selected, |this| {
this.hover(|style| style.bg(theme.settings_hover()))
})
.child(
svg()
.path(page.icon())
.size(px(16.))
.flex_shrink_0()
.text_color(if selected {
rgb(Theme::SETTINGS_ACCENT).into()
} else {
theme.settings_muted()
}),
)
.child(page.label())
.on_click(cx.listener(move |this, _, window, cx| {
// Navigating *is* a remount in the Solid router, so the
// new page's query runs -- `set_page` carries that.
this.set_page(page, window, cx);
}))
}))
}
fn render_account(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
let (update_label, update_ready) = match crate::updates::status(cx) {
crate::updates::UpdateStatus::Idle => (
tr::settings::sidebar::check_for_updates().to_string(),
false,
),
crate::updates::UpdateStatus::Checking => (
tr::settings::sidebar::checking_for_updates().to_string(),
false,
),
crate::updates::UpdateStatus::Downloading {
version,
fraction: Some(fraction),
} => (
tr::settings::sidebar::downloading_progress(
version,
(fraction * 100.).round() as u32,
),
false,
),
crate::updates::UpdateStatus::Downloading { version, .. } => {
(tr::settings::sidebar::downloading(version), false)
}
crate::updates::UpdateStatus::Ready { version }
| crate::updates::UpdateStatus::Installed { version, .. } => {
(tr::settings::sidebar::restart_to_update(version), true)
}
crate::updates::UpdateStatus::Installing { version } => {
(tr::settings::sidebar::installing(version), false)
}
};
let update_links = div()
.flex()
.flex_col()
.items_start()
.gap(px(6.))
.mb(px(8.))
.text_size(px(12.))
.text_color(theme.settings_muted())
.child(
div()
.id("settings-version")
.px(px(4.))
.py(px(2.))
.rounded(px(4.))
.child(format!("v{}", env!("CARGO_PKG_VERSION"))),
)
.child(
div()
.id("settings-previous-versions")
.child(tr::settings::sidebar::previous_versions())
.hover(|style| style.text_color(theme.settings_text()))
.on_click(|_, _, cx| cx.open_url("https://cap.so/download/versions")),
)
.child(
div()
.id("settings-check-updates")
.max_w_full()
.truncate()
.cursor_pointer()
.when(update_ready, |link| {
link.text_color(rgb(Theme::SETTINGS_ACCENT))
})
.hover(|style| style.text_color(theme.settings_text()))
.on_click(cx.listener(move |_, _, _, cx| {
if update_ready {
crate::updates::install_and_relaunch(cx);
} else {
crate::updates::check_manually(cx);
}
}))
.child(update_label),
);
div()
.flex()
.flex_col()
// `.cap-settings-account { padding: 8px var(--sidebar-padding-x)
// var(--sidebar-padding-x); border-top: 1px solid
// var(--macos-settings-border) }`
.pt(px(8.))
.px(px(SIDEBAR_PADDING_X))
.pb(px(SIDEBAR_PADDING_X))
.border_t_1()
.border_color(theme.settings_border())
.child(update_links)
.child({
let signed_in = store::auth_snapshot().signed_in();
let (variant, label) = if SignIn::global(cx).read(cx).is_pending() {
(
ui::ButtonVariant::Gray,
tr::settings::sidebar::cancel_sign_in(),
)
} else if signed_in {
(ui::ButtonVariant::Gray, tr::settings::sidebar::sign_out())
} else {
(ui::ButtonVariant::Primary, tr::settings::sidebar::sign_in())
};
self.button(
"settings-sign-in",
(variant, None),
label,
false,
cx,
|this, window, cx| this.toggle_sign_in(window, cx),
)
.full_width()
.height(px(34.))
})
}
fn toggle_sign_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let sign_in = SignIn::global(cx);
if sign_in.read(cx).is_pending() {
sign_in.update(cx, |sign_in, cx| sign_in.cancel(cx));
return;
}
if store::auth_snapshot().signed_in() {
self.clear_local_auth(window, cx);
return;
}
sign_in.update(cx, |sign_in, cx| sign_in.start(SignInOrigin::Settings, cx));
}
pub(crate) fn refresh_plan(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.plan_refresh_pending || !store::auth_snapshot().signed_in() {
return;
}
self.plan_refresh_pending = true;
self.plan_refresh_failed = false;
cx.spawn_in(window, async move |this, cx| {
let result = gpui_tokio::Tokio::spawn(cx, crate::auth::update_auth_plan()).await;
this.update_in(cx, |this, window, cx| {
this.plan_refresh_pending = false;
this.plan_refresh_failed = !matches!(result, Ok(Ok(())));
this.has_cap_pro = store::auth_snapshot().is_upgraded();
cx.notify();
window.refresh();
})
.ok();
})
.detach();
cx.notify();
}
fn clear_local_auth(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if !crate::auth::sign_out() {
tracing::error!("failed to clear the auth session");
}
self.has_cap_pro = store::auth_snapshot().is_upgraded();
self.instant_quality_notice = None;
if !store::set_store_value("user_profile", Value::Null) {
tracing::error!("failed to clear the cached user profile");
}
self.user_profile = None;
if let Some(image) = self.profile_image.take() {
let _ = window.drop_image(image);
}
cx.notify();
window.refresh();
}
fn refresh_user_profile(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.has_cap_pro = store::auth_snapshot().is_upgraded();
self.instant_quality_notice = None;
let Some(profile_session) = signed_in_profile_session() else {
return;
};
let user_id = profile_session.0.clone();
cx.spawn_in(window, async move |this, cx| {
let Ok(task) = cx.update(|_, cx| gpui_tokio::Tokio::spawn(cx, fetch_user_profile()))
else {
return;
};
let Ok(result) = task.await else {
return;
};
let profile = match result {
Ok(profile) => profile,
Err(crate::auth::AuthApiError::InvalidAuthentication) => {
let _ = this.update_in(cx, |this, window, cx| {
if signed_in_profile_session().as_ref() == Some(&profile_session) {
this.clear_local_auth(window, cx);
}
});
return;
}
Err(error) => {
tracing::warn!("loading account profile: {error}");
return;
}
};
let image_url = profile
.image_url
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.map(str::to_string);
let Ok(true) = this.update_in(cx, |this, window, cx| {
if signed_in_profile_session().as_ref() != Some(&profile_session) {
return false;
}
if !store::set_store_value(
"user_profile",
serde_json::json!({
"userId": &user_id,
"profile": &profile,
"updatedAt": chrono::Utc::now().timestamp_millis(),
}),
) {
tracing::warn!("failed to cache the user profile");
}
this.user_profile = Some(profile);
if let Some(image) = this.profile_image.take() {
let _ = window.drop_image(image);
}
cx.notify();
window.refresh();
true
}) else {
return;
};
let Some(image_url) = image_url else {
return;
};
let Ok(task) = cx.update(|_, cx| gpui_tokio::Tokio::spawn(cx, fetch_profile_image()))
else {
return;
};
let Ok(result) = task.await else {
return;
};
match result {
Ok(image) => {
let _ = this.update_in(cx, |this, window, cx| {
if signed_in_profile_session().as_ref() != Some(&profile_session)
|| this
.user_profile
.as_ref()
.and_then(|profile| profile.image_url.as_deref())
.map(str::trim)
!= Some(image_url.as_str())
{
return;
}
if let Some(old) = this.profile_image.replace(image) {
let _ = window.drop_image(old);
}
cx.notify();
window.refresh();
});
}
Err(crate::auth::AuthApiError::InvalidAuthentication) => {
let _ = this.update_in(cx, |this, window, cx| {
if signed_in_profile_session().as_ref() == Some(&profile_session) {
this.clear_local_auth(window, cx);
}
});
}
Err(error) => tracing::warn!("loading account profile image: {error}"),
}
})
.detach();
}
// -- Content pane ------------------------------------------------------
fn render_content(&self, window: &Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
div()
.flex()
.flex_col()
.flex_1()
.min_w_0()
.h_full()
.overflow_hidden()
.bg(theme.settings_content_bg())
// `divide-x divide-gray-3` on the shell, remapped to
// `var(--macos-settings-border)` under Liquid Glass.
.border_l_1()
.border_color(theme.settings_divider())
.child(
div()
.id("settings-page")
.flex()
.flex_col()
.flex_1()
.min_h_0()
.overflow_y_scroll()
.track_scroll(&self.page_scroll)
// `.cap-settings-page > .px-6 { max-width: none; padding:
// 18px var(--macos-settings-content-padding-x) 28px }`,
// and `space-y-7` between sections.
.pt(px(18.))
.px(px(CONTENT_PADDING_X))
.pb(px(28.))
.gap(px(28.))
.children(match self.page {
Page::General => self.render_general(window, cx),
Page::Quality => self.render_recording_quality(cx),
Page::Recordings => self.render_recordings(cx),
Page::Screenshots => self.render_screenshots(cx),
Page::Shortcuts => self.render_shortcuts(cx),
Page::Cli => self.render_cli(cx),
Page::Automations => self.render_automations(cx),
Page::Transcription => self.render_transcription(cx),
Page::Integrations => self.render_integrations(cx),
Page::License => self.render_license(cx),
Page::Experimental => self.render_experimental(cx),
Page::Feedback => self.render_feedback(cx),
Page::Changelog => self.render_changelog(cx),
}),
)
}
// -- The Recordings page -----------------------------------------------
/// `settings/recordings.tsx`.
///
/// The header is a `<Section>` with an Import button; below it a filter bar
/// (three tab pills and the search field) and the bordered list, which is
/// replaced wholesale by "No recordings found" when the library is empty.
fn render_recordings(&self, cx: &mut Context<Self>) -> Vec<gpui::AnyElement> {
// `variant="gray" size="sm" class="h-[36px] px-3 gap-1.5"` --
// `importVideoFromPicker` (`recordings.tsx:192-215`), through this
// build's own remux pipeline.
let import = self
.button(
"recordings-import",
(ui::ButtonVariant::Gray, Some("icons/import.svg")),
tr::settings::recordings::import(),
false,
cx,
|_, _, cx| crate::import::pick_and_import_video(cx),
)
.height(px(36.))
.into_any_element();
// `when={recordings.data && recordings.data.length > 0}`: an empty
// library and a scan still in flight take the same branch, because the
// route has no loading state of its own.
let empty_library = self
.recordings
.items
.as_ref()
.is_none_or(|items| items.is_empty());
let children = if empty_library {
vec![
self.recordings_message(tr::settings::recordings::empty_library())
.into_any_element(),
]
} else {
vec![
self.render_recordings_filters(cx).into_any_element(),
self.render_recordings_list(cx).into_any_element(),
]
};
vec![
self.section(
tr::settings::recordings::title(),
Some(tr::settings::recordings::description()),
Some(import),
children,
)
.into_any_element(),
]
}
fn render_screenshots(&self, cx: &mut Context<Self>) -> Vec<gpui::AnyElement> {
// `importImageFromPicker` (`screenshots.tsx:154-177`).
let import = self
.button(
"screenshots-import",
(ui::ButtonVariant::Gray, Some("icons/import.svg")),
tr::settings::screenshots::import(),
false,
cx,
|_, _, cx| crate::import::pick_and_import_image(cx),
)
.height(px(36.))
.into_any_element();
let empty_library = self
.screenshots
.items
.as_ref()
.is_none_or(|items| items.is_empty());
let children = if empty_library {
vec![
self.recordings_message(tr::settings::screenshots::empty_library())
.into_any_element(),
]
} else {
vec![
self.render_screenshots_filters(cx).into_any_element(),
self.render_screenshots_list(cx).into_any_element(),
]
};
vec![
self.section(
tr::settings::screenshots::title(),
Some(tr::settings::screenshots::description()),
Some(import),
children,
)
.into_any_element(),
]
}
fn render_screenshots_filters(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
self.screenshots
.search_input
.update(cx, |input, _| input.set_placeholder(tr::common::search()));
let search = div().flex().flex_row().items_center().w(px(260.)).child(
ui::TextInput::search(&theme, "screenshots-search", &self.screenshots.search_input)
.height(px(36.))
.radius(px(8.))
.bg(theme.settings_card_bg())
.border(theme.settings_border())
.text_color(theme.settings_text())
.placeholder_color(theme.settings_muted()),
);
div()
.flex()
.flex_col()
.w_full()
.gap(px(12.))
.pb(px(16.))
.border_b_1()
.border_color(theme.settings_border())
.child(search)
}
fn render_screenshots_list(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
let rows = self.screenshots.items.as_deref().unwrap_or_default();
let VisibleRows {
indices,
matching: total,
} = self.screenshots.visible_rows();
let has_search = !self.screenshots.trimmed_search().is_empty();
let visible = indices.len();
let more = has_more_recordings(total, has_search, self.screenshots.visible_count);
let mut items = Vec::with_capacity(visible);
for (index, row) in indices.into_iter().map(|row| &rows[row]).enumerate() {
items.push(
self.render_screenshot_row(row, index + 1 == visible, cx)
.into_any_element(),
);
}
div()
.flex()
.flex_col()
.relative()
.rounded(px(10.))
.border_1()
.border_color(theme.settings_border())
.bg(theme.settings_card_bg())
.overflow_hidden()
.when(total == 0, |this| {
this.child(self.recordings_message(if has_search {
tr::settings::screenshots::empty_matching()
} else {
tr::settings::screenshots::empty()
}))
})
.child(div().flex().flex_col().w_full().children(items))
.when(more, |this| {
this.child(
div()
.flex()
.flex_row()
.justify_center()
.p(px(12.))
.border_t_1()
.border_color(theme.settings_border())
.child(self.button(
"screenshots-load-more",
(ui::ButtonVariant::Gray, None),
tr::settings::screenshots::load_more(),
false,
cx,
|this, window, cx| {
let total = this.screenshots.visible_rows().matching;
this.screenshots.visible_count =
load_more_count(this.screenshots.visible_count, total);
this.decode_visible_screenshots(window, cx);
cx.notify();
},
)),
)
})
}
fn render_screenshot_row(
&self,
row: &ScreenshotRow,
last: bool,
cx: &mut Context<Self>,
) -> impl IntoElement {
let theme = self.theme;
let item = &row.item;
let png = item.path.clone();
let name = item.pretty_name.clone();
let bundle = item.bundle.clone();
let thumbnail = match row.thumbnail.clone() {
Some(image) => {
use gpui::StyledImage as _;
img(image)
.size(px(48.))
.flex_shrink_0()
.object_fit(gpui::ObjectFit::Cover)
.rounded(px(4.))
.into_any_element()
}
None => div()
.size(px(44.))
.mr(px(16.))
.flex_shrink_0()
.rounded(px(4.))
.bg(theme.gray_10)
.into_any_element(),
};
let left = div()
.flex()
.flex_row()
.items_center()
.gap(px(20.))
.flex_1()
.min_w_0()
.child(thumbnail)
.child(
div()
.w_full()
.truncate()
.text_size(px(14.))
.child(item.pretty_name.clone()),
);
let actions = div()
.flex()
.flex_row()
.items_center()
.gap(px(8.))
.child(self.row_button(
"screenshot-copy",
"icons/copy.svg",
tr::settings::screenshots::copy(),
false,
cx,
{
let png = png.clone();
move |_this, _window, cx| {
let copied = crate::platform::copy_image_to_clipboard(png.clone(), cx);
cx.spawn(async move |_, _| {
if let Err(error) = copied.await {
tracing::warn!("copying screenshot failed: {error}");
crate::platform::alert_dialog(
tr::main::library::copy_screenshot_failed(),
&error,
);
}
})
.detach();
}
},
))
.child(self.row_button(
"screenshot-save",
"icons/download.svg",
tr::settings::screenshots::save_as(),
false,
cx,
move |this, window, cx| {
this.save_screenshot(png.clone(), name.clone(), window, cx);
},
))
.child(self.row_button(
"screenshot-folder",
"icons/folder.svg",
tr::settings::screenshots::open_folder(),
false,
cx,
move |_this, _window, cx| library::reveal_path(&bundle, cx),
))
.child(self.row_button(
"screenshot-delete",
"icons/trash.svg",
tr::settings::screenshots::delete(),
false,
cx,
{
let path = item.path.clone();
move |this, window, cx| this.delete_screenshot(path.clone(), window, cx)
},
));
div()
.id(gpui::ElementId::Path(item.path.as_path().into()))
.flex()
.flex_row()
.justify_between()
.items_center()
.w_full()
.p(px(12.))
.when(!last, |this| {
this.border_b_1().border_color(theme.settings_border())
})
.child(left)
.child(actions)
.on_click({
let png = item.path.clone();
move |_, _, cx| {
let png = png.clone();
cx.defer(move |cx| crate::app_windows::open_screenshot_editor(png, cx));
}
})
}
/// Both empty states: `text-center text-(--text-tertiary) absolute flex
/// items-center justify-center w-full h-full`. Absolute over the page in
/// the TSX; here it is a flow child that fills the space the list would
/// have taken, which is what that absolute box resolves to.
fn recordings_message(&self, message: impl Into<SharedString>) -> gpui::Div {
div()
.flex()
.flex_1()
.min_h(px(200.))
.w_full()
.items_center()
.justify_center()
.text_color(self.theme.settings_muted())
.child(message.into())
}
/// The filter bar: `flex flex-col gap-3 pb-4 w-full border-b border-gray-2`.
fn render_recordings_filters(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
self.recordings
.search_input
.update(cx, |input, _| input.set_placeholder(tr::common::search()));
let active = self.recordings.tab;
let tabs = div()
// `flex flex-wrap gap-3 items-center`
.flex()
.flex_row()
.flex_wrap()
.items_center()
.gap(px(12.))
.children(RecordingsTab::ALL.iter().copied().map(|tab| {
let selected = tab == active;
div()
.id(SharedString::from(tab.id()))
// `flex gap-1.5 items-center p-2 px-3 border rounded-full`
.flex()
.flex_row()
.items_center()
.gap(px(6.))
.py(px(8.))
.px(px(12.))
.rounded_full()
.border_1()
// `border-gray-5` on both states, remapped to the settings
// border by the material.
.border_color(theme.settings_border())
.map(|this| {
if selected {
// `bg-gray-5 cursor-default`
this.bg(theme.settings_fill()).cursor_default()
} else {
// `bg-transparent hover:bg-gray-3`
this.cursor_pointer()
.hover(|style| style.bg(theme.settings_fill()))
}
})
// `size-3`, and `invert dark:invert-0` -- a dark glyph on
// the light theme and a light one on the dark, which is
// what the page's own text colour already is.
.children(tab.icon().map(|icon| {
svg()
.path(icon)
.size(px(12.))
.flex_shrink_0()
.text_color(theme.settings_text())
}))
// `text-xs text-gray-12`
.child(div().text_size(px(12.)).child(tab.label()))
.on_click(cx.listener(move |this, _, window, cx| {
this.recordings.tab = tab;
// `createEffect(() => { activeTab(); ...
// setVisibleCount(PAGE_SIZE) })`
this.recordings.visible_count = RECORDINGS_PAGE_SIZE;
this.decode_visible_recordings(window, cx);
cx.notify();
}))
}));
// `relative w-full max-w-[260px] h-[36px] flex items-center` with the
// magnifier absolutely placed at `left-2` and the input padded past it.
// `ui::TextInput::search` draws the same glyph as a flow child at the
// same offset, so the overlay is not reproduced -- there is nothing for
// it to overlay.
let search = div().flex().flex_row().items_center().w(px(260.)).child(
ui::TextInput::search(&theme, "recordings-search", &self.recordings.search_input)
.height(px(36.))
// `<Input>` is `rounded-lg bg-gray-2`, and the settings
// material paints `.bg-gray-2` as the card surface.
.radius(px(8.))
.bg(theme.settings_card_bg())
.border(theme.settings_border())
.text_color(theme.settings_text())
.placeholder_color(theme.settings_muted()),
);
div()
.flex()
.flex_col()
.w_full()
.gap(px(12.))
.pb(px(16.))
.border_b_1()
.border_color(theme.settings_border())
.child(tabs)
.child(search)
}
/// The list: `flex relative flex-col flex-1 rounded-xl border bg-gray-2
/// border-gray-3`, with the "Load more" footer under it.
fn render_recordings_list(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
let rows = self.recordings.items.as_deref().unwrap_or_default();
let VisibleRows {
indices,
matching: total,
} = self.recordings.visible_rows();
let has_search = !self.recordings.trimmed_search().is_empty();
let visible = indices.len();
let more = has_more_recordings(total, has_search, self.recordings.visible_count);
// Built up front rather than in a `.children(map(..))`: the closure
// would have to hold `cx` across every row, which it cannot.
let mut items = Vec::with_capacity(visible);
for (index, row) in indices.into_iter().map(|row| &rows[row]).enumerate() {
// `not-last:border-b` counts the *rendered* rows, so the border
// stops at the last visible one rather than the last matching one.
items.push(
self.render_recording_row(row, index + 1 == visible, cx)
.into_any_element(),
);
}
div()
.flex()
.flex_col()
.relative()
// `rounded-xl`, which the settings material takes to 10px.
.rounded(px(10.))
.border_1()
.border_color(theme.settings_border())
.bg(theme.settings_card_bg())
.overflow_hidden()
.when(total == 0, |this| {
this.child(self.recordings_message(recordings_empty_message(
self.recordings.tab,
self.recordings.trimmed_search(),
)))
})
.child(div().flex().flex_col().w_full().children(items))
.when(more, |this| {
this.child(
// `flex justify-center p-3 border-t border-gray-3`
div()
.flex()
.flex_row()
.justify_center()
.p(px(12.))
.border_t_1()
.border_color(theme.settings_border())
.child(self.button(
"recordings-load-more",
(ui::ButtonVariant::Gray, None),
tr::settings::recordings::load_more(),
false,
cx,
|this, window, cx| {
let total = this.recordings.visible_rows().matching;
this.recordings.visible_count =
load_more_count(this.recordings.visible_count, total);
this.decode_visible_recordings(window, cx);
cx.notify();
},
)),
)
})
}
/// One `<RecordingItem>`: `flex flex-row justify-between p-3 items-center
/// w-full`, bordered from every row but the last.
fn render_recording_row(
&self,
row: &RecordingRow,
last: bool,
cx: &mut Context<Self>,
) -> impl IntoElement {
let theme = self.theme;
let item = &row.item;
// `studioCompleteCheck()`: the only rows whose body is a button.
let opens_editor = item.opens_editor();
let path = item.path.clone();
let thumbnail = match row.thumbnail.clone() {
// `object-cover rounded-sm size-12`
Some(image) => {
use gpui::StyledImage as _;
img(image)
.size(px(48.))
.flex_shrink_0()
.object_fit(gpui::ObjectFit::Cover)
.rounded(px(4.))
.into_any_element()
}
// `<img onError>`'s fallback: `mr-4 rounded-sm bg-gray-10 size-11`.
// `bg-gray-10` is not one of the steps the settings material
// remaps, so it keeps its Radix value.
None => div()
.size(px(44.))
.mr(px(16.))
.flex_shrink_0()
.rounded(px(4.))
.bg(theme.gray_10)
.into_any_element(),
};
let left = div()
// `flex gap-5 items-center`
.flex()
.flex_row()
.items_center()
.gap(px(20.))
.flex_1()
.min_w_0()
.child(thumbnail)
.child(
div()
.flex()
.flex_col()
.gap(px(8.))
.min_w_0()
.child(
div()
.w_full()
.truncate()
.text_size(px(14.))
.child(item.pretty_name.clone()),
)
.child(self.render_recording_badges(item)),
);
div()
.id(gpui::ElementId::Path(item.path.as_path().into()))
.flex()
.flex_row()
.justify_between()
.items_center()
.w_full()
.p(px(12.))
.when(!last, |this| {
this.border_b_1().border_color(theme.settings_border())
})
.map(|this| {
if opens_editor {
this.cursor_pointer()
.hover(|style| style.bg(theme.settings_fill()))
} else {
this.cursor_default()
}
})
.child(left)
.child(self.render_recording_actions(item, cx))
.when(opens_editor, |this| {
this.on_click(cx.listener(move |_this, _, _window, cx| {
let path = path.clone();
tracing::info!(path = %path.display(), "opening a recording in the editor");
// Deferred: opening a window paints it synchronously, and
// doing that inside a click handler would double-lease the
// app.
cx.defer(move |cx| crate::app_windows::open_editor(path, cx));
}))
})
}
/// The badge row: `flex space-x-1`, each pill `px-2 py-0.5 gap-1.5
/// font-medium text-[11px] text-gray-12 rounded-full w-fit`.
fn render_recording_badges(&self, item: &RecordingItem) -> impl IntoElement {
let theme = self.theme;
let pill = |bg: Hsla| {
div()
.flex()
.flex_row()
.items_center()
.flex_none()
.gap(px(6.))
.px(px(8.))
.py(px(2.))
.rounded_full()
.bg(bg)
.text_size(px(11.))
.font_weight(FontWeight::MEDIUM)
.text_color(theme.settings_text())
};
// `size-2.5` on every badge glyph.
let glyph = |icon: &'static str| {
svg()
.path(icon)
.size(px(10.))
.flex_shrink_0()
.text_color(theme.settings_text())
};
div()
.flex()
.flex_row()
.items_center()
.gap(px(4.))
.child(
// `bg-blue-100` for instant, `bg-gray-4` for studio.
pill(match item.mode {
RecordingMode::Instant => Hsla::from(theme.blue_100),
RecordingMode::Studio => theme.settings_fill(),
})
.child(glyph(item.mode.icon()))
.child(item.mode.label()),
)
.when_some(item.upload.clone(), |this, upload| {
let label = upload.label();
let message = upload
.last_error
.clone()
.unwrap_or_else(|| label.to_string());
this.child(
pill(theme.settings_fill())
.id("recording-upload-status")
.child(label)
.tooltip(move |_, cx| {
ui::Tooltip::new(&theme, message.clone())
.style(ui::TooltipStyle::Light)
.view(cx)
}),
)
})
.when(item.clip_count > 1, |this| {
this.child(
pill(theme.settings_fill())
.child(tr::main::library::clips(item.clip_count as usize)),
)
})
.when(item.status.is_in_progress(), |this| {
this.child(
pill(Hsla::from(theme.blue_500))
.child(glyph("icons/record-fill.svg"))
.child(tr::settings::recordings::in_progress()),
)
})
.when_some(item.status.error().map(str::to_string), |this, error| {
this.child(
// The badge is wrapped in a `<CapTooltip>` whose content is
// the error string.
pill(Hsla::from(theme.red_9))
.id("recording-failed")
.child(glyph("icons/warning-bold.svg"))
.child(tr::settings::recordings::failed())
.tooltip(move |_window, cx| {
ui::Tooltip::new(&theme, error.clone())
.style(ui::TooltipStyle::Light)
.view(cx)
}),
)
})
}
/// The row's right-hand button group: `flex gap-2 items-center`.
///
/// Studio rows get Open link (when shared) and Edit; instant rows get
/// Reupload and Open link; both get Open recording bundle and Delete.
fn render_recording_actions(
&self,
item: &RecordingItem,
cx: &mut Context<Self>,
) -> impl IntoElement {
let mode = item.mode;
let path = item.path.clone();
let sharing = item.sharing.clone();
let failed = item.status.error().is_some();
let in_progress = item.status.is_in_progress();
let mut actions = div().flex().flex_row().items_center().gap(px(8.));
if mode == RecordingMode::Studio {
if let Some(link) = sharing.clone() {
actions = actions.child(self.row_button(
"recording-link",
"icons/link.svg",
tr::settings::recordings::open_link(),
false,
cx,
move |_this, _window, cx| cx.open_url(&link),
));
}
let editor_path = path.clone();
actions = actions.child(self.row_button(
"recording-edit",
"icons/edit.svg",
tr::settings::recordings::edit(),
// `disabled={status === "InProgress"}`
in_progress,
cx,
move |this, window, cx| {
this.open_editor_confirmed(editor_path.clone(), failed, window, cx)
},
));
}
if mode == RecordingMode::Instant {
let retry_path = path.clone();
actions = actions.child(
self.row_button(
"recording-reupload",
"icons/rotate-ccw.svg",
tr::settings::recordings::retry_upload(),
!item
.upload
.as_ref()
.is_some_and(crate::upload::queue::UploadState::can_retry),
cx,
move |_, window, cx| {
let path = retry_path.clone();
cx.spawn_in(window, async move |this, cx| {
let Ok(task) = cx.update(|_, cx| {
gpui_tokio::Tokio::spawn(cx, crate::upload::queue::retry(path))
}) else {
return;
};
if let Err(error) =
task.await.unwrap_or_else(|error| Err(error.to_string()))
{
tracing::warn!(%error, "Upload retry deferred");
}
let _ = this.update_in(cx, |this, window, cx| {
this.refresh_recordings(window, cx)
});
})
.detach();
},
),
);
if let Some(link) = sharing {
actions = actions.child(self.row_button(
"recording-instant-link",
"icons/link.svg",
tr::settings::recordings::open_link(),
false,
cx,
move |_this, _window, cx| cx.open_url(&link),
));
}
}
let folder_path = path.clone();
actions = actions.child(self.row_button(
"recording-folder",
"icons/folder.svg",
tr::settings::recordings::open_bundle(),
false,
cx,
move |_this, _window, cx| library::open_recording_folder(&folder_path, mode, cx),
));
actions.child(self.row_button(
"recording-delete",
"icons/trash.svg",
tr::settings::recordings::delete(),
false,
cx,
move |this, window, cx| this.delete_recording(path.clone(), window, cx),
))
}
/// `TooltipIconButton`: `p-2.5 opacity-70 hover:opacity-100 rounded-full
/// hover:bg-gray-3 dark:hover:bg-gray-5 disabled:pointer-events-none
/// disabled:opacity-45`, around a `size-4` glyph -- 36px of hit area.
///
/// `onClick` calls `e.stopPropagation()` before the handler, because the
/// row around it is itself a button. gpui's equivalent is to stop the
/// *mouse-down* propagating: a click listener only fires for an element
/// that saw the press, so blocking the press at this element leaves the
/// row's click unarmed while this button's own still fires (its
/// click-tracking listener is registered after the custom one and therefore
/// runs first in the bubble phase).
fn row_button(
&self,
id: impl Into<gpui::ElementId>,
icon: &'static str,
tooltip: &'static str,
disabled: bool,
cx: &mut Context<Self>,
on_click: impl Fn(&mut Self, &mut Window, &mut Context<Self>) + 'static,
) -> impl IntoElement {
let theme = self.theme;
div()
.id(id.into())
.flex()
.items_center()
.justify_center()
.size(px(36.))
.flex_shrink_0()
.rounded_full()
.opacity(if disabled { 0.45 } else { 0.7 })
.child(
svg()
.path(icon)
.size(px(16.))
.text_color(theme.settings_text()),
)
.when(!disabled, |this| {
this.cursor_pointer()
.hover(|style| style.opacity(1.).bg(theme.settings_fill()))
.tooltip(move |_window, cx| {
ui::Tooltip::new(&theme, tooltip)
.style(ui::TooltipStyle::Light)
.view(cx)
})
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _, window, cx| on_click(this, window, cx)))
})
}
// -- The General page --------------------------------------------------
fn render_general(&self, window: &Window, cx: &mut Context<Self>) -> Vec<gpui::AnyElement> {
let mut sections = Vec::with_capacity(10);
sections.push(self.render_appearance(cx).into_any_element());
if i18n::picker_enabled() {
sections.push(self.render_language(cx).into_any_element());
}
sections.extend([
self.render_app_section(cx).into_any_element(),
self.render_recording(cx).into_any_element(),
self.render_storage(cx).into_any_element(),
self.render_project_name(window, cx).into_any_element(),
self.render_excluded_windows(cx).into_any_element(),
self.render_updates(cx).into_any_element(),
self.render_self_host(window, cx).into_any_element(),
self.render_privacy(cx).into_any_element(),
]);
sections
}
/// `AppearanceSection` -- `theme`.
fn render_appearance(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
let current = self.settings.theme;
let tiles = div()
// `grid grid-cols-3 gap-3`
.flex()
.flex_row()
.gap(px(12.))
.children(AppTheme::ALL.iter().copied().map(|option| {
let selected = option == current;
div()
.id(SharedString::from(option.as_json()))
.flex()
.flex_col()
.flex_1()
.min_w_0()
.items_center()
.gap(px(8.))
.child(
div()
.w_full()
// `aspect-[5/3]`, which gpui cannot express: this
// is the height the tile has at the window's
// default 782 width (see the README).
.h(px(93.))
.rounded(px(8.))
.overflow_hidden()
.border_2()
.border_color(if selected {
theme.blue_9.into()
} else {
Hsla::from(theme.gray_4)
})
.when(!selected, |this| {
this.hover(|style| style.border_color(Hsla::from(theme.gray_6)))
})
.child(img(theme_preview(option)).size_full()),
)
.child(
// `text-xs font-medium`, gray-12 when selected and
// gray-10 -- i.e. muted -- when not.
div()
.text_size(px(12.))
.font_weight(FontWeight::MEDIUM)
.text_color(if selected {
theme.settings_text()
} else {
theme.settings_muted()
})
.child(option.label()),
)
.on_click(cx.listener(move |this, _, window, cx| {
if this.settings.theme == option {
return;
}
this.settings.theme = option;
this.write_enum("theme", option, cx);
crate::theme::set_preference(option, cx);
crate::theme::apply_native(window, cx);
this.theme.refresh(window, cx, true);
cx.defer(|cx: &mut gpui::App| crate::app_windows::broadcast_theme(cx));
}))
}));
self.section(
tr::settings::general::appearance::title(),
Some(tr::settings::general::appearance::description()),
None,
vec![self.card(true).child(tiles).into_any_element()],
)
}
fn language_preference(&self) -> i18n::Preference {
i18n::Preference::from_setting(self.settings.ui_language.as_deref())
}
/// `uiLanguage`, a GPUI-only setting.
fn render_language(&self, cx: &mut Context<Self>) -> impl IntoElement {
let label = language_label(self.language_preference());
self.section(
tr::settings::general::language::title(),
Some(tr::settings::general::language::description()),
None,
vec![
self.rows(vec![
self.setting_row(
tr::settings::general::language::label(),
None,
self.select("ui-language", label, MenuKind::Language, cx)
.into_any_element(),
),
])
.into_any_element(),
],
)
}
/// The macOS-only App section: `hideDockIcon`, `enableNotifications`.
fn render_app_section(&self, cx: &mut Context<Self>) -> impl IntoElement {
self.section(
tr::settings::general::app::title(),
Some(tr::settings::general::app::description()),
None,
vec![
self.rows(vec![
self.setting_row(
tr::settings::general::app::dock_icon::label(),
Some(tr::settings::general::app::dock_icon::description()),
// The row is the *inverse* of the stored key.
self.toggle(
"hide-dock-icon",
tr::settings::general::app::dock_icon::label(),
!self.settings.hide_dock_icon,
cx,
|this, cx| {
this.settings.hide_dock_icon = !this.settings.hide_dock_icon;
let value = this.settings.hide_dock_icon;
this.write_bool("hideDockIcon", value, cx);
// `GeneralSettingsStore::set` -> the store
// listener -> `schedule_macos_dock_visibility_sync`.
// Deferred past the debounced write, which is
// what the sync then reads back.
cx.defer(|cx: &mut gpui::App| crate::menus::schedule_dock_sync(cx));
},
)
.into_any_element(),
),
self.setting_row(
tr::settings::general::app::notifications::label(),
Some(tr::settings::general::app::notifications::description()),
self.toggle(
"enable-notifications",
tr::settings::general::app::notifications::label(),
self.settings.enable_notifications,
cx,
|this, cx| {
// The Tauri handler asks for the notification
// permission before enabling; nothing here
// posts notifications yet, so there is nothing
// to ask for.
this.settings.enable_notifications =
!this.settings.enable_notifications;
let value = this.settings.enable_notifications;
this.write_bool("enableNotifications", value, cx);
},
)
.into_any_element(),
),
])
.into_any_element(),
],
)
}
fn select_instant_resolution(&mut self, index: usize, cx: &mut Context<Self>) {
let Some((resolution, _, _)) = INSTANT_RESOLUTION_TIERS.get(index).copied() else {
return;
};
self.has_cap_pro = store::auth_snapshot().is_upgraded();
if self.instant_resolution_locked(resolution) {
cx.open_url(crate::auth::PRICING_URL);
cx.notify();
return;
}
if store::set_store_setting(
GENERAL_SETTINGS,
"instantModeMaxResolution",
Value::from(resolution),
) {
self.settings.instant_mode_max_resolution = resolution;
self.instant_quality_notice = None;
} else {
self.instant_quality_notice = Some(InstantQualityNotice::SaveFailed);
}
cx.notify();
}
fn render_recording_quality(&self, cx: &mut Context<Self>) -> Vec<gpui::AnyElement> {
vec![
self.render_studio_quality(cx).into_any_element(),
self.render_instant_quality(cx).into_any_element(),
self.section(
tr::settings::quality::sharing::title(),
None,
None,
vec![
self.rows(vec![
self.setting_row(
tr::settings::quality::sharing::auto_open(),
Some(tr::settings::quality::sharing::auto_open_description()),
self.toggle(
"auto-open-links",
tr::settings::quality::sharing::auto_open(),
!self.settings.disable_auto_open_links,
cx,
|this, cx| {
this.settings.disable_auto_open_links =
!this.settings.disable_auto_open_links;
this.write_bool(
"disableAutoOpenLinks",
this.settings.disable_auto_open_links,
cx,
);
},
)
.into_any_element(),
),
])
.into_any_element(),
],
)
.into_any_element(),
]
}
fn effective_instant_resolution(&self) -> u32 {
if self.has_cap_pro {
self.settings.instant_mode_max_resolution
} else {
FREE_INSTANT_MODE_MAX_RESOLUTION
}
}
fn instant_resolution_locked(&self, resolution: u32) -> bool {
!self.has_cap_pro && resolution > FREE_INSTANT_MODE_MAX_RESOLUTION
}
fn render_instant_quality(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
let effective = self.effective_instant_resolution();
let summary = INSTANT_RESOLUTION_TIERS
.iter()
.find(|(value, _, _)| *value == effective)
.map(|(_, _, summary)| summary())
.unwrap_or_default();
let description = if self.has_cap_pro {
summary
} else {
tr::settings::quality::instant::free_plan()
};
let options = INSTANT_RESOLUTION_TIERS
.iter()
.map(|(value, label, _)| {
let mut option = ui::SegmentOption::new(*label, *value == effective);
if self.instant_resolution_locked(*value) {
option.icon = Some("icons/lock.svg".into());
}
option
})
.collect();
let resolution = div()
.id("settings-instant-quality")
.anchor_scroll(Some(self.instant_quality_anchor.clone()))
.child(
ui::SettingRow::settings(
&theme,
tr::settings::quality::instant::max_resolution(),
None,
self.segmented_raw("instant-resolution", options, cx, |this, index, cx| {
this.select_instant_resolution(index, cx)
})
.into_any_element(),
)
.description(description),
);
let mut rows = vec![resolution.into_any_element()];
if let Some(InstantQualityNotice::SaveFailed) = self.instant_quality_notice {
rows.push(
div()
.p(px(12.))
.text_size(px(12.))
.text_color(Hsla::from(theme.amber_11))
.child(tr::settings::quality::save_failed())
.into_any_element(),
);
}
self.section(
tr::settings::quality::instant::title(),
Some(tr::settings::quality::instant::description()),
None,
vec![self.rows(rows).into_any_element()],
)
}
fn select_studio_quality(&mut self, quality: StudioQuality, cx: &mut Context<Self>) {
self.studio_quality_save_failed = !store::set_store_setting(
GENERAL_SETTINGS,
"studioRecordingQuality",
Value::String(quality.as_json().to_string()),
);
if !self.studio_quality_save_failed {
self.settings.studio_recording_quality = quality;
}
cx.notify();
}
fn radio_dot(&self, checked: bool) -> gpui::Div {
let theme = self.theme;
let accent: Hsla = rgb(Theme::SETTINGS_ACCENT).into();
div()
.size(px(16.))
.flex_none()
.flex()
.items_center()
.justify_center()
.rounded_full()
.when(checked, |this| {
this.bg(accent)
.child(div().size(px(6.)).rounded_full().bg(gpui::white()))
})
.when(!checked, |this| {
this.border_1()
.border_color(theme.settings_muted().opacity(0.55))
.group_hover("studio-quality-option", |style| {
style.border_color(theme.settings_muted())
})
.bg(if theme.is_dark() {
gpui::hsla(0., 0., 1., 0.1)
} else {
gpui::white()
})
.shadow(vec![gpui::BoxShadow {
color: gpui::hsla(0., 0., 0., 0.12),
offset: gpui::point(px(0.), px(0.5)),
blur_radius: px(1.),
spread_radius: px(0.),
inset: false,
}])
})
}
fn render_studio_quality(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
let current = self.settings.studio_recording_quality;
let mut rows: Vec<gpui::AnyElement> = STUDIO_QUALITY_TIERS
.iter()
.copied()
.map(|(quality, label, description)| {
let (label, description) = (label(), description());
let selected = current == quality;
div()
.id(SharedString::from(format!(
"studio-quality-{}",
quality.as_json()
)))
.tab_index(0)
.aria_label(label)
.aria_description(description)
.aria_selected(selected)
.cursor_pointer()
.flex()
.items_start()
.gap(px(10.))
.p(px(12.))
.group("studio-quality-option")
.child(div().mt(px(1.)).child(self.radio_dot(selected)))
.child(
div()
.flex()
.flex_col()
.flex_1()
.min_w_0()
.gap(px(2.))
.child(
div()
.flex()
.items_center()
.gap(px(6.))
.child(div().text_size(px(13.)).child(label))
.when(quality == StudioQuality::Balanced, |this| {
this.child(
div()
.px(px(6.))
.py(px(1.))
.rounded(px(4.))
.bg(theme.settings_fill())
.text_size(px(11.))
.text_color(theme.settings_muted())
.child(
tr::settings::quality::studio::recommended(
),
),
)
}),
)
.child(
div()
.text_size(px(12.))
.line_height(px(16.))
.text_color(theme.settings_muted())
.child(description),
),
)
.on_click(cx.listener(move |this, _, _, cx| {
this.select_studio_quality(quality, cx);
}))
.on_key_down(cx.listener(move |this, event: &gpui::KeyDownEvent, _, cx| {
if event.keystroke.modifiers == Default::default()
&& matches!(event.keystroke.key.as_str(), "enter" | "space")
{
this.select_studio_quality(quality, cx);
cx.stop_propagation();
}
}))
.into_any_element()
})
.collect();
if self.studio_quality_save_failed {
rows.push(
div()
.p(px(12.))
.text_size(px(12.))
.text_color(Hsla::from(theme.amber_11))
.child(tr::settings::quality::save_failed())
.into_any_element(),
);
}
self.section(
tr::settings::quality::studio::title(),
Some(tr::settings::quality::studio::description()),
None,
vec![
div()
.id("settings-studio-quality")
.anchor_scroll(Some(self.studio_quality_anchor.clone()))
.child(self.rows(rows))
.into_any_element(),
],
)
}
/// The Recording card: thirteen rows, in TSX order.
fn render_recording(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
let settings = &self.settings;
let countdown_label = COUNTDOWN_OPTIONS
.iter()
.find(|(value, _)| *value == settings.recording_countdown.unwrap_or(0))
.map(|(_, label)| label().to_string())
.unwrap_or_else(|| settings.recording_countdown.unwrap_or(0).to_string());
let fps_label = MAX_FPS_OPTIONS
.iter()
.find(|(value, _)| *value == settings.max_fps)
.map(|(_, label)| label().to_string())
.unwrap_or_else(|| settings.max_fps.to_string());
let zoom = settings.default_zoom_amount.unwrap_or(1.5);
self.section(
tr::settings::general::recording::title(),
Some(tr::settings::general::recording::description()),
None,
vec![
self.rows(vec![
self.setting_row(
tr::settings::general::recording::countdown::label(),
Some(tr::settings::general::recording::countdown::description()),
self.select("countdown", countdown_label, MenuKind::Countdown, cx)
.into_any_element(),
),
self.setting_row(
tr::settings::general::recording::confirm_without_mic::label(),
Some(tr::settings::general::recording::confirm_without_mic::description()),
self.toggle(
"confirm-without-mic",
tr::settings::general::recording::confirm_without_mic::label(),
settings.confirm_without_microphone,
cx,
|this, cx| {
// The one row on this page that is not a
// `general_settings` key.
this.settings.confirm_without_microphone =
!this.settings.confirm_without_microphone;
let value = this.settings.confirm_without_microphone;
store::set_store_setting(
RECORDING_START_SAFETY,
"confirmBeforeRecordingWithoutMicrophone",
Value::Bool(value),
);
cx.notify();
},
)
.into_any_element(),
),
self.setting_row(
tr::settings::general::recording::studio_sound::label(),
Some(tr::settings::general::recording::studio_sound::description()),
self.toggle(
"studio-sound-default",
tr::settings::general::recording::studio_sound::label(),
settings.studio_sound_by_default,
cx,
|this, cx| {
let value = !this.settings.studio_sound_by_default;
if store::set_studio_sound_by_default(value) {
this.settings.studio_sound_by_default = value;
}
cx.notify();
},
)
.into_any_element(),
),
self.setting_row(
tr::settings::general::recording::main_window_start::label(),
Some(tr::settings::general::recording::main_window_start::description()),
self.select(
"main-window-start",
settings.main_window_recording_start_behaviour.label(),
MenuKind::MainWindowStart,
cx,
)
.into_any_element(),
),
self.setting_row(
tr::settings::general::recording::window_capture::label(),
Some(tr::settings::general::recording::window_capture::description()),
self.select(
"window-capture-style",
settings.window_capture_style.label(),
MenuKind::WindowCapture,
cx,
)
.into_any_element(),
),
// "After a Studio recording" lives on the Shortcuts page,
// next to the shortcuts it shapes. There is no
// post-capture overlay in this app, so a stored
// `showOverlay` means "reshow the main window"
// (`app_windows.rs`) and is labelled "Show Cap".
self.setting_row(
tr::settings::general::recording::post_deletion::label(),
Some(tr::settings::general::recording::post_deletion::description()),
self.select(
"post-deletion",
settings.post_deletion_behaviour.label(),
MenuKind::PostDeletion,
cx,
)
.into_any_element(),
),
self.setting_row(
tr::settings::general::recording::delete_after_upload::label(),
Some(tr::settings::general::recording::delete_after_upload::description()),
self.toggle(
"delete-after-upload",
tr::settings::general::recording::delete_after_upload::label(),
settings.delete_instant_recordings_after_upload,
cx,
|this, cx| {
this.settings.delete_instant_recordings_after_upload =
!this.settings.delete_instant_recordings_after_upload;
let value = this.settings.delete_instant_recordings_after_upload;
this.write_bool("deleteInstantRecordingsAfterUpload", value, cx);
},
)
.into_any_element(),
),
self.setting_row(
tr::settings::general::recording::crash_recovery::label(),
Some(tr::settings::general::recording::crash_recovery::description()),
self.toggle(
"crash-recovery",
tr::settings::general::recording::crash_recovery::label(),
settings.crash_recovery_recording,
cx,
|this, cx| {
this.settings.crash_recovery_recording =
!this.settings.crash_recovery_recording;
let value = this.settings.crash_recovery_recording;
this.write_bool("crashRecoveryRecording", value, cx);
},
)
.into_any_element(),
),
self.setting_row(
tr::settings::general::recording::custom_cursor::label(),
Some(tr::settings::general::recording::custom_cursor::description()),
self.toggle(
"custom-cursor",
tr::settings::general::recording::custom_cursor::label(),
settings.custom_cursor_capture,
cx,
|this, cx| {
this.settings.custom_cursor_capture =
!this.settings.custom_cursor_capture;
let value = this.settings.custom_cursor_capture;
this.write_bool("custom_cursor_capture2", value, cx);
},
)
.into_any_element(),
),
self.setting_row(
tr::settings::general::recording::auto_zoom::label(),
Some(tr::settings::general::recording::auto_zoom::description()),
self.toggle(
"auto-zoom",
tr::settings::general::recording::auto_zoom::label(),
settings.auto_zoom_on_clicks,
cx,
|this, cx| {
this.settings.auto_zoom_on_clicks =
!this.settings.auto_zoom_on_clicks;
let value = this.settings.auto_zoom_on_clicks;
this.write_bool("autoZoomOnClicks", value, cx);
},
)
.into_any_element(),
),
self.setting_row(
tr::settings::general::recording::default_zoom::label(),
Some(tr::settings::general::recording::default_zoom::description()),
div()
// `flex gap-2 items-center w-52`
.flex()
.flex_row()
.items_center()
.gap(px(8.))
.w(px(208.))
.child(self.render_zoom_slider(zoom, cx))
.child(
// `w-9 text-xs text-right text-gray-11 tabular-nums`
div()
.w(px(36.))
.text_size(px(12.))
.text_color(theme.settings_muted())
.child(format!("{zoom:.1}x")),
)
.into_any_element(),
),
self.setting_row(
tr::settings::general::recording::capture_keyboard::label(),
Some(tr::settings::general::recording::capture_keyboard::description()),
self.toggle(
"capture-keyboard",
tr::settings::general::recording::capture_keyboard::label(),
settings.capture_keyboard_events,
cx,
|this, cx| {
this.settings.capture_keyboard_events =
!this.settings.capture_keyboard_events;
let value = this.settings.capture_keyboard_events;
this.write_bool("captureKeyboardEvents", value, cx);
},
)
.into_any_element(),
),
self.setting_row(
tr::settings::general::recording::notch_overlay::label(),
Some(tr::settings::general::recording::notch_overlay::description()),
self.toggle(
"notch-overlay",
tr::settings::general::recording::notch_overlay::label(),
settings.macbook_notch_overlay,
cx,
|this, cx| {
this.settings.macbook_notch_overlay =
!this.settings.macbook_notch_overlay;
let value = this.settings.macbook_notch_overlay;
this.write_bool("macbookNotchOverlay", value, cx);
},
)
.into_any_element(),
),
self.setting_row(
tr::settings::general::recording::max_fps::label(),
Some(if settings.max_fps > 60 {
tr::settings::general::recording::max_fps::description_high()
} else {
tr::settings::general::recording::max_fps::description()
}),
self.select("max-fps", fps_label, MenuKind::MaxFps, cx)
.into_any_element(),
),
])
.into_any_element(),
],
)
}
/// `StorageSection` -- `recordingsPath`.
fn render_storage(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
let path = self.settings.recordings_path.clone();
let is_custom = path.is_some();
// `Default (Application Support)`
let display =
path.unwrap_or_else(|| tr::settings::general::storage::default_location().to_string());
let mut actions = div().flex().flex_row().justify_end().gap(px(8.));
if is_custom {
actions = actions.child(self.button(
"recordings-reset",
(ui::ButtonVariant::Gray, None),
tr::common::reset_to_default(),
false,
cx,
|this, _window, cx| {
if store::set_recordings_path(None) {
this.settings = GeneralSettings::load();
cx.notify();
}
},
));
}
actions = actions.child(self.button(
"recordings-pick",
(ui::ButtonVariant::Dark, None),
tr::settings::general::storage::choose_folder(),
false,
cx,
|_, window, cx| {
// `commands.pickRecordingsFolder()` opens an NSOpenPanel in
// directory mode; gpui wraps the same panel.
let paths = cx.prompt_for_paths(gpui::PathPromptOptions {
files: false,
directories: true,
multiple: false,
prompt: None,
});
cx.spawn_in(window, async move |this, cx| {
let Ok(Ok(Some(paths))) = paths.await else {
return;
};
let Some(path) = paths.into_iter().next() else {
return;
};
this.update(cx, |this, cx| {
let path = path.to_string_lossy().to_string();
if store::set_recordings_path(Some(&path)) {
this.settings = GeneralSettings::load();
cx.notify();
}
})
.ok();
})
.detach();
},
));
self.section(
tr::settings::general::storage::title(),
Some(tr::settings::general::storage::description()),
None,
vec![
self.card(true)
.child(
div()
.flex()
.flex_col()
.gap(px(12.))
.child(
// `flex items-center gap-2 px-3 py-2 rounded-lg
// bg-gray-3 border border-gray-4 min-w-0`
div()
.flex()
.flex_row()
.items_center()
.gap(px(8.))
.px(px(12.))
.py(px(8.))
.min_w_0()
.rounded(px(8.))
.bg(theme.settings_fill())
.border_1()
.border_color(theme.settings_border())
.child(
div()
.flex_1()
.min_w_0()
.truncate()
.text_size(px(12.))
.child(display),
),
)
.child(actions),
)
.into_any_element(),
],
)
}
/// `DefaultProjectNameCard` -- `defaultProjectNameTemplate`.
fn render_project_name(&self, _window: &Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
let stored = self
.settings
.default_project_name_template
.clone()
.unwrap_or_else(|| DEFAULT_PROJECT_NAME_TEMPLATE.to_string());
let draft = self.project_name.clone();
let save_disabled = draft.is_empty() || draft == stored || draft.chars().count() <= 3;
let reset_disabled = draft == DEFAULT_PROJECT_NAME_TEMPLATE
&& self.settings.default_project_name_template.is_none();
let right = div()
.flex()
.flex_row()
.items_center()
.gap(px(8.))
.child(self.button(
"project-name-reset",
(ui::ButtonVariant::Gray, None),
tr::common::reset(),
reset_disabled,
cx,
|this, _window, cx| {
this.settings.default_project_name_template = None;
this.project_name = DEFAULT_PROJECT_NAME_TEMPLATE.to_string();
let input = this.project_name_input.clone();
input.update(cx, |input, cx| {
input.set_text(DEFAULT_PROJECT_NAME_TEMPLATE, cx)
});
this.write("defaultProjectNameTemplate", Value::Null, cx);
},
))
.child(self.button(
"project-name-save",
(ui::ButtonVariant::Dark, None),
tr::common::save(),
save_disabled,
cx,
|this, _window, cx| {
let template = this.project_name.clone();
this.settings.default_project_name_template = Some(template.clone());
this.write("defaultProjectNameTemplate", Value::String(template), cx);
},
))
.into_any_element();
let placeholder_rows: Vec<(&str, &str, &str)> = vec![
(
tr::settings::general::project_name::placeholders::recording_mode(),
"{recording_mode}",
tr::settings::general::project_name::placeholders::recording_mode_values(),
),
(
"",
"{mode}",
tr::settings::general::project_name::placeholders::mode_values(),
),
(
tr::settings::general::project_name::placeholders::target(),
"{target_kind}",
tr::settings::general::project_name::placeholders::target_kind_values(),
),
(
"",
"{target_name}",
tr::settings::general::project_name::placeholders::target_name_values(),
),
(
tr::settings::general::project_name::placeholders::date_time(),
"{date}",
tr::settings::general::project_name::placeholders::date_values(),
),
(
"",
"{time}",
tr::settings::general::project_name::placeholders::time_values(),
),
(
tr::settings::general::project_name::placeholders::random(),
"{random}",
tr::settings::general::project_name::placeholders::random_values(),
),
];
let body = div()
.flex()
.flex_col()
.gap(px(12.))
.child(self.text_field(Field::ProjectName, cx))
.child(
// The live preview box. The Tauri card renders
// `commands.formatProjectName(...)`; ours formats the six
// literal placeholders (see `format_project_name`).
div()
.flex()
.flex_row()
.items_center()
.gap(px(8.))
.px(px(12.))
.py(px(8.))
.rounded(px(8.))
.bg(theme.settings_fill())
.border_dashed()
.border_1()
.border_color(theme.settings_border())
.child(
div()
.flex_1()
.min_w_0()
.truncate()
.text_size(px(12.))
.child(format_project_name(&draft)),
),
)
.child(
div()
.id("placeholders-trigger")
.flex()
.flex_row()
.items_center()
.gap(px(4.))
.text_size(px(12.))
.text_color(theme.settings_muted())
.child(
svg()
.path("icons/chevron-down.svg")
.size(px(14.))
.text_color(theme.settings_muted()),
)
.child(tr::settings::general::project_name::available_placeholders())
.on_click(cx.listener(|this, _, _window, cx| {
this.toggle_placeholders(cx);
})),
)
// Mounted while open *and* while animating shut, so the reveal
// has something to collapse; unmounted once settled closed, or
// the parent's `gap-3` would leave a 12px hole under the
// trigger.
.when(
self.placeholders.is_open() || self.placeholders.is_animating(),
|this| {
let (height, _) = self.placeholders.height_for(std::time::Instant::now());
this.child(
ui::Collapsible::new(height, self.placeholders.measure_cell()).content(
div()
.flex()
.flex_col()
.gap(px(6.))
.text_size(px(12.))
.children(placeholder_rows.into_iter().map(
|(heading, code, meaning)| {
div()
.flex()
.flex_col()
.gap(px(4.))
.when(!heading.is_empty(), |this| {
this.child(
div()
.font_weight(FontWeight::MEDIUM)
.child(heading.to_string()),
)
})
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(6.))
.child(
div()
.px(px(6.))
.py(px(2.))
.rounded(px(6.))
.bg(theme.settings_fill())
.text_size(px(11.))
.child(code.to_string()),
)
.child(
div()
.flex_1()
.min_w_0()
.truncate()
.text_color(theme.settings_muted())
.child(format!("-> {meaning}")),
),
)
},
)),
),
)
},
);
self.section(
tr::settings::general::project_name::title(),
Some(tr::settings::general::project_name::description()),
Some(right),
vec![self.card(true).child(body).into_any_element()],
)
}
/// `ExcludedWindowsCard` -- `excludedWindows`.
fn render_excluded_windows(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
let missing = self.missing_default_exclusions();
let right = div()
.flex()
.flex_row()
.items_center()
.gap(px(8.))
.child(self.button(
"exclusions-reset",
(ui::ButtonVariant::Gray, None),
tr::common::reset(),
false,
cx,
|this, _window, cx| {
this.write_excluded(store::default_excluded_windows(), cx);
},
))
.child(
self.button(
"exclusions-add",
(ui::ButtonVariant::Dark, Some("icons/plus.svg")),
tr::common::add(),
self.windows.is_empty(),
cx,
|_, _, _| {},
)
.on_click(cx.listener(
|this, event: &gpui::ClickEvent, window, cx| {
if !this.windows.is_empty() {
this.open_menu(MenuKind::AddWindow, event.position(), window, cx);
}
},
)),
)
.into_any_element();
let chips = if self.settings.excluded_windows.is_empty() {
div()
.text_size(px(12.))
.text_color(theme.settings_muted())
.child(tr::settings::general::excluded_windows::empty())
.into_any_element()
} else {
div()
.flex()
.flex_row()
.flex_wrap()
.gap(px(8.))
.children(self.settings.excluded_windows.iter().enumerate().map(
|(index, entry)| {
let secondary = entry.secondary_label().map(str::to_string);
div()
// `flex gap-2 items-center pr-1 pl-3 py-1.5
// rounded-full border bg-gray-3 border-gray-4`
.flex()
.flex_row()
.items_center()
.gap(px(8.))
.pl(px(12.))
.pr(px(4.))
.py(px(6.))
.rounded_full()
.bg(theme.settings_fill())
.border_1()
.border_color(theme.settings_border())
.child(
div()
.flex()
.flex_col()
.child(
div()
.text_size(px(12.))
.child(entry.primary_label().to_string()),
)
.children(secondary.map(|label| {
div()
.text_size(px(10.))
.text_color(theme.settings_muted())
.child(label)
})),
)
.child(
div()
.id(SharedString::from(format!("exclusion-{index}")))
.flex()
.items_center()
.justify_center()
.size(px(20.))
.rounded_full()
.child(
svg()
.path("icons/x.svg")
.size(px(12.))
.text_color(theme.settings_muted()),
)
.hover(|style| style.bg(theme.settings_selection()))
.on_click(cx.listener(move |this, _, _window, cx| {
let mut next = this.settings.excluded_windows.clone();
if index < next.len() {
next.remove(index);
}
this.write_excluded(next, cx);
})),
)
},
))
.into_any_element()
};
let mut card = self.card(true).flex().flex_col();
if !missing.is_empty() {
let names = missing
.iter()
.map(|entry| entry.primary_label().to_string())
.collect::<Vec<_>>()
.join(", ");
let missing_title = tr::settings::general::excluded_windows::missing_title();
let missing_body = tr::settings::general::excluded_windows::missing_body(names);
card = card.child(
// `mb-3 rounded-lg border border-amber-6 bg-amber-3/30 px-3 py-2.5`
div()
.flex()
.flex_row()
.items_start()
.gap(px(8.))
.mb(px(12.))
.px(px(12.))
.py(px(10.))
.rounded(px(8.))
.border_1()
.border_color(Hsla::from(theme.amber_6))
.bg(Theme::with_alpha(theme.amber_3, 0.3))
.child(
svg()
.path("icons/triangle-alert.svg")
.size(px(16.))
.flex_shrink_0()
.mt(px(2.))
.text_color(Hsla::from(theme.amber_11)),
)
.child(
div()
.flex()
.flex_col()
.flex_1()
.min_w_0()
.gap(px(4.))
.text_color(Hsla::from(theme.amber_11))
.child(
div()
.text_size(px(12.))
.font_weight(FontWeight::MEDIUM)
.child(missing_title),
)
.child(
div()
.text_size(px(10.))
.line_height(px(14.))
.child(missing_body),
),
)
.child(self.button(
"exclusions-restore",
(ui::ButtonVariant::Gray, None),
tr::settings::general::excluded_windows::restore(),
false,
cx,
|this, _window, cx| {
this.write_excluded(store::default_excluded_windows(), cx);
},
)),
);
}
self.section(
tr::settings::general::excluded_windows::title(),
Some(tr::settings::general::excluded_windows::description()),
Some(right),
vec![card.child(chips).into_any_element()],
)
}
/// `UpdatesSection` -- `updateChannel`.
fn render_updates(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
let current = self.settings.update_channel;
let current_policy = self.settings.update_download_policy;
let description = UPDATE_CHANNEL_DESCRIPTIONS
.iter()
.find(|(channel, _)| *channel == current)
.map(|(_, description)| description())
.unwrap_or_default();
let body = div()
.flex()
.flex_col()
.gap(px(12.))
.px(px(16.))
.py(px(16.))
.child(
div()
.flex()
.flex_row()
.justify_between()
.items_start()
.gap(px(16.))
.child(
div()
.flex()
.flex_col()
.gap(px(2.))
.min_w_0()
.child(
div()
.text_size(px(13.))
.child(tr::settings::general::updates::download_policy::label()),
)
.child(
div()
.text_size(px(12.))
.line_height(px(16.))
.text_color(theme.settings_muted())
.child(
tr::settings::general::updates::download_policy::description(),
),
),
)
.child(self.segmented_raw(
"update-download-policy",
vec![
ui::SegmentOption::new(
tr::settings::general::updates::download_policy::auto(),
current_policy == UpdateDownloadPolicy::Auto,
),
ui::SegmentOption::new(
tr::settings::general::updates::download_policy::manual(),
current_policy == UpdateDownloadPolicy::Manual,
),
ui::SegmentOption::new(
tr::settings::general::updates::download_policy::never(),
current_policy == UpdateDownloadPolicy::Never,
),
],
cx,
|this, index, cx| {
let value = match index {
0 => UpdateDownloadPolicy::Auto,
1 => UpdateDownloadPolicy::Manual,
_ => UpdateDownloadPolicy::Never,
};
if this.settings.update_download_policy == value {
return;
}
this.settings.update_download_policy = value;
this.write_enum("updateDownloadPolicy", value, cx);
crate::updates::update_download_policy_changed(value, cx);
},
)),
)
.child(div().h(px(1.)).bg(theme.settings_border()))
.child(
div()
.flex()
.flex_row()
.justify_between()
.items_start()
.gap(px(16.))
.child(
div()
.flex()
.flex_col()
.gap(px(2.))
.min_w_0()
.child(
div()
.text_size(px(13.))
.child(tr::settings::general::updates::channel::label()),
)
.child(
div()
.text_size(px(12.))
.line_height(px(16.))
.text_color(theme.settings_muted())
.child(tr::settings::general::updates::channel::description()),
),
)
.child(self.segmented::<UpdateChannel>(
"update-channel",
current,
cx,
|this, value, cx| {
if this.settings.update_channel == value {
return;
}
this.settings.update_channel = value;
this.write_enum("updateChannel", value, cx);
crate::updates::update_channel_changed(
this.settings.update_channel,
cx,
);
},
)),
)
.child(
self.note_box()
.child(div().text_size(px(12.)).child(description))
.when(current == UpdateChannel::Nightly, |this| {
this.child(
div()
.text_size(px(11.))
.line_height(px(15.))
.text_color(theme.settings_muted())
.child(tr::settings::general::updates::nightly_switch_back()),
)
}),
);
self.section(
tr::settings::general::updates::title(),
Some(tr::settings::general::updates::description()),
None,
vec![self.card(false).child(body).into_any_element()],
)
}
/// `ServerURLSetting` -- `serverUrl`.
fn render_self_host(&self, _window: &Window, cx: &mut Context<Self>) -> impl IntoElement {
let stored = self.settings.server_url.clone();
let draft = self.server_url.clone();
let body = div()
.flex()
.flex_col()
.gap(px(12.))
.child(
div()
.flex()
.flex_col()
.gap(px(6.))
.child(
div()
.text_size(px(13.))
.child(tr::settings::general::self_host::server_url()),
)
.child(self.text_field(Field::ServerUrl, cx)),
)
.child(
div()
.flex()
.flex_row()
.justify_end()
.gap(px(8.))
.child(self.button(
"server-url-reset",
(ui::ButtonVariant::Gray, None),
tr::common::reset_to_default(),
stored == DEFAULT_SERVER_URL && draft == DEFAULT_SERVER_URL,
cx,
|this, window, cx| {
if this.settings.server_url == DEFAULT_SERVER_URL {
this.server_url = DEFAULT_SERVER_URL.to_string();
let input = this.server_url_input.clone();
input
.update(cx, |input, cx| input.set_text(DEFAULT_SERVER_URL, cx));
cx.notify();
return;
}
this.confirm_server_url(DEFAULT_SERVER_URL.to_string(), window, cx);
},
))
.child(self.button(
"server-url-update",
(ui::ButtonVariant::Dark, None),
tr::settings::general::self_host::update(),
stored == draft,
cx,
|this, window, cx| {
let value = this.server_url.clone();
this.confirm_server_url(value, window, cx);
},
)),
);
self.section(
tr::settings::general::self_host::title(),
Some(tr::settings::general::self_host::description()),
None,
vec![self.card(true).child(body).into_any_element()],
)
}
/// The `confirm()` the Tauri handler puts in front of a server change. It
/// also signs the user out; there is no auth store here to clear.
fn confirm_server_url(&mut self, value: String, window: &mut Window, cx: &mut Context<Self>) {
let Some(origin) = origin_of(&value) else {
return;
};
let answer = window.prompt(
gpui::PromptLevel::Warning,
&tr::settings::general::self_host::confirm_change(&origin),
None,
&[
gpui::PromptButton::ok(tr::common::ok()),
gpui::PromptButton::cancel(tr::common::cancel()),
],
cx,
);
cx.spawn(async move |this, cx| {
if answer.await.ok() != Some(0) {
return;
}
this.update(cx, |this, cx| {
this.settings.server_url = origin.clone();
this.server_url = origin.clone();
let input = this.server_url_input.clone();
input.update(cx, |input, cx| input.set_text(origin.clone(), cx));
this.write("serverUrl", Value::String(origin), cx);
})
.ok();
})
.detach();
}
/// `TelemetryCard` -- `enableTelemetry`.
fn render_privacy(&self, cx: &mut Context<Self>) -> impl IntoElement {
self.section(
tr::settings::general::privacy::title(),
None,
None,
vec![
self.rows(vec![
self.setting_row(
tr::settings::general::privacy::telemetry::label(),
Some(tr::settings::general::privacy::telemetry::description()),
self.toggle(
"telemetry",
tr::settings::general::privacy::telemetry::label(),
self.settings.enable_telemetry,
cx,
|this, cx| {
this.settings.enable_telemetry = !this.settings.enable_telemetry;
let value = this.settings.enable_telemetry;
this.write_bool("enableTelemetry", value, cx);
},
)
.into_any_element(),
),
])
.into_any_element(),
],
)
}
// -- Primitives (Setting.tsx) -----------------------------------------
/// `<Section>`: `space-y-2.5`, header `flex justify-between items-end
/// gap-3 px-1`, title `text-sm font-semibold tracking-tight`, description
/// `text-xs leading-relaxed text-gray-10`.
pub(crate) fn section(
&self,
title: &'static str,
description: Option<&'static str>,
right: Option<gpui::AnyElement>,
children: Vec<gpui::AnyElement>,
) -> ui::Section {
ui::Section::settings(&self.theme, title, description, right, children)
}
/// `<SectionCard>` -- [`ui::Card::settings`].
pub(crate) fn card(&self, padded: bool) -> gpui::Div {
ui::Card::settings(&self.theme, padded)
}
/// `<SectionRows>`: the same card with `divide-y divide-gray-3`.
pub(crate) fn rows(&self, children: Vec<gpui::AnyElement>) -> gpui::Div {
ui::Card::settings_rows(&self.theme, children)
}
/// `<SettingItem>` -- [`ui::SettingRow`].
pub(crate) fn setting_row(
&self,
label: &'static str,
description: Option<&'static str>,
control: gpui::AnyElement,
) -> gpui::AnyElement {
ui::SettingRow::settings(&self.theme, label, description, control).into_any_element()
}
/// The grey explanation box under the two segmented controls:
/// `flex flex-col gap-1.5 px-3 py-2.5 rounded-lg bg-gray-3`.
pub(crate) fn note_box(&self) -> gpui::Div {
div()
.flex()
.flex_col()
.gap(px(6.))
.px(px(12.))
.py(px(10.))
.rounded(px(8.))
.bg(self.theme.settings_fill())
}
/// `<Toggle size="sm">` on the settings material -- [`ui::Toggle::settings`].
pub(crate) fn toggle(
&self,
id: impl Into<gpui::ElementId>,
label: impl Into<SharedString>,
checked: bool,
cx: &mut Context<Self>,
on_change: impl Fn(&mut Self, &mut Context<Self>) + 'static,
) -> ui::Toggle {
ui::Toggle::settings(&self.theme, id, checked)
.label(label)
.on_click(cx.listener(move |this, _, _window, cx| on_change(this, cx)))
}
/// `SelectSettingItem`'s button -- [`ui::Select::settings`], opening the
/// in-window stand-in for `Menu.popup()`.
pub(crate) fn select(
&self,
id: impl Into<gpui::ElementId>,
label: impl Into<SharedString>,
kind: MenuKind,
cx: &mut Context<Self>,
) -> ui::Select {
ui::Select::settings(&self.theme, id, label).on_click(cx.listener(
move |this, event: &gpui::ClickEvent, window, cx| {
this.open_menu(kind, event.position(), window, cx);
},
))
}
/// `SegmentedControl` over a [`SettingsEnum`].
fn segmented<T: SettingsEnum>(
&self,
id: &'static str,
current: T,
cx: &mut Context<Self>,
on_change: impl Fn(&mut Self, T, &mut Context<Self>) + Clone + 'static,
) -> ui::SegmentedControl {
self.segmented_raw(
id,
T::ALL
.iter()
.map(|value| ui::SegmentOption::new(value.label(), *value == current))
.collect(),
cx,
move |this, index, cx| {
if let Some(value) = ui::option_at(T::ALL, index) {
on_change(this, value, cx);
}
},
)
}
/// [`ui::SegmentedControl::settings`].
fn segmented_raw(
&self,
id: &'static str,
options: Vec<ui::SegmentOption>,
cx: &mut Context<Self>,
on_change: impl Fn(&mut Self, usize, &mut Context<Self>) + Clone + 'static,
) -> ui::SegmentedControl {
ui::SegmentedControl::settings(&self.theme, id, options).on_select(
cx.listener(move |this, index: &usize, _window, cx| on_change(this, *index, cx)),
)
}
/// `<Button size="sm">` under the settings material -- [`ui::Button::settings`].
pub(crate) fn button(
&self,
id: impl Into<gpui::ElementId>,
style: (ui::ButtonVariant, Option<&'static str>),
label: impl Into<SharedString>,
disabled: bool,
cx: &mut Context<Self>,
on_click: impl Fn(&mut Self, &mut Window, &mut Context<Self>) + 'static,
) -> ui::Button {
let (variant, icon) = style;
let mut button = ui::Button::settings(&self.theme, id, variant, ui::ButtonSize::Sm)
.label(label)
.disabled_settings(&self.theme, disabled);
if let Some(icon) = icon {
button = button.icon(icon);
}
button.on_click(cx.listener(move |this, _, window, cx| on_click(this, window, cx)))
}
/// The General page's two inputs -- [`ui::TextInput::settings`], `<Input>`'s
/// `h-8 rounded-lg bg-gray-2 px-2 text-xs` re-filled from the settings
/// material.
///
/// The drafts stay on this window because the *commit* is the Save /
/// Update button, exactly as it is in the Tauri card -- neither `<input>`
/// there binds `onKeyDown`, so Return does nothing in either app. What the
/// window still owns is what Escape means, which is "revert to what is
/// stored".
fn text_field(&self, field: Field, cx: &mut Context<Self>) -> gpui::Div {
let (id, input) = match field {
Field::ProjectName => ("project-name-input", &self.project_name_input),
Field::ServerUrl => ("server-url-input", &self.server_url_input),
// Drawn by the Recordings page itself, as a search field.
Field::RecordingsSearch => ("recordings-search", &self.recordings.search_input),
Field::ScreenshotsSearch => ("screenshots-search", &self.screenshots.search_input),
};
let _ = cx;
div().child(ui::TextInput::settings(&self.theme, id, input))
}
/// Both fields' events. The draft mirrors the field so the Save/Update
/// buttons' enablement keeps reading a plain `String`.
fn on_field_event(
&mut self,
field: Field,
input: Entity<ui::TextInputState>,
event: &ui::TextInputEvent,
cx: &mut Context<Self>,
) {
match event {
ui::TextInputEvent::Changed => {
let value = input.read(cx).text().to_string();
match field {
Field::ProjectName => self.project_name = value,
Field::ServerUrl => self.server_url = value,
Field::RecordingsSearch => {
self.recordings.search = value;
// `createEffect(() => { activeTab(); trimmedSearch();
// setVisibleCount(PAGE_SIZE) })`.
self.recordings.visible_count = RECORDINGS_PAGE_SIZE;
}
Field::ScreenshotsSearch => {
self.screenshots.search = value;
self.screenshots.visible_count = RECORDINGS_PAGE_SIZE;
}
}
cx.notify();
}
// `onKeyDown`: Escape clears the field, and *only* when there is
// something in it -- `if (event.key === "Escape" && search())`.
// With the field empty the key is not even preventDefault'd.
ui::TextInputEvent::Cancelled
if field == Field::RecordingsSearch && !self.recordings.search.is_empty() =>
{
self.recordings.search.clear();
self.recordings.visible_count = RECORDINGS_PAGE_SIZE;
input.update(cx, |input, cx| input.set_text("", cx));
cx.notify();
}
ui::TextInputEvent::Cancelled
if field == Field::ScreenshotsSearch && !self.screenshots.search.is_empty() =>
{
self.screenshots.search.clear();
self.screenshots.visible_count = RECORDINGS_PAGE_SIZE;
input.update(cx, |input, cx| input.set_text("", cx));
cx.notify();
}
ui::TextInputEvent::Cancelled => {
// Revert to what is stored, the way leaving the field without
// saving does.
let stored = match field {
Field::ProjectName => self
.settings
.default_project_name_template
.clone()
.unwrap_or_else(|| DEFAULT_PROJECT_NAME_TEMPLATE.to_string()),
Field::ServerUrl => self.settings.server_url.clone(),
// Taken by the guarded arm above; nothing is "stored" for
// the search field.
Field::RecordingsSearch | Field::ScreenshotsSearch => return,
};
match field {
Field::ProjectName => self.project_name = stored.clone(),
Field::ServerUrl => self.server_url = stored.clone(),
Field::RecordingsSearch | Field::ScreenshotsSearch => return,
}
input.update(cx, |input, cx| input.set_text(stored, cx));
cx.notify();
}
_ => {}
}
}
/// `<Slider minValue={1} maxValue={4.5} step={0.1}>`: a `h-[0.3rem]`
/// `bg-gray-4` track with a `bg-blue-9` fill and a `size-4` thumb.
fn render_zoom_slider(&self, value: f32, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
let fraction = ((value - ZOOM_MIN) / (ZOOM_MAX - ZOOM_MIN)).clamp(0., 1.);
ui::Slider::new("zoom-slider", fraction, self.slider_track.clone())
.flex()
.track(px(5.), theme.settings_fill())
.fill(Hsla::from(theme.blue_9))
.thumb(
px(16.),
if theme.is_dark() {
Hsla::from(theme.gray_12)
} else {
Hsla::from(theme.gray_1)
},
Some(theme.settings_border()),
)
// Transcribed, not corrected: the thumb sits half a pixel high of
// centre over the 5px track.
.thumb_top(px(-6.))
.on_drag_start(
cx.listener(|this, event: &gpui::MouseDownEvent, _window, cx| {
this.slider_dragging = true;
this.set_zoom_from(event.position, cx);
}),
)
}
/// While the button is held the whole window takes the mouse, so a drag
/// that leaves the 164px track keeps updating -- what `KSlider` gets from
/// pointer capture.
fn render_slider_drag_layer(&self, cx: &mut Context<Self>) -> Option<gpui::AnyElement> {
if !self.slider_dragging {
return None;
}
Some(
ui::Slider::drag_layer(
"zoom-slider-drag",
cx.listener(|this, event: &gpui::MouseMoveEvent, _window, cx| {
this.set_zoom_from(event.position, cx);
}),
cx.listener(|this, _, _window, cx| {
this.slider_dragging = false;
// `onChangeEnd` -- the store write happens once, at the
// end of the drag.
let value = this.settings.default_zoom_amount.unwrap_or(1.5);
this.write(
"defaultZoomAmount",
Value::from(f64::from(ui::snap_to_step(value, ZOOM_MIN, ZOOM_MAX, 0.1))),
cx,
);
}),
)
.into_any_element(),
)
}
fn set_zoom_from(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {
// `step={0.1}`
let Some(value) =
ui::slider_value_at(&self.slider_track, position, ZOOM_MIN, ZOOM_MAX, 0.1)
else {
return;
};
if self.settings.default_zoom_amount != Some(value) {
self.settings.default_zoom_amount = Some(value);
cx.notify();
}
}
// -- The stand-in for `Menu.popup()` -----------------------------------
fn render_menu(&self, cx: &mut Context<Self>) -> Option<gpui::AnyElement> {
let menu = self.menu.as_ref()?;
let kind = menu.kind;
let items = self.menu_items(kind);
Some(
ui::Menu::settings(&self.theme, "settings-menu", items, &menu.state)
.on_select(cx.listener(move |this, index: &usize, window, cx| {
this.choose(kind, *index, window, cx);
}))
.on_dismiss(cx.listener(|this, _, _window, cx| {
this.menu = None;
cx.notify();
}))
.into_any_element(),
)
}
}
/// `minValue={1} maxValue={4.5}` on the zoom slider.
const ZOOM_MIN: f32 = 1.;
const ZOOM_MAX: f32 = 4.5;
/// `new URL(v).origin` -- the Tauri handler normalises the typed URL to its
/// origin before storing it, and throws (leaving the setting alone) when it
/// does not parse.
fn origin_of(value: &str) -> Option<String> {
let url = reqwest::Url::parse(value.trim()).ok()?;
if !matches!(url.scheme(), "http" | "https") {
return None;
}
Some(url.origin().ascii_serialization())
}
/// The preview under the project-name template.
///
/// `commands.formatProjectName` is `recording::format_project_name`, which
/// also understands `{moment:<format>}` and custom `{date:...}` / `{time:...}`
/// formats through a moment-to-chrono translation. Only the six literal
/// placeholders the card documents are substituted here (README deviation);
/// anything else is left in the string, which is what an unknown placeholder
/// does there too.
fn format_project_name(template: &str) -> String {
// The card previews a Safari window recorded in Instant mode, at 09:41 on
// today's date -- `DefaultProjectNameCard`'s `datetime`.
let now = chrono::Local::now();
let date = now.format("%Y-%m-%d").to_string();
template
.replace("{recording_mode}", "Instant")
.replace("{mode}", "instant")
.replace("{target_kind}", "Window")
.replace("{target_name}", "Safari")
.replace("{date}", &date)
.replace("{time}", "09:41 AM")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn profile_request_identity_changes_when_same_user_signs_in_again() {
let path =
std::env::temp_dir().join(format!("cap-profile-session-{}", store::new_uuid_v4()));
store::set_test_tauri_store_path(Some(path.clone()));
assert!(store::set_auth(Some(serde_json::json!({
"user_id": "user-1",
"secret": { "api_key": "old-token" }
}))));
let old_request = signed_in_profile_session();
assert!(store::set_auth(Some(serde_json::json!({
"user_id": "user-1",
"secret": { "api_key": "new-token" }
}))));
let new_request = signed_in_profile_session();
assert_ne!(old_request, new_request);
assert!(store::set_store_setting(
GENERAL_SETTINGS,
"serverUrl",
Value::String("https://other.example.com".into()),
));
assert_ne!(new_request, signed_in_profile_session());
store::set_test_tauri_store_path(None);
std::fs::remove_file(path).unwrap();
}
/// The sidebar list and its routes, which `showWindow({ Settings: { page } })`
/// addresses by slug.
#[test]
fn every_page_round_trips_through_its_slug() {
assert_eq!(Page::ALL.len(), 13);
for page in Page::ALL {
assert_eq!(Page::from_slug(page.slug()), Some(*page));
}
assert_eq!(Page::Shortcuts.slug(), "hotkeys");
assert_eq!(Page::from_slug("nope"), None);
}
#[test]
fn server_url_is_normalised_to_its_origin() {
assert_eq!(
origin_of("https://cap.example.com/dashboard?x=1"),
Some("https://cap.example.com".to_string())
);
assert_eq!(
origin_of("http://localhost:3000"),
Some("http://localhost:3000".to_string())
);
// `new URL()` throws on these, and the handler never runs.
assert_eq!(origin_of("cap.so"), None);
assert_eq!(origin_of("ftp://cap.so"), None);
assert_eq!(origin_of(""), None);
}
#[test]
fn invalid_server_authorities_are_rejected_before_saving() {
for value in [
"https://cap.example.com:invalid",
"https://cap.example.com:65536",
"https://cap example.com",
"http://[::1",
"https://user@",
] {
assert_eq!(origin_of(value), None, "{value}");
}
}
#[test]
fn server_origins_are_normalised_for_api_requests() {
for (value, expected) in [
("https://cap.example.com/", "https://cap.example.com"),
(
"https://user:[email protected]/dashboard?x=1#top",
"https://cap.example.com",
),
(" HTTPS://CAP.EXAMPLE.COM:443/ ", "https://cap.example.com"),
("http://localhost:3000/path", "http://localhost:3000"),
("http://[::1]:3000/path", "http://[::1]:3000"),
] {
let origin = origin_of(value).expect(value);
assert_eq!(origin, expected);
assert!(reqwest::Url::parse(&format!("{origin}/api/desktop/feedback")).is_ok());
}
}
#[test]
fn account_name_matches_the_tauri_profile_fallbacks() {
let mut profile = UserProfile {
name: Some(" Taylor Example ".to_string()),
email: Some("[email protected]".to_string()),
image_url: None,
};
assert_eq!(account_name(false, Some(&profile)), "Click to sign in");
assert_eq!(account_name(true, None), "Signed in");
assert_eq!(account_name(true, Some(&profile)), "Taylor Example");
profile.name = Some(" ".to_string());
assert_eq!(account_name(true, Some(&profile)), "[email protected]");
profile.email = None;
assert_eq!(account_name(true, Some(&profile)), "Signed in");
}
#[test]
fn cached_profile_must_belong_to_the_signed_in_user() {
let cached = serde_json::json!({
"userId": "user-1",
"profile": {
"name": "Taylor",
"email": "[email protected]",
"imageUrl": "https://example.com/profile.png"
},
"updatedAt": 1
});
let cached = cached.as_object().expect("cached profile object");
assert_eq!(
cached_user_profile(Some("user-1"), cached).and_then(|profile| profile.name),
Some("Taylor".to_string())
);
assert!(cached_user_profile(Some("user-2"), cached).is_none());
assert!(cached_user_profile(None, cached).is_none());
}
#[test]
fn cached_profile_accepts_the_tauri_null_user_identity() {
let cached = serde_json::json!({
"userId": null,
"profile": {
"name": null,
"email": "[email protected]",
"imageUrl": null
},
"updatedAt": 1
});
let cached = cached.as_object().expect("cached profile object");
assert_eq!(
cached_user_profile(None, cached).and_then(|profile| profile.email),
Some("[email protected]".to_string())
);
assert!(cached_user_profile(Some("user-1"), cached).is_none());
}
/// `coversDefaultExclusion`: the Reset button's "is this default already
/// covered" test, which decides whether the amber warning shows.
#[test]
fn default_exclusions_are_covered_by_title() {
let default = WindowExclusion {
window_title: Some("Cap Camera".into()),
..Default::default()
};
assert!(covers_default_exclusion(&default, &default));
assert!(covers_default_exclusion(
&WindowExclusion {
owner_name: Some("Cap".into()),
window_title: Some("Cap Camera".into()),
..Default::default()
},
&default
));
assert!(!covers_default_exclusion(
&WindowExclusion {
window_title: Some("Cap Settings".into()),
..Default::default()
},
&default
));
}
// -- The Recordings page ------------------------------------------------
fn recording(name: &str, mode: RecordingMode) -> RecordingItem {
RecordingItem {
thumbnail_version: None,
path: std::path::PathBuf::from(format!("/tmp/{name}.cap")),
mode,
status: crate::library::RecordingStatus::Complete,
upload: None,
clip_count: 1,
pretty_name: name.to_string(),
sharing: None,
sort_time_millis: 0.,
thumbnail: None,
}
}
/// `filteredRecordings()`: the tab first, then a case-insensitive substring
/// of the *trimmed* query against `prettyName`.
#[test]
fn tabs_and_search_filter_the_list() {
let items = [
recording("Team standup", RecordingMode::Studio),
recording("Bug repro", RecordingMode::Instant),
recording("STANDUP notes", RecordingMode::Instant),
];
let matching = |tab, query: &str| {
items
.iter()
.filter(|item| matches_recording_filters(item, tab, &query.trim().to_lowercase()))
.map(|item| item.pretty_name.as_str())
.collect::<Vec<_>>()
};
assert_eq!(
matching(RecordingsTab::All, ""),
["Team standup", "Bug repro", "STANDUP notes"]
);
assert_eq!(matching(RecordingsTab::Studio, ""), ["Team standup"]);
assert_eq!(
matching(RecordingsTab::Instant, ""),
["Bug repro", "STANDUP notes"]
);
// Case-insensitive, and whitespace-only is no filter at all.
assert_eq!(
matching(RecordingsTab::All, "standup"),
["Team standup", "STANDUP notes"]
);
assert_eq!(
matching(RecordingsTab::All, " "),
["Team standup", "Bug repro", "STANDUP notes"]
);
// The two filters compose.
assert_eq!(
matching(RecordingsTab::Instant, " STAND "),
["STANDUP notes"]
);
assert!(matching(RecordingsTab::Studio, "repro").is_empty());
}
/// `visibleRecordings()` / `hasMoreRecordings()` / the Load more step.
#[test]
fn pagination_pages_by_twenty_and_a_search_shows_everything() {
assert_eq!(RECORDINGS_PAGE_SIZE, 20);
// No search: capped at the visible count, with more to load.
assert_eq!(visible_recordings_len(53, false, 20), 20);
assert!(has_more_recordings(53, false, 20));
assert_eq!(load_more_count(20, 53), 40);
assert_eq!(visible_recordings_len(53, false, 40), 40);
// The last page is short, and the button goes away with it.
assert_eq!(load_more_count(40, 53), 53);
assert_eq!(visible_recordings_len(53, false, 53), 53);
assert!(!has_more_recordings(53, false, 53));
// Fewer matches than a page.
assert_eq!(visible_recordings_len(7, false, 20), 7);
assert!(!has_more_recordings(7, false, 20));
// An active search is never paginated.
assert_eq!(visible_recordings_len(53, true, 20), 53);
assert!(!has_more_recordings(53, true, 20));
}
#[test]
fn visible_rows_follow_the_filter_and_the_page() {
let all = visible_rows([true; 53], false, 20);
assert_eq!(all.indices, (0..20).collect::<Vec<_>>());
assert_eq!(all.matching, 53);
let more = visible_rows([true; 53], false, load_more_count(20, 53));
assert_eq!(more.indices, (0..40).collect::<Vec<_>>());
let last = visible_rows([true; 53], false, load_more_count(40, 53));
assert_eq!(last.indices, (0..53).collect::<Vec<_>>());
// A tab or a search matches a subset, and the indices still address the
// unfiltered rows.
let every_third: Vec<bool> = (0..90).map(|index| index % 3 == 0).collect();
let paged = visible_rows(every_third.iter().copied(), false, 20);
assert_eq!(paged.indices, (0..60).step_by(3).collect::<Vec<_>>());
assert_eq!(paged.matching, 30);
let searched = visible_rows(every_third.iter().copied(), true, 20);
assert_eq!(searched.indices, (0..90).step_by(3).collect::<Vec<_>>());
assert_eq!(searched.matching, 30);
let none = visible_rows([false; 5], true, 20);
assert!(none.indices.is_empty());
assert_eq!(none.matching, 0);
}
fn recording_row(index: usize, decoded: bool) -> RecordingRow {
let mut item = recording(&format!("Recording {index}"), RecordingMode::Studio);
item.thumbnail = Some(item.path.join("screenshots/display.jpg"));
RecordingRow {
item,
thumbnail: None,
thumbnail_stale: !decoded,
}
}
#[test]
fn only_visible_rows_are_queued_for_a_thumbnail_decode() {
let rows: Vec<RecordingRow> = (0..500).map(|index| recording_row(index, false)).collect();
let every_row: Vec<usize> = (0..rows.len()).collect();
let before = pending_thumbnail_decodes(&rows, &every_row, RecordingRow::pending_thumbnail);
let visible = visible_rows(rows.iter().map(|_| true), false, RECORDINGS_PAGE_SIZE);
let after =
pending_thumbnail_decodes(&rows, &visible.indices, RecordingRow::pending_thumbnail);
println!(
"decode jobs for a 500-row scan: every row {}, visible rows {}",
before.len(),
after.len()
);
assert_eq!(before.len(), 500);
assert_eq!(
after,
(0..20)
.map(|index| (index, rows[index].item.thumbnail.clone().unwrap()))
.collect::<Vec<_>>()
);
let mut rows = rows;
for row in &mut rows[..20] {
row.thumbnail_stale = false;
}
let more = visible_rows(
rows.iter().map(|_| true),
false,
load_more_count(RECORDINGS_PAGE_SIZE, 500),
);
let next: Vec<usize> =
pending_thumbnail_decodes(&rows, &more.indices, RecordingRow::pending_thumbnail)
.into_iter()
.map(|(index, _)| index)
.collect();
assert_eq!(next, (20..40).collect::<Vec<_>>());
// A search reaches past the first page in its own order.
let query = "recording 49";
let searched = visible_rows(
rows.iter()
.map(|row| matches_recording_filters(&row.item, RecordingsTab::All, query)),
true,
RECORDINGS_PAGE_SIZE,
);
let found: Vec<usize> =
pending_thumbnail_decodes(&rows, &searched.indices, RecordingRow::pending_thumbnail)
.into_iter()
.map(|(index, _)| index)
.collect();
assert_eq!(found, [49].into_iter().chain(490..500).collect::<Vec<_>>());
rows[30].item.thumbnail = None;
assert!(
pending_thumbnail_decodes(&rows, &[30], RecordingRow::pending_thumbnail).is_empty()
);
}
/// `emptyMessage()`.
#[test]
fn the_empty_message_names_the_tab_and_the_search() {
assert_eq!(
recordings_empty_message(RecordingsTab::All, ""),
"No recordings"
);
assert_eq!(
recordings_empty_message(RecordingsTab::Studio, ""),
"No studio recordings"
);
assert_eq!(
recordings_empty_message(RecordingsTab::Instant, ""),
"No instant recordings"
);
assert_eq!(
recordings_empty_message(RecordingsTab::Instant, "demo"),
"No matching instant recordings"
);
assert_eq!(
recordings_empty_message(RecordingsTab::All, "demo"),
"No matching recordings"
);
}
/// The tab strip, and the ids `emptyMessage()` interpolates.
#[test]
fn the_three_tabs_are_all_instant_studio() {
let ids: Vec<&str> = RecordingsTab::ALL.iter().map(|tab| tab.id()).collect();
assert_eq!(ids, ["all", "instant", "studio"]);
let labels: Vec<&str> = RecordingsTab::ALL.iter().map(|tab| tab.label()).collect();
assert_eq!(labels, ["Show all", "Instant", "Studio"]);
assert_eq!(RecordingsTab::All.icon(), None, "Show all has no glyph");
assert_eq!(RecordingsTab::Studio.icon(), Some("icons/film-cut.svg"));
assert_eq!(RecordingsTab::Instant.icon(), Some("icons/instant.svg"));
}
#[test]
fn the_preview_substitutes_the_documented_placeholders() {
let preview = format_project_name(DEFAULT_PROJECT_NAME_TEMPLATE);
assert!(preview.starts_with("Safari (Window) "));
assert!(preview.ends_with(" 09:41 AM"));
// An unknown placeholder survives untouched.
assert_eq!(format_project_name("{nope}"), "{nope}");
}
}
#[cfg(test)]
mod recording_action_tests;