diff --git a/apps/maple-agent/app/locales/de/app.ftl b/apps/maple-agent/app/locales/de/app.ftl index 3d38f3e8b..bfc184720 100644 --- a/apps/maple-agent/app/locales/de/app.ftl +++ b/apps/maple-agent/app/locales/de/app.ftl @@ -17,7 +17,7 @@ settings-chat-appearance = Chatdarstellung settings-editing = Bearbeitung settings-voice = Sprachausgabe settings-appearance = Darstellung -settings-appearance-description = Systemdesign verwenden oder immer das dunkle bzw. helle Design nutzen. +settings-appearance-description = Mit Standard-Maple dem System folgen oder ein festes Design wählen. settings-chat-font = Chatschrift settings-text-size = Textgröße settings-text-size-description = Größe des Textes im Gespräch und Eingabefeld. Seitenleiste und Schaltflächen verwenden weiterhin Manrope. @@ -66,7 +66,7 @@ settings-filter-placeholder = Einstellungen filtern… settings-filter-empty = Keine passenden Bereiche. # Hidden filter terms per section: former page names and the controls that moved there. Comma-separated, matched as plain substrings. settings-keywords-general = Standardeinstellungen, Sprache, Benachrichtigungen, Vim, Stimme, Sprachausgabe, Agentenanweisungen, Systemanweisung -settings-keywords-appearance = Design, dunkel, hell, System, Bewegung, Schrift, Textgröße, Werkzeugdetails, Zusammenfassungen +settings-keywords-appearance = Design, dunkel, hell, System, Dracula, Americana, Neon-Dämmerung, Kirschblüte, Farbe, Bewegung, Schrift, Textgröße, Werkzeugdetails, Zusammenfassungen settings-keywords-shortcuts = Tastatur, Belegungen, Tastenkürzel settings-keywords-integrations = MCP, Server, Programmieragenten, Computerbedienung, benutzerdefinierter Server settings-keywords-tools = Web, Python, Terminal, Shell, Dateien, lesen, schreiben, bearbeiten, suchen @@ -97,9 +97,13 @@ settings-shortcuts-subtitle = Integrierte Tastenkürzel suchen und anpassen. settings-back = Zurück settings-title = Einstellungen settings-sections = Einstellungsbereiche -settings-theme-label-system = System -settings-theme-label-dark = Dunkel -settings-theme-label-light = Hell +settings-theme-label-system = Standard-Maple (System) +settings-theme-label-dark = Maple Dunkel +settings-theme-label-light = Maple Hell +settings-theme-label-dracula = Dracula +settings-theme-label-americana = Americana +settings-theme-label-neon-dusk = Neon-Dämmerung +settings-theme-label-cherry-blossom = Kirschblüte settings-font-label-system = System settings-font-label-manrope = Manrope settings-font-label-geist = Geist diff --git a/apps/maple-agent/app/locales/en/app.ftl b/apps/maple-agent/app/locales/en/app.ftl index 5cdced0e0..fd99d45e6 100644 --- a/apps/maple-agent/app/locales/en/app.ftl +++ b/apps/maple-agent/app/locales/en/app.ftl @@ -17,7 +17,7 @@ settings-chat-appearance = Chat appearance settings-editing = Editing settings-voice = Voice settings-appearance = Appearance -settings-appearance-description = Follow the system theme, or force dark or light. +settings-appearance-description = Follow the system with Standard Maple, or pick a fixed theme. settings-chat-font = Chat font settings-text-size = Text size settings-text-size-description = Size of conversation and composer text. Sidebar and buttons stay Manrope. @@ -66,7 +66,7 @@ settings-filter-placeholder = Filter settings… settings-filter-empty = No matching sections. # Hidden filter terms per section: former page names and the controls that moved there. Comma-separated, matched as plain substrings. settings-keywords-general = defaults, language, notifications, vim, voice, speech, agent instructions, system prompt -settings-keywords-appearance = theme, dark, light, system, motion, font, text size, tool details, summaries +settings-keywords-appearance = theme, dark, light, system, Dracula, Americana, Neon Dusk, Cherry Blossom, color, motion, font, text size, tool details, summaries settings-keywords-shortcuts = keyboard, bindings, hotkeys settings-keywords-integrations = mcp, servers, coding agents, computer use, custom server settings-keywords-tools = web, python, terminal, shell, files, read, write, edit, search @@ -97,9 +97,13 @@ settings-shortcuts-subtitle = Search and customize built-in keyboard bindings. settings-back = Back settings-title = Settings settings-sections = Settings sections -settings-theme-label-system = System -settings-theme-label-dark = Dark -settings-theme-label-light = Light +settings-theme-label-system = Standard Maple (System) +settings-theme-label-dark = Maple Dark +settings-theme-label-light = Maple Light +settings-theme-label-dracula = Dracula +settings-theme-label-americana = Americana +settings-theme-label-neon-dusk = Neon Dusk +settings-theme-label-cherry-blossom = Cherry Blossom settings-font-label-system = System settings-font-label-manrope = Manrope settings-font-label-geist = Geist diff --git a/apps/maple-agent/app/locales/es/app.ftl b/apps/maple-agent/app/locales/es/app.ftl index d1ed75bfe..38a97bf4e 100644 --- a/apps/maple-agent/app/locales/es/app.ftl +++ b/apps/maple-agent/app/locales/es/app.ftl @@ -18,7 +18,7 @@ settings-chat-appearance = Apariencia del chat settings-editing = Edición settings-voice = Voz settings-appearance = Apariencia -settings-appearance-description = Usa el tema del sistema o elige el modo oscuro o claro. +settings-appearance-description = Sigue al sistema con Maple estándar o elige un tema fijo. settings-chat-font = Fuente del chat settings-text-size = Tamaño del texto settings-text-size-description = Tamaño del texto de la conversación y del cuadro de mensaje. La barra lateral y los botones siguen usando Manrope. @@ -66,7 +66,7 @@ settings-filter-placeholder = Filtrar configuración… settings-filter-empty = No hay secciones que coincidan. # Términos ocultos de filtro por sección: nombres anteriores de las páginas y los controles que se movieron ahí. Separados por comas, se comparan como subcadenas. settings-keywords-general = valores predeterminados, idioma, notificaciones, vim, voz, lectura, instrucciones del agente, system prompt -settings-keywords-appearance = tema, oscuro, claro, sistema, movimiento, fuente, tamaño del texto, detalles de herramientas, resúmenes +settings-keywords-appearance = tema, oscuro, claro, sistema, Dracula, Americana, Crepúsculo neón, Flor de cerezo, color, movimiento, fuente, tamaño del texto, detalles de herramientas, resúmenes settings-keywords-shortcuts = teclado, atajos, combinaciones settings-keywords-integrations = mcp, servidores, agentes de código, uso de la computadora, servidor personalizado settings-keywords-tools = web, python, terminal, shell, archivos, leer, escribir, editar, buscar @@ -97,9 +97,13 @@ settings-shortcuts-subtitle = Busca y personaliza los atajos de teclado integrad settings-back = Volver settings-title = Configuración settings-sections = Secciones de configuración -settings-theme-label-system = Sistema -settings-theme-label-dark = Oscuro -settings-theme-label-light = Claro +settings-theme-label-system = Maple estándar (Sistema) +settings-theme-label-dark = Maple oscuro +settings-theme-label-light = Maple claro +settings-theme-label-dracula = Dracula +settings-theme-label-americana = Americana +settings-theme-label-neon-dusk = Crepúsculo neón +settings-theme-label-cherry-blossom = Flor de cerezo settings-font-label-system = Sistema settings-font-label-manrope = Manrope settings-font-label-geist = Geist diff --git a/apps/maple-agent/app/locales/ko/app.ftl b/apps/maple-agent/app/locales/ko/app.ftl index bffa581fe..89dcef2a8 100644 --- a/apps/maple-agent/app/locales/ko/app.ftl +++ b/apps/maple-agent/app/locales/ko/app.ftl @@ -17,7 +17,7 @@ settings-chat-appearance = 채팅 모양 settings-editing = 편집 settings-voice = 음성 settings-appearance = 모양 -settings-appearance-description = 시스템 테마를 따르거나 다크 또는 라이트로 고정해요. +settings-appearance-description = 표준 Maple로 시스템을 따르거나 고정 테마를 선택해요. settings-chat-font = 채팅 글꼴 settings-text-size = 텍스트 크기 settings-text-size-description = 대화와 메시지 입력창의 텍스트 크기예요. 사이드바와 버튼은 Manrope로 유지돼요. @@ -66,7 +66,7 @@ settings-filter-placeholder = 설정 필터… settings-filter-empty = 일치하는 섹션이 없어요. # Hidden filter terms per section: former page names and the controls that moved there. Comma-separated, matched as plain substrings. settings-keywords-general = 기본값, 언어, 알림, 음성, 읽기, 에이전트 지침, 시스템 프롬프트, defaults, language, notifications, vim, voice, speech, agent instructions, system prompt -settings-keywords-appearance = 테마, 다크, 라이트, 어두운, 밝은, 시스템, 동작, 글꼴, 폰트, 텍스트 크기, 도구 세부 정보, 요약, theme, dark, light, system, motion, font, text size, tool details, summaries +settings-keywords-appearance = 테마, 다크, 라이트, 어두운, 밝은, 시스템, Dracula, 아메리카나, 네온 황혼, 벚꽃, 색상, 동작, 글꼴, 폰트, 텍스트 크기, 도구 세부 정보, 요약, theme, dark, light, system, motion, font, text size, tool details, summaries settings-keywords-shortcuts = 키보드, 단축키, 키 바인딩, 핫키, keyboard, bindings, hotkeys settings-keywords-integrations = 서버, 코딩 에이전트, 컴퓨터 사용, 사용자 지정 서버, mcp, servers, coding agents, computer use, custom server settings-keywords-tools = 웹, 파이썬, 터미널, 셸, 파일, 읽기, 쓰기, 편집, 검색, web, python, terminal, shell, files, read, write, edit, search @@ -97,9 +97,13 @@ settings-shortcuts-subtitle = 기본 제공 키보드 단축키를 검색하고 settings-back = 뒤로 settings-title = 설정 settings-sections = 설정 섹션 -settings-theme-label-system = 시스템 -settings-theme-label-dark = 다크 -settings-theme-label-light = 라이트 +settings-theme-label-system = 표준 Maple (시스템) +settings-theme-label-dark = Maple 다크 +settings-theme-label-light = Maple 라이트 +settings-theme-label-dracula = Dracula +settings-theme-label-americana = 아메리카나 +settings-theme-label-neon-dusk = 네온 황혼 +settings-theme-label-cherry-blossom = 벚꽃 settings-font-label-system = 시스템 settings-font-label-manrope = Manrope settings-font-label-geist = Geist diff --git a/apps/maple-agent/app/src/desktop.rs b/apps/maple-agent/app/src/desktop.rs index 231586be2..03de917c0 100644 --- a/apps/maple-agent/app/src/desktop.rs +++ b/apps/maple-agent/app/src/desktop.rs @@ -822,7 +822,17 @@ impl MapleApp { self.password_settings_refresh_pending = true; return; } + let palette = ui::theme::preference(); self.clear_store_ui(cx); + if state == maple_agent::store::StoreState::Maintenance { + // Presentation only: Maintenance is transient (the host opening + // or converting the store), not a lock. Everything above is still + // cleared, but the chosen palette stays on screen until the store + // reopens or reaches a locked or damaged state, which draw in + // Standard Maple. Without this, a Maintenance event replayed at + // startup would flash Standard Maple over a returning user's theme. + ui::theme::apply_preference(palette, cx); + } self.set_store_resident(state == maple_agent::store::StoreState::Maintenance, cx); let gate = cx.new(|cx| ui::store_gate::StoreGate::new(self.backend.clone(), state, cx)); cx.subscribe( @@ -2371,10 +2381,9 @@ impl Render for MapleApp { self.recheck_plan_on_activation(cx); } remember_window_state(window, cx); - if ui::theme::resolve(window.appearance()) { - // Every view reads the palette in render; make them all redo it. - cx.refresh_windows(); - } + // Every view reads the palette in render; a palette change makes + // them all redo it. + ui::theme::sync_window(window, cx); let titlebar = self.titlebar.clone(); // The screen fades in when it changes kind; the first screen and a // screen that only re-renders draw at once. @@ -2991,6 +3000,9 @@ fn show_quit_prompt(kind: QuitPromptKind, cx: &mut App) { messages: Default::default(), }); let closing = prompt.downgrade(); + window + .observe_window_appearance(|window, cx| ui::theme::sync_window(window, cx)) + .detach(); window.on_window_should_close(cx, move |_, cx| { cancel_quit(cx); closing @@ -3213,6 +3225,8 @@ impl NativeDialog { impl Render for NativeDialog { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + // A native dialog can be the only window left open. + ui::theme::sync_window(window, cx); if self.closing { window.on_next_frame(|window, _| window.remove_window()); return div() @@ -3331,6 +3345,9 @@ fn show_native_dialog( }, |window, cx| { let dialog = NativeDialog::view(headline, body, buttons, Some(sender), window, cx); + window + .observe_window_appearance(|window, cx| ui::theme::sync_window(window, cx)) + .detach(); let closing = dialog.downgrade(); window.on_window_should_close(cx, move |_, cx| { // Closing answers nothing, as dismissing the OS alert did. @@ -3490,6 +3507,9 @@ impl QuitPrompt { } impl Render for QuitPrompt { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + // The prompt can outlive the main window (Quit from the tray), so it + // resolves the palette itself. + ui::theme::sync_window(window, cx); if self.closing { window.on_next_frame(|window, _| window.remove_window()); return div() @@ -4119,7 +4139,7 @@ impl Render for StartupError { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { // This window never renders MapleApp, which is where the palette // otherwise resolves; follow the OS appearance here, every frame. - ui::theme::resolve(window.appearance()); + ui::theme::sync_window(window, cx); // A status that replaces the failure adds its own sentence and a // details pane; the failure-only window is sized for neither. // Grow once, when the status first appears, and never again: the @@ -4681,259 +4701,439 @@ pub fn run() { (None, None) } }; - let root_enabled = remote_enabled.clone(); - let root_resident = store_resident.clone(); - let root_backend = backend.clone(); - let root_settings = startup_settings.clone(); - let root_updater = updater.clone(); - let window = cx - .open_window(main_window_options(window_placement), move |window, cx| { - show_frame_stats(window); - cx.new(move |cx| MapleApp { - backend: root_backend, - screen: Screen::Restoring, - user_id: None, - parked_chat: None, - local_chat: None, - selected_host: None, - remote_computers: Default::default(), - remote_inventory_loaded: false, - next_connection_attempt: 0, - requested_navigation: None, - computers_sync_pending: false, - remote_enabled: root_enabled, - store_resident: root_resident, - store_load_epoch: 0, - store_state_event: 0, - store_ready: false, - store_id: None, - store_notice: None, - store_notice_is_error: false, - seen_store_notice_operation: None, - inline_password_completion: None, - mode_change_notice: None, - inline_mode_notice: None, - password_settings_refresh_pending: false, - password_settings_refreshing: false, - persistence_status: maple_agent::store::PersistenceStatus::default(), - persistence_retrying: false, - #[cfg(feature = "proxy")] - local_api_revision: 0, - #[cfg(feature = "proxy")] - local_api_host_epoch: 0, - #[cfg(feature = "proxy")] - local_api_refreshing: false, - #[cfg(feature = "proxy")] - local_api_refresh_again: false, - pending_store_attention: Default::default(), - store_attention_open: false, - restore_window_geometry: true, - #[cfg(any(target_os = "linux", target_os = "windows"))] - tray, - remote_bridges: std::cell::RefCell::new(Vec::new()), - settings: root_settings, - updater: root_updater, - restart_prompt_pending: false, - shortcuts: shortcut_runtime, - titlebar: cx.new(|_| TitleBar::new(ui::titlebar::WINDOW_TITLE)), - plan_check: PlanCheck::default(), - native_locale: None, - native_messages: Default::default(), + // Present the main window once the saved theme is known, so a + // returning user's first frame uses it. The wait is bounded and + // skipped for a locked or recovering store; see `startup_theme`. + let preflight = startup_theme(backend.clone()); + let present = move |cx: &mut App| { + let root_enabled = remote_enabled.clone(); + let root_resident = store_resident.clone(); + let root_backend = backend.clone(); + let root_settings = startup_settings.clone(); + let root_updater = updater.clone(); + let window = cx + .open_window(main_window_options(window_placement), move |window, cx| { + show_frame_stats(window); + cx.new(move |cx| MapleApp { + backend: root_backend, + screen: Screen::Restoring, + user_id: None, + parked_chat: None, + local_chat: None, + selected_host: None, + remote_computers: Default::default(), + remote_inventory_loaded: false, + next_connection_attempt: 0, + requested_navigation: None, + computers_sync_pending: false, + remote_enabled: root_enabled, + store_resident: root_resident, + store_load_epoch: 0, + store_state_event: 0, + store_ready: false, + store_id: None, + store_notice: None, + store_notice_is_error: false, + seen_store_notice_operation: None, + inline_password_completion: None, + mode_change_notice: None, + inline_mode_notice: None, + password_settings_refresh_pending: false, + password_settings_refreshing: false, + persistence_status: maple_agent::store::PersistenceStatus::default(), + persistence_retrying: false, + #[cfg(feature = "proxy")] + local_api_revision: 0, + #[cfg(feature = "proxy")] + local_api_host_epoch: 0, + #[cfg(feature = "proxy")] + local_api_refreshing: false, + #[cfg(feature = "proxy")] + local_api_refresh_again: false, + pending_store_attention: Default::default(), + store_attention_open: false, + restore_window_geometry: true, + #[cfg(any(target_os = "linux", target_os = "windows"))] + tray, + remote_bridges: std::cell::RefCell::new(Vec::new()), + settings: root_settings, + updater: root_updater, + restart_prompt_pending: false, + shortcuts: shortcut_runtime, + titlebar: cx.new(|_| TitleBar::new(ui::titlebar::WINDOW_TITLE)), + plan_check: PlanCheck::default(), + native_locale: None, + native_messages: Default::default(), + }) }) - }) - .unwrap_or_else(|error| panic!("{}", main_window_failure(&error))); - log::debug!("startup: window open at {} ms", crate::startup_elapsed()); - window - .update(cx, |app: &mut MapleApp, _window, cx| { - app.show_store_state(backend.store_state(), cx); - }) - .ok(); - // Poll/checkpoint only after current-store settings bootstrap. - let root_window = window; - cx.spawn(async move |cx| { - while update_events.changed().await.is_ok() { - let snapshot = update_events.borrow_and_update().clone(); - if root_window - .update(cx, |app: &mut MapleApp, _, cx| app.set_update(snapshot, cx)) - .is_err() - { - break; + .unwrap_or_else(|error| panic!("{}", main_window_failure(&error))); + log::debug!("startup: window open at {} ms", crate::startup_elapsed()); + window + .update(cx, |app: &mut MapleApp, _window, cx| { + app.show_store_state(backend.store_state(), cx); + }) + .ok(); + // Poll/checkpoint only after current-store settings bootstrap. + let root_window = window; + cx.spawn(async move |cx| { + while update_events.changed().await.is_ok() { + let snapshot = update_events.borrow_and_update().clone(); + if root_window + .update(cx, |app: &mut MapleApp, _, cx| app.set_update(snapshot, cx)) + .is_err() + { + break; + } } - } - }) - .detach(); - let root = window - .update(cx, |app, window, cx| { - // The only window: closing it from the window manager - // ends the app the same way the title bar button does. - #[cfg(target_os = "macos")] - let can_background = { - let _ = app; - true - }; - #[cfg(any(target_os = "linux", target_os = "windows"))] - let can_background = app.tray.is_some(); - install_close_behavior(window, cx, remote_enabled.clone(), can_background); - // A system theme change must reach every view. - window - .observe_window_appearance(|_window, cx| cx.refresh_windows()) - .detach(); - cx.entity() }) - .expect("root entity"); + .detach(); + let root = window + .update(cx, |app, window, cx| { + // The only window: closing it from the window manager + // ends the app the same way the title bar button does. + #[cfg(target_os = "macos")] + let can_background = { + let _ = app; + true + }; + #[cfg(any(target_os = "linux", target_os = "windows"))] + let can_background = app.tray.is_some(); + install_close_behavior(window, cx, remote_enabled.clone(), can_background); + // A system theme change must reach every view. + window + .observe_window_appearance(|_window, cx| cx.refresh_windows()) + .detach(); + cx.entity() + }) + .expect("root entity"); + + if let Some(kind) = native_dialog_fixture() { + cx.spawn(async move |cx| { + cx.background_executor() + .timer(std::time::Duration::from_millis(600)) + .await; + cx.update(|cx| show_native_dialog_fixture(&kind, cx)); + }) + .detach(); + } - if let Some(kind) = native_dialog_fixture() { + // Local status is cheap and does not contact the enrollment + // service. This also notices changes made through the CLI. + let status_backend = backend.clone(); + let status_root = root.clone(); + let remote_updater = updater.clone(); + let update_bridge = remote_updates::Bridge::default(); cx.spawn(async move |cx| { - cx.background_executor() - .timer(std::time::Duration::from_millis(600)) - .await; - cx.update(|cx| show_native_dialog_fixture(&kind, cx)); + loop { + let (account, epoch, owner) = status_root.update(cx, |app, _| { + ( + app.user_id.clone(), + app.store_load_epoch, + app.local_chat.as_ref().map(Entity::entity_id), + ) + }); + let backend = status_backend.clone(); + let expected_account = account.clone(); + let bridge = update_bridge.clone(); + let check_updater = remote_updater.clone(); + let task = status_backend.spawn(async move { + tokio::join!( + backend.remote_setting::( + "remote_status", + () + ), + backend.local_control::("store_status", ()), + bridge.poll(backend.clone(), expected_account, check_updater), + ) + }); + if let Ok((remote, store, update_command)) = task.await { + status_root.update(cx, |app, cx| { + if let Ok(store) = store { + app.apply_store_completion_notice(&store, cx); + app.set_store_resident(store.keeps_resident(), cx); + if store.state == maple_agent::store::StoreState::Open + && app.password_settings_refresh_pending + && !app.password_settings_refreshing + { + app.refresh_password_settings(cx); + } + } + if let Some(command) = update_command { + app.begin_remote_install(command, cx); + } + let Ok(status) = remote else { return }; + if app.user_id == account + && account.is_some() + && app.store_load_epoch == epoch + && app.local_chat.as_ref().map(Entity::entity_id) == owner + && app.store_ready + && app.backend.store_state() + == maple_agent::store::StoreState::Open + { + if let Screen::Settings(settings) = &app.screen { + settings.update(cx, |settings, cx| { + settings.update_remote_status(status.clone(), cx) + }); + } + app.update_computers(status, cx); + } + }); + } + cx.background_executor() + .timer(std::time::Duration::from_secs(5)) + .await; + } }) .detach(); - } - - // Local status is cheap and does not contact the enrollment - // service. This also notices changes made through the CLI. - let status_backend = backend.clone(); - let status_root = root.clone(); - let remote_updater = updater.clone(); - let update_bridge = remote_updates::Bridge::default(); - cx.spawn(async move |cx| { - loop { - let (account, epoch, owner) = status_root.update(cx, |app, _| { - ( - app.user_id.clone(), - app.store_load_epoch, - app.local_chat.as_ref().map(Entity::entity_id), - ) - }); - let backend = status_backend.clone(); - let expected_account = account.clone(); - let bridge = update_bridge.clone(); - let check_updater = remote_updater.clone(); - let task = status_backend.spawn(async move { - tokio::join!( - backend.remote_setting::( - "remote_status", - () - ), - backend.local_control::("store_status", ()), - bridge.poll(backend.clone(), expected_account, check_updater), - ) - }); - if let Ok((remote, store, update_command)) = task.await { - status_root.update(cx, |app, cx| { - if let Ok(store) = store { - app.apply_store_completion_notice(&store, cx); - app.set_store_resident(store.keeps_resident(), cx); - if store.state == maple_agent::store::StoreState::Open - && app.password_settings_refresh_pending - && !app.password_settings_refreshing - { - app.refresh_password_settings(cx); + #[cfg(any(target_os = "linux", target_os = "windows"))] + if let Some(mut events) = tray_events { + let tray_root = root.clone(); + let enabled = remote_enabled.clone(); + cx.spawn(async move |cx| { + while let Some(action) = events.recv().await { + match action { + crate::tray::Action::Quit => { + cx.update(quit_app); } - } - if let Some(command) = update_command { - app.begin_remote_install(command, cx); - } - let Ok(status) = remote else { return }; - if app.user_id == account - && account.is_some() - && app.store_load_epoch == epoch - && app.local_chat.as_ref().map(Entity::entity_id) == owner - && app.store_ready - && app.backend.store_state() == maple_agent::store::StoreState::Open - { - if let Screen::Settings(settings) = &app.screen { - settings.update(cx, |settings, cx| { - settings.update_remote_status(status.clone(), cx) + crate::tray::Action::CheckForUpdates => { + cx.update(|cx| { + dispatch_update_action( + crate::update::UpdateAction::Check, + cx, + ) + }); + } + crate::tray::Action::Open => { + cx.update(|cx| { + if cx.windows().is_empty() { + let root = tray_root.clone(); + let enabled = enabled.clone(); + let placement = main_window_placement( + crate::settings::load_settings().window, + cx, + ); + let _ = cx.open_window( + main_window_options(placement), + move |window, cx| { + install_close_behavior( + window, cx, enabled, true, + ); + root + }, + ); + } else { + for window in cx.windows() { + let _ = window.update(cx, |_, window, _| { + window.activate_window() + }); + } + } }); } - app.update_computers(status, cx); } - }); - } - cx.background_executor() - .timer(std::time::Duration::from_secs(5)) - .await; + } + }) + .detach(); } - }) - .detach(); - #[cfg(any(target_os = "linux", target_os = "windows"))] - if let Some(mut events) = tray_events { - let tray_root = root.clone(); - let enabled = remote_enabled.clone(); + + // The event pump runs once for the whole process and routes events to + // whichever screen is active. It exits when the root entity is gone. + let (spawn_backend, take_backend) = (backend.clone(), backend.clone()); + let rx = spawn_backend.spawn(async move { take_backend.take_events().await }); cx.spawn(async move |cx| { - while let Some(action) = events.recv().await { - match action { - crate::tray::Action::Quit => { - cx.update(quit_app); - } - crate::tray::Action::CheckForUpdates => { - cx.update(|cx| { - dispatch_update_action(crate::update::UpdateAction::Check, cx) - }); - } - crate::tray::Action::Open => { - cx.update(|cx| { - if cx.windows().is_empty() { - let root = tray_root.clone(); - let enabled = enabled.clone(); - let placement = main_window_placement( - crate::settings::load_settings().window, - cx, - ); - let _ = cx.open_window( - main_window_options(placement), - move |window, cx| { - install_close_behavior(window, cx, enabled, true); - root - }, - ); - } else { - for window in cx.windows() { - let _ = window.update(cx, |_, window, _| { - window.activate_window() - }); - } - } - }); + let Some(mut rx) = rx.await.ok().flatten() else { + return; + }; + while let Some(event) = rx.recv().await { + // Drain whatever else is queued so a burst of streaming + // chunks costs one update and one render, not one each. + let mut batch = vec![event]; + while let Ok(next) = rx.try_recv() { + batch.push(next); + if batch.len() >= 256 { + break; } } + // This gpui's entity update is infallible; the pump ends + // with the channel instead. + root.update(cx, |app, cx| app.handle_service_events(batch, cx)); } }) .detach(); - } - // The event pump runs once for the whole process and routes events to - // whichever screen is active. It exits when the root entity is gone. - let (spawn_backend, take_backend) = (backend.clone(), backend.clone()); - let rx = spawn_backend.spawn(async move { take_backend.take_events().await }); + cx.activate(true); + }; cx.spawn(async move |cx| { - let Some(mut rx) = rx.await.ok().flatten() else { - return; - }; - while let Some(event) = rx.recv().await { - // Drain whatever else is queued so a burst of streaming - // chunks costs one update and one render, not one each. - let mut batch = vec![event]; - while let Ok(next) = rx.try_recv() { - batch.push(next); - if batch.len() >= 256 { - break; - } + let theme = preflight.await.ok().flatten(); + cx.update(|cx| { + log::debug!( + "startup: saved theme {} at {} ms", + if theme.is_some() { + "applied" + } else { + "not available" + }, + crate::startup_elapsed() + ); + if let Some(theme) = theme { + ui::theme::apply_preference(ui::theme::Preference::parse(&theme), cx); } - // This gpui's entity update is infallible; the pump ends - // with the channel instead. - root.update(cx, |app, cx| app.handle_service_events(batch, cx)); - } + present(cx); + }); }) .detach(); - - cx.activate(true); }); } +/// How long the main window waits for the saved theme before it opens +/// with Standard Maple anyway. A warm or cold plain store answers well +/// inside it; a slow host shows its usual restoring screen afterwards. +const STARTUP_THEME_DEADLINE: std::time::Duration = std::time::Duration::from_millis(400); + +/// The saved theme ID for the first frame, read through the same bounded +/// host requests as the settings bootstrap: the store's status and, only +/// when the store is Open, its UI settings snapshot. A locked or recovering +/// store returns `None` without reading settings, so its gate shows at once +/// in Standard Maple; an error or the deadline also returns `None`. Nothing +/// is written or cached outside the store. +fn startup_theme(backend: Arc) -> tokio::task::JoinHandle> { + let status_backend = backend.clone(); + let settings_backend = backend.clone(); + backend.spawn(async move { + saved_theme_within( + STARTUP_THEME_DEADLINE, + async move { + status_backend + .local_control::("store_status", ()) + .await + }, + || async move { + settings_backend + .get_ui_settings() + .await + .map(|settings| settings.theme) + }, + ) + .await + }) +} + +async fn saved_theme_within( + deadline: std::time::Duration, + status: S, + settings: F, +) -> Option +where + S: std::future::Future>, + F: FnOnce() -> T, + T: std::future::Future>, +{ + tokio::time::timeout(deadline, async { + let status = status.await.ok()?; + if status.state != maple_agent::store::StoreState::Open { + return None; + } + settings().await.ok() + }) + .await + .ok() + .flatten() +} + +#[cfg(test)] +mod startup_theme_tests { + use super::*; + use maple_agent::store::StoreState; + use std::time::Duration; + + fn status(state: StoreState) -> Result { + let mut status: DesktopStoreStatus = serde_json::from_value(serde_json::json!({ + "state": {"state": "open"}, + "mode": "plain", + "setup_operation_id": null, + "store_id": "store", + })) + .expect("status fixture"); + status.state = state; + Ok(status) + } + + #[tokio::test] + async fn an_open_store_supplies_its_saved_theme() { + let theme = saved_theme_within( + STARTUP_THEME_DEADLINE, + async { status(StoreState::Open) }, + || async { Ok("dracula".to_string()) }, + ) + .await; + assert_eq!(theme.as_deref(), Some("dracula")); + } + + #[tokio::test] + async fn a_store_that_is_not_open_is_never_read() { + for state in [ + StoreState::Locked, + StoreState::NeedsSetup, + StoreState::Maintenance, + ] { + let theme = saved_theme_within( + STARTUP_THEME_DEADLINE, + async { status(state.clone()) }, + || async { panic!("settings read before unlock") }, + ) + .await; + assert_eq!(theme, None, "{state:?}"); + } + } + + #[tokio::test] + async fn host_errors_fall_back_to_standard_maple() { + let theme = saved_theme_within( + STARTUP_THEME_DEADLINE, + async { Err("host unavailable".to_string()) }, + || async { Ok("dracula".to_string()) }, + ) + .await; + assert_eq!(theme, None); + let theme = saved_theme_within( + STARTUP_THEME_DEADLINE, + async { status(StoreState::Open) }, + || async { Err("Could not read UI settings".to_string()) }, + ) + .await; + assert_eq!(theme, None); + } + + /// A slow host never holds the window: the deadline opens it with + /// Standard Maple, whichever request is slow. + #[tokio::test(start_paused = true)] + async fn a_slow_host_is_bounded_by_the_deadline() { + let slow_status = saved_theme_within( + STARTUP_THEME_DEADLINE, + async { + tokio::time::sleep(Duration::from_secs(30)).await; + status(StoreState::Open) + }, + || async { Ok("dracula".to_string()) }, + ); + let started = tokio::time::Instant::now(); + assert_eq!(slow_status.await, None); + assert_eq!(started.elapsed(), STARTUP_THEME_DEADLINE); + + let slow_settings = saved_theme_within( + STARTUP_THEME_DEADLINE, + async { status(StoreState::Open) }, + || async { + tokio::time::sleep(Duration::from_secs(30)).await; + Ok("dracula".to_string()) + }, + ); + let started = tokio::time::Instant::now(); + assert_eq!(slow_settings.await, None); + assert_eq!(started.elapsed(), STARTUP_THEME_DEADLINE); + } +} + #[cfg(test)] mod maintenance_tests; #[cfg(test)] @@ -6629,6 +6829,26 @@ mod tests { cx.run_until_parked(); } + #[gpui::test] + fn maintenance_keeps_the_chosen_palette_and_a_lock_resets_it(cx: &mut gpui::TestAppContext) { + let settings = crate::settings::SETTINGS_IO_LOCK.lock(); + let _theme = ui::theme::TestThemeGuard::acquire(); + let app = project_shell_locked(cx, &settings); + cx.update(|cx| ui::theme::apply_preference(ui::theme::Preference::Dracula, cx)); + app.update(cx, |app, cx| { + let epoch = app.store_load_epoch; + app.show_store_state(maple_agent::store::StoreState::Maintenance, cx); + // Store handling is unchanged: the open store's UI is cleared. + assert!(app.store_load_epoch > epoch); + assert!(matches!(app.screen, Screen::StoreGate(_))); + assert!(app.user_id.is_none()); + assert_eq!(ui::theme::preference(), ui::theme::Preference::Dracula); + app.show_store_state(maple_agent::store::StoreState::Locked, cx); + assert_eq!(ui::theme::preference(), ui::theme::Preference::System); + }); + cx.run_until_parked(); + } + #[gpui::test] fn maintenance_after_form_completion_waits_for_authoritative_status( cx: &mut gpui::TestAppContext, diff --git a/apps/maple-agent/app/src/platform/portal.rs b/apps/maple-agent/app/src/platform/portal.rs index f3cb80a45..9968148b4 100644 --- a/apps/maple-agent/app/src/platform/portal.rs +++ b/apps/maple-agent/app/src/platform/portal.rs @@ -179,9 +179,9 @@ pub(crate) fn start(backend: &crate::backend::AgentBackend, cx: &mut gpui::App) if let Some(scheme) = scheme { cx.update(|cx| { crate::ui::theme::set_system_appearance(scheme.appearance()); - if crate::ui::theme::preference() == crate::ui::theme::Preference::System { - cx.refresh_windows(); - } + // Resolve at app level: the main window may be closed to + // the tray with only a dialog left to repaint. + crate::ui::theme::sync(cx); }); } } diff --git a/apps/maple-agent/app/src/settings.rs b/apps/maple-agent/app/src/settings.rs index b8a99964c..d52f24391 100644 --- a/apps/maple-agent/app/src/settings.rs +++ b/apps/maple-agent/app/src/settings.rs @@ -141,7 +141,9 @@ pub struct AppSettings { /// UI language override; None follows the operating system. #[serde(default, deserialize_with = "view_preference_or_default")] pub locale: Option, - /// Color theme: "system", "dark", or "light". + /// Color theme ID, parsed by `ui::theme::Preference`: "system", "light", + /// "dark", "dracula", "americana", "neon-dusk" or "cherry-blossom". + /// An unknown ID draws as "system" and is kept until the user picks again. #[serde(default = "default_theme")] pub theme: String, /// Chat reading face: "system", "manrope", "geist", or "serif". diff --git a/apps/maple-agent/app/src/ui/chat/composer.rs b/apps/maple-agent/app/src/ui/chat/composer.rs index 33c1304e7..74710e0c7 100644 --- a/apps/maple-agent/app/src/ui/chat/composer.rs +++ b/apps/maple-agent/app/src/ui/chat/composer.rs @@ -540,7 +540,7 @@ impl ChatScreen { .child(if transcribing { spinner("transcribing", px(16.), theme::text_secondary()) } else if recording { - icon("square", px(14.), theme::on_accent()).into_any_element() + icon("square", px(14.), theme::on_error()).into_any_element() } else { icon("mic", px(16.), theme::text_secondary()).into_any_element() }), @@ -840,7 +840,7 @@ impl ChatScreen { cx.emit(OpenSettingsSection(Section::Integrations)); }, ) - .style(|row| row.text_color(gpui::rgb(theme::accent()))), + .style(|row| row.text_color(gpui::rgb(theme::accent_text()))), ) } @@ -889,7 +889,7 @@ impl ChatScreen { .child( div() .font_family(crate::assets::FONT_MONO) - .text_color(gpui::rgb(theme::accent())) + .text_color(gpui::rgb(theme::accent_text())) .child(format!("/{}", entry.name)), ) .child( diff --git a/apps/maple-agent/app/src/ui/chat/mod.rs b/apps/maple-agent/app/src/ui/chat/mod.rs index 565fa2bdd..2f65bbe67 100644 --- a/apps/maple-agent/app/src/ui/chat/mod.rs +++ b/apps/maple-agent/app/src/ui/chat/mod.rs @@ -7784,7 +7784,7 @@ impl Render for ChatScreen { "x", tr("chat-close"), px(16.), - theme::on_accent(), + theme::on_scrim(), ) .debug_selector(|| "lightbox-close".to_string()) .size_8() diff --git a/apps/maple-agent/app/src/ui/chat/transcript.rs b/apps/maple-agent/app/src/ui/chat/transcript.rs index 0b195e64a..01d9abb79 100644 --- a/apps/maple-agent/app/src/ui/chat/transcript.rs +++ b/apps/maple-agent/app/src/ui/chat/transcript.rs @@ -1648,7 +1648,7 @@ pub(super) fn render_plan_row(entry: &PlanEntry) -> Div { PlanStatus::Completed => checkbox .border_color(gpui::rgb(theme::status_success())) .bg(gpui::rgb(theme::status_success())) - .child(icon("check", px(11.), theme::on_accent())), + .child(icon("check", px(11.), theme::on_success())), PlanStatus::InProgress => checkbox .border_color(gpui::rgb(theme::status_running())) .child( diff --git a/apps/maple-agent/app/src/ui/effort_slider.rs b/apps/maple-agent/app/src/ui/effort_slider.rs index 347ef8062..ad40bc0ce 100644 --- a/apps/maple-agent/app/src/ui/effort_slider.rs +++ b/apps/maple-agent/app/src/ui/effort_slider.rs @@ -926,7 +926,7 @@ impl Element for EffortSlider { thumb, round, gpui::rgb(if self.enabled { - theme::on_accent() + theme::slider_thumb() } else { theme::text_muted() }), diff --git a/apps/maple-agent/app/src/ui/login.rs b/apps/maple-agent/app/src/ui/login.rs index 9308225e6..4f16cea0b 100644 --- a/apps/maple-agent/app/src/ui/login.rs +++ b/apps/maple-agent/app/src/ui/login.rs @@ -57,8 +57,18 @@ pub struct LoginScreen { deletion_notice: Option, busy: bool, messages: MessageCache, + /// Records the painted fill and label color of the form's submit. + #[cfg(test)] + submit_paint: Option, } +/// Where a test reads a control's painted background and text color. +#[cfg(test)] +type PaintProbe = ( + std::rc::Rc>, + std::rc::Rc>>, +); + impl LoginScreen { pub fn new(backend: Arc, cx: &mut Context) -> Self { let email = cx.new(|cx| TextInput::localized("flows-login-email", cx).with_tab_index(0)); @@ -110,6 +120,8 @@ impl LoginScreen { deletion_notice: None, busy: false, messages: Default::default(), + #[cfg(test)] + submit_paint: None, }; this.subscriptions.push(cx.subscribe( &this.password_input, @@ -392,6 +404,19 @@ impl Drop for LoginScreen { impl EventEmitter for LoginScreen {} +impl LoginScreen { + fn probe( + &self, + button: crate::ui::motion::HoverBackground, + ) -> crate::ui::motion::HoverBackground { + #[cfg(test)] + if let Some((fill, text)) = &self.submit_paint { + return button.observe_paint(fill.clone(), text.clone()); + } + button + } +} + impl Render for LoginScreen { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let busy = self.busy; @@ -407,7 +432,7 @@ impl Render for LoginScreen { .border_color(gpui::rgb(theme::border())) .when( busy && !matches!(self.oauth, OAuthFlow::Hosted { .. }), - |container| container.opacity(0.7), + |container| container.opacity(theme::BUSY_FORM_OPACITY), ) .tab_group() .child( @@ -454,7 +479,7 @@ impl Render for LoginScreen { &tr("flows-login-password"), self.password_input.clone(), )) - .child(submit_button(busy, cx)) + .child(self.probe(submit_button(busy, cx))) .child( widgets::ghost_button("guest-cancel") .debug_selector(|| "guest-cancel".to_string()) @@ -474,7 +499,7 @@ impl Render for LoginScreen { &tr("flows-login-password"), self.password_input.clone(), )) - .child(submit_button(busy, cx)) + .child(self.probe(submit_button(busy, cx))) .child( div() .flex() @@ -546,10 +571,10 @@ impl Render for LoginScreen { ) .child(field("", self.callback_input.clone())) .child( - widgets::primary_button("oauth-confirm") + self.probe(widgets::primary_button("oauth-confirm")) .debug_selector(|| "oauth-confirm".to_string()) .w_full() - .when(busy, |el| el.bg(gpui::rgb(theme::bg_sidebar_pill()))) + .when(busy, busy_submit) .when(!busy, |el| { el.on_click(cx.listener(|this, _event, _window, cx| { let redirected = this.callback_input.read(cx).text(); @@ -628,9 +653,10 @@ impl Render for LoginScreen { fn submit_button(busy: bool, cx: &mut Context) -> crate::ui::motion::HoverBackground { widgets::primary_button("login-submit") + .debug_selector(|| "login-submit".to_string()) .w_full() .mt_1() - .when(busy, |el| el.bg(gpui::rgb(theme::bg_sidebar_pill()))) + .when(busy, busy_submit) .when(!busy, |el| { el.on_click(cx.listener(LoginScreen::submit_clicked)) }) @@ -641,6 +667,19 @@ fn submit_button(busy: bool, cx: &mut Context) -> crate::ui::motion })) } +/// The busy look of a sign-in form's submit (password, guest and OAuth +/// paste): a neutral pill that keeps its fill under the pointer and while +/// pressed, with a label that reads at 4.5:1 inside the faded form. Replaces +/// the accent fill and its `on_accent` label, which is dark in some themes. +fn busy_submit(button: crate::ui::motion::HoverBackground) -> crate::ui::motion::HoverBackground { + let fill = gpui::rgb(theme::busy_button_fill()); + button + .bg(fill) + .highlighted(false) + .active(move |style| style.bg(fill)) + .text_color(gpui::rgb(theme::busy_button_text())) +} + fn deletion_status_text(status: crate::backend::AccountDeletionStatus) -> UiText { match status.label.as_deref() { Some("deletion-pending") => UiText::key("runtime-error-deletion-pending"), @@ -788,6 +827,98 @@ mod tests { } } + /// While a sign-in runs, the password, guest and OAuth-paste forms draw + /// their submit as the shared neutral busy pill with a body-text label, + /// at rest, under the pointer and while pressed. With the accent's + /// foreground (dark in Dracula and Neon Dusk) it was unreadable. + #[gpui::test] + fn busy_submit_is_a_readable_neutral_pill_in_every_form(cx: &mut TestAppContext) { + use gpui::{Modifiers, MouseButton}; + let _theme = crate::ui::theme::TestThemeGuard::acquire(); + cx.executor().allow_parking(); + let backend = + Arc::new(AgentBackend::for_test("http://127.0.0.1:9".into(), String::new()).unwrap()); + let fill = Rc::new(RefCell::new(gpui::Fill::default())); + let label = Rc::new(std::cell::Cell::new(None)); + let screen = cx.new(|cx| { + crate::desktop::register_key_bindings(cx); + let mut screen = LoginScreen::new(backend, cx); + screen.submit_paint = Some((fill.clone(), label.clone())); + screen + }); + let (_host, cx) = cx.add_window_view(|_window, _cx| LoginHost { + screen: screen.clone(), + }); + cx.simulate_resize(size(px(900.), px(700.))); + for preference in [ + theme::Preference::Dracula, + theme::Preference::NeonDusk, + theme::Preference::CherryBlossom, + ] { + cx.update(|_window, app| theme::apply_preference(preference, app)); + for (form, selector) in [ + ("password", "login-submit"), + ("guest", "login-submit"), + ("oauth paste", "oauth-confirm"), + ] { + screen.update(cx, |screen, cx| { + screen.busy = false; + screen.set_guest(form == "guest", cx); + screen.oauth = if form == "oauth paste" { + OAuthFlow::Pending { + provider: OAuthProvider::Google, + auth_url: "https://example.test/authorize".to_string(), + } + } else { + OAuthFlow::Idle + }; + screen.busy = true; + cx.notify(); + }); + cx.run_until_parked(); + let expected_fill = gpui::Fill::from(gpui::rgb(theme::busy_button_fill())); + let expected_label: Option = + Some(gpui::rgb(theme::busy_button_text()).into()); + let bounds = cx + .debug_bounds(selector) + .unwrap_or_else(|| panic!("{form}: busy submit renders")); + cx.simulate_mouse_move(bounds.center(), None, Modifiers::default()); + assert_eq!( + *fill.borrow(), + expected_fill, + "{preference:?} {form}: hovered" + ); + assert_eq!(label.get(), expected_label, "{preference:?} {form}: label"); + cx.simulate_mouse_down(bounds.center(), MouseButton::Left, Modifiers::default()); + assert_eq!( + *fill.borrow(), + expected_fill, + "{preference:?} {form}: pressed" + ); + cx.simulate_mouse_up(bounds.center(), MouseButton::Left, Modifiers::default()); + cx.simulate_mouse_move(gpui::point(px(5.), px(5.)), None, Modifiers::default()); + assert_eq!( + *fill.borrow(), + expected_fill, + "{preference:?} {form}: at rest" + ); + screen.update(cx, |screen, _| assert!(screen.busy, "{form}: still busy")); + } + } + // The probe follows the real button: an idle form paints the accent. + screen.update(cx, |screen, cx| { + screen.busy = false; + screen.set_guest(false, cx); + screen.oauth = OAuthFlow::Idle; + cx.notify(); + }); + cx.run_until_parked(); + assert_eq!( + *fill.borrow(), + gpui::Fill::from(gpui::rgb(theme::accent_fill())) + ); + } + #[gpui::test] fn account_password_moves_exact_bytes_only_after_submission_is_admitted( cx: &mut TestAppContext, diff --git a/apps/maple-agent/app/src/ui/markdown.rs b/apps/maple-agent/app/src/ui/markdown.rs index 37eae484c..14c2bc6ea 100644 --- a/apps/maple-agent/app/src/ui/markdown.rs +++ b/apps/maple-agent/app/src/ui/markdown.rs @@ -1077,24 +1077,9 @@ mod tests { assert_ne!(highlight.font_weight, Some(gpui::FontWeight::BOLD)); } - /// Serializes tests that flip the process-global theme, and pairs with - /// `ThemeRestore` so the flip never leaks into a test that reads the - /// palette while this one runs or after it panics. - static THEME_LOCK: parking_lot::Mutex<()> = parking_lot::Mutex::new(()); - - /// Restores the theme when the test ends, panics included. - struct ThemeRestore; - impl Drop for ThemeRestore { - fn drop(&mut self) { - theme::set_preference(theme::Preference::System); - theme::resolve(gpui::WindowAppearance::Dark); - } - } - #[test] fn code_span_color_follows_theme_switch() { - let _guard = THEME_LOCK.lock(); - let _restore = ThemeRestore; + let _theme = theme::TestThemeGuard::acquire(); // A document parsed under one palette must re-resolve its inline // colors under the other: parse caches blocks across theme flips. let document = parse("token at `~/.mutiny/token` end"); diff --git a/apps/maple-agent/app/src/ui/motion.rs b/apps/maple-agent/app/src/ui/motion.rs index a0288b0f9..ea305efa2 100644 --- a/apps/maple-agent/app/src/ui/motion.rs +++ b/apps/maple-agent/app/src/ui/motion.rs @@ -1133,6 +1133,8 @@ fn hover_background( observed: None, #[cfg(test)] observed_opacity: None, + #[cfg(test)] + observed_text: None, } } @@ -1147,6 +1149,8 @@ pub struct HoverBackground { observed: Option>>, #[cfg(test)] observed_opacity: Option>>, + #[cfg(test)] + observed_text: Option>>>, } impl HoverBackground { @@ -1177,6 +1181,19 @@ impl HoverBackground { self.instant = instant; self } + + /// Record the background and text color this control paints, for + /// tests that check a screen's real rendering. + #[cfg(test)] + pub(crate) fn observe_paint( + mut self, + background: std::rc::Rc>, + text: std::rc::Rc>>, + ) -> Self { + self.observed = Some(background); + self.observed_text = Some(text); + self + } } impl Styled for HoverBackground { @@ -1324,6 +1341,17 @@ impl Element for HoverBackground { .unwrap_or_default(); } #[cfg(test)] + if let Some(observed) = &self.observed_text { + use gpui::InteractiveElement; + observed.set( + self.element + .interactivity() + .compute_style(id, hitbox.as_ref(), window, cx) + .text + .color, + ); + } + #[cfg(test)] if let Some(observed) = &self.observed_opacity { use gpui::InteractiveElement; observed.set( diff --git a/apps/maple-agent/app/src/ui/remote.rs b/apps/maple-agent/app/src/ui/remote.rs index 2fbad44ed..b038e4a95 100644 --- a/apps/maple-agent/app/src/ui/remote.rs +++ b/apps/maple-agent/app/src/ui/remote.rs @@ -128,7 +128,8 @@ impl Tone { fn color(self) -> u32 { match self { Self::Muted => theme::text_muted(), - Self::Accent => theme::accent(), + // Badge and note text, so the text role of the accent. + Self::Accent => theme::accent_text(), Self::Success => theme::status_success(), Self::Warning => theme::status_warning(), Self::Error => theme::status_error(), diff --git a/apps/maple-agent/app/src/ui/rich_text.rs b/apps/maple-agent/app/src/ui/rich_text.rs index 192c04869..34178e3f8 100644 --- a/apps/maple-agent/app/src/ui/rich_text.rs +++ b/apps/maple-agent/app/src/ui/rich_text.rs @@ -44,9 +44,9 @@ pub struct Inline { const REGISTRY_CAP: usize = 8192; const REGISTRY_WINDOW: u64 = 2048; -/// Background drawn under selected text: Maple coral at ~40% alpha. +/// Background drawn under selected text: the theme's accent at ~40% alpha. fn selection_background() -> gpui::Hsla { - gpui::rgba(0xff977166).into() + crate::ui::theme::transcript_selection().into() } /// Snap a byte index to the nearest char boundary at or before it. diff --git a/apps/maple-agent/app/src/ui/settings.rs b/apps/maple-agent/app/src/ui/settings.rs index a1b7e076d..b693111f1 100644 --- a/apps/maple-agent/app/src/ui/settings.rs +++ b/apps/maple-agent/app/src/ui/settings.rs @@ -288,6 +288,9 @@ pub struct SettingsScreen { update: crate::update::Snapshot, /// `settings.theme` parsed once; render only reads the label. theme: theme::Preference, + /// One focus handle per theme choice, in `Preference::ALL` order, so + /// arrow keys can move focus between them as in a radio group. + theme_focus: Vec, section: Section, #[cfg(feature = "acp")] developer_tab: DeveloperTab, @@ -666,6 +669,7 @@ impl SettingsScreen { remote_screen, user_id, theme: theme::Preference::parse(&settings.theme), + theme_focus: general::theme_focus_handles(cx), settings, update: crate::update::Snapshot::initial(), section, diff --git a/apps/maple-agent/app/src/ui/settings/general.rs b/apps/maple-agent/app/src/ui/settings/general.rs index 0157f5146..a53c81f43 100644 --- a/apps/maple-agent/app/src/ui/settings/general.rs +++ b/apps/maple-agent/app/src/ui/settings/general.rs @@ -199,20 +199,11 @@ impl SettingsScreen { } fn theme_selector_row(&self, cx: &mut Context) -> Div { - // Tab stops after the sidebar filter (0); one slot per pill so Tab - // walks System → Dark → Light in order. - const THEME_TAB_INDEX: isize = 1; - let options = [ - (theme::Preference::System, "system"), - (theme::Preference::Dark, "dark"), - (theme::Preference::Light, "light"), - ]; + let count = theme::Preference::ALL.len(); div() .flex() - .flex_wrap() - .items_center() - .justify_between() - .gap_4() + .flex_col() + .gap_3() .child(setting_copy( tr("settings-appearance"), tr("settings-appearance-description"), @@ -220,60 +211,46 @@ impl SettingsScreen { .child( div() .id("setting-value-appearance") - .role(gpui::Role::TabList) + .role(gpui::Role::RadioGroup) .aria_label(tr("settings-appearance")) .flex() - .flex_none() + .flex_wrap() .items_center() - .gap_1() - .p_1() - .rounded_full() - .bg(gpui::rgb(theme::bg_input())) - .border_1() - .border_color(gpui::rgb(theme::border_subtle())) - .children(options.into_iter().zip(THEME_TAB_INDEX..).map( - |((preference, slug), tab_index)| { + .gap_2() + .children(theme::Preference::ALL.into_iter().enumerate().map( + |(position, preference)| { let active = self.theme == preference; - let swatch = match preference { - theme::Preference::System => div() - .size(px(12.)) - .rounded_full() - .border_1() - .border_color(gpui::rgb(theme::border())) - .overflow_hidden() - .flex() - .child(div().w_1_2().h_full().bg(gpui::rgb(0x18181c))) - .child(div().w_1_2().h_full().bg(gpui::rgb(0xffffff))), - theme::Preference::Dark => div() - .size(px(12.)) - .rounded_full() - .border_1() - .border_color(gpui::rgb(theme::border())) - .bg(gpui::rgb(0x18181c)), - theme::Preference::Light => div() - .size(px(12.)) - .rounded_full() - .border_1() - .border_color(gpui::rgb(theme::border())) - .bg(gpui::rgb(0xffffff)), - }; - let pill = div() + let slug = preference.as_str(); + let choice = div() .id(gpui::SharedString::from(format!( "setting-appearance-{slug}" ))) .debug_selector(move || format!("setting-appearance-{slug}")) - .role(gpui::Role::Tab) + .role(gpui::Role::RadioButton) .aria_label(theme_label(preference)) - .aria_selected(active) - .tab_index(tab_index) + .aria_toggled(if active { + gpui::Toggled::True + } else { + gpui::Toggled::False + }) + .aria_position_in_set(position + 1) + .aria_size_of_set(count) + .track_focus(&self.theme_focus[position]) .flex() .items_center() - .gap_1p5() - .px_3() + .gap_2() + .pl_1p5() + .pr_3() .py_1() .rounded_full() + .border_1() .text_xs() .font_weight(gpui::FontWeight::MEDIUM) + .border_color(gpui::rgb(if active { + theme::bg_default_button() + } else { + theme::border_subtle() + })) .bg(gpui::rgb(if active { theme::bg_default_button() } else { @@ -292,8 +269,8 @@ impl SettingsScreen { }) }) .when(active, |el| el.hover(|style| style.cursor_pointer())) - // The selected pill keeps its fill under the - // pointer. + // The selected choice keeps its fill under + // the pointer. .hover_bg(gpui::rgb(if active { theme::bg_default_button() } else { @@ -304,18 +281,26 @@ impl SettingsScreen { this.choose_theme(preference, cx); })) .on_key_down(cx.listener( - move |this, event: &gpui::KeyDownEvent, _, cx| { + move |this, event: &gpui::KeyDownEvent, window, cx| { if activates(event) { cx.stop_propagation(); this.choose_theme(preference, cx); + } else if let Some(target) = + theme_arrow_target(position, event) + { + // Radio convention: arrows move + // focus and select, wrapping. + cx.stop_propagation(); + this.choose_theme(theme::Preference::ALL[target], cx); + window.focus(&this.theme_focus[target], cx); } }, )) - .child(swatch) + .child(theme_swatch(preference)) .child(theme_label(preference)); self.application_target( || SettingsTarget::Appearance(AppearanceTarget::Theme(preference)), - pill, + choice, ) }, )), @@ -424,13 +409,67 @@ fn localized_toggle_row( on, )) } +/// Tab stops after the sidebar filter (0); one slot per theme choice so Tab +/// still walks them in the order shown. +const THEME_TAB_INDEX: isize = 1; + +/// Focus handles for the theme choices, created once with the screen. +pub(super) fn theme_focus_handles(cx: &mut Context) -> Vec { + (THEME_TAB_INDEX..) + .take(theme::Preference::ALL.len()) + .map(|index| cx.focus_handle().tab_index(index).tab_stop(true)) + .collect() +} + +/// The choice an unmodified arrow, Home or End key moves to from +/// `position`: Left/Up go back and Right/Down forward, wrapping at the +/// ends, as in a radio group. Other keys return `None`. +fn theme_arrow_target(position: usize, event: &gpui::KeyDownEvent) -> Option { + if event.keystroke.modifiers.modified() { + return None; + } + let count = theme::Preference::ALL.len(); + match event.keystroke.key.as_str() { + "left" | "up" => Some((position + count - 1) % count), + "right" | "down" => Some((position + 1) % count), + "home" => Some(0), + "end" => Some(count - 1), + _ => None, + } +} + pub(super) fn theme_label(value: theme::Preference) -> gpui::SharedString { match value { theme::Preference::System => tr("settings-theme-label-system"), - theme::Preference::Dark => tr("settings-theme-label-dark"), theme::Preference::Light => tr("settings-theme-label-light"), + theme::Preference::Dark => tr("settings-theme-label-dark"), + theme::Preference::Dracula => tr("settings-theme-label-dracula"), + theme::Preference::Americana => tr("settings-theme-label-americana"), + theme::Preference::NeonDusk => tr("settings-theme-label-neon-dusk"), + theme::Preference::CherryBlossom => tr("settings-theme-label-cherry-blossom"), } } + +/// Two solid dots previewing the choice ([`theme::Preference::swatch`]), +/// each rounded on its own with a hairline so a dot close to the surface +/// behind it still reads. +fn theme_swatch(preference: theme::Preference) -> Div { + let dot = |color: u32| { + div() + .flex_none() + .size(px(10.)) + .rounded_full() + .bg(gpui::rgb(color)) + .border_1() + .border_color(gpui::rgb(theme::border())) + }; + div() + .flex_none() + .flex() + .items_center() + .gap(px(3.)) + .children(preference.swatch().map(dot)) +} pub(super) fn font_label(value: crate::ui::typography::ChatFontFamily) -> gpui::SharedString { match value { crate::ui::typography::ChatFontFamily::System => tr("settings-font-label-system"), diff --git a/apps/maple-agent/app/src/ui/settings/navigation.rs b/apps/maple-agent/app/src/ui/settings/navigation.rs index cc680ca2d..51787203b 100644 --- a/apps/maple-agent/app/src/ui/settings/navigation.rs +++ b/apps/maple-agent/app/src/ui/settings/navigation.rs @@ -211,19 +211,18 @@ impl SettingsScreen { SettingsTarget::PromptSave, ]) .collect(), - Section::Appearance => [ - AppearanceTarget::Theme(crate::ui::theme::Preference::System), - AppearanceTarget::Theme(crate::ui::theme::Preference::Dark), - AppearanceTarget::Theme(crate::ui::theme::Preference::Light), - AppearanceTarget::ReduceMotion, - AppearanceTarget::ChatFont, - AppearanceTarget::ChatSize, - AppearanceTarget::ToolDetails, - AppearanceTarget::ToolSummaries, - ] - .into_iter() - .map(SettingsTarget::Appearance) - .collect(), + Section::Appearance => crate::ui::theme::Preference::ALL + .into_iter() + .map(AppearanceTarget::Theme) + .chain([ + AppearanceTarget::ReduceMotion, + AppearanceTarget::ChatFont, + AppearanceTarget::ChatSize, + AppearanceTarget::ToolDetails, + AppearanceTarget::ToolSummaries, + ]) + .map(SettingsTarget::Appearance) + .collect(), Section::Account => self.account_targets(), Section::Usage => self.usage_targets(), Section::Billing => self.billing_targets(), @@ -1484,6 +1483,7 @@ mod tests { #[gpui::test] fn spanish_general_preserves_controls_and_saved_values(cx: &mut TestAppContext) { let _localization = crate::ui::i18n::TestLocalizationGuard::enable(); + let _theme = crate::ui::theme::TestThemeGuard::acquire(); crate::ui::i18n::initialize_saved_preference(Some("es")); let (settings, cx) = dropdown_window(cx, true); cx.run_until_parked(); @@ -2243,6 +2243,7 @@ mod tests { #[gpui::test] fn appearance_segmented_theme_switches_on_pointer_and_vim_activation(cx: &mut TestAppContext) { let _guard = crate::settings::SETTINGS_IO_LOCK.lock(); + let _theme = crate::ui::theme::TestThemeGuard::acquire(); crate::settings::install_test_settings(crate::settings::AppSettings::default()); let (settings, cx) = dropdown_window(cx, true); // The Settings header Sign out is removed; Sign out lives only in Account. @@ -2255,13 +2256,47 @@ mod tests { let dark = cx .debug_bounds("setting-appearance-dark") - .expect("Dark segmented pill renders"); + .expect("Dark theme choice renders"); cx.simulate_click(dark.center(), gpui::Modifiers::default()); cx.run_until_parked(); settings.update(cx, |this, _| { assert_eq!(this.settings.theme, "dark"); assert_eq!(this.theme, crate::ui::theme::Preference::Dark); }); + // Every named theme is a choice, and selecting one saves its ID. + for (selector, slug, preference) in [ + ( + "setting-appearance-dracula", + "dracula", + crate::ui::theme::Preference::Dracula, + ), + ( + "setting-appearance-americana", + "americana", + crate::ui::theme::Preference::Americana, + ), + ( + "setting-appearance-neon-dusk", + "neon-dusk", + crate::ui::theme::Preference::NeonDusk, + ), + ( + "setting-appearance-cherry-blossom", + "cherry-blossom", + crate::ui::theme::Preference::CherryBlossom, + ), + ] { + let choice = cx + .debug_bounds(selector) + .expect("named theme choice renders"); + cx.simulate_click(choice.center(), gpui::Modifiers::default()); + cx.run_until_parked(); + settings.update(cx, |this, _| { + assert_eq!(this.settings.theme, slug); + assert_eq!(this.theme, preference); + assert_eq!(crate::ui::theme::preference(), preference); + }); + } cx.update(|window, app| { settings.update(app, |this, cx| { @@ -2277,34 +2312,95 @@ mod tests { crate::settings::discard_decrypted_cache(); } - /// Without Application Vim, the pills are ordinary tab stops: Tab walks - /// them and Space or Enter presses the focused one. (Under Application - /// Vim, Space is the leader prefix and Enter activates the Vim target.) + /// Arrow keys move between theme choices as in a radio group: they + /// select the next or previous choice, wrap at the ends, take focus + /// with them, and Home and End jump to the first and last choice. #[gpui::test] - fn appearance_theme_pills_are_keyboard_tab_stops(cx: &mut TestAppContext) { + fn appearance_theme_choices_follow_radio_arrow_keys(cx: &mut TestAppContext) { let _guard = crate::settings::SETTINGS_IO_LOCK.lock(); + let _theme = crate::ui::theme::TestThemeGuard::acquire(); crate::settings::install_test_settings(crate::settings::AppSettings::default()); let (settings, cx) = dropdown_window(cx, false); settings.update(cx, |this, cx| { this.select_section(Section::Appearance, cx); }); cx.run_until_parked(); - - // Clicking Dark focuses it; Tab then reaches Light. let dark = cx .debug_bounds("setting-appearance-dark") - .expect("Dark segmented pill renders"); + .expect("Dark theme choice renders"); cx.simulate_click(dark.center(), gpui::Modifiers::default()); + cx.run_until_parked(); + + use crate::ui::theme::Preference; + let position = |preference: Preference| { + Preference::ALL + .iter() + .position(|candidate| *candidate == preference) + .expect("listed choice") + }; + for (keys, expected) in [ + ("right", Preference::Dracula), + ("down", Preference::Americana), + ("left up", Preference::Dark), + ("end", Preference::CherryBlossom), + ("right", Preference::System), + ("left", Preference::CherryBlossom), + ("home", Preference::System), + ] { + cx.simulate_keystrokes(keys); + cx.run_until_parked(); + settings.update(cx, |this, _| { + assert_eq!(this.theme, expected, "after {keys}"); + assert_eq!(this.settings.theme, expected.as_str(), "after {keys}"); + }); + cx.update(|window, app| { + let focused = settings.read(app).theme_focus[position(expected)].is_focused(window); + assert!(focused, "focus follows the selection after {keys}"); + }); + } + // Modified arrows are left to other bindings. + cx.simulate_keystrokes("shift-right"); + cx.run_until_parked(); + settings.update(cx, |this, _| assert_eq!(this.theme, Preference::System)); + crate::settings::discard_decrypted_cache(); + } + + /// Without Application Vim, the theme choices are ordinary tab stops: + /// Tab walks them and Space or Enter presses the focused one. (Under Application + /// Vim, Space is the leader prefix and Enter activates the Vim target.) + #[gpui::test] + fn appearance_theme_pills_are_keyboard_tab_stops(cx: &mut TestAppContext) { + let _guard = crate::settings::SETTINGS_IO_LOCK.lock(); + let _theme = crate::ui::theme::TestThemeGuard::acquire(); + crate::settings::install_test_settings(crate::settings::AppSettings::default()); + let (settings, cx) = dropdown_window(cx, false); + settings.update(cx, |this, cx| { + this.select_section(Section::Appearance, cx); + }); + cx.run_until_parked(); + + // Clicking Light focuses it; Tab then reaches Maple Dark, and + // another Tab reaches Dracula. + let light = cx + .debug_bounds("setting-appearance-light") + .expect("Light theme choice renders"); + cx.simulate_click(light.center(), gpui::Modifiers::default()); cx.simulate_keystrokes("tab space"); cx.run_until_parked(); settings.update(cx, |this, _| { - assert_eq!(this.settings.theme, "light"); - assert_eq!(this.theme, crate::ui::theme::Preference::Light); + assert_eq!(this.settings.theme, "dark"); + assert_eq!(this.theme, crate::ui::theme::Preference::Dark); }); - cx.simulate_keystrokes("shift-tab enter"); + cx.simulate_keystrokes("tab enter"); cx.run_until_parked(); settings.update(cx, |this, _| { - assert_eq!(this.settings.theme, "dark"); + assert_eq!(this.settings.theme, "dracula"); + assert_eq!(this.theme, crate::ui::theme::Preference::Dracula); + }); + cx.simulate_keystrokes("shift-tab shift-tab enter"); + cx.run_until_parked(); + settings.update(cx, |this, _| { + assert_eq!(this.settings.theme, "light"); }); crate::settings::discard_decrypted_cache(); } diff --git a/apps/maple-agent/app/src/ui/settings/usage/palette.rs b/apps/maple-agent/app/src/ui/settings/usage/palette.rs index b15d5d55a..8ec3faaa4 100644 --- a/apps/maple-agent/app/src/ui/settings/usage/palette.rs +++ b/apps/maple-agent/app/src/ui/settings/usage/palette.rs @@ -18,8 +18,6 @@ struct Palette { input: u32, cached: u32, output: u32, - grid: u32, - axis: u32, } const LIGHT: Palette = Palette { @@ -34,8 +32,6 @@ const LIGHT: Palette = Palette { input: 0x64748b, cached: 0x94a3b8, output: 0x334155, - grid: 0xededed, - axis: 0xd4d4d4, }; const DARK: Palette = Palette { @@ -50,8 +46,6 @@ const DARK: Palette = Palette { input: 0x7c8ba1, cached: 0x475569, output: 0xcbd5e1, - grid: 0x262626, - axis: 0x3a3a3a, }; fn palette() -> &'static Palette { @@ -104,10 +98,12 @@ pub(super) fn model(model: &str, named_models: &[String]) -> u32 { ) } +/// Gridlines and the axis rule follow the active theme's chrome; the +/// series colors keep their validated light and dark sets. pub(super) fn grid() -> u32 { - palette().grid + theme::chart_grid() } pub(super) fn axis() -> u32 { - palette().axis + theme::chart_axis() } diff --git a/apps/maple-agent/app/src/ui/theme.rs b/apps/maple-agent/app/src/ui/theme.rs index 322254b83..4e117eeaf 100644 --- a/apps/maple-agent/app/src/ui/theme.rs +++ b/apps/maple-agent/app/src/ui/theme.rs @@ -11,38 +11,133 @@ //! `pebble-*` the secondary grey-lavender, `bark-*` the tertiary brown, //! `neutral-*` the greys. -use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; +use std::sync::atomic::{AtomicU8, Ordering}; use gpui::{Pixels, px}; -/// Theme preference from settings. +/// Theme choice from settings. The saved value is the stable ID from +/// [`Preference::as_str`]; `system`, `dark` and `light` predate the named +/// themes, so earlier settings keep their meaning without a migration. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Preference { + /// Standard Maple, following the OS appearance. System, - Dark, + /// Maple Light, always. Light, + /// Maple Dark, always. + Dark, + Dracula, + Americana, + NeonDusk, + CherryBlossom, } impl Preference { + /// Every choice, in the order Settings offers them. + pub const ALL: [Self; 7] = [ + Self::System, + Self::Light, + Self::Dark, + Self::Dracula, + Self::Americana, + Self::NeonDusk, + Self::CherryBlossom, + ]; + + /// An unknown ID (a newer app's theme, or a damaged value) falls back + /// to Standard Maple. The caller keeps the saved string, so a later + /// app that knows the ID still finds it. pub fn parse(value: &str) -> Self { - match value { - "dark" => Self::Dark, - "light" => Self::Light, - _ => Self::System, - } + Self::ALL + .into_iter() + .find(|preference| preference.as_str() == value) + .unwrap_or(Self::System) } pub fn as_str(self) -> &'static str { match self { Self::System => "system", - Self::Dark => "dark", Self::Light => "light", + Self::Dark => "dark", + Self::Dracula => "dracula", + Self::Americana => "americana", + Self::NeonDusk => "neon-dusk", + Self::CherryBlossom => "cherry-blossom", + } + } + + /// The fixed palette, or `None` when the choice follows the OS. + fn fixed_palette(self) -> Option { + match self { + Self::System => None, + Self::Light => Some(PaletteId::Light), + Self::Dark => Some(PaletteId::Dark), + Self::Dracula => Some(PaletteId::Dracula), + Self::Americana => Some(PaletteId::Americana), + Self::NeonDusk => Some(PaletteId::NeonDusk), + Self::CherryBlossom => Some(PaletteId::CherryBlossom), + } + } + + /// The two dots a Settings choice previews: the canvas and accent of + /// the palette it draws with, or for Standard Maple, which follows the + /// OS, the Maple Dark and Maple Light canvases. + pub fn swatch(self) -> [u32; 2] { + match self.fixed_palette() { + Some(palette) => [palette.palette().bg_app, palette.palette().accent], + None => [DARK.bg_app, LIGHT.bg_app], + } + } +} + +/// A complete palette. Two dark themes are different palettes, so the +/// resolver tracks identity rather than a light/dark flag. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +enum PaletteId { + Dark = 0, + Light = 1, + Dracula = 2, + Americana = 3, + NeonDusk = 4, + CherryBlossom = 5, +} + +impl PaletteId { + const ALL: [Self; 6] = [ + Self::Dark, + Self::Light, + Self::Dracula, + Self::Americana, + Self::NeonDusk, + Self::CherryBlossom, + ]; + + fn from_u8(value: u8) -> Self { + Self::ALL + .into_iter() + .find(|id| *id as u8 == value) + .unwrap_or(Self::Dark) + } + + fn is_light(self) -> bool { + matches!(self, Self::Light | Self::CherryBlossom) + } + + fn palette(self) -> &'static Palette { + match self { + Self::Dark => &DARK, + Self::Light => &LIGHT, + Self::Dracula => &DRACULA, + Self::Americana => &AMERICANA, + Self::NeonDusk => &NEON_DUSK, + Self::CherryBlossom => &CHERRY_BLOSSOM, } } } static PREFERENCE: AtomicU8 = AtomicU8::new(0); -static LIGHT_ACTIVE: AtomicBool = AtomicBool::new(false); +static ACTIVE_PALETTE: AtomicU8 = AtomicU8::new(PaletteId::Dark as u8); #[cfg(target_os = "linux")] static SYSTEM_APPEARANCE: AtomicU8 = AtomicU8::new(0); @@ -68,37 +163,62 @@ fn appearance_is_light(appearance: gpui::WindowAppearance) -> bool { } pub fn set_preference(preference: Preference) { - PREFERENCE.store( - match preference { - Preference::System => 0, - Preference::Dark => 1, - Preference::Light => 2, - }, - Ordering::Relaxed, - ); + let index = Preference::ALL + .iter() + .position(|candidate| *candidate == preference) + .unwrap_or(0); + PREFERENCE.store(index as u8, Ordering::Relaxed); } -/// Set the preference and tell the platform, so a forced theme also -/// restyles the window chrome (traffic lights, native menus, scrollbars). -/// `System` hands control back to the OS. Every view must render again. +/// Set the preference and tell the platform, so a fixed theme also +/// restyles the window chrome (traffic lights, native menus, scrollbars) +/// to match its lightness. `System` hands control back to the OS. Every +/// open window renders again, including a switch between two dark themes. pub fn apply_preference(preference: Preference, cx: &mut gpui::App) { set_preference(preference); - cx.set_window_appearance(match preference { - Preference::System => None, - Preference::Dark => Some(gpui::WindowAppearance::Dark), - Preference::Light => Some(gpui::WindowAppearance::Light), - }); + cx.set_window_appearance(preference.fixed_palette().map(|palette| { + if palette.is_light() { + gpui::WindowAppearance::Light + } else { + gpui::WindowAppearance::Dark + } + })); + // Resolve here rather than waiting for the main window's render, which + // may not exist (only a dialog open, or the main window in the tray). + resolve(cx.window_appearance()); cx.refresh_windows(); } -pub fn preference() -> Preference { - match PREFERENCE.load(Ordering::Relaxed) { - 1 => Preference::Dark, - 2 => Preference::Light, - _ => Preference::System, +/// Resolve against the app's appearance and repaint every window if the +/// palette changed. For changes that arrive outside any render: the Linux +/// portal helper reporting a new OS appearance. Other platforms deliver +/// appearance changes to each window's `observe_window_appearance`. +#[cfg(target_os = "linux")] +pub fn sync(cx: &mut gpui::App) { + if resolve(cx.window_appearance()) { + cx.refresh_windows(); + } +} + +/// Resolve against one top-level window's appearance and repaint every +/// window if the palette changed. Every top-level view calls this first in +/// its render and on `observe_window_appearance`, so whichever windows are +/// open (the main window, a quit prompt, a native dialog) keep the palette +/// current; a change between two palettes of the same lightness repaints +/// them all. +pub fn sync_window(window: &gpui::Window, cx: &mut gpui::App) { + if resolve(window.appearance()) { + cx.refresh_windows(); } } +pub fn preference() -> Preference { + Preference::ALL + .get(usize::from(PREFERENCE.load(Ordering::Relaxed))) + .copied() + .unwrap_or(Preference::System) +} + /// Pick the palette for the preference and the window appearance. Returns /// whether the active palette changed, in which case every view must /// render again. @@ -111,19 +231,131 @@ pub fn resolve(appearance: gpui::WindowAppearance) -> bool { }; #[cfg(not(target_os = "linux"))] let system = None; - let light = resolved_light(preference(), appearance, system); - LIGHT_ACTIVE.swap(light, Ordering::Relaxed) != light + let palette = resolved_palette(preference(), appearance, system) as u8; + ACTIVE_PALETTE.swap(palette, Ordering::Relaxed) != palette } -fn resolved_light( +fn resolved_palette( preference: Preference, appearance: gpui::WindowAppearance, system: Option, -) -> bool { - match preference { - Preference::Dark => false, - Preference::Light => true, - Preference::System => system.unwrap_or_else(|| appearance_is_light(appearance)), +) -> PaletteId { + preference.fixed_palette().unwrap_or_else(|| { + if system.unwrap_or_else(|| appearance_is_light(appearance)) { + PaletteId::Light + } else { + PaletteId::Dark + } + }) +} + +/// Serializes tests that change the process-global theme and restores +/// Standard Maple on a dark OS when the test ends, panics included, so a +/// flip never leaks into another test that reads the palette. +/// +/// Take it after any other test lock (`SETTINGS_IO_LOCK`, the localization +/// guard) so the locks are always acquired in one order. +#[cfg(test)] +pub(crate) struct TestThemeGuard(#[allow(dead_code)] parking_lot::MutexGuard<'static, ()>); + +#[cfg(test)] +impl TestThemeGuard { + pub(crate) fn acquire() -> Self { + static LOCK: parking_lot::Mutex<()> = parking_lot::Mutex::new(()); + Self(LOCK.lock()) + } +} + +#[cfg(test)] +impl Drop for TestThemeGuard { + fn drop(&mut self) { + #[cfg(target_os = "linux")] + SYSTEM_APPEARANCE.store(0, Ordering::Relaxed); + set_preference(Preference::System); + resolve(gpui::WindowAppearance::Dark); + } +} + +#[cfg(test)] +mod repaint_tests { + use super::*; + use gpui::{Context, IntoElement, Render, Styled as _, TestAppContext, Window, div}; + use std::{cell::Cell, rc::Rc}; + + /// A top-level view that records the canvas color it last painted. + /// `syncs` mirrors the app's top-level views, which call `sync_window` + /// first in render; a view without it stands for a window that only + /// reads the palette. + struct Probe { + painted: Rc>, + syncs: bool, + } + + impl Render for Probe { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + if self.syncs { + sync_window(window, cx); + } + self.painted.set(bg_app()); + div().size_full().bg(gpui::rgb(bg_app())) + } + } + + fn open(cx: &mut TestAppContext, syncs: bool) -> (gpui::WindowHandle, Rc>) { + let painted = Rc::new(Cell::new(0)); + let probe = painted.clone(); + let window = cx.add_window(move |_, _| Probe { + painted: probe, + syncs, + }); + (window, painted) + } + + #[gpui::test] + fn a_switch_between_dark_themes_repaints_every_window(cx: &mut TestAppContext) { + let _theme = TestThemeGuard::acquire(); + cx.update(|cx| apply_preference(Preference::Dark, cx)); + let (first, first_painted) = open(cx, true); + let (_second, second_painted) = open(cx, true); + cx.run_until_parked(); + assert_eq!(first_painted.get(), DARK.bg_app); + assert_eq!(second_painted.get(), DARK.bg_app); + + // Settings: Maple Dark to Dracula, both dark. + cx.update(|cx| apply_preference(Preference::Dracula, cx)); + cx.run_until_parked(); + assert_eq!(first_painted.get(), DRACULA.bg_app); + assert_eq!(second_painted.get(), DRACULA.bg_app); + + // A change only one window's render notices still repaints the + // other: resolution compares palettes, not lightness. + set_preference(Preference::NeonDusk); + first + .update(cx, |_, _, cx| cx.notify()) + .expect("first window is open"); + cx.run_until_parked(); + assert_eq!(first_painted.get(), NEON_DUSK.bg_app); + assert_eq!(second_painted.get(), NEON_DUSK.bg_app); + } + + /// With the main window gone (closed to the tray), an OS appearance + /// change still reaches a remaining window that never resolves the + /// palette itself: the portal update resolves at app level. + #[cfg(target_os = "linux")] + #[gpui::test] + fn an_os_change_repaints_a_window_that_does_not_resolve(cx: &mut TestAppContext) { + let _theme = TestThemeGuard::acquire(); + set_system_appearance(gpui::WindowAppearance::Dark); + cx.update(|cx| apply_preference(Preference::System, cx)); + let (_dialog, painted) = open(cx, false); + cx.run_until_parked(); + assert_eq!(painted.get(), DARK.bg_app); + + // What the portal monitor does on a new color scheme. + set_system_appearance(gpui::WindowAppearance::Light); + cx.update(sync); + cx.run_until_parked(); + assert_eq!(painted.get(), LIGHT.bg_app); } } @@ -134,21 +366,76 @@ mod system_appearance_tests { #[test] fn helper_overrides_stale_native_appearance_only_in_system_mode() { - assert!(!resolved_light(Preference::System, Light, Some(false))); - assert!(resolved_light(Preference::System, Dark, Some(true))); - assert!(!resolved_light(Preference::Dark, Light, Some(true))); - assert!(resolved_light(Preference::Light, Dark, Some(false))); + assert_eq!( + resolved_palette(Preference::System, Light, Some(false)), + PaletteId::Dark + ); + assert_eq!( + resolved_palette(Preference::System, Dark, Some(true)), + PaletteId::Light + ); + assert_eq!( + resolved_palette(Preference::Dark, Light, Some(true)), + PaletteId::Dark + ); + assert_eq!( + resolved_palette(Preference::Light, Dark, Some(false)), + PaletteId::Light + ); } #[test] fn missing_helper_preserves_native_fallback() { - assert!(resolved_light(Preference::System, Light, None)); - assert!(!resolved_light(Preference::System, Dark, None)); + assert_eq!( + resolved_palette(Preference::System, Light, None), + PaletteId::Light + ); + assert_eq!( + resolved_palette(Preference::System, Dark, None), + PaletteId::Dark + ); + } + + #[test] + fn named_themes_ignore_the_os_appearance() { + for (preference, palette) in [ + (Preference::Dracula, PaletteId::Dracula), + (Preference::Americana, PaletteId::Americana), + (Preference::NeonDusk, PaletteId::NeonDusk), + (Preference::CherryBlossom, PaletteId::CherryBlossom), + ] { + for appearance in [Light, Dark] { + for system in [None, Some(true), Some(false)] { + assert_eq!(resolved_palette(preference, appearance, system), palette); + } + } + } + } + + #[test] + fn saved_ids_round_trip_and_keep_their_earlier_meaning() { + for preference in Preference::ALL { + assert_eq!(Preference::parse(preference.as_str()), preference); + } + // Values written before named themes existed. + assert_eq!(Preference::parse("system"), Preference::System); + assert_eq!(Preference::parse("light"), Preference::Light); + assert_eq!(Preference::parse("dark"), Preference::Dark); + for unknown in ["", "solarized", "Dracula", "neon_dusk"] { + assert_eq!(Preference::parse(unknown), Preference::System); + } } } +/// Whether the active palette is a light one. Translucent overlays, +/// shadows and monochrome marks pick black or white by this; colors pick +/// from the palette itself. pub fn is_light() -> bool { - LIGHT_ACTIVE.load(Ordering::Relaxed) + active_palette().is_light() +} + +fn active_palette() -> PaletteId { + PaletteId::from_u8(ACTIVE_PALETTE.load(Ordering::Relaxed)) } macro_rules! tokens { @@ -170,7 +457,7 @@ macro_rules! tokens { } fn palette() -> &'static Palette { - if is_light() { &LIGHT } else { &DARK } + active_palette().palette() } tokens! { @@ -272,17 +559,309 @@ tokens! { bg_default_button_hover: 0xf7f7f9, 0x2c2c34; bg_default_button_active: 0xd1d2dc, 0x404040; text_on_default_button: 0x18181c, 0xf7f7f9; + + /// Usage chart gridlines and axis rule. + chart_grid: 0x262626, 0xededed; + chart_axis: 0x3a3a3a, 0xd4d4d4; + + /// Text and icons on a `status_error` fill (destructive buttons, the + /// recording stop square) and on a `status_success` fill (a completed + /// plan step). Stock palettes keep the accent foreground they used. + on_error: 0xf7f7f9, 0xf7f7f9; + on_success: 0xf7f7f9, 0xf7f7f9; + /// A switch's knob while it is off, on the off track. When on, the knob + /// takes `on_accent` on the accent track. + switch_knob_off: 0xf7f7f9, 0xf7f7f9; + /// The effort slider's thumb, drawn against the send-gradient fill. + slider_thumb: 0xf7f7f9, 0xf7f7f9; + /// Fill of the legacy accent action button behind an `on_accent` label. + /// It equals the accent except where a theme's accent must stay bright + /// for focus rings and marks, too bright for a readable label. + accent_fill: 0xff9771, 0xff9771; + accent_fill_hover: 0xffa88a, 0xf67d57; + /// The accent button's fill while pressed, behind its `on_accent` label. + accent_fill_active: 0xe8633d, 0xe8633d; + /// The accent hue as body-size text (slash commands, the Manage + /// integrations row, an Updating badge) on panels, hovered, selected + /// and pill fills. `accent` itself is for marks, borders and focus + /// rings. Stock palettes keep the accent they used. + accent_text: 0xff9771, 0xff9771; } -/// Translucent selection highlight in text inputs: the coral primary at a -/// low alpha, a little stronger on light where the white field washes it +// Named themes. Each lists every role, so a new role cannot silently fall +// back to a stock color. Dracula uses the published Dracula palette +// (draculatheme.com) and its darker editor-chrome steps. Americana, Neon +// Dusk and Cherry Blossom follow the first-pass mock-ups, tuned in the +// running app. + +const DRACULA: Palette = Palette { + bg_app: 0x282a36, + bg_sidebar: 0x21222c, + bg_elevated: 0x343746, + bg_sidebar_card: 0x2c2e3b, + bg_sidebar_pill: 0x3b3e4f, + bg_input: 0x21222c, + bg_user_bubble: 0x44475a, + bg_code_block: 0x191a21, + bg_tool_card: 0x2c2e3b, + border: 0x4d5066, + border_subtle: 0x363949, + text_primary: 0xeaeae4, + text_sidebar: 0xd6d7e0, + text_heading: 0xf8f8f2, + text_secondary: 0xcfd1e3, + text_muted: 0xaab0d4, + text_faint: 0x6272a4, + accent: 0xbd93f9, + accent_hover: 0xcaa7fa, + on_accent: 0x21222c, + accent_container: 0x3e3558, + accent_ink: 0xc9a6ff, + status_running: 0xcfd1e3, + status_success: 0x50fa7b, + status_error: 0xff5555, + spell_error: 0xff5555, + status_warning: 0xffb86c, + code_text: 0xf8f8f2, + link: 0x8be9fd, + badge_fill: 0x3e3558, + badge_text: 0xd6bcfc, + permission_fill: 0x2f2b41, + permission_border: 0x6e5c9e, + bg_composer_tray: 0x2c2e3b, + user_bubble_border: 0x55586f, + bg_sidebar_chrome: 0x21222c, + bg_sidebar_row_hover: 0x343746, + bg_sidebar_row_selected: 0x44475a, + bg_sidebar_row_selected_hover: 0x4d5066, + display_text: 0xd6bcfc, + send_top: 0xff79c6, + send_bottom: 0xbd93f9, + bg_title_control: 0x44475a, + bg_title_control_hover: 0x55586f, + text_cursor: 0xf8f8f2, + bg_default_button: 0xf8f8f2, + bg_default_button_hover: 0xffffff, + bg_default_button_active: 0xe2e2dc, + text_on_default_button: 0x21222c, + chart_grid: 0x44475a, + chart_axis: 0x6272a4, + on_error: 0x21222c, + on_success: 0x21222c, + switch_knob_off: 0xf8f8f2, + slider_thumb: 0xf8f8f2, + accent_fill: 0xbd93f9, + accent_fill_hover: 0xcaa7fa, + accent_fill_active: 0xbd93f9, + accent_text: 0xd6bcfc, +}; + +/// Navy canvas, lighter blue tool rows, ivory type and red actions. Errors +/// take a light salmon so they read apart from the crimson action fills. +const AMERICANA: Palette = Palette { + bg_app: 0x14213d, + bg_sidebar: 0x0f1a31, + bg_elevated: 0x1d2d4f, + bg_sidebar_card: 0x182746, + bg_sidebar_pill: 0x253a63, + bg_input: 0x111c34, + bg_user_bubble: 0x233760, + bg_code_block: 0x0c152a, + bg_tool_card: 0x213a67, + border: 0x3a5688, + border_subtle: 0x263c63, + text_primary: 0xf3ecdc, + text_sidebar: 0xe2d9c5, + text_heading: 0xfbf6ea, + text_secondary: 0xdcd3bf, + text_muted: 0xbfb9aa, + text_faint: 0x5f7090, + accent: 0xea4d61, + accent_hover: 0xf06276, + on_accent: 0xfbf6ea, + accent_container: 0x3e1d2e, + accent_ink: 0xff8090, + status_running: 0xdcd3bf, + status_success: 0x93d08c, + status_error: 0xffa58a, + spell_error: 0xffa58a, + status_warning: 0xf2c14e, + code_text: 0xf3ecdc, + link: 0x9cc4ff, + badge_fill: 0x3e1d2e, + badge_text: 0xff9aa6, + permission_fill: 0x2a2038, + permission_border: 0x8f3c50, + bg_composer_tray: 0x1a2a4a, + user_bubble_border: 0x3a5688, + bg_sidebar_chrome: 0x0f1a31, + bg_sidebar_row_hover: 0x1d2d4f, + bg_sidebar_row_selected: 0x2a4170, + bg_sidebar_row_selected_hover: 0x334c80, + display_text: 0xe2d9c5, + send_top: 0xea4d61, + send_bottom: 0xb3172f, + bg_title_control: 0x253a63, + bg_title_control_hover: 0x2f4777, + text_cursor: 0xfbf6ea, + bg_default_button: 0xf3ecdc, + bg_default_button_hover: 0xfbf6ea, + bg_default_button_active: 0xe3dac6, + text_on_default_button: 0x14213d, + chart_grid: 0x2c4373, + chart_axis: 0x4d6aa0, + on_error: 0x14213d, + on_success: 0x14213d, + switch_knob_off: 0xfbf6ea, + slider_thumb: 0xfbf6ea, + accent_fill: 0xc8243b, + accent_fill_hover: 0xae1c31, + accent_fill_active: 0xb3172f, + accent_text: 0xff9aa6, +}; + +/// Ink-blue canvas, plum cards, fuchsia actions and focus rings. The +/// fuchsia is bright enough that a focus ring stands out on plum. +const NEON_DUSK: Palette = Palette { + bg_app: 0x12122a, + bg_sidebar: 0x0e0e22, + bg_elevated: 0x2b1b40, + bg_sidebar_card: 0x24173a, + bg_sidebar_pill: 0x362352, + bg_input: 0x161634, + bg_user_bubble: 0x2f1d47, + bg_code_block: 0x0b0b1c, + bg_tool_card: 0x26193e, + border: 0x4a3366, + border_subtle: 0x2e2147, + text_primary: 0xe8e2f4, + text_sidebar: 0xd2cae4, + text_heading: 0xf6f1ff, + text_secondary: 0xcfc5e4, + text_muted: 0xaea4c9, + text_faint: 0x5c5378, + accent: 0xff4fbf, + accent_hover: 0xff73cc, + on_accent: 0x12122a, + accent_container: 0x441a43, + accent_ink: 0xff7dcf, + status_running: 0xcfc5e4, + status_success: 0x5ee6a8, + status_error: 0xff7070, + spell_error: 0xff7070, + status_warning: 0xffc857, + code_text: 0xf0eaff, + link: 0x7fcaff, + badge_fill: 0x441a43, + badge_text: 0xff96d8, + permission_fill: 0x2b1532, + permission_border: 0x93327a, + bg_composer_tray: 0x1d1a3c, + user_bubble_border: 0x4a3366, + bg_sidebar_chrome: 0x0e0e22, + bg_sidebar_row_hover: 0x231a3d, + bg_sidebar_row_selected: 0x3b2558, + bg_sidebar_row_selected_hover: 0x462d68, + display_text: 0xdcc8f7, + send_top: 0xff5cc6, + send_bottom: 0xc42a93, + bg_title_control: 0x2e2147, + bg_title_control_hover: 0x3b2b58, + text_cursor: 0xf6f1ff, + bg_default_button: 0xf6f1ff, + bg_default_button_hover: 0xffffff, + bg_default_button_active: 0xe2d9f2, + text_on_default_button: 0x12122a, + chart_grid: 0x3d2a59, + chart_axis: 0x5c4380, + on_error: 0x12122a, + on_success: 0x12122a, + switch_knob_off: 0xf6f1ff, + slider_thumb: 0xf6f1ff, + accent_fill: 0xff4fbf, + accent_fill_hover: 0xff73cc, + accent_fill_active: 0xff73cc, + accent_text: 0xff96d8, +}; + +/// Blush sidebar, pale pink canvas, plum type and raspberry actions. +/// Secondary text stays dark enough to read on the blush selected row. +const CHERRY_BLOSSOM: Palette = Palette { + bg_app: 0xfff6f8, + bg_sidebar: 0xfbe5eb, + bg_elevated: 0xffffff, + bg_sidebar_card: 0xfff0f4, + bg_sidebar_pill: 0xf5d2dc, + bg_input: 0xffffff, + bg_user_bubble: 0xfbe1e9, + bg_code_block: 0xfdeff3, + bg_tool_card: 0xfdeff3, + border: 0xedc6d2, + border_subtle: 0xf6dfe6, + text_primary: 0x3d1f33, + text_sidebar: 0x5a2f4b, + text_heading: 0x2e1426, + text_secondary: 0x65395a, + text_muted: 0x7c4d6b, + text_faint: 0xd9b3c3, + accent: 0xc2185b, + accent_hover: 0xa3134c, + on_accent: 0xfff6f8, + accent_container: 0xfcd9e5, + accent_ink: 0xa3134c, + status_running: 0x7c4d6b, + status_success: 0x4a7a36, + status_error: 0xc0392b, + spell_error: 0xc0392b, + status_warning: 0xa15c07, + code_text: 0x3d1f33, + link: 0x7b3fa0, + badge_fill: 0xf5d2dc, + badge_text: 0x65395a, + permission_fill: 0xfde5ed, + permission_border: 0xf0a8c0, + bg_composer_tray: 0xfdeff3, + user_bubble_border: 0xf0cad6, + bg_sidebar_chrome: 0xfff6f8, + bg_sidebar_row_hover: 0xf7d7e0, + bg_sidebar_row_selected: 0xf0c4d1, + bg_sidebar_row_selected_hover: 0xeab5c5, + display_text: 0x65395a, + send_top: 0xd81b60, + send_bottom: 0xa8134f, + bg_title_control: 0xf5d2dc, + bg_title_control_hover: 0xefc1cf, + text_cursor: 0x3d1f33, + bg_default_button: 0x3d1f33, + bg_default_button_hover: 0x522a45, + bg_default_button_active: 0x63385a, + text_on_default_button: 0xfff6f8, + chart_grid: 0xf0cfda, + chart_axis: 0xdba7b9, + on_error: 0xfff6f8, + on_success: 0xfff6f8, + switch_knob_off: 0x65395a, + slider_thumb: 0xffffff, + accent_fill: 0xc2185b, + accent_fill_hover: 0xa3134c, + accent_fill_active: 0xa8134f, + accent_text: 0x8e1043, +}; + +/// Translucent selection highlight in text inputs: the palette's accent at +/// a low alpha, a little stronger on light where the pale field washes it /// out. pub fn text_selection() -> gpui::Rgba { - if is_light() { - gpui::rgba(0xff977159) - } else { - gpui::rgba(0xff977147) - } + accent_alpha(if is_light() { 0x59 } else { 0x47 }) +} + +/// Background drawn under selected transcript text: the accent at ~40%. +pub fn transcript_selection() -> gpui::Rgba { + accent_alpha(0x66) +} + +fn accent_alpha(alpha: u8) -> gpui::Rgba { + gpui::rgba((accent() << 8) | u32::from(alpha)) } /// Dimming layer behind a modal or the image lightbox. One opacity for @@ -291,6 +870,30 @@ pub fn scrim() -> gpui::Rgba { gpui::rgba(0x000000a0) } +/// Opacity of a sign-in form while its request runs. +pub const BUSY_FORM_OPACITY: f32 = 0.7; + +/// The busy submit button of a sign-in form: a neutral pill whose label +/// reads at 4.5:1 even with the form at [`BUSY_FORM_OPACITY`]. +pub fn busy_button_fill() -> u32 { + busy_pair(palette()).0 +} + +pub fn busy_button_text() -> u32 { + busy_pair(palette()).1 +} + +/// Fill and label of a busy submit, shared with the contrast test. +fn busy_pair(palette: &Palette) -> (u32, u32) { + (palette.bg_sidebar_pill, palette.text_primary) +} + +/// Icons drawn over the dimming [`scrim`], such as the lightbox close +/// button: the scrim is black in every palette, so this stays light. +pub fn on_scrim() -> u32 { + 0xf7f7f9 +} + /// Translucent fill for hover states and inline code over any surface. pub fn overlay_hover() -> gpui::Hsla { if is_light() { @@ -373,15 +976,17 @@ mod contrast_tests { (a.max(b) + 0.05) / (a.min(b) + 0.05) } - /// Every text role must read on every resting surface in both - /// palettes: 4.5:1 for body roles (WCAG AA), 3:1 for status and link - /// colors, which the brand kit fixes and which carry short labels. - /// `text_faint` is decorative and not held to a ratio. Hover and - /// selection fills are transient and not checked. + /// Every text role must read on every resting surface in every shipped + /// palette: 4.5:1 for body roles (WCAG AA), 3:1 for status and link + /// colors, which carry short labels. `text_faint` is decorative and not + /// held to a ratio. Hover fills are transient and not checked; the + /// selected sidebar row persists, so its text is. #[test] fn text_roles_read_on_every_surface() { let mut failures = Vec::new(); - for (name, palette) in [("dark", &DARK), ("light", &LIGHT)] { + for id in PaletteId::ALL { + let name = format!("{id:?}"); + let palette = id.palette(); let surfaces = [ ("bg_app", palette.bg_app), ("bg_sidebar", palette.bg_sidebar), @@ -428,6 +1033,17 @@ mod contrast_tests { if ratio < 4.5 { failures.push(format!("{name}: badge_text on badge_fill is {ratio:.2}:1")); } + for (role, color) in [ + ("text_sidebar", palette.text_sidebar), + ("text_primary", palette.text_primary), + ] { + let ratio = contrast(color, palette.bg_sidebar_row_selected); + if ratio < 4.5 { + failures.push(format!( + "{name}: {role} on bg_sidebar_row_selected is {ratio:.2}:1" + )); + } + } for (label, fg, bg) in [ ( "default_button", @@ -453,4 +1069,239 @@ mod contrast_tests { } assert!(failures.is_empty(), "{}", failures.join("\n")); } + + /// `color` drawn at `alpha` over `under`, per channel, as gpui paints + /// each primitive of an element with reduced opacity. + fn over(color: u32, under: u32, alpha: f32) -> u32 { + let channel = |shift: u32| { + let top = f64::from((color >> shift) & 0xff); + let bottom = f64::from((under >> shift) & 0xff); + ((top * f64::from(alpha) + bottom * (1. - f64::from(alpha))).round() as u32) << shift + }; + channel(16) | channel(8) | channel(0) + } + + /// The busy submit of a sign-in form is drawn inside a card at + /// `BUSY_FORM_OPACITY`: the card over the canvas, the pill over the card + /// and the label over the pill, each faded. Its label still reads at + /// 4.5:1 in every palette. + #[test] + fn busy_sign_in_label_reads_inside_the_faded_form() { + let mut failures = Vec::new(); + for id in PaletteId::ALL { + let p = id.palette(); + let (fill, text) = busy_pair(p); + let card = over(p.bg_elevated, p.bg_app, BUSY_FORM_OPACITY); + let pill = over(fill, card, BUSY_FORM_OPACITY); + let label = over(text, pill, BUSY_FORM_OPACITY); + let ratio = contrast(label, pill); + if ratio < 4.5 { + failures.push(format!("{id:?}: busy label is {ratio:.2}:1")); + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); + } + + /// Foreground and fill pairs as the app draws them. Labels hold 4.5:1; + /// icons, marks, knobs and focus rings hold 3:1 (WCAG non-text + /// contrast); chart rules only need to separate from their card. + /// + /// The stock palettes predate this check. Their known shortfalls (the + /// coral fill under a light label, coral text on light surfaces, the pale + /// light-theme track and running label, the near-invisible dark chart + /// grid) are listed in + /// `STOCK_EXEMPT` rather than changed here; every named theme meets + /// every floor. + #[test] + fn rendered_pairs_meet_their_floors() { + const TEXT: f64 = 4.5; + const MARK: f64 = 3.; + const STOCK_EXEMPT: &[(PaletteId, &str)] = &[ + (PaletteId::Dark, "destructive button label"), + (PaletteId::Dark, "accent button label"), + (PaletteId::Dark, "accent button label (hover)"), + (PaletteId::Dark, "accent button label (pressed)"), + (PaletteId::Dark, "completed plan check"), + (PaletteId::Dark, "recording stop square"), + (PaletteId::Dark, "send arrow (top)"), + (PaletteId::Dark, "checkbox mark"), + (PaletteId::Dark, "switch knob (on)"), + (PaletteId::Dark, "chart grid"), + (PaletteId::Dark, "chart axis"), + (PaletteId::Light, "destructive button label"), + (PaletteId::Light, "accent button label"), + (PaletteId::Light, "accent button label (hover)"), + (PaletteId::Light, "accent button label (pressed)"), + (PaletteId::Light, "accent text on bg_elevated"), + (PaletteId::Light, "accent text on bg_sidebar_row_hover"), + (PaletteId::Light, "accent text on bg_sidebar_row_selected"), + (PaletteId::Light, "accent text on bg_sidebar_pill"), + (PaletteId::Light, "running label on bg_tool_card"), + (PaletteId::Light, "running label on bg_app"), + (PaletteId::Light, "running label on bg_elevated"), + (PaletteId::Light, "send arrow (top)"), + (PaletteId::Light, "checkbox mark"), + (PaletteId::Light, "switch knob (off)"), + (PaletteId::Light, "switch knob (on)"), + (PaletteId::Light, "focus ring on bg_app"), + (PaletteId::Light, "focus ring on bg_elevated"), + (PaletteId::Light, "focus ring on bg_tool_card"), + (PaletteId::Light, "focus ring on bg_user_bubble"), + (PaletteId::Light, "focus ring on bg_input"), + (PaletteId::Light, "focus ring on bg_sidebar"), + (PaletteId::Light, "chart grid"), + (PaletteId::Light, "chart axis"), + ]; + let mut failures = Vec::new(); + let mut exempt_used = Vec::new(); + for id in PaletteId::ALL { + let p = id.palette(); + let mut pairs: Vec<(String, u32, u32, f64)> = vec![ + // widgets::danger_button + ( + "destructive button label".into(), + p.on_error, + p.status_error, + TEXT, + ), + // login submit while signing in, opaque; the faded form is + // busy_sign_in_label_reads_inside_the_faded_form + ( + "busy sign-in label".into(), + busy_pair(p).1, + busy_pair(p).0, + TEXT, + ), + // widgets::primary_button + ( + "accent button label".into(), + p.on_accent, + p.accent_fill, + TEXT, + ), + ( + "accent button label (hover)".into(), + p.on_accent, + p.accent_fill_hover, + TEXT, + ), + // transcript plan step, composer dictation, send button + ( + "completed plan check".into(), + p.on_success, + p.status_success, + MARK, + ), + ( + "recording stop square".into(), + p.on_error, + p.status_error, + MARK, + ), + ("send arrow (top)".into(), p.on_accent, p.send_top, MARK), + ( + "send arrow (bottom)".into(), + p.on_accent, + p.send_bottom, + MARK, + ), + // widgets::checkbox and widgets::switch_track + ("checkbox mark".into(), p.on_accent, p.accent, MARK), + ( + "switch knob (off)".into(), + p.switch_knob_off, + p.bg_sidebar_row_selected, + MARK, + ), + ("switch knob (on)".into(), p.on_accent, p.accent, MARK), + // The effort slider's thumb sits where the fill meets the + // track; it must stand out from at least one of them. The + // pair listed is whichever it contrasts with more. + if contrast(p.slider_thumb, p.send_bottom) + >= contrast(p.slider_thumb, p.bg_sidebar_pill) + { + ("slider thumb".into(), p.slider_thumb, p.send_bottom, MARK) + } else { + ( + "slider thumb".into(), + p.slider_thumb, + p.bg_sidebar_pill, + MARK, + ) + }, + // usage chart rules on the chart card + ("chart grid".into(), p.chart_grid, p.bg_elevated, 1.25), + ("chart axis".into(), p.chart_axis, p.bg_elevated, 1.5), + ]; + // widgets::primary_button while pressed + pairs.push(( + "accent button label (pressed)".into(), + p.on_accent, + p.accent_fill_active, + TEXT, + )); + for (surface, fill) in [ + // slash palette and popup menu panels + ("bg_elevated", p.bg_elevated), + // hovered or keyboard-highlighted row + ("bg_sidebar_row_hover", p.bg_sidebar_row_hover), + // selected slash command, pressed menu row + ("bg_sidebar_row_selected", p.bg_sidebar_row_selected), + // widgets::status_badge (Remote computers' Updating) + ("bg_sidebar_pill", p.bg_sidebar_pill), + ] { + pairs.push(( + format!("accent text on {surface}"), + p.accent_text, + fill, + TEXT, + )); + } + for (surface, fill) in [ + ("bg_tool_card", p.bg_tool_card), + ("bg_app", p.bg_app), + ("bg_elevated", p.bg_elevated), + ] { + // tool status label + pairs.push(( + format!("running label on {surface}"), + p.status_running, + fill, + TEXT, + )); + } + for (surface, fill) in [ + ("bg_app", p.bg_app), + ("bg_elevated", p.bg_elevated), + ("bg_tool_card", p.bg_tool_card), + ("bg_user_bubble", p.bg_user_bubble), + ("bg_input", p.bg_input), + ("bg_sidebar", p.bg_sidebar), + ] { + // widgets::focus_ring and the composer's focus border + pairs.push((format!("focus ring on {surface}"), p.accent, fill, MARK)); + } + for (label, fg, bg, floor) in pairs { + let ratio = contrast(fg, bg); + if ratio >= floor { + continue; + } + if STOCK_EXEMPT.contains(&(id, label.as_str())) { + exempt_used.push((id, label)); + } else { + failures.push(format!("{id:?}: {label} is {ratio:.2}:1 (< {floor}:1)")); + } + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); + // An exemption that no longer fails should be removed from the list. + for (id, label) in STOCK_EXEMPT { + assert!( + exempt_used + .iter() + .any(|(used, used_label)| used == id && used_label == label), + "{id:?}: {label} now passes; drop its exemption" + ); + } + } } diff --git a/apps/maple-agent/app/src/ui/widgets.rs b/apps/maple-agent/app/src/ui/widgets.rs index ea37c60a4..78e6630e9 100644 --- a/apps/maple-agent/app/src/ui/widgets.rs +++ b/apps/maple-agent/app/src/ui/widgets.rs @@ -118,11 +118,11 @@ pub fn default_button(id: impl Into) -> HoverBackground { /// [`default_button`] for WCAG contrast until legacy callers migrate globally. pub fn primary_button(id: impl Into) -> HoverBackground { pill(id) - .bg(gpui::rgb(theme::accent())) + .bg(gpui::rgb(theme::accent_fill())) .text_color(gpui::rgb(theme::on_accent())) .hover(|style| style.cursor_pointer()) - .active(|style| press_depth(style.bg(gpui::rgb(theme::send_bottom())))) - .hover_bg(gpui::rgb(theme::accent_hover())) + .active(|style| press_depth(style.bg(gpui::rgb(theme::accent_fill_active())))) + .hover_bg(gpui::rgb(theme::accent_fill_hover())) } /// Neutral pill for the second action beside a [`primary_button`] /// (Cancel, Back, alternate sign-in): a pebble fill that darkens on hover. @@ -177,7 +177,7 @@ pub fn danger_button(id: impl Into) -> HoverBackground { let error: Hsla = gpui::rgb(theme::status_error()).into(); pill(id) .bg(error) - .text_color(gpui::rgb(theme::on_accent())) + .text_color(gpui::rgb(theme::on_error())) .hover(|style| style.cursor_pointer()) .active(|style| press_depth(style.opacity(0.85))) .hover_bg(gpui::hsla(error.h, error.s, error.l, 0.9)) @@ -342,7 +342,10 @@ const KNOB_TRAVEL: Pixels = px(34. - 2. * 3. - 14.); pub fn switch_track(on: bool) -> Div { let off_track: Hsla = gpui::rgb(theme::bg_sidebar_row_selected()).into(); let on_track = accent(); - let knob: Hsla = gpui::rgb(theme::on_accent()).into(); + // The knob has its own off color on the off track and takes the + // accent foreground on the accent track. + let knob_off: Hsla = gpui::rgb(theme::switch_knob_off()).into(); + let knob_on: Hsla = gpui::rgb(theme::on_accent()).into(); div() .flex_none() .w(px(34.)) @@ -366,7 +369,7 @@ pub fn switch_track(on: bool) -> Div { .debug_selector(|| "switch-knob".into()) .size(px(14.)) .rounded_full() - .bg(knob) + .bg(motion::mix(knob_off, knob_on, on)) .shadow_2xs(), ) .offset(gpui::point(KNOB_TRAVEL * on, px(0.))), diff --git a/apps/maple-agent/app/translation-revisions/de.txt b/apps/maple-agent/app/translation-revisions/de.txt index fbc2d9b84..45dba5d8b 100644 --- a/apps/maple-agent/app/translation-revisions/de.txt +++ b/apps/maple-agent/app/translation-revisions/de.txt @@ -1115,7 +1115,7 @@ settings-api-keys-see-plans 7e03b8e39f23e6ef settings-api-keys-unlock-api-access a90cb417d8f6464c settings-api-learn-more 06c6f22d1aac7c3e settings-appearance 63e047288ee0cb56 -settings-appearance-description 84484ee03a5c94e8 +settings-appearance-description 8eeb81e7ba9ce848 settings-appearance-subtitle c75b22e89b7b9857 settings-application-vim ecd8f5b842be0c94 settings-application-vim-description cc1b8b9e7bf4249c @@ -1246,7 +1246,7 @@ settings-integration-install-codex f2505116f461e834 settings-integration-version d94dbeea131c72f3 settings-keywords-about 14eb017c25602e9d settings-keywords-account 291c31da702e369d -settings-keywords-appearance 2810172f7551c986 +settings-keywords-appearance 3e0842f68c52369f settings-keywords-apps cf504915b2ac1282 settings-keywords-billing 2f018149058b669c settings-keywords-developer 136446487145060e @@ -1858,9 +1858,13 @@ settings-speech-voice a1bd6f42451aab37 settings-speech-voice-description 6e6cba09626879d8 settings-text-size aa4d8e4805ea9511 settings-text-size-description 5cd2782d7f3991c4 -settings-theme-label-dark aa6ad56172aedfb3 -settings-theme-label-light b07617440bda646d -settings-theme-label-system bccecf593daa2259 +settings-theme-label-americana f2b107dc181ca7e9 +settings-theme-label-cherry-blossom 5f629f7314d16472 +settings-theme-label-dark 46c9f4ff3736e822 +settings-theme-label-dracula a1d683e6bec14bd1 +settings-theme-label-light 521cdb5811a1d5ea +settings-theme-label-neon-dusk 2b55e88cd75a6e78 +settings-theme-label-system bb8127d04a5e76b2 settings-theme-motion 84bd2a0bffa4588d settings-title 90c87c9fc4bd308d settings-tool-details a5cbd93d86bbbab8 diff --git a/apps/maple-agent/app/translation-revisions/es.txt b/apps/maple-agent/app/translation-revisions/es.txt index fbc2d9b84..45dba5d8b 100644 --- a/apps/maple-agent/app/translation-revisions/es.txt +++ b/apps/maple-agent/app/translation-revisions/es.txt @@ -1115,7 +1115,7 @@ settings-api-keys-see-plans 7e03b8e39f23e6ef settings-api-keys-unlock-api-access a90cb417d8f6464c settings-api-learn-more 06c6f22d1aac7c3e settings-appearance 63e047288ee0cb56 -settings-appearance-description 84484ee03a5c94e8 +settings-appearance-description 8eeb81e7ba9ce848 settings-appearance-subtitle c75b22e89b7b9857 settings-application-vim ecd8f5b842be0c94 settings-application-vim-description cc1b8b9e7bf4249c @@ -1246,7 +1246,7 @@ settings-integration-install-codex f2505116f461e834 settings-integration-version d94dbeea131c72f3 settings-keywords-about 14eb017c25602e9d settings-keywords-account 291c31da702e369d -settings-keywords-appearance 2810172f7551c986 +settings-keywords-appearance 3e0842f68c52369f settings-keywords-apps cf504915b2ac1282 settings-keywords-billing 2f018149058b669c settings-keywords-developer 136446487145060e @@ -1858,9 +1858,13 @@ settings-speech-voice a1bd6f42451aab37 settings-speech-voice-description 6e6cba09626879d8 settings-text-size aa4d8e4805ea9511 settings-text-size-description 5cd2782d7f3991c4 -settings-theme-label-dark aa6ad56172aedfb3 -settings-theme-label-light b07617440bda646d -settings-theme-label-system bccecf593daa2259 +settings-theme-label-americana f2b107dc181ca7e9 +settings-theme-label-cherry-blossom 5f629f7314d16472 +settings-theme-label-dark 46c9f4ff3736e822 +settings-theme-label-dracula a1d683e6bec14bd1 +settings-theme-label-light 521cdb5811a1d5ea +settings-theme-label-neon-dusk 2b55e88cd75a6e78 +settings-theme-label-system bb8127d04a5e76b2 settings-theme-motion 84bd2a0bffa4588d settings-title 90c87c9fc4bd308d settings-tool-details a5cbd93d86bbbab8 diff --git a/apps/maple-agent/app/translation-revisions/ko.txt b/apps/maple-agent/app/translation-revisions/ko.txt index fbc2d9b84..45dba5d8b 100644 --- a/apps/maple-agent/app/translation-revisions/ko.txt +++ b/apps/maple-agent/app/translation-revisions/ko.txt @@ -1115,7 +1115,7 @@ settings-api-keys-see-plans 7e03b8e39f23e6ef settings-api-keys-unlock-api-access a90cb417d8f6464c settings-api-learn-more 06c6f22d1aac7c3e settings-appearance 63e047288ee0cb56 -settings-appearance-description 84484ee03a5c94e8 +settings-appearance-description 8eeb81e7ba9ce848 settings-appearance-subtitle c75b22e89b7b9857 settings-application-vim ecd8f5b842be0c94 settings-application-vim-description cc1b8b9e7bf4249c @@ -1246,7 +1246,7 @@ settings-integration-install-codex f2505116f461e834 settings-integration-version d94dbeea131c72f3 settings-keywords-about 14eb017c25602e9d settings-keywords-account 291c31da702e369d -settings-keywords-appearance 2810172f7551c986 +settings-keywords-appearance 3e0842f68c52369f settings-keywords-apps cf504915b2ac1282 settings-keywords-billing 2f018149058b669c settings-keywords-developer 136446487145060e @@ -1858,9 +1858,13 @@ settings-speech-voice a1bd6f42451aab37 settings-speech-voice-description 6e6cba09626879d8 settings-text-size aa4d8e4805ea9511 settings-text-size-description 5cd2782d7f3991c4 -settings-theme-label-dark aa6ad56172aedfb3 -settings-theme-label-light b07617440bda646d -settings-theme-label-system bccecf593daa2259 +settings-theme-label-americana f2b107dc181ca7e9 +settings-theme-label-cherry-blossom 5f629f7314d16472 +settings-theme-label-dark 46c9f4ff3736e822 +settings-theme-label-dracula a1d683e6bec14bd1 +settings-theme-label-light 521cdb5811a1d5ea +settings-theme-label-neon-dusk 2b55e88cd75a6e78 +settings-theme-label-system bb8127d04a5e76b2 settings-theme-motion 84bd2a0bffa4588d settings-title 90c87c9fc4bd308d settings-tool-details a5cbd93d86bbbab8 diff --git a/apps/maple-agent/docs/maple-theme-spec.md b/apps/maple-agent/docs/maple-theme-spec.md index 8754f6f33..7d5d08642 100644 --- a/apps/maple-agent/docs/maple-theme-spec.md +++ b/apps/maple-agent/docs/maple-theme-spec.md @@ -219,3 +219,41 @@ SF Mono, Menlo, Consolas. (`#2F2F37` to `#FF9771`). Buttons show focus with a 2 px `#FF9771` ring. - The coral `#FF9771` is the same in both themes. Only the "on primary" text changes (`#0A0A0A` dark, `#FFFFFF` light). + +## 12. Named themes + +Settings → Appearance offers Standard Maple (System), Maple Light, Maple Dark, +Dracula, Americana, Neon Dusk and Cherry Blossom. The saved `theme` setting is +the choice's stable ID (`system`, `light`, `dark`, `dracula`, `americana`, +`neon-dusk`, `cherry-blossom`). The first three IDs are the values earlier +versions saved, so upgrades keep their choice. An unknown ID draws as Standard +Maple and stays saved until the user picks another theme. + +`app/src/ui/theme.rs` resolves the choice to one complete palette by identity. +Every top-level window (main window, quit prompt, native dialogs, startup +error) calls `theme::sync_window` first in render and on OS appearance changes, +and the Linux portal update calls `theme::sync`, so a switch between two dark +themes, or an OS change while only a dialog is open, repaints every window. +Each named palette lists every role. `text_roles_read_on_every_surface` and +`rendered_pairs_meet_their_floors` pin the pairs the app actually draws: 4.5:1 +for labels, 3:1 for marks, knobs and focus rings. Error and success fills take +`on_error`/`on_success`, the switch's off knob and the slider thumb have their +own roles, and the legacy accent button fills with `accent_fill` +(`accent_fill_active` while pressed). `accent` is for marks, borders and +focus rings; text in the accent hue (slash commands, the Manage integrations +menu row, the Updating badge) uses `accent_text`. The stock +palettes predate these checks; their known shortfalls are listed in the test +rather than changed. Fixed themes set the native window appearance to their +lightness. Translucent overlays, shadows and monochrome marks still choose +black or white from `theme::is_light()`; the usage chart's series colors keep +their validated light and dark sets, while its gridlines follow the palette. + +Like the language preference, the theme lives in the local store's settings +and has no plaintext copy. At launch the main window waits, for at most +`STARTUP_THEME_DEADLINE` (400 ms), while the desktop asks the host for the +store status and, only when the store is Open, its settings snapshot; the +saved theme is applied before the first frame. A locked, damaged or +otherwise unopened store, a host error or the deadline opens the window at +once in Standard Maple, which stays until the store opens. Store lifecycle +events are handled unchanged; while the store is in transient Maintenance the +chosen palette stays on screen, and a lock resets it to Standard Maple.