From abbc836f796c7fbf3d1d677cd5b856e0f4302d9c Mon Sep 17 00:00:00 2001 From: JoyElliot <72300219+JoyElliot@users.noreply.github.com> Date: Tue, 22 Sep 2026 18:00:54 +0800 Subject: [PATCH 01/14] =?UTF-8?q?fix(startup):=20=E6=8F=90=E5=89=8D?= =?UTF-8?q?=E7=A1=AE=E5=AE=9A=E7=AA=97=E5=8F=A3=E5=B0=BA=E5=AF=B8=E5=B9=B6?= =?UTF-8?q?=E5=A4=8D=E7=94=A8=E7=9B=B8=E5=90=8C=E4=B8=BB=E9=A2=98=E5=9B=BE?= =?UTF-8?q?=E6=A0=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2026-09-22-first-frame-startup.md | 94 +++++++++++ nebula_app/AGENTS.md | 1 + nebula_app/src/display/program_identity.rs | 21 ++- nebula_app/src/gpui_shell/terminal/view.rs | 7 + .../gpui_shell/terminal/view/typography.rs | 32 +++- nebula_app/src/gpui_shell/workspace.rs | 92 +--------- nebula_app/src/gpui_shell/workspace/logos.rs | 85 ++++++++++ .../src/gpui_shell/workspace/windowing.rs | 17 +- .../workspace/windowing/startup_geometry.rs | 159 ++++++++++++++++++ nebula_app/src/platform/startup.rs | 27 +++ 10 files changed, 429 insertions(+), 106 deletions(-) create mode 100644 architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-first-frame-startup.md create mode 100644 nebula_app/src/gpui_shell/workspace/logos.rs create mode 100644 nebula_app/src/gpui_shell/workspace/windowing/startup_geometry.rs diff --git a/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-first-frame-startup.md b/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-first-frame-startup.md new file mode 100644 index 000000000..81a5a31f6 --- /dev/null +++ b/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-first-frame-startup.md @@ -0,0 +1,94 @@ +# First-frame geometry and repeated logo preparation + +## Status + +Proposed; Windows native startup measurements and focused regressions verified. + +## Context + +A regular window was created at 1080x720 logical pixels. Workspace construction +then measured the configured base font and asynchronously resized the window to +the 116x30 default grid plus chrome. GPUI exposes the native window before that +construction finishes, so synchronous logo preparation made the blank interval +and the later size jump especially visible in Debug builds. + +## Evidence + +On one Windows machine at 150% DPI, three fresh-config Debug launches spent +3.29-3.35 seconds between visible HWND and first painted controls. The HWND's UI +thread used 3.16-3.20 seconds in that interval; logo preparation used about 3.15 +seconds. Disabling blur retained the delay. Desktop Acrylic initialization and +attachment took 8-16 milliseconds in the instrumented material branch. + +Five of the ten embedded AI logos have identical source bytes and no tint for +either theme. Their full PNG decode, Lanczos3 resize and alpha-centering work was +performed twice per workspace/DPI. Sharing only those results reduced preparation +from 20 textures to 15 without changing the pixel pipeline. + +With the startup change and Desktop Acrylic combined, three Debug launches used +2.16-2.19 seconds of UI-thread CPU during a 2.19-2.27 second visible blank interval. +Every launch had one native bounds value from first visibility through settled +content. These are local measurements, not a Release or cross-machine guarantee. +The observer tracked only its launched process and HWND thread; unrelated system +CPU use was not counted. Pixel polling adds tens of milliseconds of uncertainty. + +## Decision + +- Keep PNG preparation, theme tint, Lanczos3 filtering, alpha centering and BGRA + conversion unchanged in `workspace/logos.rs`. Share immutable `Arc` + only where the identity catalog confirms an unchanged source and no theme tint. +- Keep textures owned by the workspace and rebuild them at its actual DPI. The + existing settings-logo synchronization and DPI render block remain authoritative. +- Put the common grid/chrome sizing rule in `windowing/startup_geometry.rs`. + On Windows, use the platform's primary-monitor DPI query and the existing font + shaping/rounding code before creating the native window. Clamp to the visible + work area and retain the 760x540 resize floor unless the display is smaller. +- Measure again with the actual window. Skip an asynchronous resize only when + sizes differ by less than one device pixel. Failed DPI preflight and unsupported + platforms retain the prior post-creation sizing policy; a changed DPI can still + require a corrective resize. +- Use base font metrics for window size and current zoom metrics for PTY grid + dimensions. Keep Quick Terminal's actual geometry and its animation ownership. + Do not alter show/focus/silent-start decisions or the PTY startup resize grace. + +## Rejected alternatives + +- Hiding the window until preparation finishes only conceals the CPU work and + changes activation/silent-start timing. +- Deferring logo work to workers introduces cancellation, DPI generations and + placeholder behavior. Avoid that lifecycle change for this bounded improvement. +- Smaller source assets or a different resize filter risk different icon edges. +- A process-global texture cache would need DPI/theme lifetime and eviction rules. +- Guessing display scale as 1.0 on unsupported platforms can create the wrong grid. +- Enabling optimization in the development profile changes build policy and hides + the cost without removing duplicate preparation. Release already optimizes it. + +## Consequences + +Debug startup still does synchronous image work and is not instant. The first +regular window is centered using its final size, instead of preserving the corner +of the old temporary rectangle. Small configured fonts retain a usable window +floor, and large work-area insets cannot make preflight sizing overflow that area. +The material implementation is independent: the change builds from upstream main +with Accent and was also exercised with the separate Acrylic branch. + +## Validation + +- Logo tests compare the omitted theme preparation pixel-for-pixel at 15 and 23 + physical pixels; they also check distinct theme outputs and texture ownership. +- Geometry tests cover the default grid, sidebar width, display caps, small fonts, + the minimum size, and subpixel rounding at 100/125/150/200% scale. +- Real Windows launches cover ordinary and blur-disabled startup, combined Acrylic + startup, a 4pt base font and persisted 28px zoom. Native bounds are sampled from + first visibility and diagnostic logs identify any fallback resize. +- Native macOS/Linux appearance, display changes during creation, and live Quick + Terminal/hide-to-tray interaction are not claimed by these measurements. + +## Supersedes + +None. + +## Revisit when + +GPUI exposes a portable pre-window display scale API; measured Release startup +still warrants asynchronous preparation; or logo source/tint behavior changes. diff --git a/nebula_app/AGENTS.md b/nebula_app/AGENTS.md index 96d053ef3..154f408cd 100644 --- a/nebula_app/AGENTS.md +++ b/nebula_app/AGENTS.md @@ -2,6 +2,7 @@ - 本目录是应用编排和适配层;依赖方向保持为 UI/组合 → 应用能力 → 共享领域规则,不在视图里复制设置、持久化、终端状态或协议状态机。 - `src/gpui_shell` 负责 GPUI 呈现、命令和订阅。交互改动必须覆盖默认、hover、pressed、键盘焦点、disabled/loading 以及成功/失败中实际需要的状态。 +- 首帧窗口尺寸与 logo 准备成本的因果记录见 [`workspace`](../architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-first-frame-startup.md)。 - 操作形成“触发 → 执行 → 可感知结果”的闭环。成功只能在操作真实完成或底层接口明确接受后显示,不能把回调触发当成平台级成功。 - 异步工作必须有所有者、取消/过期策略和视图销毁清理;旧结果不得覆盖新状态。渲染回调不得同步等待磁盘、网络、子进程或长锁。 - 新 UI 文案使用现有 typed message ID、命名占位符和回退合同,遵循 [`../docs/internationalization.md`](../docs/internationalization.md)。 diff --git a/nebula_app/src/display/program_identity.rs b/nebula_app/src/display/program_identity.rs index 418a207c9..ec84984cf 100644 --- a/nebula_app/src/display/program_identity.rs +++ b/nebula_app/src/display/program_identity.rs @@ -47,21 +47,30 @@ impl AiLogo { } } - pub(crate) fn tint_pixels(self, pixels: &mut [u8], ink: [u8; 3]) { - let preserve_luma = match self { - Self::OpenAi | Self::Pi => false, + fn tint_preserves_luma(self) -> Option { + match self { + Self::OpenAi | Self::Pi => Some(false), // OpenCode stores a luma map: the frame is white, the inner block gray. // Kimi's letterform is solid white with a small blue accent: embedded // unchanged it vanishes on light themes, so it rides the luma map too — // the K tracks the theme ink at full strength, the accent dims with it. - Self::OpenCode | Self::Kimi => true, + Self::OpenCode | Self::Kimi => Some(true), Self::Claude | Self::Grok | Self::Antigravity | Self::Trae | Self::OhMyPi - | Self::CodeBuddy => return, - }; + | Self::CodeBuddy => None, + } + } + + /// Reuse a prepared texture only when neither its source nor tint depends on theme. + pub(crate) fn shares_theme_texture(self) -> bool { + self.tint_preserves_luma().is_none() && std::ptr::eq(self.png(false), self.png(true)) + } + + pub(crate) fn tint_pixels(self, pixels: &mut [u8], ink: [u8; 3]) { + let Some(preserve_luma) = self.tint_preserves_luma() else { return }; for pixel in pixels.chunks_exact_mut(4) { let luma = if preserve_luma { u16::from(pixel[0]) } else { 255 }; for channel in 0..3 { diff --git a/nebula_app/src/gpui_shell/terminal/view.rs b/nebula_app/src/gpui_shell/terminal/view.rs index dea90ae9d..f01340a3e 100644 --- a/nebula_app/src/gpui_shell/terminal/view.rs +++ b/nebula_app/src/gpui_shell/terminal/view.rs @@ -495,6 +495,13 @@ impl TerminalView { typography::startup_cell_metrics(window, cx) } + pub(in crate::gpui_shell) fn startup_cell_metrics_at_scale( + scale: f32, + cx: &App, + ) -> (Pixels, Pixels) { + typography::startup_cell_metrics_at_scale(scale, cx) + } + pub(in crate::gpui_shell) fn set_output_visible( &mut self, visible: bool, diff --git a/nebula_app/src/gpui_shell/terminal/view/typography.rs b/nebula_app/src/gpui_shell/terminal/view/typography.rs index d6c173ee7..7b4fe9222 100644 --- a/nebula_app/src/gpui_shell/terminal/view/typography.rs +++ b/nebula_app/src/gpui_shell/terminal/view/typography.rs @@ -5,7 +5,8 @@ //! the startup grid from drifting away from the first prepainted frame. use gpui::{ - App, Font, FontFeatures, FontStyle, FontWeight, Hsla, Pixels, SharedString, TextRun, Window, px, + App, Font, FontFeatures, FontStyle, FontWeight, Hsla, Pixels, SharedString, TextRun, Window, + WindowTextSystem, px, }; use nebula_settings::CellWidthModeName; @@ -87,7 +88,8 @@ pub(super) fn line_height_for_view( } fn measure_cell_metrics( - window: &Window, + text_system: &WindowTextSystem, + scale: f32, family: &str, font_size: Pixels, mode: CellWidthModeName, @@ -96,7 +98,7 @@ fn measure_cell_metrics( line_height_multiplier: Option, ) -> (Pixels, Pixels) { let font = mono_font(family, FontWeight::NORMAL, FontStyle::Normal, false); - let sample = window.text_system().shape_line( + let sample = text_system.shape_line( SharedString::new_static("M"), font_size, &[TextRun { @@ -110,13 +112,13 @@ fn measure_cell_metrics( None, ); ( - effective_cell_width(sample.width.as_f32(), mode, window.scale_factor(), offset_x), + effective_cell_width(sample.width.as_f32(), mode, scale, offset_x), effective_line_height_with_theme( sample.ascent.as_f32() + sample.descent.as_f32(), font_size.as_f32(), line_height_multiplier, offset_y, - window.scale_factor(), + scale, ), ) } @@ -135,7 +137,8 @@ pub(super) fn cell_metrics(window: &Window, cx: &App) -> (Pixels, Pixels) { None => (REQUIRED_FONT_FAMILY, 15.0, CellWidthModeName::Compact, 0.0, 0.0, None), }; measure_cell_metrics( - window, + window.text_system(), + window.scale_factor(), family, px(font_size), mode, @@ -148,6 +151,20 @@ pub(super) fn cell_metrics(window: &Window, cx: &App) -> (Pixels, Pixels) { /// Startup sizing uses the configured base font, while a persisted terminal /// zoom only affects the live grid after the window has been created. pub(super) fn startup_cell_metrics(window: &Window, cx: &App) -> (Pixels, Pixels) { + measure_startup_cell_metrics(window.text_system(), window.scale_factor(), cx) +} + +/// The same font system and rounding rules can size a window before its HWND exists. +pub(super) fn startup_cell_metrics_at_scale(scale: f32, cx: &App) -> (Pixels, Pixels) { + let text_system = WindowTextSystem::new(cx.text_system().clone()); + measure_startup_cell_metrics(&text_system, scale, cx) +} + +fn measure_startup_cell_metrics( + text_system: &WindowTextSystem, + scale: f32, + cx: &App, +) -> (Pixels, Pixels) { let (family, font_size, mode, offset_x, offset_y, line_height_multiplier) = match cx.try_global::() { Some(settings) => ( @@ -161,7 +178,8 @@ pub(super) fn startup_cell_metrics(window: &Window, cx: &App) -> (Pixels, Pixels None => (REQUIRED_FONT_FAMILY, 15.0, CellWidthModeName::Compact, 0.0, 0.0, None), }; measure_cell_metrics( - window, + text_system, + scale, family, px(font_size), mode, diff --git a/nebula_app/src/gpui_shell/workspace.rs b/nebula_app/src/gpui_shell/workspace.rs index 241c375e6..d7b377b50 100644 --- a/nebula_app/src/gpui_shell/workspace.rs +++ b/nebula_app/src/gpui_shell/workspace.rs @@ -32,7 +32,6 @@ use gpui::{ SharedString, StatefulInteractiveElement as _, Styled as _, StyledImage as _, Subscription, Window, canvas, div, ease_out_quint, fill, img, px, relative, size, }; -use image::Frame; use crate::display::color::Rgb; use crate::gpui_shell::code_tab::CodeTabViewEvent; @@ -58,6 +57,8 @@ mod documents; mod file_tree; mod key_actions; mod launcher_menu; +mod logos; +use logos::sidebar_logo_images; mod notifications; mod palette; mod pane_header; @@ -264,46 +265,6 @@ type SplitBoundsStore = Rc), Bounds>>> /// 键:pane id(方向导航要拿所有叶子的屏幕矩形算最近邻)。 type PaneBoundsStore = Rc>>>; -fn decode_sidebar_logo( - logo: crate::display::AiLogo, - dark: bool, - target_size: u32, -) -> Option> { - let mut rgba = image::load_from_memory(logo.png(dark)).ok()?.into_rgba8(); - logo.tint_pixels(&mut rgba, if dark { [236, 239, 245] } else { [35, 40, 50] }); - // 直接复用旧壳的 Lanczos3 物理像素预缩放与 alpha 质量中心校正。 - // 先 tint 再缩放,避免 1024px 原图在 GPUI paint 阶段临时压到十几个 - // 逻辑像素时产生灰边、锯齿与非整数 DPI 采样。 - let (prepared, width, height) = crate::display::prepare_ai_logo_texture( - rgba.as_raw(), - rgba.width(), - rgba.height(), - target_size, - ); - let mut rgba = image::RgbaImage::from_raw(width, height, prepared)?; - // GPUI 的原始帧使用 BGRA;与壁纸解码走同一通道转换。 - for pixel in rgba.chunks_exact_mut(4) { - pixel.swap(0, 2); - } - Some(Arc::new(RenderImage::new([Frame::new(rgba)]))) -} - -fn sidebar_logo_images( - target_size: u32, -) -> HashMap<(crate::display::AiLogo, bool), Arc> { - use crate::display::AiLogo; - - let mut images = HashMap::new(); - for logo in AiLogo::ALL { - for dark in [false, true] { - if let Some(image) = decode_sidebar_logo(logo, dark, target_size) { - images.insert((logo, dark), image); - } - } - } - images -} - /// GPUI `Bounds` → `nebula_split::Rect`(同为窗口逻辑像素坐标系)。 fn to_split_rect(bounds: &Bounds) -> nebula_split::Rect { nebula_split::Rect::new( @@ -920,7 +881,7 @@ impl NebulaWorkspace { }) .detach(); } - let initial_grid = Self::prepare_initial_grid( + let initial_grid = windowing::prepare_initial_grid( window, cx, sidebar_width, @@ -1135,53 +1096,6 @@ impl NebulaWorkspace { this } - /// 默认窗口尺寸 = 旧壳默认画布 116×30 的反推(`display` 的 - /// `Dimensions` 默认值)。画布按配置基准字号定形;持久化缩放只参与 - /// 随后的实际行列反推,不能把缩放后的 116 列全加到启动窗宽上。 - /// 布局链横向:网格 + 侧栏 + 卡缝 p_2×2(16) + - /// 终端水平内边距 24;纵向:网格 + 标题栏 34(gpui-component - /// TITLE_BAR_HEIGHT)+ 卡缝 16 + 终端垂直内边距 16。各加 2px 余量让 - /// 浮点 floor 不缩行列;放不下的屏幕按 95% 工作区收拢(网格随之变小, - /// 与旧壳"开不下就小"同义)。 - fn prepare_initial_grid( - window: &mut Window, - cx: &mut App, - sidebar_width: f32, - fit_window_to_default_grid: bool, - ) -> (u16, u16) { - let (cell_w, line_h) = TerminalView::cell_metrics(window, cx); - let (startup_cell_w, startup_line_h) = TerminalView::startup_cell_metrics(window, cx); - // 标签栏位置只改变 chrome 内部布局,不能改变产品的默认外窗几何。 - // 顶栏模式仍保留与侧栏模式相同的横向预算,让两种模式启动时宽高一致。 - let chrome_w = sidebar_width + 16.0 + 24.0 + 2.0; - let chrome_h = 34.0 + 16.0 + 16.0 + 2.0; - let (w, h) = if fit_window_to_default_grid { - let mut w = f32::from(TerminalView::DEFAULT_GRID_COLUMNS) * f32::from(startup_cell_w) - + chrome_w; - let mut h = - f32::from(TerminalView::DEFAULT_GRID_LINES) * f32::from(startup_line_h) + chrome_h; - if let Some(display) = cx.primary_display() { - let bounds = display.bounds().size; - w = w.min(f32::from(bounds.width) * 0.95); - h = h.min(f32::from(bounds.height) * 0.95); - } - window.resize(size(px(w), px(h))); - (w, h) - } else { - // 快速终端的 WindowOptions 已经给出目标显示器全宽和 40% 高度。 - // 再排队一次普通网格 resize 会与原生滑入竞争,首帧 DComp 表面只 - // 覆盖旧宽度,右侧因此变黑。 - let bounds = window.bounds().size; - (f32::from(bounds.width), f32::from(bounds.height)) - }; - // 反推收拢后的目标网格:终端 spawn 直接用它,出生即最终几何, - // 启动路径零 ConPTY resize(resize 竞态会打乱 shell 首屏输出的 - // 坐标缓存,参见 set_layout 的启动稳定闸)。 - let cols = ((w - chrome_w) / f32::from(cell_w) + 0.001).floor().max(2.0) as u16; - let rows = ((h - chrome_h) / f32::from(line_h) + 0.001).floor().max(2.0) as u16; - (cols, rows) - } - /// `LaunchSession::Default` 的口语短标。 /// /// 这里不能再读运行时的“当前默认 Shell”:`Default` 已经是这个 Tab 创建 diff --git a/nebula_app/src/gpui_shell/workspace/logos.rs b/nebula_app/src/gpui_shell/workspace/logos.rs new file mode 100644 index 000000000..da8d37356 --- /dev/null +++ b/nebula_app/src/gpui_shell/workspace/logos.rs @@ -0,0 +1,85 @@ +//! DPI-specific sidebar textures, shared by tabs, panes and settings. + +use std::collections::HashMap; +use std::sync::Arc; + +use gpui::RenderImage; +use image::Frame; + +fn decode_sidebar_logo( + logo: crate::display::AiLogo, + dark: bool, + target_size: u32, +) -> Option> { + let mut rgba = image::load_from_memory(logo.png(dark)).ok()?.into_rgba8(); + logo.tint_pixels(&mut rgba, if dark { [236, 239, 245] } else { [35, 40, 50] }); + // 直接复用旧壳的 Lanczos3 物理像素预缩放与 alpha 质量中心校正。 + // 先 tint 再缩放,避免 1024px 原图在 GPUI paint 阶段临时压到十几个 + // 逻辑像素时产生灰边、锯齿与非整数 DPI 采样。 + let (prepared, width, height) = crate::display::prepare_ai_logo_texture( + rgba.as_raw(), + rgba.width(), + rgba.height(), + target_size, + ); + let mut rgba = image::RgbaImage::from_raw(width, height, prepared)?; + // GPUI 的原始帧使用 BGRA;与壁纸解码走同一通道转换。 + for pixel in rgba.chunks_exact_mut(4) { + pixel.swap(0, 2); + } + Some(Arc::new(RenderImage::new([Frame::new(rgba)]))) +} + +pub(super) fn sidebar_logo_images( + target_size: u32, +) -> HashMap<(crate::display::AiLogo, bool), Arc> { + use crate::display::AiLogo; + + let mut images = HashMap::new(); + for logo in AiLogo::ALL { + if logo.shares_theme_texture() { + if let Some(image) = decode_sidebar_logo(logo, false, target_size) { + images.insert((logo, false), image.clone()); + images.insert((logo, true), image); + } + continue; + } + for dark in [false, true] { + if let Some(image) = decode_sidebar_logo(logo, dark, target_size) { + images.insert((logo, dark), image); + } + } + } + images +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::display::AiLogo; + + #[test] + fn sidebar_logos_share_only_identical_theme_pixels_at_each_dpi() { + // 100% and 150% DPI keep separate physical textures. There is no global cache. + for target in [15, 23] { + let images = sidebar_logo_images(target); + assert_eq!(images.len(), AiLogo::ALL.len() * 2); + let unique = images.values().map(Arc::as_ptr).collect::>(); + assert_eq!(unique.len(), 15, "five color assets must not be prepared twice"); + for logo in AiLogo::ALL { + let light = &images[&(logo, false)]; + let dark = &images[&(logo, true)]; + assert_eq!(u32::from(light.size(0).width), target); + assert_eq!(u32::from(dark.size(0).height), target); + if Arc::ptr_eq(light, dark) { + // Compare the omitted dark preparation against the actual output, + // so a later asset/tint change cannot silently change its pixels. + let reference = decode_sidebar_logo(logo, true, target).unwrap(); + assert_eq!(dark.as_bytes(0), reference.as_bytes(0), "{logo:?}"); + } else { + assert_ne!(light.as_bytes(0), dark.as_bytes(0), "{logo:?}"); + } + } + } + } +} diff --git a/nebula_app/src/gpui_shell/workspace/windowing.rs b/nebula_app/src/gpui_shell/workspace/windowing.rs index 8bf78b2df..7bd72240d 100644 --- a/nebula_app/src/gpui_shell/workspace/windowing.rs +++ b/nebula_app/src/gpui_shell/workspace/windowing.rs @@ -6,6 +6,8 @@ mod shutdown; pub(crate) use shutdown::{quit_all, quit_for_update}; +mod startup_geometry; +pub(super) use startup_geometry::prepare_initial_grid; #[cfg(windows)] mod quick_window; @@ -416,10 +418,16 @@ pub(super) fn open_recipe_window(session: crate::session::Session, cx: &mut App) }); } -fn workspace_window_options(cx: &mut App, focus: bool, role: WindowRole) -> WindowOptions { +fn workspace_window_options( + cx: &mut App, + focus: bool, + role: WindowRole, + sidebar_width: f32, +) -> WindowOptions { match role { WindowRole::Regular => { - let preferred = size(px(1080.0), px(720.0)); + let preferred = startup_geometry::preferred_size(cx, sidebar_width) + .unwrap_or_else(|| size(px(1080.0), px(720.0))); let bounds = cx.primary_display().map_or_else( || Bounds::centered(None, preferred, cx), |display| { @@ -499,10 +507,11 @@ fn open_workspace_window( role: WindowRole, ) -> gpui::Result<(u64, Entity)> { let (runtime_window_id, runtime_hub) = allocate_window(cx); + let runtime = nebula_settings::RuntimeSettings::load(); let start_hidden = shell_events.is_some() && matches!(startup, WorkspaceStartup::RestoreOrDefault) - && crate::platform::startup::start_hidden(&nebula_settings::RuntimeSettings::load()); - let mut options = workspace_window_options(cx, focus, role); + && crate::platform::startup::start_hidden(&runtime); + let mut options = workspace_window_options(cx, focus, role, runtime.sidebar_width); if start_hidden { options.show = false; options.focus = false; diff --git a/nebula_app/src/gpui_shell/workspace/windowing/startup_geometry.rs b/nebula_app/src/gpui_shell/workspace/windowing/startup_geometry.rs new file mode 100644 index 000000000..ec225ae28 --- /dev/null +++ b/nebula_app/src/gpui_shell/workspace/windowing/startup_geometry.rs @@ -0,0 +1,159 @@ +//! One sizing rule for the initial native window and its first terminal grid. +//! +//! Measure the configured base font, not persisted terminal zoom. Where the +//! platform exposes display DPI, supply the final size before the window is +//! shown; otherwise keep the existing post-creation sizing fallback. + +use gpui::{App, Pixels, Size, Window, px, size}; + +use crate::gpui_shell::terminal::view::TerminalView; + +fn chrome_size(sidebar_width: f32) -> Size { + // Sidebar, gutters, terminal padding and the existing 2px rounding allowance. + size(px(sidebar_width + 16.0 + 24.0 + 2.0), px(34.0 + 16.0 + 16.0 + 2.0)) +} + +fn default_size( + metrics: (Pixels, Pixels), + sidebar_width: f32, + display_limit: Option>, +) -> Size { + let chrome = chrome_size(sidebar_width); + let preferred = size( + metrics.0 * f32::from(TerminalView::DEFAULT_GRID_COLUMNS) + chrome.width, + metrics.1 * f32::from(TerminalView::DEFAULT_GRID_LINES) + chrome.height, + ); + display_limit.map_or(preferred, |limit| preferred.min(&limit)) +} + +fn display_limit(cx: &App) -> Option> { + cx.primary_display().map(|display| { + let bounds = display.bounds().size; + size(bounds.width * 0.95, bounds.height * 0.95) + }) +} + +fn fit_native_size(preferred: Size, visible: Option>) -> Size { + // Keep the existing resize floor even for a very small configured font. + // A display smaller than that floor still owns the upper bound. + let preferred = preferred.max(&size(px(760.0), px(540.0))); + visible.map_or(preferred, |visible| preferred.min(&visible)) +} + +fn fit_preflight_size(preferred: Size, cx: &App) -> Size { + fit_native_size(preferred, cx.primary_display().map(|display| display.visible_bounds().size)) +} + +pub(super) fn preferred_size(cx: &App, sidebar_width: f32) -> Option> { + let scale = crate::platform::startup::primary_display_scale()?; + Some(fit_preflight_size( + default_size( + TerminalView::startup_cell_metrics_at_scale(scale, cx), + sidebar_width, + display_limit(cx), + ), + cx, + )) +} + +fn same_device_size(actual: Size, requested: Size, scale: f32) -> bool { + // Window placement quantizes logical sizes to device pixels. A subpixel + // round-trip difference must not schedule a second asynchronous SetWindowPos. + (f32::from(actual.width - requested.width) * scale).abs() < 1.0 + && (f32::from(actual.height - requested.height) * scale).abs() < 1.0 +} + +pub(in crate::gpui_shell::workspace) fn prepare_initial_grid( + window: &mut Window, + cx: &mut App, + sidebar_width: f32, + fit_window_to_default_grid: bool, +) -> (u16, u16) { + let (cell_w, line_h) = TerminalView::cell_metrics(window, cx); + let actual = window.bounds().size; + let target = if fit_window_to_default_grid { + let requested = default_size( + TerminalView::startup_cell_metrics(window, cx), + sidebar_width, + display_limit(cx), + ); + let requested = if crate::platform::startup::primary_display_scale().is_some() { + fit_preflight_size(requested, cx) + } else { + // Keep the original sizing policy on platforms without preflight DPI. + requested + }; + if same_device_size(actual, requested, window.scale_factor()) { + actual + } else { + // DPI changes during creation, failed preflight and unsupported + // platforms retain the measured-window fallback instead of guessing. + window.resize(requested); + requested + } + } else { + // Quick Terminal owns its monitor geometry and slide-in animation. + actual + }; + let chrome = chrome_size(sidebar_width); + let cols = ((f32::from(target.width - chrome.width) / f32::from(cell_w)) + 0.001) + .floor() + .max(2.0) as u16; + let rows = ((f32::from(target.height - chrome.height) / f32::from(line_h)) + 0.001) + .floor() + .max(2.0) as u16; + (cols, rows) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn initial_window_keeps_the_base_font_grid_and_fits_the_display() { + let metrics = (px(8.0), px(20.0)); + assert_eq!(default_size(metrics, 230.0, None), size(px(1200.0), px(668.0))); + assert_eq!( + default_size(metrics, 230.0, Some(size(px(1000.0), px(600.0)))), + size(px(1000.0), px(600.0)), + ); + assert_eq!(default_size(metrics, 300.0, None), size(px(1270.0), px(668.0)),); + } + + #[test] + fn startup_size_skips_only_device_pixel_rounding_differences() { + let requested = size(px(1200.0), px(668.0)); + for scale in [1.0, 1.25, 1.5, 2.0] { + assert!(same_device_size(requested, requested, scale)); + assert!(same_device_size( + size(requested.width + px(0.5 / scale), requested.height), + requested, + scale, + )); + assert!(!same_device_size(size(px(1080.0), px(720.0)), requested, scale)); + assert!(!same_device_size( + size(requested.width + px(2.0 / scale), requested.height), + requested, + scale, + )); + } + } + + #[test] + fn small_fonts_keep_the_resize_floor_unless_the_display_is_smaller() { + let small_font = size(px(504.0), px(248.0)); + assert_eq!(fit_native_size(small_font, None), size(px(760.0), px(540.0))); + assert_eq!( + fit_native_size(small_font, Some(size(px(1920.0), px(1040.0)))), + size(px(760.0), px(540.0)), + ); + assert_eq!( + fit_native_size(small_font, Some(size(px(640.0), px(480.0)))), + size(px(640.0), px(480.0)), + ); + assert_eq!( + fit_native_size(size(px(1200.0), px(668.0)), Some(size(px(1000.0), px(600.0)))), + size(px(1000.0), px(600.0)), + ); + } +} diff --git a/nebula_app/src/platform/startup.rs b/nebula_app/src/platform/startup.rs index 0d5f4d94d..a6dacf52b 100644 --- a/nebula_app/src/platform/startup.rs +++ b/nebula_app/src/platform/startup.rs @@ -9,6 +9,33 @@ pub(crate) fn report_error(error: &dyn std::fmt::Display, gui_launch: bool) { #[cfg(windows)] mod console; +/// Match GPUI's primary-monitor DPI query before a native window is created. +/// Other platforms retain post-creation sizing until their display API exposes scale. +pub(crate) fn primary_display_scale() -> Option { + #[cfg(windows)] + { + use windows_sys::Win32::Foundation::POINT; + use windows_sys::Win32::Graphics::Gdi::{MONITOR_DEFAULTTOPRIMARY, MonitorFromPoint}; + use windows_sys::Win32::UI::HiDpi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI}; + + // SAFETY: the monitor is borrowed and both DPI outputs are valid local pointers. + unsafe { + let monitor = MonitorFromPoint(POINT { x: 0, y: 0 }, MONITOR_DEFAULTTOPRIMARY); + let (mut x, mut y) = (0, 0); + if monitor.is_null() + || GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut x, &mut y) < 0 + || x == 0 + || x != y + { + return None; + } + Some(x as f32 / 96.0) + } + } + #[cfg(not(windows))] + None +} + /// Prepare process-wide GUI state before worker threads or terminal children exist. pub(crate) fn prepare_gui_process() -> std::io::Result<()> { #[cfg(windows)] From fc39fdf580351acb4ea95e318b426afb5204ab4a Mon Sep 17 00:00:00 2001 From: JoyElliot <72300219+JoyElliot@users.noreply.github.com> Date: Tue, 22 Sep 2026 20:11:02 +0800 Subject: [PATCH 02/14] =?UTF-8?q?fix(startup):=20=E5=90=8E=E5=8F=B0?= =?UTF-8?q?=E5=87=86=E5=A4=87=E5=9B=BE=E6=A0=87=E5=B9=B6=E5=9C=A8=E9=A6=96?= =?UTF-8?q?=E5=B8=A7=E5=91=88=E7=8E=B0=E5=90=8E=E6=98=BE=E7=A4=BA=E7=AA=97?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2026-09-22-first-frame-startup.md | 3 + .../2026-09-22-nonblocking-first-frame.md | 97 +++++++++++++++ nebula_app/AGENTS.md | 2 +- nebula_app/src/gpui_shell/workspace.rs | 13 +- nebula_app/src/gpui_shell/workspace/logos.rs | 116 +++++++++++++++++- .../src/gpui_shell/workspace/pane_header.rs | 13 +- .../workspace/settings_navigation.rs | 1 + .../src/gpui_shell/workspace/sidebar.rs | 6 +- .../gpui_shell/workspace/tab_presentation.rs | 10 +- .../src/gpui_shell/workspace/top_tabs.rs | 3 +- .../src/gpui_shell/workspace/windowing.rs | 4 + nebula_app/src/platform/startup.rs | 2 + .../src/platform/startup/first_frame.rs | 64 ++++++++++ 13 files changed, 307 insertions(+), 27 deletions(-) create mode 100644 architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-nonblocking-first-frame.md create mode 100644 nebula_app/src/platform/startup/first_frame.rs diff --git a/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-first-frame-startup.md b/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-first-frame-startup.md index 81a5a31f6..97bd58307 100644 --- a/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-first-frame-startup.md +++ b/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-first-frame-startup.md @@ -1,5 +1,8 @@ # First-frame geometry and repeated logo preparation +Superseded in its synchronous-preparation choice by +[nonblocking first frame](2026-09-22-nonblocking-first-frame.md); geometry remains. + ## Status Proposed; Windows native startup measurements and focused regressions verified. diff --git a/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-nonblocking-first-frame.md b/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-nonblocking-first-frame.md new file mode 100644 index 000000000..5bf1485fc --- /dev/null +++ b/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-nonblocking-first-frame.md @@ -0,0 +1,97 @@ +# Nonblocking logo preparation and first presentation + +## Status + +Proposed; Windows native launch probes and targeted regression tests passed. + +## Context + +The initial first-frame change computed final geometry before creating the HWND +and removed duplicate logo work, but still prepared the remaining 15 textures on +the UI thread. Debug startup consequently retained about two seconds of blank +window time. The user requires usable content without waiting for those textures. + +The Acrylic-only test package did not contain that separate startup branch. +Combined test packages must identify both changes; material and startup ownership +remain separate from the packaging integration branch. + +## Evidence + +- Pinned GPUI `App::open_window` builds/draws the initial scene after the Windows + platform constructor has already shown its HWND. That draw does not present. +- `on_next_frame` callbacks and effects deferred from them run before present; + they are not completion notifications. Windows has no frame waker, and ordinary + invalidation of a hidden HWND does not guarantee delivery of its first paint. +- GPUI Windows handles `WM_PAINT` synchronously through its frame callback, which + presents an initial pending scene even while the window is hidden. +- In isolated Debug launches with the combined material/startup code, first paint + completed before visibility. The first full screenshots contained the controls; + sampled native bounds stayed constant through settled content. UI-thread CPU + from process start to visibility was about 0.52-0.59 seconds. Logo CPU work + continued on the worker after the UI became usable. Windows' opening animation + still affects early screen pixels; an HWND visibility event is not a screenshot. + +## Decision + +- A workspace-owned `LogoLoad` prepares the existing pixel pipeline on the + background executor. Its UI task holds a weak entity and returns pixels into a + ready slot. Render consumes ready pixels and keeps the existing settings sync + call; it never waits for decoding. +- Each request carries target physical pixels and a generation. Replacing or + dropping its task signals cooperative cancellation between images. An image + already decoding can finish; its stale result cannot update a newer request. +- Initial missing brand images use the existing glyph fallback in exactly the + eventual image width. A DPI transition keeps its prior image while replacement + is pending, avoiding a flash back to a different glyph. This can briefly resample + the old DPI texture; no old-generation result is committed afterward. +- Only visible, focused Windows windows defer their initial show. The caller + leaves silent-start, background-created windows and Quick Terminal unchanged. +- After window creation and deferred material setup, schedule a foreground task. + Resolve the live HWND in a short GPUI update, leave that App/Window borrow, then + synchronously send `WM_PAINT`. After its handler returns, activate through GPUI + to consume pending placement and honor the original focus request. + +## Rejected alternatives + +- A fixed sleep or next-frame/defer callback cannot prove a frame was presented. +- Raw `ShowWindow` would leave GPUI's pending initial placement unconsumed and + could reset geometry at later activation. +- Making every window activate would break background and silent-start behavior. +- A synchronous decode before showing merely relocates the startup stall. +- New image filters, rescaled source assets or persistent caches would change + visual output or introduce unrelated cache/version/persistence policy. + +## Consequences + +No new thread pool, timer, per-frame native operation or global logo cache is +introduced. Each window owns at most one publishing request. Cancelled synchronous +image work is bounded by the current image; it does not mutate UI state. + +The presentation adapter depends on the pinned GPUI Windows paint path. Its native +message must run outside any App/Window borrow, on the foreground thread. A queued +task resolves a still-live GPUI handle and cannot revive a destroyed workspace. +Windows' normal opening animation remains enabled. + +## Validation + +- Pixel comparisons at 15px/23px preserve the previous PNG/tint/filter output. +- Replaced/DPI-returning requests reject old generations; dropping a request + signals cancellation, and a pre-cancelled worker does not decode images. +- Option tests cover visible/hidden and focused/background combinations. +- Geometry and the first-PTY-size/maximize regression remain passing. +- Native launch screenshots/logs distinguish completed first paint, HWND visibility + and compositor animation; blur-disabled launches use the same presentation path. +- macOS/Linux retain their original show path. Their native appearance is not + claimed by Windows probes; Quick Terminal interaction requires separate native + coverage when that path is changed. + +## Supersedes + +The synchronous-preparation choice in +[the initial first-frame note](2026-09-22-first-frame-startup.md). +Its base-font geometry, zoom/grid ownership and per-window texture sharing remain. + +## Revisit when + +GPUI changes `WM_PAINT`, frame throttling or presentation ownership, adds a public +post-present show API, or the product needs a shared cross-window texture cache. diff --git a/nebula_app/AGENTS.md b/nebula_app/AGENTS.md index 154f408cd..3c03223b3 100644 --- a/nebula_app/AGENTS.md +++ b/nebula_app/AGENTS.md @@ -2,7 +2,7 @@ - 本目录是应用编排和适配层;依赖方向保持为 UI/组合 → 应用能力 → 共享领域规则,不在视图里复制设置、持久化、终端状态或协议状态机。 - `src/gpui_shell` 负责 GPUI 呈现、命令和订阅。交互改动必须覆盖默认、hover、pressed、键盘焦点、disabled/loading 以及成功/失败中实际需要的状态。 -- 首帧窗口尺寸与 logo 准备成本的因果记录见 [`workspace`](../architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-first-frame-startup.md)。 +- 首帧窗口尺寸、非阻塞 logo 准备与原生呈现顺序的因果记录见 [`workspace`](../architecture/notes/nebula_app/gpui_shell/workspace/)。 - 操作形成“触发 → 执行 → 可感知结果”的闭环。成功只能在操作真实完成或底层接口明确接受后显示,不能把回调触发当成平台级成功。 - 异步工作必须有所有者、取消/过期策略和视图销毁清理;旧结果不得覆盖新状态。渲染回调不得同步等待磁盘、网络、子进程或长锁。 - 新 UI 文案使用现有 typed message ID、命名占位符和回退合同,遵循 [`../docs/internationalization.md`](../docs/internationalization.md)。 diff --git a/nebula_app/src/gpui_shell/workspace.rs b/nebula_app/src/gpui_shell/workspace.rs index d7b377b50..32162e0cf 100644 --- a/nebula_app/src/gpui_shell/workspace.rs +++ b/nebula_app/src/gpui_shell/workspace.rs @@ -58,7 +58,6 @@ mod file_tree; mod key_actions; mod launcher_menu; mod logos; -use logos::sidebar_logo_images; mod notifications; mod palette; mod pane_header; @@ -783,6 +782,7 @@ pub struct NebulaWorkspace { sidebar_logo_images: HashMap<(crate::display::AiLogo, bool), Arc>, /// 品牌图缓存对应的整数物理像素边长;窗口跨 DPI 显示器时据此重建。 sidebar_logo_target_px: u32, + sidebar_logo_load: logos::LogoLoad, /// 跟随系统深浅:OS 外观切换的监听(旧壳 ThemeChanged 的对应物)。 _appearance_sub: Subscription, /// spinner 在窗口失焦时冻结为静态状态;重新聚焦后由一次 render 恢复按需帧循环。 @@ -942,8 +942,6 @@ impl NebulaWorkspace { cx.subscribe_in(&command_manager_input, window, Self::on_command_manager_input_event); let file_tree_search_subscription = cx.subscribe_in(&file_tree_search_input, window, Self::on_file_tree_search_event); - let sidebar_logo_target_px = - (TAB_LABEL_ICON_SIZE * window.scale_factor()).round().max(1.0) as u32; let mut this = Self { tabs: Vec::new(), tab_meta: Vec::new(), @@ -1022,8 +1020,9 @@ impl NebulaWorkspace { remote_files_scroll: gpui::UniformListScrollHandle::new(), tab_menu: None, selection_context_menu: None, - sidebar_logo_images: sidebar_logo_images(sidebar_logo_target_px), - sidebar_logo_target_px, + sidebar_logo_images: HashMap::new(), + sidebar_logo_target_px: 0, + sidebar_logo_load: logos::LogoLoad::default(), _appearance_sub: appearance_sub, spinner_window_active, _spinner_activation_sub: spinner_activation_sub, @@ -3023,10 +3022,10 @@ impl Render for NebulaWorkspace { let draw_file_divider = self.side_panel.open; let sidebar_logo_target_px = (TAB_LABEL_ICON_SIZE * window.scale_factor()).round().max(1.0) as u32; - if sidebar_logo_target_px != self.sidebar_logo_target_px { + if let Some(images) = logos::poll_sidebar_logo_images(self, sidebar_logo_target_px, cx) { // GPUI 窗口可跨不同 DPI 的显示器;原纹理只在整数物理像素尺寸 // 变化时重建,普通 render 不重复解码 PNG。 - self.sidebar_logo_images = sidebar_logo_images(sidebar_logo_target_px); + self.sidebar_logo_images = images; self.sidebar_logo_target_px = sidebar_logo_target_px; self.sync_settings_agent_logos(cx); } diff --git a/nebula_app/src/gpui_shell/workspace/logos.rs b/nebula_app/src/gpui_shell/workspace/logos.rs index da8d37356..ed96c2a83 100644 --- a/nebula_app/src/gpui_shell/workspace/logos.rs +++ b/nebula_app/src/gpui_shell/workspace/logos.rs @@ -2,10 +2,87 @@ use std::collections::HashMap; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; -use gpui::RenderImage; +use gpui::{Context, RenderImage, Task}; use image::Frame; +use super::NebulaWorkspace; + +type LogoImages = HashMap<(crate::display::AiLogo, bool), Arc>; + +#[derive(Default)] +pub(super) struct LogoLoad { + target: u32, + generation: u64, + pending: Option, + ready: Option, +} + +struct PendingLoad { + cancelled: Arc, + _task: Task<()>, +} + +impl Drop for PendingLoad { + fn drop(&mut self) { + // A synchronous decode already running on a worker cannot be preempted; + // stop between images, and drop the foreground task that would publish it. + self.cancelled.store(true, Ordering::Relaxed); + } +} + +impl LogoLoad { + fn reset(&mut self, target: u32) -> u64 { + self.pending = None; + self.ready = None; + self.target = target; + self.generation = self.generation.wrapping_add(1); + self.generation + } + + fn complete(&mut self, target: u32, generation: u64, images: LogoImages) -> bool { + if self.target != target || self.generation != generation { + return false; + } + self.ready = Some(images); + true + } +} + +/// Render consumes already prepared pixels; it never decodes or waits for a worker. +pub(super) fn poll_sidebar_logo_images( + workspace: &mut NebulaWorkspace, + target: u32, + cx: &mut Context, +) -> Option { + let load = &mut workspace.sidebar_logo_load; + if target == workspace.sidebar_logo_target_px { + if load.target != target { + load.reset(target); + } + return None; + } + if load.target != target { + let generation = load.reset(target); + let cancelled = Arc::new(AtomicBool::new(false)); + let worker_cancelled = cancelled.clone(); + let worker = cx + .background_executor() + .spawn(async move { sidebar_logo_images(target, &worker_cancelled) }); + let task = cx.spawn(async move |workspace, cx| { + let Some(images) = worker.await else { return }; + let _ = workspace.update(cx, |workspace, cx| { + if workspace.sidebar_logo_load.complete(target, generation, images) { + cx.notify(); + } + }); + }); + load.pending = Some(PendingLoad { cancelled, _task: task }); + } + load.ready.take() +} + fn decode_sidebar_logo( logo: crate::display::AiLogo, dark: bool, @@ -30,13 +107,14 @@ fn decode_sidebar_logo( Some(Arc::new(RenderImage::new([Frame::new(rgba)]))) } -pub(super) fn sidebar_logo_images( - target_size: u32, -) -> HashMap<(crate::display::AiLogo, bool), Arc> { +fn sidebar_logo_images(target_size: u32, cancelled: &AtomicBool) -> Option { use crate::display::AiLogo; let mut images = HashMap::new(); for logo in AiLogo::ALL { + if cancelled.load(Ordering::Relaxed) { + return None; + } if logo.shares_theme_texture() { if let Some(image) = decode_sidebar_logo(logo, false, target_size) { images.insert((logo, false), image.clone()); @@ -45,12 +123,15 @@ pub(super) fn sidebar_logo_images( continue; } for dark in [false, true] { + if cancelled.load(Ordering::Relaxed) { + return None; + } if let Some(image) = decode_sidebar_logo(logo, dark, target_size) { images.insert((logo, dark), image); } } } - images + Some(images) } #[cfg(test)] @@ -62,7 +143,7 @@ mod tests { fn sidebar_logos_share_only_identical_theme_pixels_at_each_dpi() { // 100% and 150% DPI keep separate physical textures. There is no global cache. for target in [15, 23] { - let images = sidebar_logo_images(target); + let images = sidebar_logo_images(target, &AtomicBool::new(false)).unwrap(); assert_eq!(images.len(), AiLogo::ALL.len() * 2); let unique = images.values().map(Arc::as_ptr).collect::>(); assert_eq!(unique.len(), 15, "five color assets must not be prepared twice"); @@ -82,4 +163,27 @@ mod tests { } } } + + #[test] + fn superseded_dpi_results_cannot_replace_the_current_request() { + let mut load = LogoLoad::default(); + let old = load.reset(15); + let current = load.reset(23); + assert!(!load.complete(15, old, HashMap::new())); + assert!(load.ready.is_none()); + assert!(load.complete(23, current, HashMap::new())); + let newest = load.reset(15); + assert!(load.ready.is_none()); + assert!(!load.complete(15, old, HashMap::new()), "same DPI does not revive an old job"); + assert!(load.complete(15, newest, HashMap::new())); + } + + #[test] + fn releasing_or_replacing_a_load_cancels_further_image_work() { + let cancelled = Arc::new(AtomicBool::new(false)); + let pending = PendingLoad { cancelled: cancelled.clone(), _task: Task::ready(()) }; + drop(pending); + assert!(cancelled.load(Ordering::Relaxed)); + assert!(sidebar_logo_images(23, &cancelled).is_none()); + } } diff --git a/nebula_app/src/gpui_shell/workspace/pane_header.rs b/nebula_app/src/gpui_shell/workspace/pane_header.rs index f5a7c6e04..28bf4894a 100644 --- a/nebula_app/src/gpui_shell/workspace/pane_header.rs +++ b/nebula_app/src/gpui_shell/workspace/pane_header.rs @@ -202,6 +202,7 @@ fn broadcast_mark(side: f32, color: Hsla) -> impl IntoElement { /// 一个 pane 的标题信息:图标(AI 品牌图 / Nerd Font 字位)+ 一行标题。 struct PaneTitle { logo: Option>, + logo_pending: bool, glyph: Option<&'static str>, text: SharedString, } @@ -215,10 +216,9 @@ impl NebulaWorkspace { .running_program .clone() .or_else(|| view.ai_session.as_ref().map(|identity| identity.source.clone())); - let logo = program - .as_deref() - .and_then(crate::display::ai_logo_for_program) - .and_then(|logo| self.sidebar_logo_images.get(&(logo, dark)).cloned()); + let brand_logo = program.as_deref().and_then(crate::display::ai_logo_for_program); + let logo = brand_logo.and_then(|logo| self.sidebar_logo_images.get(&(logo, dark)).cloned()); + let logo_pending = brand_logo.is_some() && logo.is_none(); let glyph = program .as_deref() .filter(|_| logo.is_none()) @@ -229,7 +229,7 @@ impl NebulaWorkspace { (None, Some(destination)) => SharedString::from(destination.clone()), (None, None) => SharedString::from(view.tab_label()), }; - PaneTitle { logo, glyph, text } + PaneTitle { logo, logo_pending, glyph, text } } /// 一个 pane 的标题条。左区整条是切焦点的命中区,右区三枚按钮各自 @@ -262,7 +262,7 @@ impl NebulaWorkspace { let symbol_family: SharedString = crate::font_install::REQUIRED_FONT_FAMILY.into(); let label_px = settings.map(|settings| settings.ui_font_size_px).unwrap_or(15.0); let title_px = label_px * 0.78; - let PaneTitle { logo, glyph, text } = self.pane_title(view, cx, dark); + let PaneTitle { logo, logo_pending, glyph, text } = self.pane_title(view, cx, dark); let group: SharedString = format!("pane-header-{pane_id}").into(); let icon_ink = if focused { ink } else { muted }; @@ -330,6 +330,7 @@ impl NebulaWorkspace { .when_some(glyph, |grip, glyph| { grip.child( div() + .when(logo_pending, |slot| slot.w(px(title_px))) .flex_shrink_0() .font_family(symbol_family) .text_size(px(title_px)) diff --git a/nebula_app/src/gpui_shell/workspace/settings_navigation.rs b/nebula_app/src/gpui_shell/workspace/settings_navigation.rs index 843670777..4269ef998 100644 --- a/nebula_app/src/gpui_shell/workspace/settings_navigation.rs +++ b/nebula_app/src/gpui_shell/workspace/settings_navigation.rs @@ -137,6 +137,7 @@ impl NebulaWorkspace { is_settings: true, activity: SidebarActivity::Idle, logo_image: None, + logo_pending: false, program_glyph: None, shell_tag: None, color: None, diff --git a/nebula_app/src/gpui_shell/workspace/sidebar.rs b/nebula_app/src/gpui_shell/workspace/sidebar.rs index 6ee9b7ae4..ac5863282 100644 --- a/nebula_app/src/gpui_shell/workspace/sidebar.rs +++ b/nebula_app/src/gpui_shell/workspace/sidebar.rs @@ -231,6 +231,7 @@ impl NebulaWorkspace { is_settings, activity, logo_image, + logo_pending, program_glyph, shell_tag, color: tab_color, @@ -444,7 +445,7 @@ impl NebulaWorkspace { .when_some(program_glyph, |row, glyph| { row.child( div() - .w(px(TAB_LABEL_ICON_W)) + .w(px(if logo_pending { TAB_LABEL_ICON_SIZE } else { TAB_LABEL_ICON_W })) .flex_shrink_0() .font_family(symbol_family.clone()) .text_size(px(label_px)) @@ -964,7 +965,7 @@ impl NebulaWorkspace { let chrome_family = theme.mono_font_family.clone(); let symbol_family: SharedString = crate::font_install::REQUIRED_FONT_FAMILY.into(); let label_px = settings.map(|settings| settings.ui_font_size_px).unwrap_or(15.0); - let TabPresentation { title, logo_image, program_glyph, pane_count, .. } = + let TabPresentation { title, logo_image, logo_pending, program_glyph, pane_count, .. } = self.tab_presentation(self.active, cx, dark); slot.child( h_flex() @@ -986,6 +987,7 @@ impl NebulaWorkspace { .when_some(program_glyph, |row, glyph| { row.child( div() + .when(logo_pending, |slot| slot.w(px(TAB_LABEL_ICON_SIZE))) .flex_shrink_0() .font_family(symbol_family) .text_size(px(label_px)) diff --git a/nebula_app/src/gpui_shell/workspace/tab_presentation.rs b/nebula_app/src/gpui_shell/workspace/tab_presentation.rs index c23ea646e..27d338233 100644 --- a/nebula_app/src/gpui_shell/workspace/tab_presentation.rs +++ b/nebula_app/src/gpui_shell/workspace/tab_presentation.rs @@ -10,6 +10,7 @@ pub(super) struct TabPresentation { pub(super) is_settings: bool, pub(super) activity: SidebarActivity, pub(super) logo_image: Option>, + pub(super) logo_pending: bool, pub(super) program_glyph: Option<&'static str>, pub(super) shell_tag: Option, pub(super) color: Option, @@ -71,10 +72,10 @@ impl NebulaWorkspace { // 事件 vs 状态的唯一裁定处(侧栏与顶栏共用这份 presentation),规则与 // 理由见 [`sidebar::resting_activity`]。 let activity = sidebar::resting_activity(activity, active, self.meta(ix).has_bell); - let logo_image = program - .as_deref() - .and_then(crate::display::ai_logo_for_program) - .and_then(|logo| self.sidebar_logo_images.get(&(logo, dark)).cloned()); + let brand_logo = program.as_deref().and_then(crate::display::ai_logo_for_program); + let logo_image = + brand_logo.and_then(|logo| self.sidebar_logo_images.get(&(logo, dark)).cloned()); + let logo_pending = brand_logo.is_some() && logo_image.is_none(); let program_glyph = program .as_deref() .filter(|_| logo_image.is_none()) @@ -111,6 +112,7 @@ impl NebulaWorkspace { is_settings, activity, logo_image, + logo_pending, program_glyph, shell_tag, color: meta.color, diff --git a/nebula_app/src/gpui_shell/workspace/top_tabs.rs b/nebula_app/src/gpui_shell/workspace/top_tabs.rs index 45bdac498..f5692834c 100644 --- a/nebula_app/src/gpui_shell/workspace/top_tabs.rs +++ b/nebula_app/src/gpui_shell/workspace/top_tabs.rs @@ -177,6 +177,7 @@ impl NebulaWorkspace { is_settings, activity, logo_image, + logo_pending, program_glyph, shell_tag, color, @@ -380,7 +381,7 @@ impl NebulaWorkspace { .when_some(program_glyph, |row, glyph| { row.child( div() - .w(px(TAB_LABEL_ICON_W)) + .w(px(if logo_pending { TAB_LABEL_ICON_SIZE } else { TAB_LABEL_ICON_W })) .flex_shrink_0() .font_family(symbol_family.clone()) .text_size(px(label_px)) diff --git a/nebula_app/src/gpui_shell/workspace/windowing.rs b/nebula_app/src/gpui_shell/workspace/windowing.rs index 7bd72240d..4aa0234f9 100644 --- a/nebula_app/src/gpui_shell/workspace/windowing.rs +++ b/nebula_app/src/gpui_shell/workspace/windowing.rs @@ -516,6 +516,7 @@ fn open_workspace_window( options.show = false; options.focus = false; } + let deferred_show = crate::platform::startup::first_frame::defer_show(&mut options); let workspace_slot = Rc::new(RefCell::new(None)); let hwnd_slot = Rc::new(RefCell::new(0isize)); let workspace_out = workspace_slot.clone(); @@ -566,6 +567,9 @@ fn open_workspace_window( role, }); crate::gpui_shell::wallpaper::refresh(cx); + if deferred_show { + crate::platform::startup::first_frame::present_then_show(handle, cx); + } Ok((runtime_window_id, workspace)) } diff --git a/nebula_app/src/platform/startup.rs b/nebula_app/src/platform/startup.rs index a6dacf52b..6ed192478 100644 --- a/nebula_app/src/platform/startup.rs +++ b/nebula_app/src/platform/startup.rs @@ -8,6 +8,8 @@ pub(crate) fn report_error(error: &dyn std::fmt::Display, gui_launch: bool) { #[cfg(windows)] mod console; +#[cfg(feature = "gpui-shell")] +pub(crate) mod first_frame; /// Match GPUI's primary-monitor DPI query before a native window is created. /// Other platforms retain post-creation sizing until their display API exposes scale. diff --git a/nebula_app/src/platform/startup/first_frame.rs b/nebula_app/src/platform/startup/first_frame.rs new file mode 100644 index 000000000..2e44f2e41 --- /dev/null +++ b/nebula_app/src/platform/startup/first_frame.rs @@ -0,0 +1,64 @@ +//! Present a regular Windows startup window before making it visible. +//! +//! GPUI builds the scene in App::open_window, but its Windows backend normally +//! shows the HWND before that scene exists. Its next-frame callbacks run BEFORE +//! presentation, so neither those callbacks nor App::defer are a paint barrier. + +use gpui::{AnyWindowHandle, App, WindowOptions}; + +pub(crate) fn defer_show(options: &mut WindowOptions) -> bool { + if !cfg!(windows) || !options.show || !options.focus { + return false; + } + // Preserve the requested activation; GPUI retains the original placement + // until activate_window. Silent/background/Quick Terminal paths never enter. + options.show = false; + true +} + +pub(crate) fn present_then_show(handle: AnyWindowHandle, cx: &mut App) { + #[cfg(windows)] + cx.spawn(async move |cx| { + use windows_sys::Win32::UI::WindowsAndMessaging::{SendMessageW, WM_PAINT}; + use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle}; + + let hwnd = handle.update(cx, |_, window, _| { + let native = HasWindowHandle::window_handle(window).ok()?; + let RawWindowHandle::Win32(native) = native.as_raw() else { return None }; + Some(native.hwnd.get()) + }); + let Ok(Some(hwnd)) = hwnd else { return }; + + // SAFETY: this one-shot task runs on GPUI's foreground thread. The handle + // was resolved from a live GPUI window above, and no App/Window borrow is + // held across SendMessage: WM_PAINT re-enters GPUI's frame callback. + // Pinned GPUI Windows handles WM_PAINT by synchronously drawing/presenting + // even when hidden. Explicit delivery avoids relying on hidden-window + // WM_PAINT generation by Windows. There are no timers or polling loops. + unsafe { SendMessageW(hwnd as _, WM_PAINT, 0, 0) }; + + // Only after the paint handler returns, use GPUI activation to consume + // its pending placement. Raw ShowWindow would leave that placement stale. + let _ = handle.update(cx, |_, window, _| window.activate_window()); + }) + .detach(); + + #[cfg(not(windows))] + let _ = (handle, cx); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_visible_focused_windows_defer_their_initial_show() { + for (show, focus) in [(true, true), (true, false), (false, true), (false, false)] { + let mut options = WindowOptions { show, focus, ..Default::default() }; + let deferred = defer_show(&mut options); + assert_eq!(deferred, cfg!(windows) && show && focus); + assert_eq!(options.show, show && !deferred); + assert_eq!(options.focus, focus); + } + } +} From 63cbd3754c060abe7caf28c54a504fcd2187c3a2 Mon Sep 17 00:00:00 2001 From: JoyElliot <72300219+JoyElliot@users.noreply.github.com> Date: Tue, 22 Sep 2026 22:50:18 +0800 Subject: [PATCH 03/14] =?UTF-8?q?refactor(startup):=20=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E4=BB=BB=E5=8A=A1=E6=89=80=E6=9C=89=E6=9D=83=E5=8F=96=E6=B6=88?= =?UTF-8?q?=E6=97=A7=E5=9B=BE=E6=A0=87=E5=9B=9E=E5=A1=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2026-09-22-nonblocking-first-frame.md | 13 ++-- nebula_app/src/gpui_shell/workspace/logos.rs | 64 +++++++++++-------- 2 files changed, 44 insertions(+), 33 deletions(-) diff --git a/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-nonblocking-first-frame.md b/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-nonblocking-first-frame.md index 5bf1485fc..fb3b05068 100644 --- a/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-nonblocking-first-frame.md +++ b/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-nonblocking-first-frame.md @@ -37,13 +37,14 @@ remain separate from the packaging integration branch. background executor. Its UI task holds a weak entity and returns pixels into a ready slot. Render consumes ready pixels and keeps the existing settings sync call; it never waits for decoding. -- Each request carries target physical pixels and a generation. Replacing or - dropping its task signals cooperative cancellation between images. An image - already decoding can finish; its stale result cannot update a newer request. +- Replacing or dropping a request cancels its sole foreground publishing task + and signals cooperative cancellation between images. Reset and publication + run on the same foreground thread; a cancelled publisher cannot apply an old + worker result. An image already decoding can finish without updating the UI. - Initial missing brand images use the existing glyph fallback in exactly the eventual image width. A DPI transition keeps its prior image while replacement is pending, avoiding a flash back to a different glyph. This can briefly resample - the old DPI texture; no old-generation result is committed afterward. + the old DPI texture; cancelled requests cannot replace it afterward. - Only visible, focused Windows windows defer their initial show. The caller leaves silent-start, background-created windows and Quick Terminal unchanged. - After window creation and deferred material setup, schedule a foreground task. @@ -58,6 +59,8 @@ remain separate from the packaging integration branch. could reset geometry at later activation. - Making every window activate would break background and silent-start behavior. - A synchronous decode before showing merely relocates the startup stall. +- Generation checks duplicate the owned foreground task's cancellation guarantee: + background workers only produce pixels and never publish into the workspace. - New image filters, rescaled source assets or persistent caches would change visual output or introduce unrelated cache/version/persistence policy. @@ -75,7 +78,7 @@ Windows' normal opening animation remains enabled. ## Validation - Pixel comparisons at 15px/23px preserve the previous PNG/tint/filter output. -- Replaced/DPI-returning requests reject old generations; dropping a request +- Replaced/DPI-returning requests cancel their old publishers; dropping a request signals cancellation, and a pre-cancelled worker does not decode images. - Option tests cover visible/hidden and focused/background combinations. - Geometry and the first-PTY-size/maximize regression remain passing. diff --git a/nebula_app/src/gpui_shell/workspace/logos.rs b/nebula_app/src/gpui_shell/workspace/logos.rs index ed96c2a83..8b4a884c8 100644 --- a/nebula_app/src/gpui_shell/workspace/logos.rs +++ b/nebula_app/src/gpui_shell/workspace/logos.rs @@ -14,7 +14,6 @@ type LogoImages = HashMap<(crate::display::AiLogo, bool), Arc>; #[derive(Default)] pub(super) struct LogoLoad { target: u32, - generation: u64, pending: Option, ready: Option, } @@ -33,20 +32,12 @@ impl Drop for PendingLoad { } impl LogoLoad { - fn reset(&mut self, target: u32) -> u64 { + fn reset(&mut self, target: u32) { + // Reset and publication run on the foreground thread. Dropping the sole + // publishing task prevents an old worker result from reaching this load. self.pending = None; self.ready = None; self.target = target; - self.generation = self.generation.wrapping_add(1); - self.generation - } - - fn complete(&mut self, target: u32, generation: u64, images: LogoImages) -> bool { - if self.target != target || self.generation != generation { - return false; - } - self.ready = Some(images); - true } } @@ -64,7 +55,7 @@ pub(super) fn poll_sidebar_logo_images( return None; } if load.target != target { - let generation = load.reset(target); + load.reset(target); let cancelled = Arc::new(AtomicBool::new(false)); let worker_cancelled = cancelled.clone(); let worker = cx @@ -73,9 +64,8 @@ pub(super) fn poll_sidebar_logo_images( let task = cx.spawn(async move |workspace, cx| { let Some(images) = worker.await else { return }; let _ = workspace.update(cx, |workspace, cx| { - if workspace.sidebar_logo_load.complete(target, generation, images) { - cx.notify(); - } + workspace.sidebar_logo_load.ready = Some(images); + cx.notify(); }); }); load.pending = Some(PendingLoad { cancelled, _task: task }); @@ -164,18 +154,36 @@ mod tests { } } - #[test] - fn superseded_dpi_results_cannot_replace_the_current_request() { - let mut load = LogoLoad::default(); - let old = load.reset(15); - let current = load.reset(23); - assert!(!load.complete(15, old, HashMap::new())); - assert!(load.ready.is_none()); - assert!(load.complete(23, current, HashMap::new())); - let newest = load.reset(15); - assert!(load.ready.is_none()); - assert!(!load.complete(15, old, HashMap::new()), "same DPI does not revive an old job"); - assert!(load.complete(15, newest, HashMap::new())); + #[cfg(feature = "gpui-test-support")] + #[gpui::test] + fn replacing_load_cancels_already_queued_publication(cx: &mut gpui::TestAppContext) { + use std::cell::Cell; + use std::rc::Rc; + + for replace in [true, false] { + let published = Rc::new(Cell::new(false)); + let result = published.clone(); + let (reply, received) = futures::channel::oneshot::channel::<()>(); + let worker = cx.executor().spawn(async move { received.await.unwrap() }); + let task = cx.foreground_executor().spawn(async move { + worker.await; + result.set(true); + }); + let mut load = LogoLoad::default(); + load.reset(15); + load.pending = + Some(PendingLoad { cancelled: Arc::new(AtomicBool::new(false)), _task: task }); + cx.run_until_parked(); + reply.send(()).unwrap(); + // Finish the worker, leaving its foreground publisher queued. + assert!(cx.dispatcher.tick(true)); + if replace { + load.reset(23); + load.reset(15); // Returning to the old DPI must not revive its task. + } + cx.run_until_parked(); + assert_eq!(published.get(), !replace, "only the retained request may publish"); + } } #[test] From 5382c99681ba3f125e38404b79fdbe85576ed187 Mon Sep 17 00:00:00 2001 From: JoyElliot <72300219+JoyElliot@users.noreply.github.com> Date: Tue, 22 Sep 2026 23:20:49 +0800 Subject: [PATCH 04/14] =?UTF-8?q?docs(startup):=20=E5=AF=B9=E9=BD=90?= =?UTF-8?q?=E4=B8=8A=E6=B8=B8=E8=AE=BE=E7=BD=AE=E9=A1=B5=E5=9B=BE=E6=A0=87?= =?UTF-8?q?=E5=BD=92=E5=B1=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../gpui_shell/workspace/2026-09-22-first-frame-startup.md | 2 ++ .../workspace/2026-09-22-nonblocking-first-frame.md | 5 +++-- nebula_app/src/gpui_shell/workspace/logos.rs | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-first-frame-startup.md b/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-first-frame-startup.md index 97bd58307..13f7e0a1f 100644 --- a/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-first-frame-startup.md +++ b/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-first-frame-startup.md @@ -2,6 +2,8 @@ Superseded in its synchronous-preparation choice by [nonblocking first frame](2026-09-22-nonblocking-first-frame.md); geometry remains. +The later upstream #241 integration also replaced the settings-logo synchronization +described below with static SVGs, as recorded in that successor note. ## Status diff --git a/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-nonblocking-first-frame.md b/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-nonblocking-first-frame.md index fb3b05068..e6aeae63a 100644 --- a/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-nonblocking-first-frame.md +++ b/architecture/notes/nebula_app/gpui_shell/workspace/2026-09-22-nonblocking-first-frame.md @@ -35,8 +35,9 @@ remain separate from the packaging integration branch. - A workspace-owned `LogoLoad` prepares the existing pixel pipeline on the background executor. Its UI task holds a weak entity and returns pixels into a - ready slot. Render consumes ready pixels and keeps the existing settings sync - call; it never waits for decoding. + ready slot. Render consumes ready pixels for tabs and pane headers without + waiting for decoding. Upstream #241 moved settings Agent icons to static SVGs; + the former settings-logo synchronization is no longer needed. - Replacing or dropping a request cancels its sole foreground publishing task and signals cooperative cancellation between images. Reset and publication run on the same foreground thread; a cancelled publisher cannot apply an old diff --git a/nebula_app/src/gpui_shell/workspace/logos.rs b/nebula_app/src/gpui_shell/workspace/logos.rs index 8b4a884c8..918597c29 100644 --- a/nebula_app/src/gpui_shell/workspace/logos.rs +++ b/nebula_app/src/gpui_shell/workspace/logos.rs @@ -1,4 +1,4 @@ -//! DPI-specific sidebar textures, shared by tabs, panes and settings. +//! DPI-specific sidebar textures, shared by tabs and pane headers. use std::collections::HashMap; use std::sync::Arc; From fde914bb5020ec9fc4f5363e4577078500d4a283 Mon Sep 17 00:00:00 2001 From: thynome <125388433+thynomex@users.noreply.github.com> Date: Sat, 26 Sep 2026 04:20:46 +0000 Subject: [PATCH 05/14] fix(i18n): localize GPUI workspace controls and confirmations (#133) Localize GPUI workspace controls, split actions, file panels, and close confirmations using existing typed messages and application language. Add 57 English/Chinese message entries and focused i18n regressions. Keep close confirmations in the existing closing lifecycle module. Retain the scoped contribution from PR #133 without adding global language state, translation macros, or legacy-shell migrations. --- nebula_app/i18n/en-US.json | 81 +++++++++++- nebula_app/i18n/zh-CN.json | 81 +++++++++++- nebula_app/src/gpui_shell/workspace.rs | 60 --------- .../src/gpui_shell/workspace/closing.rs | 81 +++++++++++- .../src/gpui_shell/workspace/file_tree.rs | 122 ++++++++++-------- .../src/gpui_shell/workspace/pane_header.rs | 23 ++-- .../src/gpui_shell/workspace/remote_files.rs | 42 +++--- .../src/gpui_shell/workspace/sidebar.rs | 8 +- nebula_app/src/gpui_shell/workspace/tests.rs | 14 +- .../src/gpui_shell/workspace/top_tabs.rs | 25 ++-- nebula_app/src/i18n/tests.rs | 27 ++++ 11 files changed, 401 insertions(+), 163 deletions(-) diff --git a/nebula_app/i18n/en-US.json b/nebula_app/i18n/en-US.json index 3a1643f1e..4b9a99d35 100644 --- a/nebula_app/i18n/en-US.json +++ b/nebula_app/i18n/en-US.json @@ -503,7 +503,34 @@ "ignore_failed": "Could not change Git ignore rules: {error}", "preview_loading": "Preparing preview…", "preview_unavailable": "Preview unavailable for this file", - "preview_pages": "Page 1 of {pages}" + "preview_pages": "Page 1 of {pages}", + "open_terminal_here": "Open terminal here", + "tree": { + "open_in_explorer": "Open in File Explorer", + "follow_refresh": "Follow the current terminal and refresh (Alt+R)" + }, + "copy_linux_path": "Copy Linux path", + "reveal_in_explorer": "Show in File Explorer", + "copy_path": "Copy path", + "empty": { + "reading_title": "Reading directory", + "reading_body": "Still enumerating the current working directory.", + "reading_hint": "Wait a moment, or click Follow again in the top-right.", + "read_failed_title": "Could not read directory", + "read_failed_body": "The directory could not be read completely. Check access permissions or try again.", + "read_failed_hint": "Click Follow again in the top-right, or choose another directory.", + "no_directory_title": "No directory to browse", + "no_directory_body": "The current terminal has not reported a working directory yet.", + "no_directory_hint": "Enter a directory in the terminal, then click Follow in the top-right.", + "directory_empty_title": "This directory is empty", + "directory_empty_body": "The current working directory has no files to show.", + "directory_empty_hint": "Create files in the terminal, or choose another directory." + }, + "delete": { + "title": "Delete {name}?", + "folder_body": "The folder and all of its contents will be moved to the Recycle Bin.", + "file_body": "The file will be moved to the Recycle Bin." + } }, "recipe": { "title": "Layout recipes", @@ -921,5 +948,57 @@ "move_left": "Move left", "move_right": "Move right", "tab_color": "Tab color" + }, + "chrome": { + "new_terminal_ctrl_shift_t": "New terminal (Ctrl+Shift+T)", + "more": "More", + "scroll_tabs_left": "Scroll tabs left", + "scroll_tabs_right": "Scroll tabs right", + "select_terminal": "Select terminal", + "command_list": "Command list", + "toggle_sidebar": "Show/hide sidebar (Ctrl+Shift+B)", + "settings_shortcut": "Settings (Ctrl+,)" + }, + "workspace": { + "pane": { + "stop_broadcast_input": "Stop broadcasting input", + "broadcast_input_tooltip": "Broadcast input to every pane in this tab", + "close": "Close this pane", + "extract_release": "Release to extract as a new tab", + "extract_drag_hint": "Drag outside the terminal to extract", + "broadcast_enabled": "Broadcasting input to {count} panes in this tab", + "restore_layout": "Restore pane layout (Ctrl+Shift+Enter)", + "zoom": "Zoom this pane (Ctrl+Shift+Enter)" + }, + "close": { + "running_process": "{process} is still running. Closing will stop it.", + "running_window_process": "{process} is still running. Closing the window will stop it." + }, + "close_window": { + "title": "Close window?" + }, + "close_pane": { + "title": "Close this pane?" + }, + "close_tab": { + "title": "Close this tab?" + } + }, + "remote": { + "locating": "Locating the remote directory…", + "parent": "Up one level", + "reread": "Reload", + "upload_files": "Upload files", + "upload_folder": "Upload folder", + "download": "Download to this computer", + "copy_item": "Copy remote item", + "paste_here": "Paste into the current remote directory", + "skip_unchanged": "Skip unchanged", + "cancel": "Cancel transfer", + "preparing": "Preparing the transfer…", + "reading": "Reading the remote directory…", + "empty": "This directory is empty.", + "error_retry": "{error} (click Reload in the top-right to retry)", + "busy_other": "Another host is transferring: {destination}" } } diff --git a/nebula_app/i18n/zh-CN.json b/nebula_app/i18n/zh-CN.json index 25ec97f86..a78fd32e2 100644 --- a/nebula_app/i18n/zh-CN.json +++ b/nebula_app/i18n/zh-CN.json @@ -503,7 +503,34 @@ "ignore_failed": "修改 Git 忽略规则失败:{error}", "preview_loading": "正在生成预览…", "preview_unavailable": "此文件暂时无法预览", - "preview_pages": "第 1 页 · 共 {pages} 页" + "preview_pages": "第 1 页 · 共 {pages} 页", + "open_terminal_here": "在此处打开终端", + "tree": { + "open_in_explorer": "在资源管理器中打开", + "follow_refresh": "跟随当前终端并刷新 (Alt+R)" + }, + "copy_linux_path": "复制 Linux 路径", + "reveal_in_explorer": "在资源管理器中显示", + "copy_path": "复制路径", + "empty": { + "reading_title": "正在读取目录", + "reading_body": "还在枚举当前工作目录的内容。", + "reading_hint": "稍等一下,或点右上角重新跟随。", + "read_failed_title": "读取目录失败", + "read_failed_body": "未能完整读取此目录,请检查访问权限或重试。", + "read_failed_hint": "点右上角重新跟随重试,或换一个目录。", + "no_directory_title": "没有可浏览的目录", + "no_directory_body": "当前终端尚未报告工作目录。", + "no_directory_hint": "在终端中进入一个目录后点击右上角跟随。", + "directory_empty_title": "此目录为空", + "directory_empty_body": "当前工作目录中没有可显示的文件。", + "directory_empty_hint": "在终端创建文件,或选择其他目录。" + }, + "delete": { + "title": "删除 {name}?", + "folder_body": "文件夹及其全部内容会移入回收站。", + "file_body": "文件会移入回收站。" + } }, "recipe": { "title": "布局配方", @@ -921,5 +948,57 @@ "move_left": "向左移动", "move_right": "向右移动", "tab_color": "标签颜色" + }, + "chrome": { + "new_terminal_ctrl_shift_t": "新建终端 (Ctrl+Shift+T)", + "more": "更多", + "scroll_tabs_left": "向左翻标签", + "scroll_tabs_right": "向右翻标签", + "select_terminal": "选择终端", + "command_list": "命令列表", + "toggle_sidebar": "折叠/展开侧边栏 (Ctrl+Shift+B)", + "settings_shortcut": "设置 (Ctrl+,)" + }, + "workspace": { + "pane": { + "stop_broadcast_input": "关闭广播输入", + "broadcast_input_tooltip": "广播输入到本标签全部分栏", + "close": "关闭此分栏", + "extract_release": "松手:拉出为独立标签", + "extract_drag_hint": "拖到终端区外可拉出", + "broadcast_enabled": "广播输入已开启:键入将同步到本标签的 {count} 个分栏", + "restore_layout": "还原分栏布局 (Ctrl+Shift+Enter)", + "zoom": "独占放大此分栏 (Ctrl+Shift+Enter)" + }, + "close": { + "running_process": "{process} 仍在运行,关闭会中止它。", + "running_window_process": "{process} 仍在运行,关闭窗口会中止它。" + }, + "close_window": { + "title": "关闭窗口?" + }, + "close_pane": { + "title": "关闭此分栏?" + }, + "close_tab": { + "title": "关闭此标签页?" + } + }, + "remote": { + "locating": "正在定位远端目录…", + "parent": "上一级", + "reread": "重新读取", + "upload_files": "上传文件", + "upload_folder": "上传文件夹", + "download": "下载到本地", + "copy_item": "复制远端项目", + "paste_here": "粘贴到当前远端目录", + "skip_unchanged": "跳过未变", + "cancel": "取消传输", + "preparing": "正在准备传输…", + "reading": "正在读取远端目录…", + "empty": "此目录为空。", + "error_retry": "{error}(点右上角重新读取)", + "busy_other": "另一主机正在传输:{destination}" } } diff --git a/nebula_app/src/gpui_shell/workspace.rs b/nebula_app/src/gpui_shell/workspace.rs index f0d7be7af..71aec1ff6 100644 --- a/nebula_app/src/gpui_shell/workspace.rs +++ b/nebula_app/src/gpui_shell/workspace.rs @@ -1656,66 +1656,6 @@ impl NebulaWorkspace { ) } - fn request_close_pane( - &mut self, - tab_ix: usize, - pane_id: u64, - window: &mut Window, - cx: &mut Context, - ) { - let Some(process) = self.busy_process_in_tab(tab_ix, Some(pane_id), cx) else { - self.close_pane(tab_ix, pane_id, window, cx); - return; - }; - let body: SharedString = format!("{process} 仍在运行,关闭会中止它。").into(); - let workspace = cx.entity().downgrade(); - window.open_dialog(cx, move |dialog, window, _cx| { - let workspace = workspace.clone(); - confirm_dialog( - dialog, - window, - "关闭此分栏?", - body.clone(), - "关闭", - "取消", - ButtonVariant::Danger, - ) - .on_ok(move |_, window, cx| { - let _ = workspace.update(cx, |workspace, cx| { - workspace.close_pane(tab_ix, pane_id, window, cx); - }); - true - }) - }); - } - - fn request_close_tab(&mut self, tab_ix: usize, window: &mut Window, cx: &mut Context) { - let Some(process) = self.busy_process_in_tab(tab_ix, None, cx) else { - self.close_tab(tab_ix, window, cx); - return; - }; - let body: SharedString = format!("{process} 仍在运行,关闭会中止它。").into(); - let workspace = cx.entity().downgrade(); - window.open_dialog(cx, move |dialog, window, _cx| { - let workspace = workspace.clone(); - confirm_dialog( - dialog, - window, - "关闭此标签页?", - body.clone(), - "关闭", - "取消", - ButtonVariant::Danger, - ) - .on_ok(move |_, window, cx| { - let _ = workspace.update(cx, |workspace, cx| { - workspace.close_tab(tab_ix, window, cx); - }); - true - }) - }); - } - /// 聚焦另一个 pane(点击上报或方向导航落点)。 fn focus_pane( &mut self, diff --git a/nebula_app/src/gpui_shell/workspace/closing.rs b/nebula_app/src/gpui_shell/workspace/closing.rs index 195883493..0e4571d8f 100644 --- a/nebula_app/src/gpui_shell/workspace/closing.rs +++ b/nebula_app/src/gpui_shell/workspace/closing.rs @@ -1,6 +1,76 @@ use super::*; +use crate::i18n::Message; impl NebulaWorkspace { + pub(super) fn request_close_pane( + &mut self, + tab_ix: usize, + pane_id: u64, + window: &mut Window, + cx: &mut Context, + ) { + let Some(process) = self.busy_process_in_tab(tab_ix, Some(pane_id), cx) else { + self.close_pane(tab_ix, pane_id, window, cx); + return; + }; + let language = crate::gpui_shell::config::ui_language(cx); + let body: SharedString = + language.format(Message::WorkspaceCloseRunningProcess, &[("process", &process)]).into(); + let workspace = cx.entity().downgrade(); + window.open_dialog(cx, move |dialog, window, _cx| { + let workspace = workspace.clone(); + confirm_dialog( + dialog, + window, + language.text(Message::WorkspaceClosePaneTitle), + body.clone(), + language.text(Message::CommonClose), + language.text(Message::CommonCancel), + ButtonVariant::Danger, + ) + .on_ok(move |_, window, cx| { + let _ = workspace.update(cx, |workspace, cx| { + workspace.close_pane(tab_ix, pane_id, window, cx); + }); + true + }) + }); + } + + pub(super) fn request_close_tab( + &mut self, + tab_ix: usize, + window: &mut Window, + cx: &mut Context, + ) { + let Some(process) = self.busy_process_in_tab(tab_ix, None, cx) else { + self.close_tab(tab_ix, window, cx); + return; + }; + let language = crate::gpui_shell::config::ui_language(cx); + let body: SharedString = + language.format(Message::WorkspaceCloseRunningProcess, &[("process", &process)]).into(); + let workspace = cx.entity().downgrade(); + window.open_dialog(cx, move |dialog, window, _cx| { + let workspace = workspace.clone(); + confirm_dialog( + dialog, + window, + language.text(Message::WorkspaceCloseTabTitle), + body.clone(), + language.text(Message::CommonClose), + language.text(Message::CommonCancel), + ButtonVariant::Danger, + ) + .on_ok(move |_, window, cx| { + let _ = workspace.update(cx, |workspace, cx| { + workspace.close_tab(tab_ix, window, cx); + }); + true + }) + }); + } + /// GPUI 的 should-close 回调必须同步返回:无繁忙进程时直接允许系统关闭; /// 有繁忙进程时先返回 false,再由对话框确认回调显式移除窗口。 pub(super) fn should_close_window( @@ -43,7 +113,10 @@ impl NebulaWorkspace { } self.window_close_confirm_open = true; - let body: SharedString = format!("{process} 仍在运行,关闭窗口会中止它。").into(); + let language = crate::gpui_shell::config::ui_language(cx); + let body: SharedString = language + .format(Message::WorkspaceCloseRunningWindowProcess, &[("process", &process)]) + .into(); let confirm_workspace = cx.entity().downgrade(); let close_workspace = confirm_workspace.clone(); window.open_dialog(cx, move |dialog, window, _cx| { @@ -52,10 +125,10 @@ impl NebulaWorkspace { confirm_dialog( dialog, window, - "关闭窗口?", + language.text(Message::WorkspaceCloseWindowTitle), body.clone(), - "关闭", - "取消", + language.text(Message::CommonClose), + language.text(Message::CommonCancel), ButtonVariant::Danger, ) .on_ok(move |_, window, cx| { diff --git a/nebula_app/src/gpui_shell/workspace/file_tree.rs b/nebula_app/src/gpui_shell/workspace/file_tree.rs index bb4737831..bb164be90 100644 --- a/nebula_app/src/gpui_shell/workspace/file_tree.rs +++ b/nebula_app/src/gpui_shell/workspace/file_tree.rs @@ -17,6 +17,7 @@ use gpui::{ use gpui_component::menu::PopupMenuItem; use crate::gpui_shell::prelude::*; +use crate::i18n::Message; use super::NebulaWorkspace; @@ -454,7 +455,7 @@ impl NebulaWorkspace { .ghost() .xsmall() .disabled(root_dir.is_none()) - .tooltip("在此新建终端") + .tooltip(language.text(Message::FilesOpenTerminalHere)) .on_click(cx.listener(|this, _, window, cx| { // WSL 树根要开的是**来宾**终端:宿主那份拼写只是 // 展开用的键,在来宾的 shell 里不存在。 @@ -481,7 +482,7 @@ impl NebulaWorkspace { .ghost() .xsmall() .disabled(root_dir.is_none()) - .tooltip("在资源管理器中打开") + .tooltip(language.text(Message::FilesTreeOpenInExplorer)) .on_click(cx.listener(|this, _, _, _cx| { let wsl = this .side_panel @@ -510,7 +511,7 @@ impl NebulaWorkspace { .icon(IconName::Redo2) .ghost() .xsmall() - .tooltip("跟随当前终端并刷新 (Alt+R)") + .tooltip(language.text(Message::FilesTreeFollowRefresh)) .on_click(cx.listener(|this, _, _, cx| { this.side_panel.request_refresh(); // 刷新同时恢复“跟随当前 pane”;否则点过 `..` 后 @@ -612,12 +613,11 @@ impl NebulaWorkspace { /// 目录仍然是空的;"读不到"和"确实是空的"必须分开说,否则用户没法判断该 /// 重试还是该换目录。 fn file_tree_empty_state(&self, cx: &gpui::App) -> Option { + let language = crate::gpui_shell::config::ui_language(cx); if self.side_panel.file_rows().iter().any(|row| !row.is_parent) { return None; } if !self.side_panel.search.trim().is_empty() { - use crate::i18n::Message; - let language = crate::gpui_shell::config::ui_language(cx); return Some(if let Some(error) = self.side_panel.file_search_error() { crate::ux::EmptyState::new( language.text(Message::FilesSearchFailed), @@ -647,28 +647,28 @@ impl NebulaWorkspace { Some(if self.side_panel.snapshot_pending() { crate::ux::EmptyState::new( - "正在读取目录", - "还在枚举当前工作目录的内容。", - "稍等一下,或点右上角重新跟随。", + language.text(Message::FilesEmptyReadingTitle), + language.text(Message::FilesEmptyReadingBody), + language.text(Message::FilesEmptyReadingHint), ) } else if self.side_panel.enumeration_failed() { // 读不到 ≠ 目录是空的。WSL 冷启动可能耗尽预算,那时必须给可重试的提示。 crate::ux::EmptyState::new( - "读取目录失败", - "枚举这个目录时被系统拒绝,或超出了单次预算。", - "点右上角重新跟随重试,或换一个目录。", + language.text(Message::FilesEmptyReadFailedTitle), + language.text(Message::FilesEmptyReadFailedBody), + language.text(Message::FilesEmptyReadFailedHint), ) } else if self.side_panel.root().is_none() { crate::ux::EmptyState::new( - "没有可浏览的目录", - "当前终端尚未报告工作目录。", - "在终端中进入一个目录后点击右上角跟随。", + language.text(Message::FilesEmptyNoDirectoryTitle), + language.text(Message::FilesEmptyNoDirectoryBody), + language.text(Message::FilesEmptyNoDirectoryHint), ) } else { crate::ux::EmptyState::new( - "此目录为空", - "当前工作目录中没有可显示的文件。", - "在终端创建文件,或选择其他目录。", + language.text(Message::FilesEmptyDirectoryEmptyTitle), + language.text(Message::FilesEmptyDirectoryEmptyBody), + language.text(Message::FilesEmptyDirectoryEmptyHint), ) }) } @@ -784,12 +784,17 @@ impl NebulaWorkspace { .file_name() .map(|name| name.to_string_lossy().into_owned()) .unwrap_or_else(|| path.display().to_string()); - let title: SharedString = - format!("删除 {}?", crate::display::truncate_tab_label(&name, 28)).into(); + let language = crate::gpui_shell::config::ui_language(cx); + let title: SharedString = language + .format( + Message::FilesDeleteTitle, + &[("name", &crate::display::truncate_tab_label(&name, 28))], + ) + .into(); let body: SharedString = if is_dir { - "文件夹及其全部内容会移入回收站。".into() + language.text(Message::FilesDeleteFolderBody).into() } else { - "文件会移入回收站。".into() + language.text(Message::FilesDeleteFileBody).into() }; let workspace = cx.entity().downgrade(); window.open_dialog(cx, move |dialog, window, _cx| { @@ -800,8 +805,8 @@ impl NebulaWorkspace { window, title.clone(), body.clone(), - "删除", - "取消", + language.text(Message::CommonDelete), + language.text(Message::CommonCancel), ButtonVariant::Danger, ) .on_ok(move |_, _, cx| { @@ -870,8 +875,9 @@ fn file_tree_popup_menu( ) -> PopupMenu { if let Some(guest_path) = guest_path { let copy_guest = guest_path.clone(); - let copy = - PopupMenuItem::new("复制 Linux 路径").icon(IconName::Copy).on_click(move |_, _, cx| { + let copy = PopupMenuItem::new(language.text(Message::FilesCopyLinuxPath)) + .icon(IconName::Copy) + .on_click(move |_, _, cx| { cx.write_to_clipboard(ClipboardItem::new_string(copy_guest.clone())); }); let Some(distro) = wsl_distro else { return menu.item(copy) }; @@ -879,8 +885,9 @@ fn file_tree_popup_menu( let open_here = workspace.clone(); let open_distro = distro.clone(); let open_guest = guest_path.clone(); - PopupMenuItem::new("在此处打开终端").icon(IconName::SquareTerminal).on_click( - move |_, window, cx| { + PopupMenuItem::new(language.text(Message::FilesOpenTerminalHere)) + .icon(IconName::SquareTerminal) + .on_click(move |_, window, cx| { if let Some(workspace) = open_here.upgrade() { workspace.update(cx, |this, cx| { this.add_wsl_terminal_at( @@ -891,51 +898,56 @@ fn file_tree_popup_menu( ); }); } - }, - ) + }) } else { let open = workspace.clone(); let open_guest = guest_path.clone(); - PopupMenuItem::new("打开").icon(IconName::File).on_click(move |_, window, cx| { - if let Some(workspace) = open.upgrade() { - workspace.update(cx, |this, cx| { - this.open_wsl_document_path(open_guest.clone(), window, cx); - }); - } - }) + PopupMenuItem::new(language.text(Message::CommonOpen)).icon(IconName::File).on_click( + move |_, window, cx| { + if let Some(workspace) = open.upgrade() { + workspace.update(cx, |this, cx| { + this.open_wsl_document_path(open_guest.clone(), window, cx); + }); + } + }, + ) }; let reveal_path = crate::shell_detect::wsl_unc_path(&distro, &guest_path); return menu .item(first) - .item(PopupMenuItem::new("在资源管理器中显示").icon(IconName::FolderOpen).on_click( - move |_, _, _| { - super::reveal_in_file_manager(&reveal_path); - }, - )) + .item( + PopupMenuItem::new(language.text(Message::FilesRevealInExplorer)) + .icon(IconName::FolderOpen) + .on_click(move |_, _, _| { + super::reveal_in_file_manager(&reveal_path); + }), + ) .item(copy); } let first = if is_dir { let open_here = workspace.clone(); let dir = path.clone(); - PopupMenuItem::new("在此处打开终端").icon(IconName::SquareTerminal).on_click( - move |_, window, cx| { + PopupMenuItem::new(language.text(Message::FilesOpenTerminalHere)) + .icon(IconName::SquareTerminal) + .on_click(move |_, window, cx| { if let Some(workspace) = open_here.upgrade() { workspace.update(cx, |this, cx| { this.add_terminal_at(Some(dir.clone()), None, window, cx); }); } - }, - ) + }) } else { let open = workspace.clone(); let file = path.clone(); - PopupMenuItem::new("打开").icon(IconName::File).on_click(move |_, window, cx| { - if let Some(workspace) = open.upgrade() { - workspace.update(cx, |this, cx| { - this.open_document_path(file.clone(), window, cx); - }); - } - }) + PopupMenuItem::new(language.text(Message::CommonOpen)).icon(IconName::File).on_click( + move |_, window, cx| { + if let Some(workspace) = open.upgrade() { + workspace.update(cx, |this, cx| { + this.open_document_path(file.clone(), window, cx); + }); + } + }, + ) }; let reveal_path = path.clone(); let copy_path = path.clone(); @@ -963,18 +975,18 @@ fn file_tree_popup_menu( }); let delete = workspace; menu.item(first) - .item(PopupMenuItem::new("在资源管理器中显示").icon(IconName::FolderOpen).on_click( + .item(PopupMenuItem::new(language.text(Message::FilesRevealInExplorer)).icon(IconName::FolderOpen).on_click( move |_, _, _| { super::reveal_in_file_manager(&reveal_path); }, )) - .item(PopupMenuItem::new("复制路径").icon(IconName::Copy).on_click(move |_, _, cx| { + .item(PopupMenuItem::new(language.text(Message::FilesCopyPath)).icon(IconName::Copy).on_click(move |_, _, cx| { cx.write_to_clipboard(ClipboardItem::new_string(copy_path.display().to_string())); })) .separator() // 忽略在删除上面:两者都改工作区,但删除不可逆,危险的排最后。 .when_some(ignore_item, |menu, item| menu.item(item)) - .item(PopupMenuItem::new("删除").icon(IconName::Delete).on_click(move |_, window, cx| { + .item(PopupMenuItem::new(language.text(Message::CommonDelete)).icon(IconName::Delete).on_click(move |_, window, cx| { if let Some(workspace) = delete.upgrade() { workspace.update(cx, |this, cx| { this.request_delete_file_tree_path(path.clone(), window, cx); diff --git a/nebula_app/src/gpui_shell/workspace/pane_header.rs b/nebula_app/src/gpui_shell/workspace/pane_header.rs index f5a7c6e04..407df7ea3 100644 --- a/nebula_app/src/gpui_shell/workspace/pane_header.rs +++ b/nebula_app/src/gpui_shell/workspace/pane_header.rs @@ -33,6 +33,7 @@ use nebula_split::{SplitDirection, SplitTree}; use crate::gpui_shell::prelude::*; use crate::gpui_shell::terminal::view::{TerminalInput, TerminalView}; +use crate::i18n::Message; use super::{NebulaWorkspace, WorkspaceTab}; @@ -247,6 +248,7 @@ impl NebulaWorkspace { corners: HeaderCorners, cx: &mut Context, ) -> gpui::AnyElement { + let language = crate::gpui_shell::config::ui_language(cx); let theme = cx.theme(); let dark = theme.is_dark(); let muted = theme.muted_foreground; @@ -360,9 +362,9 @@ impl NebulaWorkspace { .xsmall() .selected(broadcast) .tooltip(if broadcast { - "关闭广播输入" + language.text(Message::WorkspacePaneStopBroadcastInput) } else { - "广播输入到本标签全部分栏" + language.text(Message::WorkspacePaneBroadcastInputTooltip) }) .child(broadcast_mark( title_px, @@ -387,9 +389,9 @@ impl NebulaWorkspace { .xsmall() .selected(zoomed) .tooltip(if zoomed { - "退出独占 (Ctrl+Shift+Enter)" + language.text(Message::WorkspacePaneRestoreLayout) } else { - "独占放大 (Ctrl+Shift+Enter)" + language.text(Message::WorkspacePaneZoom) }) .on_click(cx.listener(move |this, _, window, cx| { cx.stop_propagation(); @@ -402,7 +404,7 @@ impl NebulaWorkspace { .icon(Icon::new(IconName::Close).text_color(icon_ink)) .ghost() .xsmall() - .tooltip("关闭此分栏") + .tooltip(language.text(Message::WorkspacePaneClose)) .on_click(cx.listener(move |this, _, window, cx| { cx.stop_propagation(); this.request_close_pane(tab_ix, pane_id, window, cx); @@ -434,11 +436,15 @@ impl NebulaWorkspace { // toast 而不是消息栏:开关本身没有待办动作,只需要在开启的一刻说清 // 影响面。关闭时不打扰。 if on { + let language = crate::gpui_shell::config::ui_language(cx); crate::gpui_shell::toast::toast( window, cx, crate::display::ToastKind::Info, - format!("广播输入已开启:键入将同步到本标签的 {count} 个分栏"), + language.format( + Message::WorkspacePaneBroadcastEnabled, + &[("count", &count.to_string())], + ), ); } cx.notify(); @@ -665,6 +671,7 @@ impl NebulaWorkspace { pub(super) fn pane_drag_overlay(&self, cx: &mut Context) -> Option { let drag = self.pane_drag.as_ref().filter(|drag| drag.active)?; let (x, y, detach) = (drag.x, drag.y, drag.detach); + let language = crate::gpui_shell::config::ui_language(cx); let theme = cx.theme(); let hint_bg = if detach { theme.primary } else { theme.muted }; let hint_fg = if detach { theme.primary_foreground } else { theme.muted_foreground }; @@ -695,9 +702,9 @@ impl NebulaWorkspace { .text_size(px(11.0)) .text_color(hint_fg) .child(if detach { - "松手:拉出为独立标签" + language.text(Message::WorkspacePaneExtractRelease) } else { - "拖到终端区外可拉出" + language.text(Message::WorkspacePaneExtractDragHint) }), ) .into_any_element(), diff --git a/nebula_app/src/gpui_shell/workspace/remote_files.rs b/nebula_app/src/gpui_shell/workspace/remote_files.rs index 4502ce039..0b412b151 100644 --- a/nebula_app/src/gpui_shell/workspace/remote_files.rs +++ b/nebula_app/src/gpui_shell/workspace/remote_files.rs @@ -37,6 +37,7 @@ use gpui::{ }; use crate::gpui_shell::prelude::*; +use crate::i18n::Message; use crate::ssh_sftp::{ SftpBrowseSession, SftpConflictPolicy, SftpController, SftpEntry, SftpEntryKind, SftpPhase, SftpSnapshot, SftpTransferOptions, @@ -463,7 +464,7 @@ impl NebulaWorkspace { let row_count = rows.len(); let destination = self.remote_browser.destination.clone(); let path = if self.remote_browser.path.is_empty() { - "正在定位远端目录…".to_owned() + language.text(Message::RemoteLocating).to_owned() } else { self.remote_browser.path.clone() }; @@ -528,7 +529,7 @@ impl NebulaWorkspace { .ghost() .xsmall() .disabled(at_root) - .tooltip("上一级") + .tooltip(language.text(Message::RemoteParent)) .on_click(cx.listener(|this, _, _, cx| this.remote_parent(cx))), ) .child( @@ -538,7 +539,7 @@ impl NebulaWorkspace { .icon(IconName::Redo2) .ghost() .xsmall() - .tooltip("重新读取") + .tooltip(language.text(Message::RemoteReread)) .on_click(cx.listener(|this, _, _, cx| this.remote_refresh(cx))), ), ) @@ -554,7 +555,7 @@ impl NebulaWorkspace { .ghost() .xsmall() .disabled(transfer_working) - .tooltip("上传文件") + .tooltip(language.text(Message::RemoteUploadFiles)) .on_click(cx.listener(|this, _, window, cx| { this.remote_pick_upload_files(window, cx); })), @@ -565,7 +566,7 @@ impl NebulaWorkspace { .ghost() .xsmall() .disabled(transfer_working) - .tooltip("上传文件夹") + .tooltip(language.text(Message::RemoteUploadFolder)) .on_click(cx.listener(|this, _, window, cx| { this.remote_pick_upload_directory(window, cx); })), @@ -576,7 +577,7 @@ impl NebulaWorkspace { .ghost() .xsmall() .disabled(!has_selection || transfer_working) - .tooltip("下载到本地") + .tooltip(language.text(Message::RemoteDownload)) .on_click(cx.listener(|this, _, window, cx| { this.remote_pick_download_directory(window, cx); })), @@ -587,7 +588,7 @@ impl NebulaWorkspace { .ghost() .xsmall() .disabled(!has_selection) - .tooltip("复制远端项目") + .tooltip(language.text(Message::RemoteCopyItem)) .on_click(cx.listener(|this, _, window, cx| { this.remote_copy_selected(window, cx); })), @@ -598,13 +599,13 @@ impl NebulaWorkspace { .ghost() .xsmall() .disabled(!has_clipboard || transfer_working) - .tooltip("粘贴到当前远端目录") + .tooltip(language.text(Message::RemotePasteHere)) .on_click(cx.listener(|this, _, window, cx| { this.remote_paste(window, cx); })), ) .child(div().flex_1()) - .child(div().text_xs().text_color(muted).child("跳过未变")) + .child(div().text_xs().text_color(muted).child(language.text(Message::RemoteSkipUnchanged))) .child(skip_toggle), ) .when_some(notice, |panel, text| { @@ -658,10 +659,15 @@ impl NebulaWorkspace { let theme = cx.theme(); let muted = theme.muted_foreground; + let language = crate::gpui_shell::config::ui_language(cx); let is_working = snapshot.phase == SftpPhase::Working; let progress = snapshot.progress.clone(); let label = progress.as_ref().map(|progress| progress.label.clone()).unwrap_or_else(|| { - if is_working { "正在准备传输…".to_owned() } else { "传输失败".to_owned() } + if is_working { + language.text(Message::RemotePreparing).to_owned() + } else { + language.text(Message::TransferFailed).to_owned() + } }); let detail = if let Some(progress) = progress.as_ref() { format!( @@ -702,7 +708,7 @@ impl NebulaWorkspace { .icon(IconName::CircleX) .ghost() .xsmall() - .tooltip("取消传输") + .tooltip(language.text(Message::RemoteCancel)) .on_click(cx.listener(|this, _, _, cx| { this.remote_cancel_transfer(cx); })), @@ -852,7 +858,7 @@ impl NebulaWorkspace { /// 还是该换目录——这是空态里最常见也最误导人的一处偷懒。 fn remote_notice(&self, language: crate::display::UiLanguage) -> Option { if let Some(error) = self.remote_browser.error.as_deref() { - return Some(format!("{error}(点右上角重新读取)")); + return Some(language.format(Message::RemoteErrorRetry, &[("error", error)])); } if self.remote_browser.preflighting { return Some(language.text(crate::i18n::Message::TransferChecking).to_owned()); @@ -861,15 +867,21 @@ impl NebulaWorkspace { && snapshot.phase == SftpPhase::Working && snapshot.destination != self.remote_browser.destination { - return Some(format!("另一主机正在传输:{}", snapshot.destination)); + return Some( + language + .format(Message::RemoteBusyOther, &[("destination", &snapshot.destination)]), + ); } if self.remote_browser.loading { - return Some("正在读取远端目录…".to_owned()); + return Some(language.text(Message::RemoteReading).to_owned()); } if let Some(outcome) = self.remote_browser.last_outcome { return Some(language.text(outcome).to_owned()); } - self.remote_browser.entries.is_empty().then(|| "此目录为空。".to_owned()) + self.remote_browser + .entries + .is_empty() + .then(|| language.text(Message::RemoteEmpty).to_owned()) } } diff --git a/nebula_app/src/gpui_shell/workspace/sidebar.rs b/nebula_app/src/gpui_shell/workspace/sidebar.rs index 6ee9b7ae4..72a58a1a6 100644 --- a/nebula_app/src/gpui_shell/workspace/sidebar.rs +++ b/nebula_app/src/gpui_shell/workspace/sidebar.rs @@ -1,4 +1,5 @@ use super::*; +use crate::i18n::Message; /// 折叠箭头的固定布局槽。图标是 SVG,不应借任一字体的 advance 决定留白。 const TABS_DISCLOSURE_SLOT_W: f32 = 24.0; @@ -865,6 +866,7 @@ impl NebulaWorkspace { let settings_active_bg = cx.theme().sidebar_accent; let settings_active_fg = cx.theme().sidebar_accent_foreground; let sidebar_visible = !self.sidebar_collapsed && !self.reader_focus_active(cx); + let language = crate::gpui_shell::config::ui_language(cx); h_flex() .size_full() .items_center() @@ -887,7 +889,7 @@ impl NebulaWorkspace { // Ghost 的全局 selected 使用 hover_strong,静态底比 // 旧壳亮一档;仅此按钮覆写回旧壳 surface。 .when(sidebar_visible, |button| button.bg(secondary)) - .tooltip("折叠/展开侧边栏 (Ctrl+Shift+B)") + .tooltip(language.text(Message::ChromeToggleSidebar)) .on_click(cx.listener(|this, _, _, cx| { if this.reader_focus_active(cx) { this.clear_reader_focus(cx); @@ -906,7 +908,7 @@ impl NebulaWorkspace { .when(settings_active, |button| { button.bg(settings_active_bg).text_color(settings_active_fg) }) - .tooltip("设置 (Ctrl+,)") + .tooltip(language.text(Message::ChromeSettingsShortcut)) .on_click(cx.listener(|this, _, window, cx| { this.toggle_settings(window, cx); })), @@ -924,7 +926,7 @@ impl NebulaWorkspace { ) .ghost() .selected(self.command_manager_open) - .tooltip("命令列表") + .tooltip(language.text(Message::ChromeCommandList)) .on_click(cx.listener(|this, _, window, cx| { this.toggle_command_manager(window, cx); })), diff --git a/nebula_app/src/gpui_shell/workspace/tests.rs b/nebula_app/src/gpui_shell/workspace/tests.rs index fb76b4b48..5d1769a92 100644 --- a/nebula_app/src/gpui_shell/workspace/tests.rs +++ b/nebula_app/src/gpui_shell/workspace/tests.rs @@ -54,6 +54,7 @@ mod title_bar_panel_control_tests { ) .child(div().w(px(64.0)).h(px(48.0)).flex().items_end().child( super::top_tabs::top_new_tab_control( + crate::i18n::UiLanguage::EnUs, cx.listener(|this, _, _, _| this.tab_count += 1), ), )) @@ -91,13 +92,16 @@ mod title_bar_panel_control_tests { .h(px(super::top_tabs::TOP_TAB_H)), ) .child(super::top_tabs::top_tab_action_slot( - super::top_tabs::top_new_tab_control(|_, _, _| {}) - .debug_selector(|| "top-new-tab-geometry-probe".to_owned()), + super::top_tabs::top_new_tab_control( + crate::i18n::UiLanguage::EnUs, + |_, _, _| {}, + ) + .debug_selector(|| "top-new-tab-geometry-probe".to_owned()), )) .child(super::top_tabs::top_tab_action_slot( - h_flex() - .debug_selector(|| "top-tabs-menu-geometry-probe".to_owned()) - .child(super::top_tabs::top_tabs_menu_button(false)), + h_flex().debug_selector(|| "top-tabs-menu-geometry-probe".to_owned()).child( + super::top_tabs::top_tabs_menu_button(false, crate::i18n::UiLanguage::EnUs), + ), )) } } diff --git a/nebula_app/src/gpui_shell/workspace/top_tabs.rs b/nebula_app/src/gpui_shell/workspace/top_tabs.rs index 45bdac498..cdbd12250 100644 --- a/nebula_app/src/gpui_shell/workspace/top_tabs.rs +++ b/nebula_app/src/gpui_shell/workspace/top_tabs.rs @@ -16,6 +16,7 @@ use gpui_component::menu::PopupMenuItem; use crate::gpui_shell::prelude::*; use crate::gpui_shell::terminal::view::SidebarActivity; +use crate::i18n::{Message, UiLanguage}; use super::{ NebulaWorkspace, NewWindow, OpenSettings, TAB_LABEL_ICON_SIZE, TAB_LABEL_ICON_W, TabDrag, @@ -88,24 +89,25 @@ fn horizontal_wheel_delta(x: f32, y: f32) -> f32 { /// 顶部加号的生产调用点与鼠标测试共用同一个元素构造,避免测试只证明 /// `title_bar_panel_controls` 本身,却漏掉真实按钮没有接入它。 pub(super) fn top_new_tab_control( + language: UiLanguage, on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, ) -> gpui::Div { title_bar_panel_controls().h_auto().child( Button::new("top-new-tab") .icon(IconName::Plus) .ghost() - .tooltip("新建终端 (Ctrl+Shift+T)") + .tooltip(language.text(Message::ChromeNewTerminalCtrlShiftT)) .on_click(on_click), ) } /// “更多”入口的生产按钮与几何探针共用同一个构造,避免测试用近似尺寸替代。 -pub(super) fn top_tabs_menu_button(settings_active: bool) -> Button { +pub(super) fn top_tabs_menu_button(settings_active: bool, language: UiLanguage) -> Button { Button::new("top-tabs-menu") .icon(IconName::EllipsisVertical) .ghost() .selected(settings_active) - .tooltip("更多") + .tooltip(language.text(Message::ChromeMore)) } /// 紧邻 TabView 的操作按钮占满同一条 34px 行,再在槽内居中 32px 按钮。 @@ -128,6 +130,7 @@ impl NebulaWorkspace { window: &mut Window, cx: &mut Context, ) -> gpui::AnyElement { + let language = crate::gpui_shell::config::ui_language(cx); let theme = cx.theme(); let muted = theme.muted_foreground; let active_bg = theme.sidebar_accent; @@ -555,7 +558,7 @@ impl NebulaWorkspace { .ghost() .xsmall() .disabled(at_strip_start(scroll_x)) - .tooltip("向左翻标签") + .tooltip(language.text(Message::ChromeScrollTabsLeft)) .on_click(cx.listener(move |this, _, _, cx| { this.nudge_top_tabs( -1.0, @@ -603,7 +606,7 @@ impl NebulaWorkspace { .ghost() .xsmall() .disabled(at_strip_end(scroll_x, strip_w, tab_viewport_w)) - .tooltip("向右翻标签") + .tooltip(language.text(Message::ChromeScrollTabsRight)) .on_click(cx.listener(move |this, _, _, cx| { this.nudge_top_tabs( 1.0, @@ -618,7 +621,7 @@ impl NebulaWorkspace { ) }) .child( - top_tab_action_slot(top_new_tab_control(cx.listener( + top_tab_action_slot(top_new_tab_control(language, cx.listener( |this, _, window, cx| { this.add_terminal(window, cx); }, @@ -626,7 +629,7 @@ impl NebulaWorkspace { ) .child( top_tab_action_slot( - top_tabs_menu_button(settings_active).dropdown_menu_with_anchor( + top_tabs_menu_button(settings_active, language).dropdown_menu_with_anchor( gpui::Anchor::TopRight, move |menu, _, _| { let shell_picker = menu_workspace.clone(); @@ -634,7 +637,7 @@ impl NebulaWorkspace { let settings = menu_workspace.clone(); menu.external_link_icon(false) .item( - PopupMenuItem::new("新建窗口") + PopupMenuItem::new(language.text(Message::CommonNewWindow)) .icon(IconName::Plus) .action(Box::new(NewWindow)) .on_click(move |_, _, cx| { @@ -648,7 +651,7 @@ impl NebulaWorkspace { }), ) .item( - PopupMenuItem::new("选择终端") + PopupMenuItem::new(language.text(Message::ChromeSelectTerminal)) .icon(IconName::SquareTerminal) .action(Box::new(ToggleShellPicker)) .on_click(move |_, window, cx| { @@ -661,7 +664,7 @@ impl NebulaWorkspace { ) .separator() .item( - PopupMenuItem::new("设置") + PopupMenuItem::new(language.text(Message::CommonSettings)) .icon(IconName::Settings) .action(Box::new(OpenSettings)) .on_click(move |_, window, cx| { @@ -691,7 +694,7 @@ impl NebulaWorkspace { ) .ghost() .selected(self.command_manager_open) - .tooltip("命令列表") + .tooltip(language.text(Message::ChromeCommandList)) .on_click(cx.listener(|this, _, window, cx| { this.toggle_command_manager(window, cx); })), diff --git a/nebula_app/src/i18n/tests.rs b/nebula_app/src/i18n/tests.rs index 1bd788055..08342d65e 100644 --- a/nebula_app/src/i18n/tests.rs +++ b/nebula_app/src/i18n/tests.rs @@ -72,6 +72,33 @@ fn inline_migration_preserves_bilingual_text_and_english_fallback() { assert_eq!(UiLanguage::EnUs.pick("网络", "Network"), "Network"); assert_eq!(UiLanguage::FrFr.pick("网络", "Network"), "Réseau"); assert_eq!(UiLanguage::FrFr.pick("未迁移文案", "Unmigrated text"), "Unmigrated text"); + // File menus reuse CommonOpen instead of adding an en/zh-only "Open" + // alias which would disable the existing translations in the bridge. + for language in UiLanguage::ALL { + assert_eq!(language.pick("打开", "Open"), language.text(Message::CommonOpen)); + } +} + +#[test] +fn workspace_confirmations_preserve_names_and_resolve_each_language_independently() { + let process = "worker {process} 世界"; + let message = Message::WorkspaceCloseRunningProcess; + assert_eq!( + UiLanguage::EnUs.format(message, &[("process", process)]), + "worker {process} 世界 is still running. Closing will stop it." + ); + assert_eq!( + UiLanguage::ZhCn.format(message, &[("process", process)]), + "worker {process} 世界 仍在运行,关闭会中止它。" + ); + assert_eq!( + UiLanguage::EnUs.format(Message::FilesDeleteTitle, &[("name", "{name}.txt")]), + "Delete {name}.txt?" + ); + assert_eq!( + UiLanguage::FrFr.format(message, &[("process", process)]), + UiLanguage::EnUs.format(message, &[("process", process)]) + ); } #[test] From 33e7b1d00d5728e96b745eaa3d8a21feb97a1669 Mon Sep 17 00:00:00 2001 From: Kuddev Date: Sat, 26 Sep 2026 13:25:29 +0800 Subject: [PATCH 06/14] ci: speed up full cross-platform PR validation (#296) Use pinned nextest for full native tests while retaining doctests, production-feature checks and both macOS release checks. Publish shared dependency snapshots from successful default-branch runs, keep compiled artifacts architecture-specific, and preserve cross-process exclusion for shared theme fixtures. Run the full platform matrix for both draft and ready pull requests without repeating it for readiness-only transitions. --- .config/nextest.toml | 8 ++ .github/actions/rust-cache/action.yml | 47 +++++-- .github/workflows/linux-lua.yml | 28 ++-- CONTRIBUTING.md | 21 +-- .../ci/2026-09-23-native-matrix-planning.md | 2 + .../ci/2026-09-25-shared-native-pr-cache.md | 122 ++++++++++++++++++ scripts/ci_native_tests.py | 31 ++++- scripts/ci_plan.py | 29 ++--- scripts/tests/test_ci_cache.py | 35 ++++- scripts/tests/test_ci_native_tests.py | 116 +++++++++++++---- scripts/tests/test_ci_plan.py | 13 +- 11 files changed, 368 insertions(+), 84 deletions(-) create mode 100644 .config/nextest.toml create mode 100644 architecture/notes/scripts/ci/2026-09-25-shared-native-pr-cache.md diff --git a/.config/nextest.toml b/.config/nextest.toml new file mode 100644 index 000000000..51b7cc3d4 --- /dev/null +++ b/.config/nextest.toml @@ -0,0 +1,8 @@ +# 这些现有夹具共享真实设置文件;进程内 Mutex 在 nextest 多进程模型下不再互斥。 +# 只还原该夹具组的串行合同,其余测试继续使用 runner 的并行度。 +[test-groups] +theme-studio = { max-threads = 1 } + +[[profile.default.overrides]] +filter = 'test(gpui_shell::settings_pane::theme_studio_tests::)' +test-group = 'theme-studio' diff --git a/.github/actions/rust-cache/action.yml b/.github/actions/rust-cache/action.yml index 3415bd8ab..2bd1d34a0 100644 --- a/.github/actions/rust-cache/action.yml +++ b/.github/actions/rust-cache/action.yml @@ -14,6 +14,12 @@ inputs: extra-key: description: Additional inputs for native build tools stored with this target default: "" + revision: + description: Snapshot suffix; empty uses the source SHA, dependency snapshots use a fixed generation + default: "" + save-if: + description: Allow publishing caches; PR consumers can restore without competing with the default branch + default: "true" outputs: cache-key: @@ -25,6 +31,9 @@ outputs: cache-matched-key: description: The compiled target cache key actually restored by actions/cache value: ${{ steps.target.outputs.cache-matched-key }} + save-enabled: + description: Whether the caller permits publishing cache snapshots + value: ${{ inputs.save-if }} legacy-fallback-invoked: description: Whether the optional legacy cache fallback action was invoked value: ${{ steps.cache-summary.outputs.legacy-fallback-invoked }} @@ -42,7 +51,7 @@ runs: CACHE_OS: ${{ runner.os }} CACHE_ARCH: ${{ runner.arch }} CACHE_WORKLOAD: ${{ inputs.key }} - CACHE_REVISION: ${{ github.sha }} + CACHE_REVISION: ${{ inputs.revision || github.sha }} CACHE_MANIFESTS: ${{ hashFiles('Cargo.lock', '**/Cargo.toml', 'rust-toolchain.toml', '**/.cargo/config.toml', '.github/ci-profile.toml') }}${{ inputs.extra-key }} run: | python - <<'PY' @@ -66,8 +75,8 @@ runs: ("CACHE_OS", "CACHE_ARCH", "CACHE_WORKLOAD")) prefix += "-" + fingerprint + "-" with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: - # Immutable caches need a new entry after a source change, including - # when the prior revision failed before it compiled every profile. + # 发布任务按源码刷新;原生 CI 可固定代次,只在依赖或工具链变化后新建快照。 + # 缓存命中只复用编译输入,调用方仍须执行当前提交的全部检查。 output.write("key=" + prefix + os.environ["CACHE_MANIFESTS"] + "-" + os.environ["CACHE_REVISION"] + "\n") output.write("manifest-key=" + prefix + os.environ["CACHE_MANIFESTS"] + "\n") output.write("restore-key=" + prefix + "\n") @@ -92,8 +101,11 @@ runs: ${{ steps.identity.outputs.cargo-home }}/registry/cache ${{ steps.identity.outputs.cargo-home }}/git/db ${{ steps.identity.outputs.cargo-home }}/git/checkouts - key: cargo-downloads-v2-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('Cargo.lock', '**/Cargo.toml') }} - restore-keys: cargo-downloads-v2-${{ runner.os }}-${{ runner.arch }}- + # 同一 OS 的两种架构共享源码,编译产物仍按架构隔离。 + key: cargo-downloads-v3-${{ runner.os }}-${{ hashFiles('Cargo.lock', '**/Cargo.toml') }} + restore-keys: | + cargo-downloads-v3-${{ runner.os }}- + cargo-downloads-v2-${{ runner.os }}-${{ runner.arch }}- - name: Restore compiled targets id: target uses: actions/cache/restore@v4 @@ -127,6 +139,7 @@ runs: CACHE_WORKLOAD: ${{ inputs.key }} RUNNER_OS_VALUE: ${{ runner.os }} RUNNER_ARCH_VALUE: ${{ runner.arch }} + CACHE_SAVE_ENABLED: ${{ inputs.save-if }} run: | set -euo pipefail @@ -148,6 +161,7 @@ runs: echo "- Target cache exact hit: \`$target_cache_hit\`" echo "- Target cache matched key: \`$target_cache_matched_key\`" echo "- Save key: \`$save_key\`" + echo "- Cache publishing enabled: \`$CACHE_SAVE_ENABLED\`" echo "- Legacy fallback configured: \`$legacy_configured\`" echo "- Legacy fallback invoked: \`$legacy_invoked\`" echo "- Legacy fallback outcome: \`$legacy_outcome\`" @@ -159,14 +173,27 @@ runs: echo "legacy-fallback-outcome=$legacy_outcome" } >> "$GITHUB_OUTPUT" - name: Populate complete downloads before sharing the cache - if: steps.downloads.outputs.cache-hit != 'true' + if: inputs.save-if == 'true' && steps.downloads.outputs.cache-hit != 'true' shell: bash + env: + CACHE_OS: ${{ runner.os }} run: | - host_target="$(rustc -vV | sed -n 's/^host: //p')" - test -n "$host_target" - cargo fetch --locked --target "$host_target" + # 缓存由先完成的架构写入,必须预取两者的源码,不能把半份下载标成精确命中。 + case "$CACHE_OS" in + Windows) + cargo fetch --locked --target x86_64-pc-windows-msvc --target aarch64-pc-windows-msvc + ;; + macOS) + cargo fetch --locked --target x86_64-apple-darwin --target aarch64-apple-darwin + ;; + *) + host_target="$(rustc -vV | sed -n 's/^host: //p')" + test -n "$host_target" + cargo fetch --locked --target "$host_target" + ;; + esac - name: Save complete shared Cargo downloads - if: steps.downloads.outputs.cache-hit != 'true' + if: inputs.save-if == 'true' && steps.downloads.outputs.cache-hit != 'true' uses: actions/cache/save@v4 with: path: | diff --git a/.github/workflows/linux-lua.yml b/.github/workflows/linux-lua.yml index 8205936e4..2d70f4d9a 100644 --- a/.github/workflows/linux-lua.yml +++ b/.github/workflows/linux-lua.yml @@ -11,14 +11,15 @@ on: push: branches: [main] # Include docs, catalogs, assets and workflow edits: every PR gets test results. - # ready_for_review starts the scarce-runner jobs that draft pushes skip. + # 草稿已跑完整矩阵,转为 Ready 而没有新提交时不重复申请七个原生 runner。 pull_request: - types: [opened, synchronize, reopened, ready_for_review] + types: [opened, synchronize, reopened] merge_group: concurrency: group: native-${{ github.workflow }}-${{ github.event_name }}-${{ github.ref }} - cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'merge_group' }} + # main 的过期验证也应释放 runner;手动诊断和发布调用不互相取消。 + cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/main') }} permissions: contents: read @@ -75,9 +76,7 @@ jobs: --output "$GITHUB_OUTPUT" # The required lint job validates the matrix before heavy runners are - # requested. Draft PRs omit deferred platforms entirely; ready PRs and - # release callers require the full matrix. Deferred checks remain missing - # on drafts instead of being reported as successful tests. + # requested. Every PR, including a draft, requires the complete matrix. native-tests: needs: lint if: ${{ inputs.windows_diagnostics_run == '' }} @@ -131,6 +130,10 @@ jobs: if ($LASTEXITCODE -ne 0 -or $compiler -notcontains 'host: aarch64-pc-windows-msvc') { throw 'The Windows ARM job must compile and run ARM64 tests.' } + - name: Install the pinned native test runner + uses: taiki-e/install-action@v2 + with: + tool: cargo-nextest@0.9.146 - uses: ./.github/actions/rust-cache id: rust-cache with: @@ -139,7 +142,9 @@ jobs: target: | target/ci ${{ runner.os != 'macOS' && 'target/release' || '' }} - legacy-key: ${{ runner.os == 'Windows' && 'windows' || runner.os == 'Linux' && 'linux' || 'macos' }} + # PR merge-ref 缓存不与其他 PR 共享;只由默认分支维护可复用的依赖快照。 + revision: dependencies-v1 + save-if: ${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} - name: Prepare pinned Windows console runtime if: ${{ runner.os == 'Windows' }} shell: pwsh @@ -148,7 +153,7 @@ jobs: ./scripts/prepare-windows-runtime.ps1 -Destination assets/windows/conhost -Architecture $architecture ./scripts/tests/windows-runtime.tests.ps1 -Architecture $architecture - name: Test complete workspace and native harness - run: python scripts/ci_native_tests.py + run: python scripts/ci_native_tests.py --runner nextest - name: Check source architecture if: ${{ !cancelled() && runner.os == 'Linux' }} run: python scripts/check_architecture.py @@ -159,7 +164,7 @@ jobs: if: ${{ !cancelled() && runner.os != 'macOS' }} run: cargo check --locked --workspace --release - name: Save compiled workload - if: ${{ always() && steps.rust-cache.outcome == 'success' && steps.rust-cache.outputs.cache-hit != 'true' }} + if: ${{ success() && steps.rust-cache.outputs.save-enabled == 'true' && steps.rust-cache.outputs.cache-hit != 'true' }} uses: actions/cache/save@v4 with: path: | @@ -214,11 +219,12 @@ jobs: with: key: native-release-check target: target/release - legacy-key: macos + revision: dependencies-v1 + save-if: ${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} - name: Check the release workspace run: cargo check --locked --workspace --release --timings - name: Save compiled workload - if: ${{ always() && steps.rust-cache.outcome == 'success' && steps.rust-cache.outputs.cache-hit != 'true' }} + if: ${{ success() && steps.rust-cache.outputs.save-enabled == 'true' && steps.rust-cache.outputs.cache-hit != 'true' }} uses: actions/cache/save@v4 with: path: target/release diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d2547b272..6ef5132cc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -130,13 +130,18 @@ compile check into a claim that UI tests or a packaged application were run. `Tests ()` jobs and both `Release workspace ()` jobs are required checks on `main`, together with Code Owner approval; see the [activation checklist](docs/project-constraints.md#server-side-activation). -Open pull requests as drafts while iterating: drafts run Linux, Windows x64 and -Apple Silicon tests plus the Apple Silicon release-profile compile check. The -required lint job validates the event and selects the matrix before requesting -platform runners. Drafts omit Intel Mac and Windows ARM64 jobs entirely, so their -required contexts may be missing until the PR is marked ready. Ready PRs run the -full matrix; every required check must succeed before merging. The ready event -still reruns core validation rather than reusing an earlier check conclusion. +Draft and ready pull requests both run all five native platforms and both macOS +release-profile compile checks. The required lint job validates the event and +selects the matrix before requesting platform runners. Every required check must +succeed before merging. Marking a draft ready without changing its commits does +not repeat the matrix; source updates and reopen events run it again. Native CI +uses pinned `cargo-nextest` for unit and +integration tests, followed by `cargo test --doc` with the same workspace features; +the production feature graph and release workspace are still checked separately. +PRs restore Cargo caches without uploading merge-ref snapshots. The default branch +publishes reusable snapshots per dependency/toolchain configuration; a cache hit +never skips current-commit tests. Downloads are shared between architectures of +the same OS, while compiled targets remain isolated by architecture and SDK. Local hooks are convenient, but bypassable; they are not the enforcement boundary. Submitting a workflow or `CODEOWNERS` file does not configure server-side rules. @@ -150,7 +155,7 @@ feature work; there is no routine `--skip-architecture` option. - 先读架构图、工程合同和决策记录;按职责拆分,不按行号切片。 - 一个 PR 只做一件事;改动超过 1500 行源码(不计文档、lockfile、资源)`pr-size` 会失败,请拆分。 -- Draft PR 先运行必需的格式检查和矩阵规划,再创建 Linux / Windows x64 / Apple Silicon 测试及 Apple Silicon release 编译检查;不创建 Intel Mac / Windows ARM64 任务。Ready 后运行完整矩阵,十项必需检查全绿才能合并。 +- Draft 和 Ready PR 都先运行必需的格式检查和矩阵规划,再执行五平台原生测试及两项 macOS release 编译检查;十项必需检查全绿才能合并。提速使用共享缓存与并行测试,不省略平台或 doctest。 - 2000 行是现有仓库的防灾上限,800 行只提示审查,不是“大厂标准”。 - 普通功能 PR 不得增加存量债务;有问题的规则可以修订,但要有反例、测试和维护者审批。 - 新增核心抽象、依赖方向、持久化或线程模型改变要先说明设计,不强迫每个小修复写 ADR。 diff --git a/architecture/notes/scripts/ci/2026-09-23-native-matrix-planning.md b/architecture/notes/scripts/ci/2026-09-23-native-matrix-planning.md index dfe22fd46..5fc1d9723 100644 --- a/architecture/notes/scripts/ci/2026-09-23-native-matrix-planning.md +++ b/architecture/notes/scripts/ci/2026-09-23-native-matrix-planning.md @@ -1,5 +1,7 @@ # Plan the native matrix before requesting runners +Draft coverage policy superseded by [shared native PR caches](2026-09-25-shared-native-pr-cache.md). + ## Status Implemented for review. Preserves the existing ten required check names and diff --git a/architecture/notes/scripts/ci/2026-09-25-shared-native-pr-cache.md b/architecture/notes/scripts/ci/2026-09-25-shared-native-pr-cache.md new file mode 100644 index 000000000..8c827f719 --- /dev/null +++ b/architecture/notes/scripts/ci/2026-09-25-shared-native-pr-cache.md @@ -0,0 +1,122 @@ +# Speed up native PR checks without dropping platform coverage + +## Status + +Implemented for review. The five native check names and two macOS release-check +names are unchanged. Hosted-runner measurements are pending the independent PR; +this change does not modify GitHub rulesets or claim a fixed completion time. + +## Context + +PR speed must improve without omitting native architectures, doctests, production +features or release-profile compilation. Draft PRs now have the same coverage as +ready PRs. Existing test assertions and failure propagation remain in force. + +## Evidence + +In [run 36119856851](https://github.com/Kuddev/pebrel/actions/runs/36119856851), +the Intel Mac job took 23m55s, including 12m59s of test compilation after both +cache layers missed. In +[run 36084876307](https://github.com/Kuddev/pebrel/actions/runs/36084876307), its +queue alone took 109m24s. Queue time and test execution are different bottlenecks. + +Inspected native target snapshots were approximately 1–1.37 GB. Saving a new +snapshot for every PR commit consumes repository storage even though a sibling +PR cannot restore that merge-ref cache. GitHub documents this scope boundary and +the default cache limit in its +[dependency caching reference](https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching). +Default-branch caches can be restored by PRs. + +Nextest 0.9.146 publishes native Windows ARM64 and x64 binaries and a universal +macOS binary. Its CLI supports the current Cargo profile and timing options. +[Nextest](https://nexte.st/docs/running/) runs unit/integration tests separately +but does not replace Cargo's doctest execution. + +The first hosted nextest run, [Linux job 108135574634](https://github.com/Kuddev/pebrel/actions/runs/36154433909/job/108135574634), +ran 2,245 tests and exposed six theme-studio fixture conflicts. Those tests already +share `lock_theme_studio` because they read and restore the same settings file. +An in-process mutex does not protect separate nextest processes. Nextest's +[test groups](https://nexte.st/docs/configuration/test-groups/) provide the +corresponding cross-process scheduling boundary. + +## Decision + +- The existing validated platform catalog selects all five native platforms and + both macOS release checks for draft and ready PRs. Keep the lint prerequisite, + unfiltered PR triggers, native Windows ARM compiler assertion and SDK checks. + Readiness alone no longer reruns the matrix: its commit already receives full + coverage on `opened`/`synchronize`, and `reopened` still revalidates the PR. +- Native CI installs pinned nextest, runs the complete workspace without test + filters or automatic retries, and explicitly runs `cargo test --doc` with the + same profile/features. Keep the independent production-feature check. The + script's default remains Cargo for existing local and release callers. +- Give the entire existing theme-studio fixture module one nextest group with + `max-threads = 1`, including readers and writers. This restores its previous + mutual exclusion without serializing other tests or changing assertions. +- Native jobs restore caches on PRs but publish only on the default branch. + Use a fixed `dependencies-v1` snapshot suffix together with the existing + compiler, OS, architecture, workload, SDK, flags and manifest identity. Source + changes still run Cargo and all tests; cache hits never substitute results. +- Save the immutable native snapshot only after successful checks. A failed + first attempt must not permanently publish an incomplete snapshot under the + fixed key. Dependency/toolchain changes create new keys; deliberate generation + changes can refresh an otherwise unchanged snapshot. +- Share Cargo downloads between architectures of the same OS. Before publishing, + fetch both supported Windows or macOS targets. Keep compiled targets separate. + Read-only PR consumers fetch only what their actual commands require. Restore + old per-architecture downloads during the cache transition. +- Cancel obsolete main validation runs as well as obsolete PR/merge-group runs. + Do not add more macOS runner jobs or change required status contexts. + +## Rejected alternatives + +- Omit draft, docs-only or platform-specific PR tests: violates the required + cross-platform coverage. +- Drop doctests or the production feature graph when adopting nextest: they + cover contracts not replaced by its unit/integration test execution. +- Remove macOS release checks or fold them back into the long native test job: + they remain required, and prior execution measurements motivated parallelism. +- Cache a new full target directory under every source SHA: duplicates large + snapshots while merge-ref scope prevents reuse by other PRs. +- Add sccache and incremental compilation together: sccache's Rust cache requires + incremental compilation to be disabled and does not cache executable linking. + This change leaves the existing tested compiler profile intact. +- Retry failing tests until green or copy earlier check conclusions: obscures + current-commit failures rather than making validation more efficient. + +## Consequences + +There are still seven native runner jobs for every PR. Drafts request more jobs +than the superseded policy, not fewer. Shared caches and parallel test execution +target avoidable work; hosted-runner capacity still determines queue latency. + +The first successful default-branch run seeds each new snapshot. A dependency +change can still cause a cold build. Release/package callers retain SHA-based +target snapshots; this PR does not change their build or publication semantics. + +## Validation + +The existing planner, native-workflow, cache, stable-release, platform-cfg and +PR-size contract suites ran 58 tests locally: 57 passed, one POSIX-only summary +execution test was skipped on Windows. Tests cover full draft/ready matrices, +read-only PR cache behavior, cross-architecture download completeness, retained +doctests/features and failure propagation at each command. + +Actionlint 1.7.12 passed for the native workflow. The architecture check passed +against the PR base without policy/budget changes. Nextest ran all 71 +`nebula-settings` tests successfully on Windows; its discovered test names match +Cargo's inventory exactly. Rustfmt and the subset's doctest command also passed +(that subset has zero doctests). Full native/GPUI execution, +cache restore/save behavior and cold/warm timing comparisons are validated by +the hosted PR runs, not inferred from the local subset. + +## Supersedes + +The draft coverage reduction in +[native matrix planning](2026-09-23-native-matrix-planning.md). Its validated +event planning and required lint ownership remain unchanged. + +## Revisit when + +Measured cache hit rates, archive transfer costs, nextest process overhead or +runner queue times justify a different bounded cache or test scheduling policy. diff --git a/scripts/ci_native_tests.py b/scripts/ci_native_tests.py index e68b68281..2b3ac219a 100644 --- a/scripts/ci_native_tests.py +++ b/scripts/ci_native_tests.py @@ -3,19 +3,32 @@ from __future__ import annotations +import argparse import subprocess import sys +from typing import Sequence -def native_commands() -> list[list[str]]: +def native_commands(runner: str = "cargo") -> list[list[str]]: profile = ["--config", ".github/ci-profile.toml", "--profile", "ci"] + workspace = ["--locked", "--workspace", "--features", "nebula/gpui-test-support", "--timings"] + if runner == "cargo": + tests = [["cargo", "test", *profile, *workspace]] + elif runner == "nextest": + tests = [ + [ + "cargo", "nextest", "run", "--config", ".github/ci-profile.toml", + "--cargo-profile", "ci", *workspace, "--no-fail-fast", "--retries", "0", + ], + # nextest 不执行 doctest;显式补跑,提速不改变 workspace 的覆盖范围。 + ["cargo", "test", *profile, *workspace, "--doc"], + ] + else: + raise ValueError(f"unknown test runner: {runner}") return [ [sys.executable, "-m", "unittest", "discover", "-s", "scripts/tests", "-v"], [sys.executable, "-m", "unittest", "discover", "-s", "scripts/conformance/tests", "-v"], - [ - "cargo", "test", "--locked", *profile, "--workspace", - "--features", "nebula/gpui-test-support", "--timings", - ], + *tests, # Link the test graph first: check can reuse compatible compiled # dependencies, while metadata-only check output cannot link the tests. # Keep the actual production feature graph independently checked. @@ -26,8 +39,12 @@ def native_commands() -> list[list[str]]: ] -def main() -> int: - for command in native_commands(): +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + # 发布脚本和本地入口保留 cargo 默认值,仅原生 CI 显式选择已安装的 nextest。 + parser.add_argument("--runner", choices=("cargo", "nextest"), default="cargo") + arguments = parser.parse_args(argv) + for command in native_commands(arguments.runner): print("Running:", " ".join(command), flush=True) subprocess.run(command, check=True) return 0 diff --git a/scripts/ci_plan.py b/scripts/ci_plan.py index 4e6432f0b..7fbce87fe 100644 --- a/scripts/ci_plan.py +++ b/scripts/ci_plan.py @@ -1,9 +1,8 @@ #!/usr/bin/env python3 """Plan the native CI matrices before GitHub creates runner jobs. -The output file is the path normally supplied as ``GITHUB_OUTPUT``. Planning -is deliberately separate from workflow steps: a draft pull request therefore -does not materialize jobs for the scarce platforms. +The output file is the path normally supplied as ``GITHUB_OUTPUT``. Validate +the event before requesting runners; draft and ready PRs get the same coverage. """ from __future__ import annotations @@ -19,17 +18,16 @@ @dataclass(frozen=True) class Platform: runner: str - draft: bool release_check: bool = False -# One platform catalog owns both draft eligibility and release compilation. +# 所有 PR 共用平台清单,避免提速时把草稿的原生覆盖悄悄省略。 PLATFORMS = ( - Platform("ubuntu-24.04", draft=True), - Platform("windows-2022", draft=True), - Platform("macos-26", draft=True, release_check=True), - Platform("windows-11-arm", draft=False), - Platform("macos-26-intel", draft=False, release_check=True), + Platform("ubuntu-24.04"), + Platform("windows-2022"), + Platform("macos-26", release_check=True), + Platform("windows-11-arm"), + Platform("macos-26-intel", release_check=True), ) FULL_EVENTS = frozenset( @@ -41,11 +39,10 @@ class PlanError(ValueError): """An event cannot be converted into a safe CI plan.""" -def _matrices(draft: bool) -> tuple[list[dict[str, str]], list[dict[str, str]]]: - selected = [platform for platform in PLATFORMS if not draft or platform.draft] +def _matrices() -> tuple[list[dict[str, str]], list[dict[str, str]]]: return ( - [{"os": platform.runner} for platform in selected], - [{"os": platform.runner} for platform in selected if platform.release_check], + [{"os": platform.runner} for platform in PLATFORMS], + [{"os": platform.runner} for platform in PLATFORMS if platform.release_check], ) @@ -79,10 +76,10 @@ def plan_matrices(event_name: str, payload: dict[str, Any]) -> tuple[list[dict[s draft = pull_request.get("draft") if not isinstance(draft, bool): raise PlanError("pull_request.draft must be a boolean") - return _matrices(draft) + return _matrices() if event_name in FULL_EVENTS: - return _matrices(draft=False) + return _matrices() supported = sorted(FULL_EVENTS | {"pull_request"}) raise PlanError(f"unsupported event name {event_name!r}; expected one of {', '.join(supported)}") diff --git a/scripts/tests/test_ci_cache.py b/scripts/tests/test_ci_cache.py index 764ea3db0..99a083a5e 100644 --- a/scripts/tests/test_ci_cache.py +++ b/scripts/tests/test_ci_cache.py @@ -108,6 +108,7 @@ def test_summary_exposes_real_target_cache_outputs(self): "Target cache exact hit", "Target cache matched key", "Save key", + "Cache publishing enabled", "Legacy fallback invoked", "Legacy fallback outcome", ): @@ -149,21 +150,51 @@ def test_summary_executes_exact_partial_and_legacy_cache_cases(self): "GITHUB_OUTPUT": str(root / "outputs"), "TARGET_CACHE_HIT": hit, "TARGET_CACHE_MATCHED_KEY": matched, "SAVE_KEY": "new-save-key", "LEGACY_CONFIGURED": configured, + "CACHE_SAVE_ENABLED": "false", "LEGACY_OUTCOME": outcome, "CACHE_WORKLOAD": workload, "RUNNER_OS_VALUE": "Linux", "RUNNER_ARCH_VALUE": "X64", } result = subprocess.run([shutil.which("bash"), "-c", script], env=environment, text=True, capture_output=True, check=False) self.assertEqual(result.returncode, 0, result.stderr) - summary = (root / "summary").read_text() - outputs = (root / "outputs").read_text() + summary = (root / "summary").read_text(encoding="utf-8") + outputs = (root / "outputs").read_text(encoding="utf-8") self.assertIn(f"Target cache exact hit: `{hit or 'false'}`", summary) self.assertIn(f"Target cache matched key: `{matched or ''}`", summary) + self.assertIn("Cache publishing enabled: `false`", summary) self.assertIn(f"legacy-fallback-invoked={invoked}\n", outputs) self.assertIn(f"legacy-fallback-outcome={outcome}\n", outputs) self.assertIn(workload, summary) self.assertFalse(marker.exists(), "summary values must never execute as shell code") + def test_dependency_snapshot_revision_preserves_compatibility_boundaries(self): + source = self.action_text() + self.assertIn("CACHE_REVISION: ${{ inputs.revision || github.sha }}", source) + snapshot = self.identity(CACHE_REVISION="dependencies-v1") + changed = self.identity(CACHE_REVISION="dependencies-v1", CACHE_MANIFESTS="new-dependencies") + self.assertNotEqual(snapshot["key"], changed["key"]) + self.assertEqual(snapshot["restore-key"], changed["restore-key"]) + + def test_source_downloads_share_architectures_but_targets_do_not(self): + source = self.action_text() + self.assertIn("key: cargo-downloads-v3-${{ runner.os }}-${{ hashFiles('Cargo.lock', '**/Cargo.toml') }}", source) + self.assertIn("cargo-downloads-v2-${{ runner.os }}-${{ runner.arch }}-", source) + fetch = source.split("- name: Populate complete downloads before sharing the cache", 1)[1] + for targets in ( + "--target x86_64-pc-windows-msvc --target aarch64-pc-windows-msvc", + "--target x86_64-apple-darwin --target aarch64-apple-darwin", + ): + self.assertIn(f"cargo fetch --locked {targets}", fetch) + self.assertNotEqual(self.identity(CACHE_ARCH="X64")["restore-key"], + self.identity(CACHE_ARCH="ARM64")["restore-key"]) + + def test_read_only_consumers_neither_prefetch_other_architectures_nor_save(self): + source = self.action_text() + self.assertIn("value: ${{ inputs.save-if }}", source) + for step in ("Populate complete downloads before sharing the cache", "Save complete shared Cargo downloads"): + body = source.split(f"- name: {step}", 1)[1].split("\n - name:", 1)[0] + self.assertIn("if: inputs.save-if == 'true' && steps.downloads.outputs.cache-hit != 'true'", body) + @unittest.skipUnless(os.name == "nt", "Windows cache migration") def test_windows_migration_preserves_compiler_and_workload_boundaries(self): before = self.identity() diff --git a/scripts/tests/test_ci_native_tests.py b/scripts/tests/test_ci_native_tests.py index 0055e55c7..383f8a54e 100644 --- a/scripts/tests/test_ci_native_tests.py +++ b/scripts/tests/test_ci_native_tests.py @@ -13,7 +13,7 @@ class NativeSuiteTests(unittest.TestCase): def test_required_lint_plans_runners_before_native_jobs(self): root = Path(__file__).resolve().parents[2] - workflow = (root / ".github/workflows/linux-lua.yml").read_text() + workflow = (root / ".github/workflows/linux-lua.yml").read_text(encoding="utf-8") lint = workflow.split("\n lint:\n", 1)[1].split("\n native-tests:\n", 1)[0] self.assertIn("name: lint", lint) self.assertIn("Test CI contracts before matrix planning", lint) @@ -61,7 +61,7 @@ def test_required_lint_plans_runners_before_native_jobs(self): def test_packages_run_after_merge_or_manual_dispatch_not_for_prs(self): root = Path(__file__).resolve().parents[2] - workflow = (root / ".github/workflows/preview-packages.yml").read_text() + workflow = (root / ".github/workflows/preview-packages.yml").read_text(encoding="utf-8") events = workflow.split("\non:\n", 1)[1].split("\nconcurrency:", 1)[0] triggers = set(re.findall(r"^ ([a-z_]+):", events, re.M)) self.assertEqual(triggers, {"push", "workflow_dispatch"}) @@ -71,7 +71,7 @@ def test_packages_run_after_merge_or_manual_dispatch_not_for_prs(self): self.assertIn("paths:", push.group(1)) # Packaging still needs explicit dispatch to create a public release. self.assertIn("github.event_name == 'workflow_dispatch' && inputs.publish == true", workflow) - stable = (root / ".github/workflows/release.yml").read_text() + stable = (root / ".github/workflows/release.yml").read_text(encoding="utf-8") stable_events = stable.split("\non:\n", 1)[1].split("\nconcurrency:", 1)[0] self.assertEqual(set(re.findall(r"^ ([a-z_]+):", stable_events, re.M)), {"push", "workflow_dispatch"}) @@ -79,7 +79,7 @@ def test_packages_run_after_merge_or_manual_dispatch_not_for_prs(self): def test_every_pr_and_merge_group_runs_without_path_exclusions(self): root = Path(__file__).resolve().parents[2] - workflow = (root / ".github/workflows/linux-lua.yml").read_text() + workflow = (root / ".github/workflows/linux-lua.yml").read_text(encoding="utf-8") events = workflow.split("\non:\n", 1)[1].split("\nconcurrency:", 1)[0] for event in ("pull_request", "merge_group"): declaration = re.search(rf"^ {event}:(.*?)(?=^ [a-z_]+:|\Z)", events, re.M | re.S) @@ -87,9 +87,9 @@ def test_every_pr_and_merge_group_runs_without_path_exclusions(self): self.assertNotIn("paths", declaration.group(1)) self.assertNotIn("branches", declaration.group(1)) if event == "pull_request": - # ready_for_review starts the scarce-runner jobs that draft - # pushes skip; the default activity types must stay listed. - self.assertIn("types: [opened, synchronize, reopened, ready_for_review]", declaration.group(1)) + # Drafts already run the full matrix; readiness alone changes no source. + self.assertIn("types: [opened, synchronize, reopened]", declaration.group(1)) + self.assertNotIn("ready_for_review", declaration.group(1)) else: self.assertNotIn("types", declaration.group(1)) self.assertIn("branches: [main]", events) @@ -100,14 +100,14 @@ def test_every_pr_and_merge_group_runs_without_path_exclusions(self): def test_arm_job_requires_native_execution_and_matching_console_runtime(self): root = Path(__file__).resolve().parents[2] - workflow = (root / ".github/workflows/linux-lua.yml").read_text() + workflow = (root / ".github/workflows/linux-lua.yml").read_text(encoding="utf-8") self.assertIn("windows-11-arm", workflow) self.assertIn("host: aarch64-pc-windows-msvc", workflow) self.assertIn("OSArchitecture -ne 'Arm64'", workflow) self.assertIn("-Architecture $architecture", workflow) self.assertLess(workflow.index("Prepare pinned Windows console runtime"), workflow.index("Test complete workspace")) - preview = (root / ".github/workflows/preview-packages.yml").read_text() + preview = (root / ".github/workflows/preview-packages.yml").read_text(encoding="utf-8") windows = preview.split("\n windows:\n", 1)[1].split("\n aggregate:", 1)[0] self.assertNotIn("prepare-windows-runtime.ps1", preview.split("\njobs:", 1)[1].split("\n windows:", 1)[0]) self.assertLess(windows.index("prepare-windows-runtime.ps1"), @@ -128,16 +128,75 @@ def test_full_workspace_and_interactions_share_one_unfiltered_invocation(self): self.assertNotIn("--", command) def test_actual_product_feature_graph_is_also_checked(self): - checks = [command for command in native_commands() if command[:2] == ["cargo", "check"]] - self.assertEqual(len(checks), 1) - command = checks[0] - self.assertEqual(command[command.index("--features") + 1], "gpui-shell") - self.assertEqual(command[command.index("--bin") + 1], "pebrel") + for runner in ("cargo", "nextest"): + with self.subTest(runner=runner): + checks = [command for command in native_commands(runner) if command[:2] == ["cargo", "check"]] + self.assertEqual(len(checks), 1) + command = checks[0] + self.assertEqual(command[command.index("--features") + 1], "gpui-shell") + self.assertEqual(command[command.index("--bin") + 1], "pebrel") + + def test_nextest_runs_all_native_targets_and_preserves_doctests(self): + commands = native_commands("nextest") + tests = [command for command in commands if command[:3] == ["cargo", "nextest", "run"]] + docs = [command for command in commands if command[:2] == ["cargo", "test"]] + self.assertEqual(len(tests), 1) + self.assertEqual(len(docs), 1) + self.assertIn("--doc", docs[0]) + self.assertNotIn("--doc", tests[0]) + for command, profile_flag in ((tests[0], "--cargo-profile"), (docs[0], "--profile")): + self.assertIn("--locked", command) + self.assertIn("--workspace", command) + self.assertIn("--timings", command) + self.assertEqual(command[command.index("--features") + 1], "nebula/gpui-test-support") + self.assertEqual(command[command.index(profile_flag) + 1], "ci") + self.assertEqual(command[command.index("--config") + 1], ".github/ci-profile.toml") + for excluded in ("--exclude", "--lib", "--skip", "--filterset", "--partition", "--no-run"): + self.assertNotIn(excluded, command) + self.assertIn("--no-fail-fast", tests[0]) + self.assertEqual(tests[0][tests[0].index("--retries") + 1], "0") + self.assertLess(commands.index(tests[0]), commands.index(docs[0])) + + def test_native_workflow_installs_nextest_without_changing_release_callers(self): + root = Path(__file__).resolve().parents[2] + workflow = (root / ".github/workflows/linux-lua.yml").read_text(encoding="utf-8") + native = workflow.split("\n native-tests:\n", 1)[1].split("\n macos-release-check:\n", 1)[0] + install = native.split("- name: Install the pinned native test runner", 1)[1].split(" - uses:", 1)[0] + self.assertIn("uses: taiki-e/install-action@v2", install) + self.assertIn("tool: cargo-nextest@0.9.146", install) + self.assertNotIn("if:", install) + self.assertIn("run: python scripts/ci_native_tests.py --runner nextest", native) + release = (root / ".github/workflows/release.yml").read_text(encoding="utf-8") + self.assertIn("run: python scripts/ci_native_tests.py\n", release) + + def test_nextest_preserves_only_the_existing_shared_theme_fixture_mutex(self): + root = Path(__file__).resolve().parents[2] + config = tomllib.loads((root / ".config/nextest.toml").read_text(encoding="utf-8")) + self.assertEqual(config["test-groups"], {"theme-studio": {"max-threads": 1}}) + self.assertEqual(config["profile"]["default"], { + "overrides": [{ + "filter": "test(gpui_shell::settings_pane::theme_studio_tests::)", + "test-group": "theme-studio", + }], + }) + + def test_native_caches_are_default_branch_snapshots_not_per_pr_uploads(self): + root = Path(__file__).resolve().parents[2] + workflow = (root / ".github/workflows/linux-lua.yml").read_text(encoding="utf-8") + for job in ("native-tests", "macos-release-check"): + body = workflow.split(f"\n {job}:\n", 1)[1] + body = re.split(r"\n [a-z][a-z-]*:\n", body, maxsplit=1)[0] + self.assertIn("revision: dependencies-v1", body) + self.assertIn("save-if: ${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }}", body) + save = body.split("- name: Save compiled workload", 1)[1].split(" - name:", 1)[0] + self.assertIn("success() && steps.rust-cache.outputs.save-enabled == 'true'", save) + self.assertNotIn("always()", save) + self.assertIn("steps.rust-cache.outputs.cache-hit != 'true'", save) def test_fast_test_profile_preserves_runtime_checks_and_resets_named_overrides(self): root = Path(__file__).resolve().parents[2] - config = tomllib.loads((root / ".github/ci-profile.toml").read_text()) - workspace = tomllib.loads((root / "Cargo.toml").read_text()) + config = tomllib.loads((root / ".github/ci-profile.toml").read_text(encoding="utf-8")) + workspace = tomllib.loads((root / "Cargo.toml").read_text(encoding="utf-8")) profile = config["profile"]["ci"] self.assertEqual(profile["inherits"], "dev") self.assertTrue(profile["debug-assertions"]) @@ -155,17 +214,24 @@ def test_both_python_test_roots_are_discovered(self): self.assertTrue(all("discover" in command for command in suites)) def test_success_runs_every_command_and_checks_exit_codes(self): - with patch("scripts.ci_native_tests.subprocess.run") as run: - self.assertEqual(main(), 0) - self.assertEqual(run.call_count, len(native_commands())) - self.assertTrue(all(call.kwargs["check"] for call in run.call_args_list)) + for runner in ("cargo", "nextest"): + with self.subTest(runner=runner), patch("scripts.ci_native_tests.subprocess.run") as run: + self.assertEqual(main(["--runner", runner]), 0) + self.assertEqual([call.args[0] for call in run.call_args_list], native_commands(runner)) + self.assertTrue(all(call.kwargs["check"] for call in run.call_args_list)) def test_failure_stops_the_suite_and_is_not_reported_as_success(self): - with patch("scripts.ci_native_tests.subprocess.run") as run: - run.side_effect = subprocess.CalledProcessError(7, "test") - with self.assertRaises(subprocess.CalledProcessError): - main() - self.assertEqual(run.call_count, 1) + for runner in ("cargo", "nextest"): + for failed in range(len(native_commands(runner))): + with self.subTest(runner=runner, failed=failed), patch("scripts.ci_native_tests.subprocess.run") as run: + run.side_effect = [None] * failed + [subprocess.CalledProcessError(7, "test")] + with self.assertRaises(subprocess.CalledProcessError): + main(["--runner", runner]) + self.assertEqual(run.call_count, failed + 1) + + def test_unknown_runner_is_rejected_before_running_commands(self): + with self.assertRaises(ValueError): + native_commands("typo") if __name__ == "__main__": diff --git a/scripts/tests/test_ci_plan.py b/scripts/tests/test_ci_plan.py index b4f2309b0..e485559b6 100644 --- a/scripts/tests/test_ci_plan.py +++ b/scripts/tests/test_ci_plan.py @@ -36,7 +36,7 @@ def outputs(path: Path) -> dict[str, object]: lines = path.read_text(encoding="utf-8").splitlines() return {name: json.loads(value) for name, value in (line.split("=", 1) for line in lines)} - def test_draft_pr_does_not_materialize_scarce_runner_rows(self) -> None: + def test_draft_pr_has_the_same_full_native_coverage_as_ready_pr(self) -> None: with tempfile.TemporaryDirectory() as directory: output = Path(directory) / "github-output" result = self.run_cli("pull_request", {"pull_request": {"draft": True}}, output) @@ -44,12 +44,15 @@ def test_draft_pr_does_not_materialize_scarce_runner_rows(self) -> None: self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual( output.read_text(encoding="utf-8"), - 'native_matrix=[{"os":"ubuntu-24.04"},{"os":"windows-2022"},{"os":"macos-26"}]\n' - 'release_matrix=[{"os":"macos-26"}]\n', + 'native_matrix=[{"os":"ubuntu-24.04"},{"os":"windows-2022"},{"os":"macos-26"},' + '{"os":"windows-11-arm"},{"os":"macos-26-intel"}]\n' + 'release_matrix=[{"os":"macos-26"},{"os":"macos-26-intel"}]\n', ) plan = self.outputs(output) - self.assertNotIn({"os": "windows-11-arm"}, plan["native_matrix"]) - self.assertNotIn({"os": "macos-26-intel"}, plan["native_matrix"]) + ready_output = Path(directory) / "ready-output" + ready = self.run_cli("pull_request", {"pull_request": {"draft": False}}, ready_output) + self.assertEqual(ready.returncode, 0, ready.stderr) + self.assertEqual(plan, self.outputs(ready_output)) def test_ready_pr_has_all_native_and_release_checks(self) -> None: with tempfile.TemporaryDirectory() as directory: From 83f7246aa377ce16eef9874b28dfbaf78294b8bd Mon Sep 17 00:00:00 2001 From: Anx <130662349+AnxForever@users.noreply.github.com> Date: Sat, 26 Sep 2026 13:49:36 +0800 Subject: [PATCH 07/14] fix(env): translate PEBREL_HOOK_EXE across the WSL boundary (#290) Forward the current and legacy hook executable variables through WSLENV with /p path translation. Document the boundary contract and cover the primary hook variable in the existing environment test. --- docs/runtime-control-api.md | 2 +- nebula_app/src/agent_env.rs | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/docs/runtime-control-api.md b/docs/runtime-control-api.md index 5693c6368..1798c2584 100644 --- a/docs/runtime-control-api.md +++ b/docs/runtime-control-api.md @@ -45,7 +45,7 @@ CLI 路径由环境给出,调用方无需根据展示名称猜测文件名。 还会绕开远端 pane 不得取用本地上下文的护栏。 2. **幂等。** 在 Pebrel 的 pane 里再开一个 Pebrel 是常规操作(嵌套 shell、`wsl.exe`、隔离实例)。 `PATH` 前置与 `WSLENV` 追加都按值判重,套多少层环境块都不增长。 -3. **WSL 透传。** `WSLENV` 里带 `PEBREL_CLI/p`、`PEBREL_BIN_DIR/p`——`/p` 让 WSL 把 Windows +3. **WSL 透传。** `WSLENV` 里带 `PEBREL_CLI/p`、`PEBREL_BIN_DIR/p`、`PEBREL_HOOK_EXE/p`——`/p` 让 WSL 把 Windows 路径翻成 `/mnt/...`,否则来宾 shell 拿到的是一个执行不了的 `D:\…` 字面量。合并以环境表里的 现值为基准,因此与 `shell_detect::wsl_cwd_report_env` 的 cwd 上报条目互不覆盖。 diff --git a/nebula_app/src/agent_env.rs b/nebula_app/src/agent_env.rs index a6788d820..b9e7647ff 100644 --- a/nebula_app/src/agent_env.rs +++ b/nebula_app/src/agent_env.rs @@ -175,10 +175,12 @@ const WSLENV_ENTRIES: &[&str] = &[ "COLORTERM", "PEBREL_CLI/p", "PEBREL_BIN_DIR/p", + "PEBREL_HOOK_EXE/p", PROCESS_ENV, crate::runtime_api::ENDPOINT_ENV, "NEBULA_CLI/p", "NEBULA_BIN_DIR/p", + "NEBULA_HOOK_EXE/p", ]; /// 把 [`WSLENV_ENTRIES`] 合并进 `WSLENV`,保留已有条目。 @@ -319,6 +321,13 @@ mod tests { "{CLI_ENV} missing from WSLENV passthrough: {names:?}" ); assert!(names.contains(&BIN_DIR_ENV), "{BIN_DIR_ENV} missing: {names:?}"); + // Hook 的绝对路径同样是 `D:\…` 字面量,漏掉它 WSL 侧只能照抄出一个 + // 跑不起来的命令(Issue: hook 接线在 WSL pane 里永远 ENOENT)。 + let hook_exe = crate::ai_hook::HOOK_EXE_ENV; + assert!( + names.contains(&hook_exe), + "{hook_exe} missing from WSLENV passthrough: {names:?}" + ); assert!(names.contains(&PROCESS_ENV), "{PROCESS_ENV} missing: {names:?}"); assert!(names.contains(&crate::runtime_api::ENDPOINT_ENV)); assert!(names.contains(&"COLORTERM")); From acea926f913770a6cadfe6c29af8f13d484f42ba Mon Sep 17 00:00:00 2001 From: Cec1c <1518585189@qq.com> Date: Sat, 26 Sep 2026 14:06:55 +0800 Subject: [PATCH 08/14] feat(terminal): add tested cursor motion and preference contracts (#293) Add opt-in off/smooth cursor-motion preferences with conservative defaults and reset support. Add GPUI-local motion trajectory contracts and synchronized-update snapshot regression coverage. Renderer and settings UI integration remain separate. --- .../2026-09-25-opt-in-cursor-motion.md | 28 +++ .../src/gpui_shell/terminal/cursor_motion.rs | 198 ++++++++++++++++++ .../terminal/cursor_motion/tests.rs | 134 ++++++++++++ nebula_app/src/gpui_shell/terminal/mod.rs | 1 + nebula_settings/src/cursor_motion.rs | 65 ++++++ nebula_settings/src/lib.rs | 7 + nebula_settings/src/reset.rs | 10 + nebula_terminal/src/event_loop.rs | 24 +++ 8 files changed, 467 insertions(+) create mode 100644 architecture/notes/nebula_settings/cursor_motion/2026-09-25-opt-in-cursor-motion.md create mode 100644 nebula_app/src/gpui_shell/terminal/cursor_motion.rs create mode 100644 nebula_app/src/gpui_shell/terminal/cursor_motion/tests.rs create mode 100644 nebula_settings/src/cursor_motion.rs diff --git a/architecture/notes/nebula_settings/cursor_motion/2026-09-25-opt-in-cursor-motion.md b/architecture/notes/nebula_settings/cursor_motion/2026-09-25-opt-in-cursor-motion.md new file mode 100644 index 000000000..c90ba8471 --- /dev/null +++ b/architecture/notes/nebula_settings/cursor_motion/2026-09-25-opt-in-cursor-motion.md @@ -0,0 +1,28 @@ +# Opt-in cursor motion preference + +## Status +Accepted for local implementation, 2026-09-25. + +## Context +Expose smooth terminal cursor movement as a dropdown under Appearance / Cursor without changing existing installations. + +## Evidence +RuntimeSettings owns persisted runtime preferences. SettingsPane persists keys and broadcasts Changed, and the workspace hot-applies Settings to open TerminalViews. The existing notification-duration selector demonstrates failure rollback. + +## Decision +Add the shared enum CursorMotion with stable values `off` and `smooth`. Missing, empty or invalid values resolve to Off. Smooth means the fixed 90 ms silkmux trajectory. Include the key in preference reset. The GPUI adapter reads cached settings and applies changes to existing panes; no PTY restart is involved. + +## Rejected alternatives +A boolean loses the explicit option contract. Multiple duration settings are unnecessary for reproducing the approved effect. A new Lua/TOML override would introduce a second source and priority policy without a user need. + +## Consequences +Old settings retain instant movement. Saving does not modify cursor shape/blinking or unknown keys. Failed writes restore the visible selection and show an error. Other shells can ignore the additive preference. + +## Validation +Shared default/invalid/round-trip/reset tests plus GPUI selection, error rollback, localization and hot-application tests. + +## Supersedes +None. + +## Revisit when +Additional user-visible motion modes or a deliberate default change are requested. diff --git a/nebula_app/src/gpui_shell/terminal/cursor_motion.rs b/nebula_app/src/gpui_shell/terminal/cursor_motion.rs new file mode 100644 index 000000000..6189f22ee --- /dev/null +++ b/nebula_app/src/gpui_shell/terminal/cursor_motion.rs @@ -0,0 +1,198 @@ +//! Visual cursor trajectory; never writes terminal coordinates. +//! +//! Behavioral reference: silkmux CursorMotionTracker / projection retreat guard. +//! Match Flutter Curves.easeOutCubic, including its 0.001 Bezier x tolerance. + +use std::collections::VecDeque; +use std::time::Duration; + +pub(super) const DURATION: Duration = Duration::from_millis(90); +const INPUT_LIFETIME: Duration = Duration::from_millis(250); + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(super) struct Position { + pub col: f64, + pub row: f64, +} + +impl Position { + pub fn new(col: f64, row: f64) -> Self { + Self { col, row } + } + fn distance(self, other: Self) -> f64 { + (self.col - other.col).hypot(self.row - other.row) + } +} + +#[derive(Default)] +pub(super) struct CursorMotion { + pub visual: Position, + target: Option, + from: Position, + started: Duration, + last_time: Duration, + moving: bool, + candidate: Option<(Position, Duration, u32)>, + input_guard: Duration, + authorizations: VecDeque<(Option, Duration)>, +} + +impl CursorMotion { + pub fn reset(&mut self) { + *self = Self::default(); + } + pub fn active(&self) -> bool { + self.moving || self.candidate.is_some() + } + + /// Input bytes are already encoded by the terminal adapter. These permits + /// only classify explicit editing; they do not predict a logical position. + pub fn note_input(&mut self, bytes: &[u8], now: Duration) { + let budget = match bytes { + b"\x08" | b"\x7f" | b"\x02" | b"\x1b[D" | b"\x1bOD" => Some(Some(2.0)), + b"\x01" | b"\x15" | b"\x17" | b"\x1bb" | b"\x1b[H" | b"\x1bOH" | b"\x1b[1~" + | b"\x1b[7~" | b"\x1b[A" | b"\x1b[B" | b"\x1bOA" | b"\x1bOB" | b"\x1b[1;5D" => { + Some(None) + }, + _ => None, + }; + self.authorizations.retain(|(_, until)| now < *until); + if let Some(budget) = budget { + if self.authorizations.len() < 8 { + self.authorizations.push_back((budget, now + INPUT_LIFETIME)); + } + } else if bytes.first().is_some_and(|b| *b >= 0x20 && *b != 0x7f) + || matches!( + bytes, + b"\x05" + | b"\x1b[C" + | b"\x1bOC" + | b"\x1b[F" + | b"\x1bOF" + | b"\x1b[4~" + | b"\x1b[8~" + | b"\x1b[3~" + ) + { + self.input_guard = now + INPUT_LIFETIME; + } + } + + pub fn update( + &mut self, + target: Position, + now: Duration, + enabled: bool, + prompt_guard: bool, + cols: usize, + ) -> Position { + let now = now.max(self.last_time); + self.last_time = now; + self.advance(now); + self.authorizations.retain(|(_, until)| now < *until); + let Some(previous) = self.target.filter(|_| enabled) else { + self.snap(target); + return self.visual; + }; + if target == previous { + self.candidate = None; + return self.visual; + } + let retreat = (previous.row - target.row) * cols as f64 + previous.col - target.col; + if prompt_guard && retreat > 0.0 { + let bounded = self + .authorizations + .iter() + .position(|(budget, _)| budget.is_some_and(|max| retreat <= max)); + if let Some(index) = bounded { + self.authorizations.remove(index); + } else { + let (candidate, since, frames) = self.candidate.get_or_insert((target, now, 0)); + if *candidate != target { + (*candidate, *since, *frames) = (target, now, 0); + } + *frames += 1; + if *frames < 4 || now.saturating_sub(*since) < DURATION || now < self.input_guard { + return self.visual; + } + let permit = self + .authorizations + .iter() + .position(|(budget, _)| budget.is_none_or(|max| retreat <= max)); + if let Some(index) = permit { + self.authorizations.remove(index); + } else { + self.snap(target); + return self.visual; + } + } + } else if retreat < 0.0 { + self.input_guard = Duration::ZERO; + } + self.candidate = None; + if self.visual.distance(target) > 8.0 { + self.snap(target); + } else { + self.from = self.visual; + self.target = Some(target); + self.started = now; + self.moving = true; + } + self.visual + } + + fn snap(&mut self, target: Position) { + self.visual = target; + self.target = Some(target); + self.from = target; + self.moving = false; + self.candidate = None; + } + + fn advance(&mut self, now: Duration) { + if !self.moving { + return; + } + let target = self.target.unwrap(); + let progress = now.saturating_sub(self.started).as_secs_f64() / DURATION.as_secs_f64(); + if progress >= 1.0 { + self.visual = target; + self.moving = false; + } else { + let t = ease_out_cubic(progress); + self.visual = Position::new( + self.from.col + (target.col - self.from.col) * t, + self.from.row + (target.row - self.from.row) * t, + ); + } + } +} + +fn ease_out_cubic(t: f64) -> f64 { + if t <= 0.0 { + return 0.0; + } + if t >= 1.0 { + return 1.0; + } + let bezier = |a: f64, b: f64, s: f64| { + 3.0 * a * (1.0 - s) * (1.0 - s) * s + 3.0 * b * (1.0 - s) * s * s + s * s * s + }; + let (mut low, mut high) = (0.0, 1.0); + loop { + let s = (low + high) / 2.0; + let x = bezier(0.215, 0.355, s); + if (t - x).abs() < 0.001 { + return bezier(0.61, 1.0, s); + } + if x < t { + low = s; + } else { + high = s; + } + } +} + +#[cfg(test)] +#[path = "cursor_motion/tests.rs"] +mod tests; diff --git a/nebula_app/src/gpui_shell/terminal/cursor_motion/tests.rs b/nebula_app/src/gpui_shell/terminal/cursor_motion/tests.rs new file mode 100644 index 000000000..16c8ff66d --- /dev/null +++ b/nebula_app/src/gpui_shell/terminal/cursor_motion/tests.rs @@ -0,0 +1,134 @@ +use super::*; + +fn at(ms: u64) -> Duration { + Duration::from_millis(ms) +} +fn p(col: f64) -> Position { + Position::new(col, 0.0) +} +fn step(m: &mut CursorMotion, col: f64, ms: u64) -> Position { + m.update(p(col), at(ms), true, false, 80) +} + +#[test] +fn flutter_reference_samples_and_endpoints_match() { + for (ms, expected) in [ + (0, 0.0), + (15, 0.436340294), + (30, 0.722610222), + (45, 0.875116348), + (60, 0.954034002), + (75, 0.990065658), + (90, 1.0), + ] { + assert!((ease_out_cubic(ms as f64 / 90.0) - expected).abs() < 1e-9); + } + let mut motion = CursorMotion::default(); + step(&mut motion, 0.0, 0); + step(&mut motion, 4.0, 0); + assert!((step(&mut motion, 4.0, 45).col - 3.500465393).abs() < 1e-8); + assert_eq!(step(&mut motion, 4.0, 90), p(4.0)); + assert!(!motion.active()); +} + +#[test] +fn continuous_targets_and_repeated_or_regressed_frames_do_not_pull_back() { + let mut m = CursorMotion::default(); + step(&mut m, 0.0, 0); + step(&mut m, 4.0, 0); + let halfway = step(&mut m, 4.0, 45); + assert_eq!(step(&mut m, 6.0, 45), halfway); + assert_eq!(step(&mut m, 6.0, 20), halfway); + assert!(step(&mut m, 6.0, 60).col > halfway.col); + assert_eq!(step(&mut m, 6.0, 135), p(6.0)); +} + +#[test] +fn eight_cells_animate_but_euclidean_distance_above_eight_snaps() { + let mut m = CursorMotion::default(); + step(&mut m, 0.0, 0); + assert_eq!(step(&mut m, 8.0, 0), p(0.0)); + assert!(m.active()); + step(&mut m, 8.0, 90); + assert_eq!(step(&mut m, 16.01, 90), p(16.01)); + assert!(!m.active()); + assert_eq!( + m.update(Position::new(22.01, 6.0), at(90), true, false, 80), + Position::new(22.01, 6.0) + ); +} + +#[test] +fn disable_reset_and_independent_panes_discard_motion() { + let mut a = CursorMotion::default(); + let mut b = CursorMotion::default(); + step(&mut a, 0.0, 0); + step(&mut b, 10.0, 0); + step(&mut a, 4.0, 0); + assert_eq!(step(&mut b, 10.0, 45), p(10.0)); + assert_eq!(a.update(p(4.0), at(45), false, false, 80), p(4.0)); + assert!(!a.active()); + a.reset(); + assert_eq!(step(&mut a, 5.0, 46), p(5.0)); +} + +#[test] +fn prompt_reset_is_held_but_explicit_left_gets_one_bounded_permit() { + let mut m = CursorMotion::default(); + step(&mut m, 7.0, 0); + m.note_input(b"x", at(1)); + assert_eq!(m.update(p(0.0), at(2), true, true, 80), p(7.0)); + assert_eq!(m.update(p(8.0), at(30), true, true, 80), p(7.0)); + m.update(p(8.0), at(120), true, true, 80); + m.note_input(b"\x1b[D", at(121)); + assert_eq!(m.update(p(0.0), at(122), true, true, 80), p(8.0)); + assert_eq!(m.update(p(7.0), at(130), true, true, 80), p(8.0)); + assert_eq!(m.update(p(7.0), at(220), true, true, 80), p(7.0)); + // That authorization cannot grant a second retreat. + assert_eq!(m.update(p(6.0), at(221), true, true, 80), p(7.0)); + for ms in [240, 260, 311] { + m.update(p(6.0), at(ms), true, true, 80); + } + assert_eq!(m.visual, p(6.0)); + assert!(!m.active()); +} + +#[test] +fn changing_retreat_candidate_restarts_both_time_and_frame_confirmation() { + let mut m = CursorMotion::default(); + step(&mut m, 8.0, 0); + for ms in [1, 30, 60] { + m.update(p(0.0), at(ms), true, true, 80); + } + assert_eq!(m.update(p(1.0), at(91), true, true, 80), p(8.0)); + for ms in [100, 110, 120] { + assert_eq!(m.update(p(1.0), at(ms), true, true, 80), p(8.0)); + } + assert_eq!(m.update(p(1.0), at(181), true, true, 80), p(1.0)); + assert!(!m.active()); +} + +#[test] +fn expired_input_and_alternate_screen_do_not_authorize_prompt_heuristics() { + let mut m = CursorMotion::default(); + step(&mut m, 8.0, 0); + m.note_input(b"\x7f", at(1)); + assert_eq!(m.update(p(7.0), at(300), true, true, 80), p(8.0)); + // TUI positioning is allowed immediately when prompt guarding is off. + assert_eq!(m.update(p(6.0), at(301), true, false, 80), p(8.0)); + assert_eq!(m.update(p(6.0), at(391), true, false, 80), p(6.0)); +} + +#[test] +fn forward_editing_keys_hold_prompt_redraws_until_the_input_guard_expires() { + for input in [&b"x"[..], b"\x1b[C", b"\x1b[F", b"\x1b[3~"] { + let mut m = CursorMotion::default(); + step(&mut m, 8.0, 0); + m.note_input(input, at(1)); + for ms in [2, 35, 70, 100, 200, 250] { + assert_eq!(m.update(p(0.0), at(ms), true, true, 80), p(8.0)); + } + assert_eq!(m.update(p(0.0), at(251), true, true, 80), p(0.0)); + assert!(!m.active()); + } +} diff --git a/nebula_app/src/gpui_shell/terminal/mod.rs b/nebula_app/src/gpui_shell/terminal/mod.rs index 012f095f1..cf3e7ce2a 100644 --- a/nebula_app/src/gpui_shell/terminal/mod.rs +++ b/nebula_app/src/gpui_shell/terminal/mod.rs @@ -7,6 +7,7 @@ mod answer_reader; pub mod colors; mod completion_viewport; pub(super) mod confirmation; +mod cursor_motion; pub mod element; mod event_mailbox; mod inline_image; diff --git a/nebula_settings/src/cursor_motion.rs b/nebula_settings/src/cursor_motion.rs new file mode 100644 index 000000000..eed71ad45 --- /dev/null +++ b/nebula_settings/src/cursor_motion.rs @@ -0,0 +1,65 @@ +//! Persistent opt-in for presentation-only terminal cursor movement. + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum CursorMotion { + #[default] + Off, + Smooth, +} + +impl CursorMotion { + pub const VALUES: &'static [&'static str] = &["off", "smooth"]; + + pub fn from_settings(value: &str) -> Option { + match value.trim() { + value if value.eq_ignore_ascii_case("off") => Some(Self::Off), + value if value.eq_ignore_ascii_case("smooth") => Some(Self::Smooth), + _ => None, + } + } + + pub fn settings_value(self) -> &'static str { + match self { + Self::Off => "off", + Self::Smooth => "smooth", + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{RawSettings, RuntimeSettings, apply_updates}; + + #[test] + fn cursor_motion_is_opt_in_and_invalid_values_preserve_instant_motion() { + for text in [ + "", + "cursor_motion=", + "cursor_motion=true", + "cursor_motion=90", + "cursor_motion=unknown", + ] { + assert_eq!( + RuntimeSettings::from_raw(&RawSettings::from_text(text)).cursor_motion, + CursorMotion::Off + ); + } + } + + #[test] + fn cursor_motion_round_trips_independently_of_shape_blink_and_unknown_data() { + for value in CursorMotion::VALUES { + let text = apply_updates( + "cursor_shape=block\ncursor_blink=0\ncustom=keep\n", + &[("cursor_motion", (*value).into())], + ); + let loaded = RuntimeSettings::from_raw(&RawSettings::from_text(&text)); + assert_eq!(loaded.cursor_motion.settings_value(), *value); + assert_eq!(loaded.cursor_shape, Some(crate::CursorShapeName::Block)); + assert_eq!(loaded.cursor_blink, Some(false)); + assert!(text.contains("custom=keep")); + } + assert_eq!(CursorMotion::from_settings(" SMOOTH "), Some(CursorMotion::Smooth)); + } +} diff --git a/nebula_settings/src/lib.rs b/nebula_settings/src/lib.rs index 7628b3a51..81e8d8a32 100644 --- a/nebula_settings/src/lib.rs +++ b/nebula_settings/src/lib.rs @@ -19,7 +19,9 @@ mod agent_hooks; pub use agent_hooks::AgentHook; mod app_icon; pub use app_icon::{AppIconName, AppIconPalette}; +mod cursor_motion; mod custom_theme; +pub use cursor_motion::CursorMotion; pub use custom_theme::{ IndexedPalette, TerminalThemeColors, ThemeAppearance, ThemeDefinition, ThemeEffects, ThemeLayout, ThemeTypography, ThemeUiColors, ThemeValidationError, foreground_recommendations, @@ -979,6 +981,7 @@ pub struct RuntimeSettings { pub ligatures: Ligatures, pub cursor_shape: Option, pub cursor_blink: Option, + pub cursor_motion: CursorMotion, pub copy_on_select: bool, /// Maximum retained history for new terminals, without altering open sessions. pub scrollback_lines: usize, @@ -1152,6 +1155,10 @@ impl RuntimeSettings { .unwrap_or_default(), cursor_shape: raw.value("cursor_shape").and_then(CursorShapeName::from_settings), cursor_blink: raw.bool_on("cursor_blink"), + cursor_motion: raw + .value("cursor_motion") + .and_then(CursorMotion::from_settings) + .unwrap_or_default(), copy_on_select: raw.bool_on("copy_on_select").unwrap_or(false), scrollback_lines: scrolling::scrollback_lines(raw), scroll_speed: normalize_scroll_speed( diff --git a/nebula_settings/src/reset.rs b/nebula_settings/src/reset.rs index 494818d8f..4760a134b 100644 --- a/nebula_settings/src/reset.rs +++ b/nebula_settings/src/reset.rs @@ -19,6 +19,7 @@ const RESET_KEYS: &[&str] = &[ "ligatures", "cursor_shape", "cursor_blink", + "cursor_motion", "copy_on_select", "focus_follows_mouse", "dim_inactive_panes", @@ -178,6 +179,15 @@ mod tests { assert!(!restored.contains("notification_duration=")); } + #[test] + fn resetting_preferences_disables_cursor_motion_and_preserves_unrelated_data() { + let restored = default_settings_text("cursor_motion=smooth\ncustom_data=keep\n"); + let runtime = crate::RuntimeSettings::from_raw(&crate::RawSettings::from_text(&restored)); + assert_eq!(runtime.cursor_motion, crate::CursorMotion::Off); + assert!(!restored.contains("cursor_motion=")); + assert!(restored.contains("custom_data=keep")); + } + #[test] fn reset_enables_ligatures_even_after_following_a_theme() { for value in ["off", "theme"] { diff --git a/nebula_terminal/src/event_loop.rs b/nebula_terminal/src/event_loop.rs index 339bd04c0..120a20e51 100644 --- a/nebula_terminal/src/event_loop.rs +++ b/nebula_terminal/src/event_loop.rs @@ -960,6 +960,30 @@ mod tests { use crate::term::Config; use crate::term::test::TermSize; + #[test] + fn animation_snapshots_cannot_observe_a_partial_synchronized_update() { + use crate::render::{RenderSnapshot, SnapshotConfig}; + let mut term = Term::new(Config::default(), &TermSize::new(20, 2), VoidListener); + let mut stream = StreamProcessor::default(); + let cfg = SnapshotConfig { rows: 2, cols: 20 }; + stream.feed(&mut term, &VoidListener, b"old"); + let before = RenderSnapshot::capture(&term, &cfg); + for bytes in [b"\x1b[?20".as_slice(), b"26h\r", b"new", b"\x1b[10G", b"\x1b[?2026"] { + stream.feed(&mut term, &VoidListener, bytes); + // Animation frames read the grid even without a Wakeup. + let frame = RenderSnapshot::capture(&term, &cfg); + assert_eq!(frame.cursor.as_ref().unwrap().col, before.cursor.as_ref().unwrap().col); + assert_eq!(term.grid()[Line(0)][Column(0)].c, 'o'); + } + stream.feed(&mut term, &VoidListener, b"l"); + assert_eq!(RenderSnapshot::capture(&term, &cfg).cursor.unwrap().col, 9); + assert_eq!(term.grid()[Line(0)][Column(0)].c, 'n'); + stream.feed(&mut term, &VoidListener, b"\x1b[?2026h\rtimeout"); + assert_eq!(term.grid()[Line(0)][Column(0)].c, 'n'); + stream.stop_sync(&mut term); + assert_eq!(term.grid()[Line(0)][Column(0)].c, 't'); + } + #[test] fn authenticated_hook_frames_survive_every_chunk_boundary_and_reject_other_panes() { #[derive(Clone, Default)] From 976a883280fbcb3f4f408875321ef9992c166ba0 Mon Sep 17 00:00:00 2001 From: Tavric Date: Sat, 26 Sep 2026 17:00:33 +0800 Subject: [PATCH 09/14] i18n(zh-TW): use Taiwan UI wording (#301) Complete the Traditional Chinese catalog and align Taiwan UI terminology. Preserve message IDs and placeholders, correct the search coverage wording, and label backup contents consistently. --- nebula_app/i18n/zh-TW.json | 833 +++++++++++++++++++++++++++++++++++-- 1 file changed, 801 insertions(+), 32 deletions(-) diff --git a/nebula_app/i18n/zh-TW.json b/nebula_app/i18n/zh-TW.json index b827ae943..74bb6b432 100644 --- a/nebula_app/i18n/zh-TW.json +++ b/nebula_app/i18n/zh-TW.json @@ -1,11 +1,24 @@ { + "notification": { + "bell": "終端機響鈴", + "turn_failed_reason": "請求失敗:{error}", + "turn_failed": "請求失敗,請查看終端機中的錯誤詳情。", + "turn_incomplete": "回覆未完成,請查看終端機後再繼續。", + "turn_ended": "回合已結束,請查看終端機中的結果。" + }, "language": { - "system": "跟隨系統", "self_name": "繁體中文", + "system": "跟隨系統", "zh_cn": "简体中文", "en_us": "English" }, "settings": { + "scrolling": { + "history": "回捲行數", + "history_description": "每個窗格保留的歷史行數。僅適用於新窗格。", + "speed": "滾動速度", + "speed_description": "滑鼠滾輪滾動的倍率。即時生效,不影響觸控板滾動。" + }, "sidebar": { "application": "應用程式", "appearance": "外觀", @@ -19,6 +32,21 @@ "backup": "備份", "agents": "Agents" }, + "notifications": { + "duration": "通知顯示時間", + "duration_description": "選擇應用程式內通知多久後自動關閉,也可以讓通知持續顯示。", + "duration_details": "適用於新顯示或重新整理的應用程式內通知。預設時間為:簡短提示 5 秒、訊息提醒 90 秒;更新通知持續顯示。畫面最多保留最新的 3 則通知,即使設為持續顯示也是如此。關閉或取代通知不會代你同意或拒絕確認請求,也不會改變任務狀態。系統通知不受影響。", + "duration_default": "使用預設顯示時間", + "duration_five": "5 秒", + "duration_ten": "10 秒", + "duration_thirty": "30 秒", + "duration_ninety": "90 秒", + "duration_persistent": "持續顯示", + "ai_messages": "AI 浮動通知", + "ai_messages_description": "在右下角顯示 AI 浮動通知;系統通知不受影響。", + "ai_messages_details": "關閉後,現有的應用程式內 AI 浮動通知會收起,也不再顯示新的完成及確認通知。Windows 系統通知和分頁狀態提示仍會保留;終端機輸出及其中的確認請求不受影響。", + "save_failed": "無法儲存通知設定:{error}" + }, "network": { "title": "網路代理", "mode": { @@ -30,25 +58,116 @@ "address": { "label": "代理位址" }, + "status": { + "idle": "測試目前設定能否連上網路", + "running": "正在使用目前設定測試網路…", + "success": "網路連線正常 · {route} · {elapsed_ms} ms", + "failed": "測試失敗:{error}", + "unexpected_end": "網路測試意外中止,請重試", + "start_failed": "無法啟動網路測試:{error}" + }, "action": { "test": "測試網路", "testing": "測試中…" }, "route": { "direct": "直接連線", - "direct_address": "直連位址", - "custom_command": "自訂命令" + "direct_address": "直接連線位址", + "custom_command": "自訂命令", + "proxy_server": "代理 {server}", + "ssh_jump": "SSH {target}" + }, + "failure": { + "load_settings": "讀取代理設定失敗:{error}", + "invalid_settings": "代理設定無效:{error}", + "timeout": "網路測試逾時({seconds} 秒無回應)", + "send_request": "傳送網頁測試請求失敗:{error}", + "read_response": "讀取網頁測試回應失敗:{error}", + "invalid_http_status_line": "目標網站未傳回有效的 HTTP 狀態行:{line}", + "http_status": "目標網站傳回 HTTP {status}", + "proxy_server": "無法透過代理伺服器 {server} 連上網路:{error}", + "custom_command": "無法透過自訂代理命令連上網路:{error}", + "jump_task": "無法解析跳板主機任務:{error}", + "jump_resolve": "無法解析跳板主機 {target}:{error}", + "jump_connect": "無法連線至跳板主機 {target}:{error}", + "jump_channel": "無法透過跳板主機 {target} 開啟對外連線通道:{error}", + "direct": "無法直接連線至測試網站:{error}" } }, + "appearance": { + "background_color_description": "覆蓋主題的終端機背景色。變更後,OSC 11 回報給程式的背景色也會跟著改變;TUI 會根據這個值判斷明暗模式。", + "background_cover_title": "讓背景圖覆蓋視窗控制項區域?", + "background_cover_description": "背景圖片會延伸到標題列、視窗按鈕、分頁和 SSH 側邊欄下方。對比不足的圖片可能讓控制項不易辨識;介面仍會維持最低不透明度。" + }, "font": { - "loading": "正在列舉系統字型…", - "no_matches": "沒有符合的字型" + "ligatures": "字型連字", + "ligatures_description": "將 ->、!= 等字元組合顯示為字型支援的連字。變更會立即套用至已開啟的終端機。", + "ligatures_on": "開啟", + "ligatures_off": "關閉", + "ligatures_theme": "跟隨主題", + "ui_family": "介面字型", + "ui_family_description": "輸入已安裝的字型名稱;留空則使用預設字型。按 Enter 或離開輸入欄位後生效。", + "ui_size": "介面字型大小", + "ui_size_description": "獨立調整介面文字和控制項字型大小,不影響終端機文字。", + "english": "英文終端機字型", + "chinese": "中文終端機字型", + "chinese_description": "用於中文等全形字元。輸入字型名稱,多種字型請以逗號分隔;留空則使用 Maple Mono NF CN。按 Enter 或離開輸入欄位後生效。", + "fallback_description": "優先使用清單中的第一種字型;若缺少字形,會依序嘗試後續字型,最後使用內建的 Maple 字型。", + "group_description": "第一種為主要字型,其餘依序作為備用字型", + "loading": "正在讀取系統字型…", + "no_matches": "沒有符合的字型", + "expand": "展開字型清單", + "collapse": "收合字型清單" + }, + "keymap": { + "conflict": "{combo} 同時指定給「{first}」和「{second}」;只有排在前面的「{first}」會生效", + "help": "點選快速鍵後,按下新的組合鍵。按 Backspace 清除,按 Esc 取消;也可以使用右側按鈕清除或還原預設值。", + "clear": "清除快速鍵(按鍵會傳送至終端機)", + "restore": "還原此動作的預設快速鍵" + }, + "input": { + "backup_secret": "認證資訊只會儲存至系統認證管理員" + }, + "ssh": { + "default_keys": "未指定時,將使用 IdentityFile 和預設的 id_* 私鑰", + "address_hint": "支援 user@host,也可貼上 ssh://host:2222", + "auth_auto_description": "依序嘗試可用的私鑰;若都無法使用,再詢問密碼。多數情況下選這個即可。", + "auth_interactive_description": "不預先儲存認證資訊。連線時請依終端機提示輸入,支援雙重驗證。", + "save_password": "儲存到 Windows 認證管理員", + "hide_config_host": "隱藏(無法刪除 ~/.ssh/config 中的主機)", + "empty_hint": "按「+ 新增主機」,或在 ~/.ssh/config 設定主機別名", + "shared_data_hint": "與舊版介面共用資料;刪除來自 ~/.ssh/config 的主機別名只會將其隱藏,之後仍可還原" + }, + "quick_terminal": { + "mode": "快速終端機開啟方式", + "description": "獨立視窗會記住大小;叫出現有視窗時,不會新增分頁。", + "dedicated": "獨立視窗", + "existing": "叫出現有視窗" + }, + "search_empty": "沒有符合的設定", + "mouse": { + "focus_follows_mouse": "焦點跟隨滑鼠", + "focus_follows_mouse_description": "滑鼠移到終端機窗格時自動切換焦點。預設關閉。" + }, + "panes": { + "dim_inactive": "調暗非使用中窗格", + "dim_inactive_description": "調暗其他分割窗格,讓目前使用的窗格更顯眼。" + }, + "save_failed": "無法儲存設定:{error}", + "reset_title": "還原預設設定?", + "reset_description": "這會重設設定和快速鍵,但保留 SSH 主機、認證資訊與歷史紀錄,並備份目前的設定。要繼續嗎?", + "startup": { + "launch_at_login": "登入時自動啟動", + "launch_at_login_help": "登入 Windows 後啟動 Pebrel;使用與安裝程式相同的啟動捷徑。", + "silent_start": "在背景啟動", + "silent_start_help": "啟動後在背景執行,不顯示視窗。啟用時也會開啟系統匣,可點選圖示重新顯示視窗。此設定只在系統匣啟用時生效;若指定了啟動目錄則不適用。", + "save_failed": "無法變更啟動設定:{error}" }, "agents": { - "title": "程式設計智能體", + "title": "程式設計代理程式", "description": "在 Pebrel 中顯示執行狀態、完成通知和授權請求。Claude Code 與 Codex 預設開啟。", "refresh": "重新整理", - "platform_unsupported": "目前僅 Windows 支援自動安裝 hooks。", + "platform_unsupported": "目前只有 Windows 支援自動安裝 hooks。", "checking": "正在偵測工具與 hooks…", "applying": "處理中…", "installed": "Hook 已安裝", @@ -58,9 +177,9 @@ "unsupported": "尚未提供 hook 整合", "unavailable": "無法使用", "needs_attention": "需要檢查", - "restart": "變更將在重新啟動 Agent 後生效。這裡管理安裝在本機的 Agent。", - "enabled": "Hooks 已安裝,請重新啟動 agent 使其生效。", - "disabled": "Hooks 已移除,請重新啟動 agent 使其生效。", + "restart": "變更會在重新啟動 Agent 後生效。此處管理安裝在本機的 Agent。", + "enabled": "Hooks 已安裝。請重新啟動 Agent 讓變更生效。", + "disabled": "Hooks 已移除。請重新啟動 Agent 讓變更生效。", "failed": "無法更新 hooks:{error}", "helper_missing": "缺少 hook 輔助程式,請修復 Pebrel 安裝後再啟用。", "needs_repair": "Hook 已安裝 · 需修復", @@ -68,6 +187,27 @@ "config_path": "設定:{path}" } }, + "provider": { + "test": { + "success": "連線成功(HTTP {status})", + "invalid_endpoint": "請求網址必須以 http:// 或 https:// 開頭", + "missing_model": "請先填寫預設模型", + "missing_api_key": "請先儲存 API Key", + "credential_read_failed": "無法從認證管理員讀取 API Key", + "invalid_credential_encoding": "認證管理員中的 API Key 編碼無效", + "timeout": "連線逾時", + "host_not_found": "找不到伺服器", + "connection_failed": "無法連線至伺服器", + "io_error": "網路錯誤:{kind}", + "tls_failed": "TLS 握手失敗", + "request_failed": "請求失敗", + "auth_failed": "身分驗證失敗(HTTP {status}),請檢查 API Key", + "endpoint_not_found": "端點不存在(HTTP {status}),請檢查請求位址", + "rate_limited": "服務已限制請求頻率(HTTP {status});可以連線,但目前無法驗證額度", + "http_status": "服務傳回 HTTP {status}", + "start_failed": "無法開始測試供應商連線:{error}" + } + }, "common": { "link_command_click": "Command+左鍵開啟", "link_ctrl_click": "Ctrl+左鍵開啟", @@ -165,12 +305,12 @@ "opacity": "不透明度", "background": "背景", "background_image": "背景圖片", - "background_color": "背景色彩", + "background_color": "背景色", "foreground": "前景", "text": "文字", "standard": "標準", - "compact": "緊湊", - "relaxed": "寬鬆", + "compact": "緊密", + "relaxed": "寬敞", "left": "左側", "right": "右側", "top": "頂端", @@ -191,39 +331,616 @@ "command": "命令", "run": "執行", "stop": "停止", - "history": "歷程", + "history": "歷史紀錄", "saved_commands": "已儲存的命令", "session": "工作階段", "key": "按鍵", "action": "動作", - "update_notice": "Pebrel v{latest} 已發布(目前 v{current})", + "update_notice": "Pebrel v{latest} 已推出(目前為 v{current})", "copied_lines": "已複製 {lines} 行到剪貼簿", - "copy_working_directory": "複製工作目錄", - "cwd_copied": "工作目錄已複製", + "copy_working_directory": "複製目前工作目錄", + "cwd_copied": "已複製工作目錄", "paste_lines": "貼上 {lines} 行文字?", - "sent_to": "已傳送至 {target}" + "drop_paths_invalid": "無法貼上這些路徑,請檢查特殊字元或減少拖入的檔案數量。", + "drop_paths_busy": "上一批拖入的路徑仍在轉換中。", + "drop_paths_expired": "輸入狀態已變更,已取消貼上路徑。", + "drop_paths_failed": "無法為此 WSL 工作階段轉換路徑,請重試。", + "drop_paths_remote": "無法在 SSH 工作階段直接使用本機路徑。請將檔案拖至遠端檔案樹上傳。", + "image_paste_failed": "無法貼上圖片:{error}", + "image_paste_busy": "上一張圖片仍在處理。", + "image_paste_expired": "輸入狀態已變更,已取消貼上圖片。", + "image_paste_limit": "目前分頁的暫存圖片數量已達上限。", + "image_paste_disconnected": "請先連線 SSH 工作階段再貼上圖片。", + "sent_to": "已傳送至 {target}", + "yes": "是", + "no": "否", + "confirmation_expired": "確認請求已變更或結束。", + "link_missing_cwd": "無法開啟相對路徑(缺少工作目錄):{path}", + "link_file_not_found": "找不到檔案:{path}", + "link_open_failed": "無法開啟檔案:{error}", + "link_unrecognized": "無法辨識連結格式:{target}", + "link_open_url_failed": "無法開啟連結:{error}" + }, + "editor": { + "bold_selection": "將選取文字設為粗體(Ctrl+B / ⌘B)", + "italic_selection": "將選取文字設為斜體(Ctrl+I / ⌘I)", + "release_to_close_sidebar": "放開以收合側邊欄", + "document_actions": "檔案操作", + "source": "原始碼", + "edit_in_place": "編輯", + "finish_editing": "完成", + "finish_editing_shortcut": "結束編輯(Ctrl+Enter / ⌘Enter)", + "edit_block": "編輯此段落", + "right_sidebar": "展開或收合右側邊欄", + "loading": "正在讀取檔案…", + "save": "儲存", + "saving": "正在儲存…", + "saved": "已儲存", + "unsaved": "未儲存", + "edit": "編輯", + "preview": "預覽", + "reading": "閱讀", + "statistics": "檔案統計", + "properties": "檔案屬性", + "details_toggle": "切換檔案側邊欄", + "details_close": "隱藏檔案側邊欄", + "fullscreen": "進入全螢幕", + "exit_fullscreen": "離開全螢幕", + "focus_reading": "專注閱讀", + "exit_focus_reading": "離開專注閱讀模式", + "search_code_language": "搜尋語言…", + "copy_code": "複製程式碼", + "copy_math_latex": "複製 LaTeX 原始碼", + "copy_math_image": "複製公式圖片", + "math_image_unavailable": "公式圖片仍在產生中,或包含只能以文字呈現的字元", + "math_latex_copied": "LaTeX 原始碼已複製", + "math_image_copied": "公式圖片已複製", + "markdown_document": "Markdown 檔案", + "outline": "目錄", + "no_headings": "這份檔案沒有標題", + "copy_heading": "複製標題", + "reload": "重新讀取檔案", + "copy_path": "複製檔案路徑", + "read_only": "唯讀檔案", + "truncated": "檔案超過 8 MB,只能預覽開頭部分,無法編輯或儲存", + "encoding": "檔案不是完整的 UTF-8 文字,只能預覽", + "conflict": "檔案已由其他程式修改。你的編輯內容仍在,請先複製要保留的內容,再重新讀取檔案。", + "read_failed": "讀取失敗:{error}", + "save_failed": "儲存失敗:{error}", + "discard_title": "放棄未儲存的修改?", + "close_title": "儲存檔案修改?", + "discard": "放棄修改", + "cancel": "取消", + "lines": "{count} 行", + "save_shortcut": "儲存(Ctrl+S / ⌘S)", + "info": "檔案資訊", + "type": "檔案類型", + "size": "檔案大小", + "modified": "修改時間", + "characters": "字元數", + "line_count": "行數", + "encoding_label": "編碼", + "line_ending": "換行字元", + "status": "狀態", + "copy_name": "複製檔名", + "reveal": "在檔案總管中顯示", + "open_external": "使用預設應用程式開啟", + "preview_limited": "檔案較大,僅顯示部分格式化預覽。切換至編輯模式,可查看已載入的原始碼。" + }, + "commands": { + "add_command": "新增命令", + "root": "所有命令", + "back_to_root": "回到所有命令", + "group_count": "{count} 個命令", + "add_group": "新增群組", + "group_name": "群組名稱", + "builtin_group": "內建命令", + "ungrouped": "未分類", + "remove_from_group": "移出群組", + "move_to_group": "移至群組", + "delete_group": "刪除群組,但保留其中的命令", + "group_save_failed": "無法儲存命令群組", + "builtin": { + "python_install_windows": "安裝 Python 3.14 · Windows", + "python_install_mac": "安裝 Python · macOS", + "python_install_ubuntu": "安裝 Python · Ubuntu/Debian", + "python_install_fedora": "安裝 Python · Fedora", + "git_install_windows": "安裝 Git · Windows", + "git_install_mac": "安裝 Git · macOS", + "git_install_ubuntu": "安裝 Git · Ubuntu/Debian", + "git_install_fedora": "安裝 Git · Fedora", + "docker_install_windows": "安裝 Docker Desktop · Windows", + "docker_install_mac": "安裝 Docker Desktop · macOS", + "docker_install_ubuntu": "安裝 Docker · Ubuntu 24.04", + "docker_install_fedora": "安裝 Docker · Fedora", + "docker_ps": "Docker · 查看所有容器", + "docker_images": "Docker · 查看映像檔", + "docker_build": "Docker · 建置目前專案映像檔", + "docker_run": "Docker · 執行並對應連接埠", + "docker_logs": "Docker · 持續查看容器紀錄", + "docker_exec": "Docker · 進入容器 Shell", + "compose_up": "Docker Compose · 啟動開發服務", + "compose_logs": "Docker Compose · 查看服務紀錄", + "compose_down": "Docker Compose · 停止服務(保留磁碟區)", + "conda_install_windows": "安裝 Miniconda · Windows", + "conda_install_mac": "安裝 Miniconda · macOS", + "conda_install_linux": "安裝 Miniconda · Linux", + "conda_list": "Conda · 查看環境清單", + "conda_create": "Conda · 建立 Python 開發環境", + "conda_activate": "Conda · 啟用開發環境", + "conda_deactivate": "Conda · 停用目前環境", + "conda_install": "Conda · 安裝常用資料科學套件", + "conda_export": "Conda · 匯出環境相依性", + "conda_restore": "Conda · 從檔案建立環境", + "python_venv": "Python · 建立虛擬環境", + "python_activate_windows": "Python · 啟用虛擬環境 · PowerShell", + "python_activate_posix": "Python · 啟用虛擬環境 · Bash/Zsh", + "pip_install": "Python · 安裝專案相依性", + "uv_sync": "uv · 同步專案環境與相依性", + "npm_install": "npm · 安裝鎖定相依性", + "npm_dev": "npm · 啟動開發服務", + "pnpm_install": "pnpm · 安裝專案相依性", + "git_status": "Git · 檢視工作區狀態", + "git_diff": "Git · 檢視未暫存修改", + "git_log": "Git · 查看提交紀錄圖", + "git_branch": "Git · 建立並切換開發分支", + "cargo_test": "Rust · 執行專案測試", + "cargo_check": "Rust · 檢查所有目標", + "ssh_key": "SSH · 建立 Ed25519 金鑰" + }, + "builtin_label": "內建", + "save_copy": "儲存副本" + }, + "files": { + "path_unavailable": "路徑已不存在", + "delete_failed": "刪除失敗:{error}", + "ignore_add": "加入 .gitignore", + "ignore_remove": "從 .gitignore 移除", + "ignore_added": "已寫入 .gitignore:{entry}", + "ignore_removed": "已取消忽略:{entry}", + "ignore_present": ".gitignore 已有這項規則:{entry}", + "ignore_visible": "此路徑未被忽略:{entry}", + "ignore_failed": "無法修改 Git 忽略規則:{error}", + "preview_loading": "正在產生預覽…", + "preview_unavailable": "此檔案暫時無法預覽", + "preview_pages": "第 1 頁 · 共 {pages} 頁", + "open_terminal_here": "在此處開啟終端機", + "tree": { + "open_in_explorer": "在檔案總管中開啟", + "follow_refresh": "跟隨目前終端機並重新整理(Alt+R)" + }, + "copy_linux_path": "複製 Linux 路徑", + "reveal_in_explorer": "在檔案總管中顯示", + "copy_path": "複製路徑", + "empty": { + "reading_title": "正在讀取目錄", + "reading_body": "正在讀取目前工作目錄的內容。", + "reading_hint": "請稍候,或點選右上角的跟隨按鈕重新讀取。", + "read_failed_title": "讀取目錄失敗", + "read_failed_body": "無法完整讀取此目錄,請檢查存取權限或重試。", + "read_failed_hint": "點選右上角的跟隨按鈕重試,或改選其他目錄。", + "no_directory_title": "沒有可瀏覽的目錄", + "no_directory_body": "目前終端機尚未提供工作目錄。", + "no_directory_hint": "先在終端機切換至目錄,再點選右上角的跟隨按鈕。", + "directory_empty_title": "此目錄為空", + "directory_empty_body": "目前工作目錄沒有可顯示的檔案。", + "directory_empty_hint": "在終端機建立檔案,或選擇其他目錄。" + }, + "delete": { + "title": "刪除 {name}?", + "folder_body": "資料夾及其全部內容會移入資源回收筒。", + "file_body": "檔案會移入資源回收筒。" + } + }, + "recipe": { + "title": "版面配置範本", + "name": "範本名稱", + "save": "儲存版面配置", + "tab": "目前分頁", + "window": "目前視窗", + "empty": "尚未儲存任何版面配置。排好分頁和分割窗格後,幫它取個名字。", + "description": "儲存分頁、分割窗格比例及工作目錄。還原時會在新視窗建立終端機。", + "open": "還原", + "delete": "刪除", + "loading": "正在讀取版面配置…", + "saved": "已儲存版面配置", + "failed": "操作失敗:{error}", + "delete_title": "刪除此版面配置範本?", + "open_failed": "無法還原版面配置", + "count": "{tabs} 個分頁 · {panes} 個分割窗格", + "save_window": "儲存目前視窗的版面配置…", + "open_library": "開啟版面配置範本…" + }, + "chemistry": { + "loading": "正在繪製分子結構…", + "invalid": "目前無法繪製此 SMILES,將保留原始碼。" + }, + "markdown": { + "plain_text": "純文字", + "choose_language": "選擇此程式碼區塊的語法醒目提示語言" + }, + "transfer": { + "not_ready": "遠端目錄尚未就緒", + "target_changed": "目標位置已變更,請在所需目錄重新開始傳輸。", + "busy": "已有傳輸正在進行,請等待完成或先取消。", + "checking": "正在檢查傳輸目標…", + "downloaded": "下載完成", + "cancelled": "傳輸已取消", + "failed": "傳輸失敗", + "upload_hint": "拖入檔案以上傳", + "download_hint": "拖至檔案總管中的資料夾即可下載", + "conflict_title": "已有同名項目", + "conflict_body": "目標位置已有 {count} 個同名項目。", + "incompatible": "部分項目的檔案與資料夾類型不符,無法覆寫。", + "symlink_warning": "覆寫符號連結會直接修改其目標,失敗或取消可能留下部分內容。", + "overwrite": "覆寫", + "skip": "略過", + "keep_both": "保留兩者", + "cancel": "取消", + "cancelling": "正在取消操作…", + "busy_at": "{host} 已有傳輸正在進行", + "destination": "目標位置:{destination}", + "copied_item": "已複製遠端項目:{name}", + "choose_files": "選擇要上傳的檔案", + "choose_upload_directory": "選擇要上傳的資料夾", + "choose_download_directory": "選擇下載位置", + "drag_hint": "將檔案拖進來即可上傳;拖至檔案總管即可下載。" + }, + "hosts": { + "search": "搜尋名稱、位址、群組、標籤或備註", + "group": "群組", + "tags": "標籤", + "notes": "備註", + "tags_hint": "用逗號分隔多個標籤", + "all_groups": "所有群組", + "ungrouped": "未分類", + "all": "全部主機", + "managed": "長期主機", + "recent": "最近連線", + "no_matches": "沒有符合的主機", + "import": "匯入 CSV", + "export": "匯出 CSV", + "import_preview": "將新增 {added} 台主機;已有的 {skipped} 台主機會保留認證資訊和連線設定。原本隱藏的符合主機也會重新顯示。", + "invalid": "主機資訊無效:{error}", + "processing": "正在處理主機資訊…", + "reloaded": "已重新讀取主機資訊", + "exported": "主機資訊已匯出,不含認證資訊", + "imported": "已新增 {added} 台主機,略過 {skipped} 台現有主機", + "imported_partial": "已新增 {added} 台主機,但顯示狀態未能更新。請重試匯入:{error}", + "title": "SSH 主機", + "subtitle": "整理已儲存的主機、管理登入方式,並直接開啟終端機工作階段。", + "add": "新增主機", + "connect": "連線", + "exchange": "匯入 / 匯出", + "pinned": "置頂", + "config_empty": "可讀取 ~/.ssh/config,與已儲存的主機一起使用。", + "config_shared": "共用 ~/.ssh/config 中的 {count} 個主機別名。", + "reload": "重新讀取", + "auth_auto": "自動認證", + "auth_password": "密碼", + "auth_key": "私鑰", + "auth_interactive": "互動式認證" + }, + "vcs": { + "changes": "變更", + "staged": "已暫存", + "merge_conflicts": "合併衝突", + "no_conflicts": "沒有待解決的衝突", + "no_changes": "沒有更改", + "no_history": "還沒有提交歷史", + "no_branch": "(沒有分支)", + "confirm_discard": "確認捨棄變更", + "discard": "捨棄變更", + "stage": "暫存", + "unstage": "取消暫存", + "resolve_in_merge_editor": "在三欄合併編輯器中解決衝突", + "commit_changes": "提交 / 變更", + "graph": "提交紀錄圖", + "history_graph": "提交歷史圖", + "conflicts": "衝突", + "resolve_conflicts": "解決衝突", + "commit": "提交", + "commit_placeholder": "提交資訊…", + "stage_all": "全部暫存", + "pull": "拉取", + "push": "推送", + "push_ahead": "推送 ↑{count}", + "follow_directory": "回到終端機目前所在的目錄", + "not_repository": "目前目錄不在 Git 或 SVN 儲存庫中", + "refresh_status": "重新整理 {vcs} 狀態", + "close_status": "關閉 {vcs} 狀態", + "toggle_git": "Git 狀態 (Ctrl+Shift+G)", + "time_now": "剛剛", + "time_minute": "1 分鐘前", + "time_minutes": "{count} 分鐘前", + "time_hour": "1 小時前", + "time_hours": "{count} 小時前", + "time_day": "1 天前", + "time_days": "{count} 天前", + "time_month": "1 個月前", + "time_months": "{count} 個月前", + "time_year": "1 年前", + "time_years": "{count} 年前", + "directory_unavailable": "所選目錄無法使用", + "following_directory": "所選目錄無法使用,已改為跟隨目前目錄", + "command_failed": "{program} 失敗", + "task_start_failed": "無法啟動版本控制任務:{error}" + }, + "launcher": { + "open_admin": "以系統管理員身分開啟", + "set_default": "設為預設 Shell", + "current_default": "目前預設 Shell", + "connect": "連線", + "edit": "編輯", + "delete": "刪除", + "default_saved": "已將 {shell} 設為預設 Shell。", + "admin_started": "已要求在新的 Pebrel 系統管理員視窗中開啟 {shell}。", + "admin_cancelled": "已取消以系統管理員身分啟動。", + "admin_failed": "無法開啟系統管理員終端機:{error}" + }, + "theme_transfer": { + "import_title": "匯入主題", + "export_title": "匯出主題", + "import_description": "選擇主題檔案,預覽後作為範本使用。", + "export_description": "選擇格式,查看哪些設定可以保留。", + "cancel": "取消", + "close": "關閉", + "candidates": "主題", + "diagnostics": "檔案資訊", + "completed": "完成", + "error": "需要處理", + "export": "匯出", + "exported": "已匯出至", + "inspecting": "正在讀取主題檔案…", + "losses": "此格式無法保留的設定", + "no_candidates": "找不到可匯入的主題。", + "output_format": "格式", + "picking": "選擇檔案", + "preparing": "正在準備匯出…", + "preview": "預覽", + "template_ready": "範本已載入編輯器", + "use_template": "用作範本", + "warnings": "匯入說明", + "writing": "正在寫入檔案…" + }, + "theme_editor": { + "title": "自訂主題", + "description": "從現有主題開始,調整成自己的配色。", + "template": "範本", + "name": "主題名稱", + "background": "終端機背景", + "foreground": "文字顏色", + "accent": "強調色", + "cursor": "游標顏色", + "font_family": "字型", + "font_size": "字型大小", + "line_height": "行高", + "opacity": "不透明度", + "advanced": "進階設定", + "reset": "重設變更", + "back": "返回上一頁", + "save_only": "僅儲存", + "apply": "儲存並套用", + "import": "匯入", + "export": "匯出", + "common": "常用設定", + "preview_terminal": "終端機", + "preview_interface": "介面", + "preview_ansi": "ANSI 色彩", + "invalid_value": "請檢查標示的顏色或數值。", + "new_name": "{name} · 我的配色", + "discard_title": "放棄未儲存修改?", + "discard_body": "目前草稿尚未儲存。", + "discard": "放棄修改", + "keep_editing": "繼續編輯", + "loading": "正在讀取主題…", + "saving": "正在儲存…", + "library_error": "無法讀取主題庫:{error}", + "save_error": "無法儲存主題:{error}", + "use_template": "用作範本", + "saved": "已儲存至自訂主題", + "preview_only": "變更只會在此處預覽,套用後才會顯示在終端機。", + "advanced_hide": "收合進階設定", + "ansi": "ANSI 16 色", + "selection": "選取區域與游標文字", + "selection_background": "選取範圍背景", + "selection_foreground": "選取範圍文字", + "cursor_text": "游標文字", + "inherit": "留空以使用自動配色", + "layout": "卡片版面配置", + "radius": "圓角", + "gutter": "間距", + "shadow": "陰影", + "divider": "分割線", + "invalid_color": "顏色格式不正確", + "invalid_number": "數值格式不正確", + "change_template_title": "更換範本?", + "change_template_body": "更換範本會捨棄目前未儲存的變更。", + "change_template": "更換範本", + "current_setting": "目前設定", + "live_preview": "即時預覽", + "selected_line": "選取的文字行", + "based_on": "以 {name} 為基礎,原主題不會變更。", + "editing_status": "主題草稿", + "editing_unchanged": "目前設定沒有變更", + "editing_changed": "預覽包含尚未儲存的變更", + "reset_short": "重設" + }, + "theme_picker": { + "title": "選擇主題", + "all": "全部", + "light": "淺色", + "dark": "深色", + "custom": "自訂", + "customize": "自訂主題", + "text_original": "原主題文字", + "text_cool": "推薦冷色文字", + "text_warm": "推薦暖色文字", + "text_custom": "自訂文字顏色", + "discard_body": "外觀變更尚未套用。", + "apply": "使用此主題", + "cancel": "取消", + "color_title": "文字顏色", + "hex_color": "十六進位色碼", + "invalid_color": "請輸入 #aabbcc 格式的顏色代碼。", + "preview_hint": "文字顏色會即時顯示在預覽中,套用後才會變更終端機。", + "loading": "正在讀取主題…", + "empty": "儲存的自訂主題會顯示在這裡。", + "save_error": "無法套用主題:{error}", + "manual_hint": "套用後會使用這些顏色,並關閉「跟隨系統」。", + "preview_ready": "準備好開始新的工作。", + "apply_icon": "使用此圖示", + "icon_title": "選擇應用程式圖示", + "description": "挑選喜歡的配色,預覽後再套用。", + "icon_description": "保留原本的圖案,挑選喜歡的配色。", + "selected": "已選取", + "text_suggestion": "輸入顏色或選擇推薦色", + "color_hint": "顏色會即時顯示在預覽中;套用主題後才會顯示在終端機。", + "saturation_value": "飽和度和明度", + "hue": "色相", + "theme_count": "{count} 款主題", + "icon_count": "{count} 款配色", + "neutral": "中性", + "blue": "藍色", + "violet": "紫色", + "green": "青綠" + }, + "wallpaper": { + "load_failed": "無法載入背景圖。請選擇可正常讀取的 PNG、JPEG、WebP、GIF 或 BMP 圖片。", + "too_large": "背景圖片超過記憶體限制,請選擇尺寸較小的圖片。" + }, + "update": { + "downloading_hint": "正在背景下載並驗證適用於此裝置的更新安裝檔。", + "no_verified_package": "此版本沒有適用於此裝置、可供驗證的安裝檔。請開啟發行頁面手動下載。", + "check_fallback_failed": "GitHub API 存取受限(HTTP {status}),備用發行頁面也無法查詢:{error}。請稍後重試或開啟發行頁面。", + "check_unrecognized_release": "官方發行頁面未傳回可辨識的穩定版本。請稍後重試或開啟發行頁面。", + "installation_failed": "更新安裝失敗", + "installation_failed_hint": "更新未完成,原本的工作階段快照仍在。檢查錯誤後,可以重新驗證安裝檔,再確認安裝。", + "recheck_package": "重新驗證安裝檔", + "view_details": "檢視詳情", + "download": { + "dns": "無法解析更新伺服器或代理位址。請檢查網路和代理設定後重試。", + "tls": "無法為更新建立安全連線。請檢查系統時間,以及代理是否攔截了 TLS 連線。", + "refused": "更新連線被拒絕。請檢查網路;如果使用代理,請確認代理正在執行且埠正確。", + "timeout": "更新下載逾時。請檢查網路和代理連線後重試。", + "interrupted": "更新下載中斷。請檢查連線後重新下載。", + "proxy": "無法透過代理連線更新伺服器。請檢查代理位址、協議和認證資訊後重試。", + "http": "更新伺服器傳回 HTTP {status}。請稍後重試,或至發行頁面手動下載安裝檔。", + "network": "無法下載更新。請檢查網路和代理設定,或至發行頁面手動下載。" + }, + "auto_download": "在背景預先下載更新", + "stop_download": "停止下載", + "skip_version": "略過此版本", + "restart_install": "重新啟動並安裝", + "install_next_launch": "下次啟動時安裝", + "ready_hint": "更新已準備好。Pebrel 會儲存工作區、安裝更新,然後重新啟動。", + "later": "稍後", + "prepare_failed": "更新準備失敗:{error}。Pebrel 將保持開啟。", + "draft_changed": "準備關閉期間檔案已變更。請儲存或捨棄最新變更後重試。", + "in_progress": "正在安裝更新。請稍候,完成後 Pebrel 會自動重新開啟。" + }, + "files.search_failed": "無法完成搜尋", + "files.search_running": "正在搜尋…", + "files.search_limited": "顯示 {count} 筆結果 · 縮小搜尋範圍可查看更多", + "files.search_count": "{count} 筆結果", + "files.search_retry": "請檢查目錄和關鍵字,或關閉搜尋選項後重試。", + "files.search_progress": "找到的檔案會陸續顯示。", + "files.search_continue": "可以繼續輸入關鍵字或切換目錄。", + "files.search_incomplete": "尚未搜尋所有檔案", + "files.search_limit_reason": "已達搜尋上限,或部分目錄無法讀取。", + "files.search_narrow": "請選擇範圍較小的目錄,或輸入更具體的關鍵字。", + "files.search_empty": "沒有符合的檔案", + "files.search_empty_reason": "目前目錄中沒有符合查詢條件的檔案或資料夾。", + "session": { + "choose_conversation": "選擇要繼續的對話…", + "exit_incomplete_title": "仍有 AI 工作階段無法辨識。確定要關閉嗎?", + "exit_incomplete_body": "關閉前會儲存視窗版面配置及已知的對話 ID,並停止執行中的命令。尚未取得 ID 的對話,下次開啟時可能需要手動選擇。", + "exit_anyway": "儲存已知狀態並關閉", + "save_failed": "無法儲存工作區,Pebrel 會保持開啟。請檢查剩餘空間和目錄權限後重試。", + "identity_pending": "部分執行中的 AI 工作階段尚未提供可用於恢復的識別資訊。請等它們完成啟動後再試。", + "restore_failed": "無法恢復此 AI 對話,原本的恢復紀錄已保留。你可以在分頁選單重試,或到工作階段歷史中尋找。", + "restore_choose_codex": "儲存的 Codex 對話已無法使用。請在 Codex 的工作階段清單中選擇要繼續的對話。", + "restore_ambiguous": "有多個原生工作階段檔案符合此對話,原本的恢復紀錄已保留。請在工作階段歷史中選擇正確的對話。", + "retry": "重試工作階段恢復" + }, + "ssh.agent.unavailable": "無法在偵測時限內存取系統 SSH Agent。", + "ssh.agent.empty": "SSH Agent 未提供任何身分資訊。", + "ssh.agent.rejected": "伺服器拒絕 SSH Agent 提供的身分資訊(已嘗試 {attempted} 個,共提供 {available} 個)。", + "ssh.agent.partial": "SSH Agent 身分已通過驗證,但仍需其他認證方式(已嘗試 {attempted} 個,共提供 {available} 個)。", + "ssh.agent.fatal": "SSH Agent 驗證或簽章失敗,本次連線已中止。請檢查 Agent 後重新連線。{detail}", + "cloud": { + "title": "雲備份", + "snapshots": "備份紀錄", + "settings": "雲端儲存", + "configure": "設定雲端儲存", + "scope": "備份內容", + "provider": "儲存服務", + "off": "未設定", + "folder": "本機 / 網路目錄", + "nutstore": "堅果雲", + "webdav": "WebDAV", + "s3": "S3 相容儲存", + "sftp": "SSH 檔案儲存", + "checking": "檢查中…", + "unreachable": "無法存取", + "reachable": "可存取", + "not_checked": "尚未檢查", + "retention": "保留最近 {count} 份備份", + "refresh": "重新整理備份", + "empty": "尚無備份", + "load_history": "重新整理以取得備份紀錄", + "restore": "還原", + "restore_warning": "這會覆寫備份涵蓋的本機設定和資料。要繼續嗎?", + "restore_latest": "還原最近的備份", + "backup_now": "立即建立備份", + "encrypted_archive": "加密完整備份檔", + "latest": "最近備份", + "export": "匯出備份檔案", + "import": "匯入備份檔案", + "folder_path": "目錄路徑", + "address": "儲存位址", + "username": "帳號", + "s3_address": "服務位址", + "region": "區域", + "bucket": "儲存貯體", + "access_key": "存取金鑰 ID", + "ssh_host": "已儲存的 SSH 主機", + "remote_path": "遠端目錄", + "credential": "密碼 / 存取金鑰", + "credential_set": "已安全儲存", + "credential_needed": "未儲存", + "store_credential": "儲存認證資訊", + "saved": "已儲存", + "save_failed": "儲存失敗", + "saving": "儲存中…", + "auto_save": "修改自動儲存", + "test": "檢查連線", + "retry_save": "重試儲存", + "passphrase": "備份密碼", + "passphrase_hint": "至少 8 個字元,只供本次使用。還原時需輸入相同密碼。", + "scope_hint": "不包含 SSH 私鑰。歷史紀錄可能含有敏感資訊。", + "appearance": "外觀", + "terminal": "終端機設定", + "hosts": "SSH 主機", + "sync": "同步設定", + "assistant": "助手設定", + "sessions": "工作區中的工作階段", + "directories": "目錄歷史紀錄", + "commands": "命令歷史紀錄", + "fonts": "自訂字型" }, "ai_hooks": { - "announced": "已接入 AI 回合通知(Claude / Codex / Kimi / Pi / opencode)。撤銷:pebrel setup-ai --remove" - }, - "notification.command_finished": "命令結束,耗時 {seconds} 秒", - "notification.command_failed": "命令失敗(結束代碼 {code}),耗時 {seconds} 秒", - "commands.add_command": "新增命令", - "commands.root": "全部命令", - "commands.back_to_root": "返回全部命令", - "commands.group_count": "{count} 條命令", + "announced": "已啟用 AI 回合通知(Claude / Codex / Kimi / Pi / opencode)。移除方式:pebrel setup-ai --remove" + }, + "notification.command_finished": "命令已結束,耗時 {seconds} 秒", + "notification.command_failed": "命令失敗(結束碼 {code}),耗時 {seconds} 秒", "files.path_edit": "編輯目錄路徑", "files.path_placeholder": "輸入絕對路徑或相對路徑", "files.path_choose": "選擇目錄", "files.path_open": "開啟目錄", "files.path_failed": "無法開啟這個目錄:{error}", - "session.restore_choose_codex": "儲存的 Codex 對話已無法使用。請在 Codex 的工作階段清單中選擇要繼續的對話。", - "session.choose_conversation": "選擇要繼續的對話…", - "session.exit_incomplete_title": "仍有 AI 工作階段無法識別,繼續關閉?", - "session.exit_incomplete_body": "關閉前會儲存視窗配置及已知的對話 ID,並停止正在執行的命令。尚未取得 ID 的對話,重新開啟後可能需要手動選擇。", - "session.exit_anyway": "儲存已知狀態並關閉", "tab_menu": { - "fork_ai_session": "分叉 AI 工作階段", + "fork_ai_session": "建立 AI 工作階段分支", "move_to_new_window": "移到新視窗", "export_as_workspace": "匯出為工作區…", "split_left_right": "左右分割", @@ -231,5 +948,57 @@ "move_left": "向左移動", "move_right": "向右移動", "tab_color": "分頁顏色" + }, + "chrome": { + "new_terminal_ctrl_shift_t": "新增終端機(Ctrl+Shift+T)", + "more": "更多", + "scroll_tabs_left": "向左捲動分頁", + "scroll_tabs_right": "向右捲動分頁", + "select_terminal": "選擇終端機", + "command_list": "命令清單", + "toggle_sidebar": "收合或展開側邊欄(Ctrl+Shift+B)", + "settings_shortcut": "設定(Ctrl+,)" + }, + "workspace": { + "pane": { + "stop_broadcast_input": "停止廣播輸入", + "broadcast_input_tooltip": "將輸入廣播至目前分頁的所有窗格", + "close": "關閉此窗格", + "extract_release": "放開滑鼠:移至獨立分頁", + "extract_drag_hint": "拖出終端機區域可移至獨立分頁", + "broadcast_enabled": "已開啟廣播輸入:輸入內容會同步至目前分頁的 {count} 個窗格", + "restore_layout": "還原窗格版面配置(Ctrl+Shift+Enter)", + "zoom": "放大此窗格(Ctrl+Shift+Enter)" + }, + "close": { + "running_process": "{process} 仍在執行,關閉會中止它。", + "running_window_process": "{process} 仍在執行,關閉視窗會中止它。" + }, + "close_window": { + "title": "關閉視窗?" + }, + "close_pane": { + "title": "關閉此窗格?" + }, + "close_tab": { + "title": "關閉此分頁?" + } + }, + "remote": { + "locating": "正在定位遠端目錄…", + "parent": "上一級", + "reread": "重新讀取", + "upload_files": "上傳檔案", + "upload_folder": "上傳資料夾", + "download": "下載到本機", + "copy_item": "複製遠端項目", + "paste_here": "貼至目前遠端目錄", + "skip_unchanged": "略過未變", + "cancel": "取消傳輸", + "preparing": "正在準備傳輸…", + "reading": "正在讀取遠端目錄…", + "empty": "此目錄為空。", + "error_retry": "{error}(點選右上角重新讀取)", + "busy_other": "另一主機正在傳輸:{destination}" } } From d30d1c9bbc226f0eddfec1d369970d3601326cde Mon Sep 17 00:00:00 2001 From: Kuddev Date: Sat, 26 Sep 2026 17:23:44 +0800 Subject: [PATCH 10/14] fix(terminal): keep color report subscriptions silent (#302) Keep DECSET 2031 enable/re-enable silent while retaining reports for actual palette changes. Cover repeated subscriptions and byte boundaries. Fixes #283. --- ...09-26-silent-color-report-subscriptions.md | 70 +++++++++++++++++++ nebula_terminal/src/term/mod.rs | 8 +-- nebula_terminal/src/term/tests.rs | 45 +++++++++--- 3 files changed, 109 insertions(+), 14 deletions(-) create mode 100644 architecture/notes/nebula_terminal/term/2026-09-26-silent-color-report-subscriptions.md diff --git a/architecture/notes/nebula_terminal/term/2026-09-26-silent-color-report-subscriptions.md b/architecture/notes/nebula_terminal/term/2026-09-26-silent-color-report-subscriptions.md new file mode 100644 index 000000000..93573b608 --- /dev/null +++ b/architecture/notes/nebula_terminal/term/2026-09-26-silent-color-report-subscriptions.md @@ -0,0 +1,70 @@ +# Keep color-report subscriptions silent + +## Status + +Reviewed for integration on 2026-09-26. + +## Context + +Issue [#283](https://github.com/Kuddev/pebrel/issues/283) reports literal +`^[[?997;1n` input around Fish prompts in native SSH panes, sometimes twice per +command. The terminal emitted this report every time DECSET 2031 was enabled, +even when the palette had not changed. + +## Evidence + +- [Fish's compatibility contract](https://github.com/fish-shell/fish-shell/blob/966dbbbd4de0b0efcf27275e465d081de900d9a8/doc_src/terminal-compatibility.rst#L226-L233) + defines `CSI ? 2031 h` as enabling future color-theme reports and expects + `CSI ? 997;1n` / `CSI ? 997;2n` when the theme changes. Enabling a + subscription is not itself a change or a `CSI ? 996 n` query. +- [Fish's terminal handoff implementation](https://github.com/fish-shell/fish-shell/blob/966dbbbd4de0b0efcf27275e465d081de900d9a8/src/tty_handoff.rs#L194-L195) + enables and disables this mode around terminal ownership changes. +- A production-core reproducer with two enables and an unchanged palette emitted + two `ESC[?997;1n` replies. The regression added to `term/tests.rs` also failed on + the original implementation before the fix. + +## Decision + +DECSET 2031 updates subscription state without emitting a report. The existing +palette-change path retains its change detection and only notifies subscribers. +Both first-time and repeated enables stay silent, including fragmented input. + +## Rejected alternatives + +The original immediate reply tried to compensate for vte 0.15 not routing the +private DSR query to `Handler::device_status`. Unsolicited input is not a valid +substitute for a query response: it may reach the shell during terminal handoff. +Filtering these bytes only in SSH would leave the shared terminal behavior +incorrect for other transports. Changing the parser dependency is unnecessary +for this notification regression. + +## Consequences + +The subscription path no longer formats or queues a response. No per-byte parser +work, timer, thread or stored state is added. Actual dark/light changes continue +to notify subscribed programs; disabled notifications and same-color updates +remain silent. The existing private DSR query limitation is unchanged. + +## Validation + +The regression covers both starting color schemes and every two-chunk split of +repeated enable/disable sequences. It also verifies a real color flip still +reports, repeated application stays silent, and disabling suppresses reports. +Existing direct-handler and parser tests retain their mode-state and real-change +assertions with the corrected subscription expectation. + +Local Windows validation on the updated integration base passed: 277 unit tests, +45 replay cases, the connection +transport test, the bundled ConPTY lifecycle test and one doctest. The native +fixtures used the repository-pinned console runtime and an explicit Git Bash. +The original Windows-to-Debian Fish SSH session has not been replayed locally. + +## Supersedes + +The immediate-report rationale in `Term::set_private_mode` and its regression +expectations; no previous decision note exists. + +## Revisit when + +Revisit query support separately when the VT parser exposes private DSR handling. +Keep query replies separate from change subscriptions. diff --git a/nebula_terminal/src/term/mod.rs b/nebula_terminal/src/term/mod.rs index 951779918..c9fa81cd5 100644 --- a/nebula_terminal/src/term/mod.rs +++ b/nebula_terminal/src/term/mod.rs @@ -2094,14 +2094,10 @@ impl Handler for Term { self.mode.insert(TermMode::WIN32_INPUT_MODE); return; } - // DECSET 2031。订阅的同一刻先答一次当前值:规范里取初值靠 `CSI ? 996 n` - // 查询,但 vte 0.15 只把**没有** `?` 中间字节的 `CSI n` 路由到 - // `device_status`,私有 DSR 根本到不了 handler,我们答不了那条查询。 - // 订阅即回报把这个洞补上——多一条报告对订阅方无害(它本来就要处理这个 - // 序列),少一条则意味着 app 在主题变化之前永远不知道当前是亮还是暗。 + // DECSET 2031 只订阅后续配色变化,不是 CSI ? 996 n 查询; + // 在这里回报会在 shell 交接终端时注入它未请求的输入。 if matches!(mode, PrivateMode::Unknown(2031)) { self.mode.insert(TermMode::COLOR_SCHEME_UPDATES); - self.report_color_scheme(); return; } let mode = match mode { diff --git a/nebula_terminal/src/term/tests.rs b/nebula_terminal/src/term/tests.rs index 719fa6527..336dc6261 100644 --- a/nebula_terminal/src/term/tests.rs +++ b/nebula_terminal/src/term/tests.rs @@ -69,24 +69,53 @@ fn keyboard_queries_follow_live_flags_after_replace_union_and_difference() { } } -/// DECSET 2031 订阅的同一刻就要收到当前亮暗:规范里取初值靠 -/// `CSI ? 996 n`,但 vte 0.15 不把私有 DSR 路由给 handler,我们答不了那条 -/// 查询。订阅即回报是这个洞的替代品,掉了它 app 在下次换主题前无从得知。 +/// 订阅后续变化不等于查询当前配色,启用时应保持静默。 #[test] -fn decset_2031_reports_the_current_scheme_immediately() { +fn decset_2031_subscribes_without_reporting_the_current_scheme() { let size = TermSize::new(5, 5); let events = WriteRecorder::default(); let mut term = Term::new(Config::default(), &size, events.clone()); term.set_private_mode(PrivateMode::Unknown(2031)); assert!(term.mode().contains(TermMode::COLOR_SCHEME_UPDATES)); - // 构造默认是暗底 → 1。 - assert_eq!(events.take(), vec!["\x1b[?997;1n".to_owned()]); + assert!(events.take().is_empty()); term.unset_private_mode(PrivateMode::Unknown(2031)); assert!(!term.mode().contains(TermMode::COLOR_SCHEME_UPDATES)); } +/// Fish 在命令交接时会重新订阅;这些操作不是配色变化,也不是当前配色查询。 +/// 遍历分块边界,避免网络拆包改变应答行为。 +#[test] +fn repeated_color_subscriptions_are_silent_at_every_stream_boundary() { + let sequence = b"\x1b[?2031h\x1b[?2031h\x1b[?2031l\x1b[?2031h"; + for dark in [true, false] { + for split in 0..=sequence.len() { + let events = WriteRecorder::default(); + let mut term = Term::new(Config::default(), &TermSize::new(5, 5), events.clone()); + term.set_color_scheme(dark); + let mut parser: ansi::Processor = ansi::Processor::new(); + parser.advance(&mut term, &sequence[..split]); + parser.advance(&mut term, &sequence[split..]); + assert!( + events.take().is_empty(), + "unexpected prompt input: dark={dark}, split={split}" + ); + assert!(term.mode().contains(TermMode::COLOR_SCHEME_UPDATES)); + + term.set_color_scheme(!dark); + let expected = if dark { "\x1b[?997;2n" } else { "\x1b[?997;1n" }; + assert_eq!(events.take(), [expected], "a real palette change still reports"); + parser.advance(&mut term, b"\x1b[?2031h"); + term.set_color_scheme(!dark); + assert!(events.take().is_empty(), "same-color reapplication stays silent"); + parser.advance(&mut term, b"\x1b[?2031l"); + term.set_color_scheme(dark); + assert!(events.take().is_empty(), "disabled notifications stay silent"); + } + } +} + /// 没订阅的程序不该收到这串字节——它会当成用户敲进来的输入。 #[test] fn color_scheme_change_stays_quiet_without_a_subscriber() { @@ -107,7 +136,7 @@ fn color_scheme_reports_only_on_a_real_flip() { let mut term = Term::new(Config::default(), &size, events.clone()); term.set_private_mode(PrivateMode::Unknown(2031)); - assert_eq!(events.take(), vec!["\x1b[?997;1n".to_owned()]); + assert!(events.take().is_empty()); // 暗 → 亮:一条 `;2n`。 term.set_color_scheme(false); @@ -151,7 +180,7 @@ fn decset_2031_survives_the_real_parser() { term.mode().contains(TermMode::COLOR_SCHEME_UPDATES), "`\\e[?2031h` 必须经解析器落到 PrivateMode::Unknown(2031)" ); - assert_eq!(events.take(), vec!["\x1b[?997;1n".to_owned()]); + assert!(events.take().is_empty()); // 主题翻成浅色:订阅方收到 `;2n`。 term.set_color_scheme(false); From bdee8d22c55038d8de072e90c46aacc558de9b5b Mon Sep 17 00:00:00 2001 From: galact-byte <94279960+galact-byte@users.noreply.github.com> Date: Sat, 26 Sep 2026 17:55:14 +0800 Subject: [PATCH 11/14] fix(terminal): preserve Pi reading position across synchronized redraws (#234) Reanchor only uniquely matched content after complete synchronized Pi redraws. Preserve standard clearing and cancel stale anchors on user actions or interrupted updates. Related to #159. --- .../terminal/view/activity_tests.rs | 40 +++ .../terminal/view/agent_activity.rs | 5 + .../src/gpui_shell/terminal/view/pointer.rs | 3 + .../src/gpui_shell/terminal/view/runtime.rs | 3 + nebula_terminal/src/event_loop.rs | 18 +- nebula_terminal/src/term/clear.rs | 57 ++++ nebula_terminal/src/term/mod.rs | 80 +---- nebula_terminal/src/term/redraw_anchor.rs | 144 +++++++++ nebula_terminal/tests/pi_redraw_anchor.rs | 273 ++++++++++++++++++ 9 files changed, 551 insertions(+), 72 deletions(-) create mode 100644 nebula_terminal/src/term/clear.rs create mode 100644 nebula_terminal/src/term/redraw_anchor.rs create mode 100644 nebula_terminal/tests/pi_redraw_anchor.rs diff --git a/nebula_app/src/gpui_shell/terminal/view/activity_tests.rs b/nebula_app/src/gpui_shell/terminal/view/activity_tests.rs index c1552ed23..dec49d6a9 100644 --- a/nebula_app/src/gpui_shell/terminal/view/activity_tests.rs +++ b/nebula_app/src/gpui_shell/terminal/view/activity_tests.rs @@ -14,6 +14,46 @@ fn hook(session: &str, name: &str, sequence: u64) -> AiHookEvent { crate::ai_hook::parse_remote_envelope(wire.as_bytes(), Some(42)).unwrap() } +#[gpui::test] +fn pi_redraw_anchor_follows_accepted_hook_and_command_lifecycle(cx: &mut TestAppContext) { + use nebula_terminal::term::test::TermSize; + use nebula_terminal::vte::ansi::Processor; + + let (view, window, _) = open(cx); + view.update(window, |view, cx| { + let event = |kind: &str, seq: u64| { + crate::ai_hook::parse_remote_envelope( + format!("nebula-hook/1 source=pi pane=42\n{{\"kind\":\"{kind}\",\"session_id\":\"redraw-policy\",\"bridge_sequence\":{seq}}}").as_bytes(), + Some(42), + ).unwrap() + }; + let check = |view: &mut TerminalView, expected: usize| { + let mut term = view.session.as_ref().unwrap().term.lock(); + term.resize(TermSize::new(60, 5)); + let mut stream = Processor::::default(); + let text = (0..12).map(|n| format!("ROW_{n:03}")).collect::>().join("\r\n"); + let frame = format!("\x1b[?2026h\x1b[2J\x1b[H\x1b[3J{text}\x1b[?2026l"); + term.scroll_display(Scroll::Bottom); + stream.advance(&mut *term, frame.as_bytes()); + term.scroll_display(Scroll::Top); + term.scroll_display(Scroll::Delta(-2)); + stream.advance(&mut *term, frame.as_bytes()); + assert_eq!(term.grid().display_offset(), expected); + }; + check(view, 0); + assert!(view.handle_ai_hook(&event("session-start", 1), cx)); + check(view, 5); + assert!(view.handle_ai_hook(&event("done", 2), cx)); + check(view, 5); // 回合结束不是 Pi 进程退出。 + assert!(view.handle_ai_hook(&event("session-end", 3), cx)); + check(view, 0); + assert!(view.handle_ai_hook(&event("session-start", 4), cx)); + check(view, 5); + view.finish_foreground_command(Some(0), cx); + check(view, 0); + }); +} + fn screen(view: &mut TerminalView, text: &str) { feed(view, format!("\x1b[2J\x1b[H{}", text.replace('\n', "\r\n")).as_bytes()); } diff --git a/nebula_app/src/gpui_shell/terminal/view/agent_activity.rs b/nebula_app/src/gpui_shell/terminal/view/agent_activity.rs index 625e23dc4..14b7617e0 100644 --- a/nebula_app/src/gpui_shell/terminal/view/agent_activity.rs +++ b/nebula_app/src/gpui_shell/terminal/view/agent_activity.rs @@ -67,6 +67,11 @@ impl TerminalView { | crate::ai_hook::AiTurnOutcome::Incomplete ); } + if let Some(session) = &self.session { + session.term.lock().set_redraw_anchor_enabled( + event.source == "pi" && event.kind != AiHookKind::SessionEnd, + ); + } if let Some(target) = target { let previous = self.recovery.target.clone(); self.recovery.confirm(target); diff --git a/nebula_app/src/gpui_shell/terminal/view/pointer.rs b/nebula_app/src/gpui_shell/terminal/view/pointer.rs index 0ae380253..a5f6221d6 100644 --- a/nebula_app/src/gpui_shell/terminal/view/pointer.rs +++ b/nebula_app/src/gpui_shell/terminal/view/pointer.rs @@ -853,6 +853,9 @@ impl TerminalView { _window: &mut Window, cx: &mut Context, ) { + if let Some(session) = &self.session { + session.term.lock().cancel_redraw_anchor(); + } let delta_y = event.delta.pixel_delta(self.line_height).y.as_f32(); // 旧壳 `mouse_wheel_input`:Ctrl+滚轮先于一切滚动消费者,一步 1 // 逻辑像素,钳在 4–64。设置页步进会写盘;这里同样写 `font_size=`, diff --git a/nebula_app/src/gpui_shell/terminal/view/runtime.rs b/nebula_app/src/gpui_shell/terminal/view/runtime.rs index bf8b1583d..194022534 100644 --- a/nebula_app/src/gpui_shell/terminal/view/runtime.rs +++ b/nebula_app/src/gpui_shell/terminal/view/runtime.rs @@ -127,6 +127,9 @@ impl TerminalView { /// the primary edge; the cached-prompt path calls the same reset so the two /// lifecycle routes cannot drift apart. pub(super) fn clear_foreground_agent_state(&mut self, cx: &mut Context) -> bool { + if let Some(session) = &self.session { + session.term.lock().set_redraw_anchor_enabled(false); + } self.confirmation.observe_waiting(false); self.recovery.command_ended(); self.answers.close(); diff --git a/nebula_terminal/src/event_loop.rs b/nebula_terminal/src/event_loop.rs index 120a20e51..3f455f35c 100644 --- a/nebula_terminal/src/event_loop.rs +++ b/nebula_terminal/src/event_loop.rs @@ -185,9 +185,21 @@ impl StreamProcessor { } pub fn stop_sync(&mut self, terminal: &mut Term) { + terminal.cancel_redraw_anchor(); self.parser.stop_sync(terminal); } + fn advance(&mut self, terminal: &mut Term, bytes: &[u8]) { + // VTE 0.15 在约 2 MiB 时强制提交同步缓冲;提前取消兼容锚点, + // 但不强制结束/截断输出。分块保证单次大输入也不会绕过检查。 + for chunk in bytes.chunks(4096) { + if self.parser.sync_bytes_count() >= 1024 * 1024 { + terminal.cancel_redraw_anchor(); + } + self.parser.advance(terminal, chunk); + } + } + pub fn feed( &mut self, terminal: &mut Term, @@ -200,7 +212,7 @@ impl StreamProcessor { // Titles and shell identity/cwd reports must retain wire order: // coalescing a remote cwd past a parent prompt would attribute that // directory to the parent shell's completion history. - self.parser.advance(terminal, &bytes[advanced..offset]); + self.advance(terminal, &bytes[advanced..offset]); advanced = offset; match event { OscEvent::Cwd(cwd) => event_proxy.send_event(Event::CwdReport(cwd)), @@ -239,7 +251,7 @@ impl StreamProcessor { let rows = (disp_h / cell_h).ceil().max(1.0) as usize; let abs_line = terminal.nebula_cursor_abs_line(); for _ in 0..=rows { - self.parser.advance(terminal, b"\r\n"); + self.advance(terminal, b"\r\n"); } event_proxy.send_event(Event::InlineImage { data: std::sync::Arc::new(data), @@ -250,7 +262,7 @@ impl StreamProcessor { }, } } - self.parser.advance(terminal, &bytes[advanced..]); + self.advance(terminal, &bytes[advanced..]); } } diff --git a/nebula_terminal/src/term/clear.rs b/nebula_terminal/src/term/clear.rs new file mode 100644 index 000000000..ef6805baa --- /dev/null +++ b/nebula_terminal/src/term/clear.rs @@ -0,0 +1,57 @@ +//! 清屏与滚动历史清除的网格、选区及阅读位置合同。 +use super::{Boundary, Column, Dimensions, EventListener, Line, Term, TermMode, ansi, cmp}; + +impl Term { + pub(super) fn clear_screen_contents(&mut self, mode: ansi::ClearMode) { + self.observe_redraw_clear(&mode); + log::trace!("Clearing screen: {mode:?}"); + let bg = self.grid.cursor.template.bg; + let screen_lines = self.screen_lines(); + + match mode { + ansi::ClearMode::Above => { + let cursor = self.grid.cursor.point; + if cursor.line > 1 { + self.grid.reset_region(..cursor.line); + } + let end = cmp::min(cursor.column + 1, Column(self.columns())); + for cell in &mut self.grid[cursor.line][..end] { + *cell = bg.into(); + } + let range = Line(0)..=cursor.line; + self.selection = self.selection.take().filter(|s| !s.intersects_range(range)); + }, + ansi::ClearMode::Below => { + let cursor = self.grid.cursor.point; + for cell in &mut self.grid[cursor.line][cursor.column..] { + *cell = bg.into(); + } + if (cursor.line.0 as usize) < screen_lines - 1 { + self.grid.reset_region((cursor.line + 1)..); + } + let range = cursor.line..Line(screen_lines as i32); + self.selection = self.selection.take().filter(|s| !s.intersects_range(range)); + }, + ansi::ClearMode::All => { + if self.mode.contains(TermMode::ALT_SCREEN) { + self.grid.reset_region(..); + } else { + let old_offset = self.grid.display_offset(); + self.grid.clear_viewport(); + let lines = self.grid.display_offset().saturating_sub(old_offset); + self.vi_mode_cursor.point.line = + (self.vi_mode_cursor.point.line - lines).grid_clamp(self, Boundary::Grid); + } + self.selection = None; + }, + ansi::ClearMode::Saved if self.history_size() > 0 => { + self.grid.clear_history(); + self.vi_mode_cursor.point.line = + self.vi_mode_cursor.point.line.grid_clamp(self, Boundary::Cursor); + self.selection = self.selection.take().filter(|s| !s.intersects_range(..Line(0))); + }, + ansi::ClearMode::Saved => (), + } + self.mark_fully_damaged(); + } +} diff --git a/nebula_terminal/src/term/mod.rs b/nebula_terminal/src/term/mod.rs index c9fa81cd5..cffb9dc90 100644 --- a/nebula_terminal/src/term/mod.rs +++ b/nebula_terminal/src/term/mod.rs @@ -28,12 +28,14 @@ use crate::vte::ansi::{ }; pub mod cell; +mod clear; pub mod color; mod damage; mod keyboard; #[cfg(test)] mod keyboard_contract_tests; mod prompt; +mod redraw_anchor; mod renderable; pub mod search; @@ -158,6 +160,7 @@ pub fn viewport_to_point_from(origin: Line, point: Point) -> Point { } pub struct Term { + redraw_anchor: redraw_anchor::RedrawAnchor, /// Terminal focus controlling the cursor shape. pub is_focused: bool, @@ -342,6 +345,7 @@ impl Term { where T: EventListener, { + self.cancel_redraw_anchor(); let old_display_offset = self.grid.display_offset(); self.grid.scroll_display(scroll); self.event_proxy.send_event(Event::MouseCursorDirty); @@ -382,6 +386,7 @@ impl Term { let damage = TermDamageState::new(num_cols, num_lines); Term { + redraw_anchor: Default::default(), inactive_grid, scroll_region, event_proxy, @@ -727,6 +732,7 @@ impl Term { /// Resize terminal to new dimensions. pub fn resize(&mut self, size: S) { + self.cancel_redraw_anchor(); let old_cols = self.columns(); let old_lines = self.screen_lines(); @@ -804,6 +810,7 @@ impl Term { /// Swap primary and alternate screen buffer. pub fn swap_alt(&mut self) { + self.cancel_redraw_anchor(); if !self.mode.contains(TermMode::ALT_SCREEN) { // Set alt screen cursor to the current primary screen cursor. self.inactive_grid.cursor = self.grid.cursor.clone(); @@ -1902,73 +1909,7 @@ impl Handler for Term { #[inline] fn clear_screen(&mut self, mode: ansi::ClearMode) { - trace!("Clearing screen: {mode:?}"); - let bg = self.grid.cursor.template.bg; - - let screen_lines = self.screen_lines(); - - match mode { - ansi::ClearMode::Above => { - let cursor = self.grid.cursor.point; - - // If clearing more than one line. - if cursor.line > 1 { - // Fully clear all lines before the current line. - self.grid.reset_region(..cursor.line); - } - - // Clear up to the current column in the current line. - let end = cmp::min(cursor.column + 1, Column(self.columns())); - for cell in &mut self.grid[cursor.line][..end] { - *cell = bg.into(); - } - - let range = Line(0)..=cursor.line; - self.selection = self.selection.take().filter(|s| !s.intersects_range(range)); - }, - ansi::ClearMode::Below => { - let cursor = self.grid.cursor.point; - for cell in &mut self.grid[cursor.line][cursor.column..] { - *cell = bg.into(); - } - - if (cursor.line.0 as usize) < screen_lines - 1 { - self.grid.reset_region((cursor.line + 1)..); - } - - let range = cursor.line..Line(screen_lines as i32); - self.selection = self.selection.take().filter(|s| !s.intersects_range(range)); - }, - ansi::ClearMode::All => { - if self.mode.contains(TermMode::ALT_SCREEN) { - self.grid.reset_region(..); - } else { - let old_offset = self.grid.display_offset(); - - self.grid.clear_viewport(); - - // Compute number of lines scrolled by clearing the viewport. - let lines = self.grid.display_offset().saturating_sub(old_offset); - - self.vi_mode_cursor.point.line = - (self.vi_mode_cursor.point.line - lines).grid_clamp(self, Boundary::Grid); - } - - self.selection = None; - }, - ansi::ClearMode::Saved if self.history_size() > 0 => { - self.grid.clear_history(); - - self.vi_mode_cursor.point.line = - self.vi_mode_cursor.point.line.grid_clamp(self, Boundary::Cursor); - - self.selection = self.selection.take().filter(|s| !s.intersects_range(..Line(0))); - }, - // We have no history to clear. - ansi::ClearMode::Saved => (), - } - - self.mark_fully_damaged(); + self.clear_screen_contents(mode); } #[inline] @@ -1987,6 +1928,7 @@ impl Handler for Term { /// Reset all important fields in the term struct. #[inline] fn reset_state(&mut self) { + self.cancel_redraw_anchor(); if self.mode.contains(TermMode::ALT_SCREEN) { mem::swap(&mut self.grid, &mut self.inactive_grid); } @@ -2156,7 +2098,7 @@ impl Handler for Term { self.cursor_blinking_override = Some(true); self.event_proxy.send_event(Event::CursorBlinkingChange); }, - NamedPrivateMode::SyncUpdate => (), + NamedPrivateMode::SyncUpdate => self.begin_redraw_anchor(), } } @@ -2212,7 +2154,7 @@ impl Handler for Term { self.cursor_blinking_override = Some(false); self.event_proxy.send_event(Event::CursorBlinkingChange); }, - NamedPrivateMode::SyncUpdate => (), + NamedPrivateMode::SyncUpdate => self.finish_redraw_anchor(), } } diff --git a/nebula_terminal/src/term/redraw_anchor.rs b/nebula_terminal/src/term/redraw_anchor.rs new file mode 100644 index 000000000..11546cb27 --- /dev/null +++ b/nebula_terminal/src/term/redraw_anchor.rs @@ -0,0 +1,144 @@ +//! 同步重绘后的保守阅读定位;只查找新网格,不恢复被应用清掉的内容。 +use super::{Cell, EventListener, Flags, Term, TermMode}; +use crate::grid::{Dimensions, Grid, Scroll}; +use crate::index::{Column, Line}; + +const ANCHOR_ROWS: usize = 3; +const MAX_COLUMNS: usize = 1024; +const MAX_SCAN_CELLS: usize = 4 * 1024 * 1024; + +#[derive(Default)] +pub(super) struct RedrawAnchor { + enabled: bool, + active: bool, + rows: Option>, + cleared_viewport: bool, + cleared_history: bool, +} + +impl Term { + /// 由宿主根据已确认的应用生命周期选择;默认不改变终端滚动语义。 + pub fn set_redraw_anchor_enabled(&mut self, enabled: bool) { + if self.redraw_anchor.enabled != enabled { + self.cancel_redraw_anchor(); + self.redraw_anchor.enabled = enabled; + } + } + + /// 用户操作或不完整同步更新优先,迟到的输出不得恢复旧阅读位置。 + pub fn cancel_redraw_anchor(&mut self) { + self.redraw_anchor.rows = None; + } + + pub(super) fn begin_redraw_anchor(&mut self) { + let previous_active = self.redraw_anchor.active; + self.redraw_anchor = RedrawAnchor { + enabled: self.redraw_anchor.enabled, + active: true, + ..Default::default() + }; + if previous_active + || !self.redraw_anchor.enabled + || self.grid.display_offset() == 0 + || self.mode.intersects(TermMode::ALT_SCREEN | TermMode::VI) + || self.selection.is_some() + || self.columns() > MAX_COLUMNS + || self.screen_lines() < ANCHOR_ROWS + { + return; + } + let start = -(self.grid.display_offset() as i32); + let rows: Option> = (0..ANCHOR_ROWS) + .map(|offset| row_key(&self.grid, Line(start + offset as i32))) + .collect(); + self.redraw_anchor.rows = rows.filter(|rows| rows.iter().any(|row| !row.is_empty())); + } + + pub(super) fn observe_redraw_clear(&mut self, mode: &super::ansi::ClearMode) { + if !self.redraw_anchor.active { + return; + } + match mode { + super::ansi::ClearMode::All => self.redraw_anchor.cleared_viewport = true, + super::ansi::ClearMode::Saved => self.redraw_anchor.cleared_history = true, + _ => (), + } + } +} + +impl Term { + pub(super) fn finish_redraw_anchor(&mut self) { + let enabled = self.redraw_anchor.enabled; + let state = std::mem::replace( + &mut self.redraw_anchor, + RedrawAnchor { enabled, ..Default::default() }, + ); + let Some(rows) = state.rows else { return }; + if !state.cleared_viewport + || !state.cleared_history + || self.mode.intersects(TermMode::ALT_SCREEN | TermMode::VI) + || self.selection.is_some() + || self.grid.total_lines().saturating_mul(self.columns()) > MAX_SCAN_CELLS + { + return; + } + let start = -(self.history_size() as i32); + let end = self.screen_lines() as i32 - ANCHOR_ROWS as i32; + let mut matched = None; + for line in start..=end { + if rows.iter().enumerate().all(|(offset, expected)| { + row_key(&self.grid, Line(line + offset as i32)).as_ref() == Some(expected) + }) { + if matched.is_some() { + return; + } + matched = Some(line); + } + } + if let Some(line) = matched.filter(|line| *line <= 0) { + self.scroll_display(Scroll::Bottom); + self.scroll_display(Scroll::Delta(-line)); + } + } +} + +fn row_key(grid: &Grid, line: Line) -> Option { + let mut text = String::new(); + let mut space = false; + for column in 0..grid.columns() { + let cell = &grid[line][Column(column)]; + // 换行重排没有可靠的行身份,不以不完整片段猜测原位置。 + if cell.flags.contains(Flags::WRAPLINE) { + return None; + } + if cell.flags.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER) { + continue; + } + if cell.c == ' ' && cell.zerowidth().is_none() { + space = !text.is_empty(); + continue; + } + if space { + text.push(' '); + space = false; + } + text.push(cell.c); + if let Some(chars) = cell.zerowidth() { + text.extend(chars); + } + } + // Pi 表格的纯边框随列宽伸长;只归一纯边框,不折叠正文中的重复字符。 + if text.contains('─') + && text + .chars() + .all(|c| matches!(c, '─' | '┌' | '┬' | '┐' | '├' | '┼' | '┤' | '└' | '┴' | '┘')) + { + let mut previous = None; + text.retain(|c| { + let keep = c != '─' || previous != Some(c); + previous = Some(c); + keep + }); + } + Some(text) +} diff --git a/nebula_terminal/tests/pi_redraw_anchor.rs b/nebula_terminal/tests/pi_redraw_anchor.rs new file mode 100644 index 000000000..2744698ab --- /dev/null +++ b/nebula_terminal/tests/pi_redraw_anchor.rs @@ -0,0 +1,273 @@ +use nebula_terminal::Term; +use nebula_terminal::event::VoidListener; +use nebula_terminal::event_loop::StreamProcessor; +use nebula_terminal::grid::{Dimensions, Scroll}; +use nebula_terminal::index::{Column, Line}; +use nebula_terminal::term::{Config, test::TermSize}; + +type Terminal = Term; + +fn feed(stream: &mut StreamProcessor, term: &mut Terminal, bytes: &[u8]) { + stream.feed(term, &VoidListener, bytes); +} + +fn numbered(count: usize) -> String { + (0..count).map(|n| format!("ROW_{n:03}")).collect::>().join("\r\n") +} + +fn frame(text: &str) -> String { + format!("\x1b[?2026h\x1b[2J\x1b[H\x1b[3J{text}\x1b[?2026l") +} + +fn row(term: &Terminal, line: i32) -> String { + (0..term.columns()) + .map(|col| term.grid()[Line(line)][Column(col)].c) + .collect::() + .trim_end() + .to_owned() +} + +fn top(term: &Terminal) -> String { + row(term, -(term.grid().display_offset() as i32)) +} + +fn initial(enabled: bool) -> (Terminal, StreamProcessor) { + let mut term = Term::new(Config::default(), &TermSize::new(60, 5), VoidListener); + let mut stream = StreamProcessor::default(); + term.set_redraw_anchor_enabled(enabled); + feed(&mut stream, &mut term, format!("SECRET_OLD\r\n{}", numbered(10)).as_bytes()); + term.scroll_display(Scroll::Top); + term.scroll_display(Scroll::Delta(-3)); + assert_eq!(top(&term), "ROW_002"); + (term, stream) +} + +#[test] +fn complete_sync_redraw_reanchors_new_content_without_resurrecting_history() { + let (mut term, mut stream) = initial(true); + feed(&mut stream, &mut term, frame(&numbered(12)).as_bytes()); + assert_eq!(top(&term), "ROW_002"); + assert_eq!(term.history_size(), 7); + let rows: Vec<_> = (-7..5).map(|line| row(&term, line)).collect(); + assert_eq!(rows, numbered(12).split("\r\n").collect::>()); +} + +#[test] +fn disabled_policy_preserves_standard_clear_behavior() { + let (mut term, mut stream) = initial(false); + feed(&mut stream, &mut term, frame(&numbered(12)).as_bytes()); + assert_eq!(term.grid().display_offset(), 0); + assert_eq!(top(&term), "ROW_007"); +} + +#[test] +fn byte_boundaries_do_not_change_reanchoring() { + let bytes = frame(&numbered(12)).into_bytes(); + for split in 0..=bytes.len() { + let (mut term, mut stream) = initial(true); + feed(&mut stream, &mut term, &bytes[..split]); + feed(&mut stream, &mut term, &bytes[split..]); + assert_eq!(top(&term), "ROW_002", "split={split}"); + } +} + +#[test] +fn plain_clear_and_missing_or_ambiguous_anchor_do_not_reanchor() { + for bytes in [ + "\x1b[3J".to_owned(), + frame("new\r\ncontent"), + frame(&format!("{}\r\n{}", numbered(12), numbered(12))), + format!("\x1b[2J\x1b[H\x1b[3J{}", numbered(12)), + ] { + let (mut term, mut stream) = initial(true); + feed(&mut stream, &mut term, bytes.as_bytes()); + assert_eq!(term.grid().display_offset(), 0); + } +} + +#[test] +fn user_scroll_or_disable_during_sync_cancels_pending_anchor() { + for disable in [false, true] { + let (mut term, mut stream) = initial(true); + feed(&mut stream, &mut term, b"\x1b[?2026h"); + if disable { + term.set_redraw_anchor_enabled(false); + } else { + term.scroll_display(Scroll::Bottom); + } + feed( + &mut stream, + &mut term, + format!("\x1b[2J\x1b[H\x1b[3J{}\x1b[?2026l", numbered(12)).as_bytes(), + ); + assert_eq!(term.grid().display_offset(), 0); + } +} + +#[test] +fn forced_sync_stop_does_not_restore_a_partial_redraw() { + let (mut term, mut stream) = initial(true); + feed( + &mut stream, + &mut term, + format!("\x1b[?2026h\x1b[2J\x1b[H\x1b[3J{}", numbered(12)).as_bytes(), + ); + stream.stop_sync(&mut term); + assert_eq!(term.grid().display_offset(), 0); + feed(&mut stream, &mut term, b"\x1b[?2026l"); + assert_eq!(term.grid().display_offset(), 0); +} + +#[test] +fn cancellation_resize_reset_and_alt_screen_do_not_restore_old_anchor() { + for operation in 0..4 { + let (mut term, mut stream) = initial(true); + feed(&mut stream, &mut term, b"\x1b[?2026h"); + match operation { + 0 => term.cancel_redraw_anchor(), + 1 => term.resize(TermSize::new(61, 5)), + 2 => term.swap_alt(), + _ => (), + } + let reset = if operation == 3 { "\x1bc" } else { "" }; + feed( + &mut stream, + &mut term, + format!("{reset}\x1b[2J\x1b[H\x1b[3J{}\x1b[?2026l", numbered(12)).as_bytes(), + ); + assert_eq!(term.grid().display_offset(), 0, "operation={operation}"); + } +} + +#[test] +fn oversized_sync_update_cancels_even_for_single_large_input() { + let (mut term, mut stream) = initial(true); + let bytes = format!( + "\x1b[?2026h{}\x1b[2J\x1b[H\x1b[3J{}\x1b[?2026l", + "\x00".repeat(2 * 1024 * 1024), + numbered(12) + ); + feed(&mut stream, &mut term, bytes.as_bytes()); + assert_eq!(term.grid().display_offset(), 0); +} + +#[test] +fn bottom_follow_and_append_remain_unchanged() { + let (mut term, mut stream) = initial(true); + feed(&mut stream, &mut term, b"\r\nAPPEND"); + assert_eq!(top(&term), "ROW_002"); + term.scroll_display(Scroll::Bottom); + feed(&mut stream, &mut term, frame(&numbered(12)).as_bytes()); + assert_eq!(term.grid().display_offset(), 0); +} + +#[test] +fn paragraph_spacing_preserves_anchor_including_blank_top_row() { + for blank_top in [false, true] { + let (mut term, mut stream) = initial(true); + let paragraphs = + (0..12).map(|n| format!("PARAGRAPH_{n:03}")).collect::>().join("\r\n\r\n"); + feed(&mut stream, &mut term, frame(¶graphs).as_bytes()); + term.scroll_display(Scroll::Top); + term.scroll_display(Scroll::Delta(if blank_top { -5 } else { -4 })); + let before: Vec<_> = + (0..3).map(|n| row(&term, -(term.grid().display_offset() as i32) + n)).collect(); + feed( + &mut stream, + &mut term, + frame(&format!("{paragraphs}\r\n\r\nNEW_PARAGRAPH")).as_bytes(), + ); + let after: Vec<_> = + (0..3).map(|n| row(&term, -(term.grid().display_offset() as i32) + n)).collect(); + assert_eq!(after, before, "blank_top={blank_top}"); + } +} + +#[test] +fn table_rules_widen_without_losing_the_reading_row() { + let table = |padding: usize| { + (0..12) + .map(|n| { + format!( + "│ ROW_{n:03}{}│ value {n} │\r\n├{}┼──────────┤", + " ".repeat(padding), + "─".repeat(9 + padding) + ) + }) + .collect::>() + .join("\r\n") + }; + let (mut term, mut stream) = initial(true); + feed(&mut stream, &mut term, frame(&table(1)).as_bytes()); + term.scroll_display(Scroll::Top); + term.scroll_display(Scroll::Delta(-4)); + assert_eq!(top(&term), "│ ROW_002 │ value 2 │"); + feed(&mut stream, &mut term, frame(&table(6)).as_bytes()); + assert_eq!(top(&term), "│ ROW_002 │ value 2 │"); +} + +#[test] +fn partial_clear_does_not_trigger_compatibility_relocation() { + for clear in ["\x1b[2J\x1b[H", "\x1b[3J"] { + let (mut enabled, mut stream) = initial(true); + let (mut standard, mut control) = initial(false); + let bytes = format!("\x1b[?2026h{clear}{}\x1b[?2026l", numbered(12)); + feed(&mut stream, &mut enabled, bytes.as_bytes()); + feed(&mut control, &mut standard, bytes.as_bytes()); + assert_eq!(top(&enabled), top(&standard)); + assert_eq!(enabled.grid().display_offset(), standard.grid().display_offset()); + } +} + +#[test] +fn repeated_sync_frames_recapture_the_current_reading_position() { + let (mut term, mut stream) = initial(true); + for count in 12..20 { + feed(&mut stream, &mut term, frame(&numbered(count)).as_bytes()); + assert_eq!(top(&term), "ROW_002"); + } +} + +#[test] +fn wide_and_combining_characters_survive_reanchoring() { + let content = |count| { + (0..count).map(|n| format!("中文_{n:03} e\u{301}")).collect::>().join("\r\n") + }; + let (mut term, mut stream) = initial(true); + feed(&mut stream, &mut term, frame(&content(12)).as_bytes()); + term.scroll_display(Scroll::Top); + term.scroll_display(Scroll::Delta(-2)); + let before = top(&term); + feed(&mut stream, &mut term, frame(&content(15)).as_bytes()); + assert_eq!(top(&term), before); + assert_eq!(term.grid().display_offset(), 8); +} + +#[test] +fn ambiguous_normalized_padding_does_not_choose_a_matching_copy() { + let (mut term, mut stream) = initial(true); + let first = (0..12).map(|n| format!("ROW_{n:03} value")).collect::>().join("\r\n"); + feed(&mut stream, &mut term, frame(&first).as_bytes()); + term.scroll_display(Scroll::Top); + term.scroll_display(Scroll::Delta(-2)); + let second = first.replace(" value", " value"); + feed(&mut stream, &mut term, frame(&format!("{first}\r\n{second}")).as_bytes()); + assert_eq!(term.grid().display_offset(), 0); +} + +#[test] +fn table_padding_changes_preserve_three_row_anchor() { + let (mut term, mut stream) = initial(true); + let table = |padding: usize| { + (0..12) + .map(|n| format!("│ ROW_{n:03}{}│ value {n} │", " ".repeat(padding))) + .collect::>() + .join("\r\n") + }; + feed(&mut stream, &mut term, frame(&table(1)).as_bytes()); + term.scroll_display(Scroll::Top); + term.scroll_display(Scroll::Delta(-2)); + assert_eq!(top(&term), "│ ROW_002 │ value 2 │"); + feed(&mut stream, &mut term, frame(&table(6)).as_bytes()); + assert_eq!(top(&term), "│ ROW_002 │ value 2 │"); +} From 3ad289e3e2a793d57cc3fc7614c7a127e1e92e97 Mon Sep 17 00:00:00 2001 From: JoyLin <72300219+JoyElliot@users.noreply.github.com> Date: Sat, 26 Sep 2026 18:20:16 +0800 Subject: [PATCH 12/14] fix(windows): preserve Acrylic blur at edges and on deactivation (#250) Use a supported installed Acrylic controller with owned window and runtime lifetimes. Retain the existing Accent fallback and pixel-opacity behavior. Addresses the Acrylic portion of #236; the Aero issue remains open. --- .../platform/2026-09-22-acrylic-controller.md | 103 +++++++ .../2026-09-22-acrylic-window-transitions.md | 110 +++++++ nebula_app/AGENTS.md | 2 + nebula_app/Cargo.toml | 2 +- nebula_app/src/gpui_shell/mod.rs | 2 + nebula_app/src/gpui_shell/wallpaper.rs | 54 +++- nebula_app/src/platform/acrylic.rs | 32 +++ nebula_app/src/platform/acrylic/bindings.rs | 154 ++++++++++ .../src/platform/acrylic/composition.rs | 206 +++++++++++++ nebula_app/src/platform/acrylic/controller.rs | 94 ++++++ nebula_app/src/platform/acrylic/gpui_tests.rs | 114 ++++++++ nebula_app/src/platform/acrylic/runtime.rs | 105 +++++++ nebula_app/src/platform/acrylic/tests.rs | 225 +++++++++++++++ .../src/platform/acrylic/transitions.rs | 270 ++++++++++++++++++ nebula_app/src/platform/mod.rs | 2 + 15 files changed, 1467 insertions(+), 8 deletions(-) create mode 100644 architecture/notes/nebula_app/platform/2026-09-22-acrylic-controller.md create mode 100644 architecture/notes/nebula_app/platform/2026-09-22-acrylic-window-transitions.md create mode 100644 nebula_app/src/platform/acrylic.rs create mode 100644 nebula_app/src/platform/acrylic/bindings.rs create mode 100644 nebula_app/src/platform/acrylic/composition.rs create mode 100644 nebula_app/src/platform/acrylic/controller.rs create mode 100644 nebula_app/src/platform/acrylic/gpui_tests.rs create mode 100644 nebula_app/src/platform/acrylic/runtime.rs create mode 100644 nebula_app/src/platform/acrylic/tests.rs create mode 100644 nebula_app/src/platform/acrylic/transitions.rs diff --git a/architecture/notes/nebula_app/platform/2026-09-22-acrylic-controller.md b/architecture/notes/nebula_app/platform/2026-09-22-acrylic-controller.md new file mode 100644 index 000000000..94a7125fc --- /dev/null +++ b/architecture/notes/nebula_app/platform/2026-09-22-acrylic-controller.md @@ -0,0 +1,103 @@ +# Windows Acrylic controller ownership and compatibility + +## Status + +Implemented on the GPUI Windows path; local native acceptance on Windows 11 +build 26200.9457, x64 Windows App Runtime 1.8 version 8000.946.1701.0. + +## Context + +AccentPolicy Acrylic leaves a measurable pattern near screen edges. Dark edge +overlays hide that pattern by changing the visual design. DesktopAcrylicController +reduces it, but its default target policy falls back to opaque gray on deactivation. +Pebrel must retain its existing pixel-alpha opacity model and fast opacity slider. + +## Evidence + +- A local 2560x1600 / 150% DPI comparison used colored bands and an 8 px checker + behind floating, screen-edge-aligned and maximized GPUI windows. Configuration + applied before SetTarget alone still went gray. Applying it after SetTarget, + followed by zero tint/luminosity opacity, preserved the blurred background. +- The production build's clean background ROI matched that successful prototype + pixel-for-pixel, including active/inactive/reactivated states. It is slightly + brighter than Accent, not a promise of identical pixels across implementations. +- The original 16 valid alternating prototype measurements isolated the target + PID/window-thread CPU and PID GPU counters. Window-thread cycles medians rose + about 5–10%, working set about 3 MiB; CPU time was noisy. Shared DWM cost cannot + be attributed reliably to this HWND. These are local prototype observations, + not a product performance guarantee. +- GPUI's pinned Windows platform runs its quit callback after GetMessage exits; + App shutdown borrows App and its async wait does not pump Windows messages. +- [SetTarget requirements](https://learn.microsoft.com/en-us/windows/windows-app-sdk/api/winrt/microsoft.ui.composition.systembackdrops.desktopacryliccontroller.settarget?view=windows-app-sdk-1.8) + require a DispatcherQueue and host backdrop opt-in. The + [native dynamic dependency API](https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/framework-packages/use-the-dynamic-dependency-api) + supports an installed Windows App SDK framework on Windows 11 22H2+. + +## Decision + +- [acrylic.rs](../../../../nebula_app/src/platform/acrylic.rs) owns controller/target + pairs by GPUI WindowId on the UI thread. One optional compositor/queue is shared + across material changes; there is no worker, frame callback or focus polling. +- Clear Accent, blur-behind and system backdrop before attaching the lower + DesktopWindowTarget. GPUI keeps its upper target. Configuration sets input + active after attachment; tint and luminosity opacity are zero. Window pixel + alpha continues to supply the user's opacity and theme color. +- Close per-window resources before changing material or destroying the HWND. + The synchronous app-quit callback closes remaining targets. A guard around + Application::run drains the owned queue only after run returns, outside the + App borrow. Its own RoInitialize reference survives GPUI's OleUninitialize. + An existing external queue is borrowed and never shut down here. +- Keep runtime activation valid until owned resources are released. Queue drain + failure retains the context until process exit instead of invalidating pending + callbacks. The drain has a two-second deadline; it is not on the render path. +- Resolve native package-graph APIs from the already loaded OS module. Require + build 22621+, the 1.8 framework family and minimum tested 8000.946.1701.0. Select + a matching installed architecture/version; never install or search for DLLs. + Missing runtime, unsupported API or failed attachment uses existing Accent. +- Use a private, narrow WinAppSDK 1.8 ABI plus existing Windows crate projections. + No bootstrap DLL, new NuGet build step or bundled runtime enters the installer. + SDK activation factories are local rather than process-cached interface pointers. +- Keep the existing per-mode/per-window application gate. Failed GPUI updates + are not cached as successful; opacity changes do not recreate native resources. + +## Rejected alternatives + +- Edge masks, larger opaque borders and CPU/capture blur change the visual design + or add recurring work. +- DWMSBT_TRANSIENTWINDOW/default controller policy does not preserve unfocused + transparency. Reapplying focus policy before SetTarget does not fix that order. +- Bundling the complete runtime exceeds the existing installer budget. Bootstrap + alone still requires runtime deployment. An opportunistic installed-runtime + path preserves startup compatibility without introducing an installer action. +- A new composition thread complicates HWND teardown and adds a thread lifetime. +- Pumping a shutdown queue inside on_app_quit can reenter an already borrowed App. + +## Consequences + +Machines without the supported runtime retain the old edge behavior. Windows 10, +other GPUs, mixed-DPI monitors, accessibility and system transparency-policy +changes need their own native acceptance; this local run does not certify them. +The selected minimum may be widened only with evidence for that runtime version. + +## Validation + +- `cargo build -p nebula --locked` +- `cargo test -p nebula --bin pebrel platform::acrylic:: -- --include-ignored --test-threads=1` + exercises missing-package failure, invalid HWND rollback, independent targets, + repeated close/reattach, full-size roots and actual DispatcherQueue shutdown. +- `cargo test -p nebula --bin pebrel native_acrylic_gpui_material_switches_and_window_lifecycle -- --ignored --test-threads=1` + opens real GPUI windows, switches all five material modes, creates a second + window under an unchanged mode, verifies opacity refreshes do not reattach, + closes one window and quits with the other still alive. +- Production captures cover floating/left/right/maximized and focus transitions; + isolated processes exited normally and removed their runtime endpoints. +- Architecture gate uses the upstream-synchronized base commit. + +## Supersedes + +None. Accent remains the compatibility implementation. + +## Revisit when + +GPUI owns a system-backdrop lifecycle, the supported runtime changes, or portable +runtime distribution can meet the existing size and platform contracts. diff --git a/architecture/notes/nebula_app/platform/2026-09-22-acrylic-window-transitions.md b/architecture/notes/nebula_app/platform/2026-09-22-acrylic-window-transitions.md new file mode 100644 index 000000000..718f87f8a --- /dev/null +++ b/architecture/notes/nebula_app/platform/2026-09-22-acrylic-window-transitions.md @@ -0,0 +1,110 @@ +# Acrylic during native window transitions + +## Status + +Implemented as a compatibility fallback on the GPUI Windows controller path. +Local native acceptance uses Windows 11 build 26200.9457 and Windows App Runtime +1.8 version 8000.946.1701.0; other compositor/driver combinations need acceptance. + +## Context + +Desktop Acrylic fixes the Accent edge artifact and preserves unfocused blur, but +its old blurred background can stretch or crop during maximize and restore to a +floating window. Ordinary window movement does not reproduce this incident. +The previous Accent path becomes temporarily clear during those animations. +Taskbar minimize/restore keeps native behavior: clearing before shrink introduces +a more noticeable flash than its existing, brief blurred snapshot. + +## Evidence + +- Colored horizontal bands and repeated text behind the same GPUI window expose + the stale blur geometry. A flat background does not establish correctness. +- An Accent/controller comparison keeps the GPUI renderer, theme and opacity + constant. The controller's old sample remains visible during the transition; + Accent exposes the clear background and resumes blur afterward. No application + code explicitly pauses Accent during these transitions. +- Native message traces put WINDOWPOSCHANGED and SIZE only a few milliseconds + after the command, while the visible transition continues. Neither message is + a completion notification for the compositor animation. +- The root already fills the desktop target. The public controller APIs provide + no force-recompute or per-HWND animation-completion operation. This does not + establish a documented internal DWM defect. +- [DWMWINDOWATTRIBUTE](https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute) + documents TRANSITIONS_FORCEDISABLED for setting only. A local native probe + confirms readback returns E_INVALIDARG, so it cannot identify animation state. + +## Decision + +- [transitions.rs](../../../../nebula_app/src/platform/acrylic/transitions.rs) + belongs to the per-window Backdrop and installs a subclass on its owning UI + thread. Pause only the system-backdrop brush before a meaningful system command + or a maximize state change. The latter also covers ShowWindow calls. Minimize + and return from the taskbar are tracked but never initiate a material pause. + Hidden-window startup, ordinary movement and interactive geometry changes + retain their material. +- Resume after a nonblocking 300 ms settling interval, measured to cover the local + native animation. This is a bounded fallback, not an exact completion signal. + Repeated transitions extend the deadline; a queued old timer cannot shorten it. + If a window is minimized during a pending maximum-size transition, the timer + still restores its saved brush without delaying or replaying the minimize. +- Preserve a newer SDK brush instead of overwriting a policy/accessibility update + with the saved brush. Respect the system's SPI_GETANIMATION setting. Do not + change animation settings, focus policy, GPUI content, opacity or startup flow. +- Remove the timer/subclass before closing the controller/target. The subclass + holds its own Rc until removal or HWND destruction; callbacks also hold a local + Rc for nested teardown. No RefCell borrow spans a COM call or DefSubclassProc. +- Timer allocation failure restores usable material and logs the failure; it + must not leave a visible window permanently clear. Failed subclass removal + retains an inert callback allocation until HWND destruction. +- There is no new worker or per-frame update. Additional native work occurs on + state changes and their settling timer, not continuously during rendering. + +## Rejected alternatives + +- SYSTEMBACKDROP AUTO and a transparent Accent alongside the controller did not + remove the stretched sample in the native comparison. +- Disabling GPUI DirectComposition still reproduced the sample artifact and + removed visible GPUI content in the probe; it is not a production solution. +- Disabling Windows animations or adding edge masks changes the requested visual + behavior. A rendering-backend replacement exceeds this focused repair. +- Restoring at WINDOWPOSCHANGED exposes stale material while DWM is still animating. +- Polling a write-only DWM attribute cannot detect disabled transitions. +- For taskbar minimization, RequestCommitAsync, DwmFlush and earlier CBT notification + still retained the old snapshot in local probes. A 32 ms asynchronous preparation + did clear it, but added a visible clear frame before shrinking. That tradeoff is + rejected: there is no CBT hook, minimize veto/replay or synchronous DWM wait in + production. Preserve the less distracting native minimize animation. + +## Consequences + +The fallback deliberately exposes a clear background during maximize/windowed +restore transitions, then +restores normal blur. It does not make Acrylic resample throughout the animation. +An unusually long system animation may outlast the measured settling interval. +The system animation setting is supported; per-HWND external suppression has no +supported readback and is not inferred. Runtime changes to accessibility policy +still require their own native visual acceptance. +If the composition target itself fails during restoration, the error is logged; +the guard does not retry COM calls indefinitely or overwrite an unknown SDK state. + +## Validation + +- Native tests exercise ordinary geometry, system commands, ShowWindowAsync, + queued stale timers, successive transitions, unchanged taskbar material, a newer SDK + brush, owner teardown and HWND destruction before the Rust owner. +- Colored-background recordings compare all four transition directions with the + old Accent and unguarded controller. Static material/focus acceptance remains + documented in the original controller note. +- Test processes have isolated configuration and are closed by their own HWND; + existing user sessions are not used as test targets. + +## Supersedes + +None. Extends [controller ownership](2026-09-22-acrylic-controller.md) with the +animation compatibility boundary. + +## Revisit when + +The Windows controller exposes supported transition synchronization, GPUI shares +ownership of the backdrop target, or a tested direct solution preserves material +through the animation without changing the existing rendering behavior. diff --git a/nebula_app/AGENTS.md b/nebula_app/AGENTS.md index 96d053ef3..0ced93278 100644 --- a/nebula_app/AGENTS.md +++ b/nebula_app/AGENTS.md @@ -8,3 +8,5 @@ - 测试真实控件和布局路径;编译或状态单测不能代替 hover、命中区域、键盘路径和视觉验收。 - 只有跨层所有权、持久化、协议、线程/生命周期或重要性能取舍才写 note,路径镜像到 `architecture/notes/nebula_app//`。 - Agent 集成、改键输入与 SSH 认证的因果记录分别位于 [`ai_hook`](../architecture/notes/nebula_app/ai_hook/)、[`input`](../architecture/notes/nebula_app/input/) 和 [`ssh_session`](../architecture/notes/nebula_app/ssh_session/)。 +- Windows Acrylic 的运行库回退与窗口生命周期见 [`platform`](../architecture/notes/nebula_app/platform/2026-09-22-acrylic-controller.md)。 +- Windows Acrylic 的动画期间透明回退与计时边界见 [`窗口状态切换`](../architecture/notes/nebula_app/platform/2026-09-22-acrylic-window-transitions.md)。 diff --git a/nebula_app/Cargo.toml b/nebula_app/Cargo.toml index 9ef316039..c1a84a960 100644 --- a/nebula_app/Cargo.toml +++ b/nebula_app/Cargo.toml @@ -193,7 +193,7 @@ objc2-app-kit = { version = "0.3.1", default-features = false, features = [ [target.'cfg(windows)'.dependencies] windows-core = "=0.61.2" -windows = { version = "=0.61.3", features = ["Data_Xml_Dom", "UI_Notifications", "Data_Pdf", "Storage", "Storage_Streams", "Foundation", "Win32_System_WinRT", "Win32_Graphics_Gdi", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_DataExchange", "Win32_System_Memory", "Win32_System_Ole", "Win32_System_SystemServices", "Win32_UI_Shell", "Win32_UI_Shell_PropertiesSystem", "Win32_System_Variant", "Win32_Storage_FileSystem", "Win32_UI_Input_KeyboardAndMouse"] } +windows = { version = "=0.61.3", features = ["Data_Xml_Dom", "UI_Notifications", "Data_Pdf", "Storage", "Storage_Streams", "Foundation", "System", "UI_Composition", "UI_Composition_Desktop", "Win32_System_WinRT_Composition", "Win32_System_WinRT", "Win32_Graphics_Gdi", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_DataExchange", "Win32_System_Memory", "Win32_System_Ole", "Win32_System_SystemServices", "Win32_UI_Shell", "Win32_UI_Shell_PropertiesSystem", "Win32_System_Variant", "Win32_Storage_FileSystem", "Win32_UI_Input_KeyboardAndMouse"] } dirs = "6.0.0" dwrote = "0.11.5" # Registry reads for installed-shell detection (WSL distros under Lxss, Git / diff --git a/nebula_app/src/gpui_shell/mod.rs b/nebula_app/src/gpui_shell/mod.rs index b2d8a9519..4b0bdba43 100644 --- a/nebula_app/src/gpui_shell/mod.rs +++ b/nebula_app/src/gpui_shell/mod.rs @@ -164,6 +164,7 @@ pub fn run_shell( } } let _runtime_server = runtime_server; + let _acrylic = crate::platform::acrylic::RunGuard::default(); // GPUI 默认只有 macOS 在最后一扇窗关掉后仍驻留(Dock 里留个没有窗口的 // 进程)。Nebula 没有 Dock 重开入口,也没法在 Mac 上验证那个无窗状态, // 首版三端统一:最后一扇窗关闭即退出(驻留另有 keep_session 能力位管)。 @@ -189,6 +190,7 @@ pub fn run_shell( /// 组件库/主题/快捷键/用户配置的一次性初始化。 fn init(cx: &mut App) { + crate::platform::acrylic::init(cx); // 三端都注册内嵌 Maple:Linux/macOS 的系统等宽字体没有 NF 图标码点, // 侧栏与提示符会出方框;字形同源也是跨平台截图能互相比对的前提。 register_bundled_fonts(cx); diff --git a/nebula_app/src/gpui_shell/wallpaper.rs b/nebula_app/src/gpui_shell/wallpaper.rs index 981f4492e..5336a64b5 100644 --- a/nebula_app/src/gpui_shell/wallpaper.rs +++ b/nebula_app/src/gpui_shell/wallpaper.rs @@ -400,17 +400,22 @@ fn apply_window_effects(cx: &mut App) { .into_iter() .filter(|handle| !already_applied.contains(&handle.window_id())) .collect::>(); - cx.set_global(AppliedBlur { blur, windows: window_ids }); + let mut applied = + already_applied.intersection(&window_ids).copied().collect::>(); for handle in pending { if let Err(err) = handle.update(cx, |_, window, _| { + crate::platform::acrylic::remove(window.window_handle().window_id()); window.set_background_appearance(appearance); #[cfg(windows)] apply_windows_accent_policy(window, blur, appearance); window.refresh(); }) { log::warn!("failed to apply window visual effects: {err}"); + } else { + applied.insert(handle.window_id()); } } + cx.set_global(AppliedBlur { blur, windows: applied }); }); } @@ -424,11 +429,14 @@ fn apply_window_effects(cx: &mut App) { /// | `Aero` | state 3 + 玻璃色调 | `DWMSBT_NONE` | 整窗实时玻璃模糊 | /// | `Mica` | 全零 | `DWMSBT_MAINWINDOW` | 系统壁纸 backdrop | /// | `Mica Alt` | 全零 | `DWMSBT_TABBEDWINDOW` | 强色调系统壁纸 backdrop | -/// | `Acrylic` | state 4 + 非零 alpha | `DWMSBT_NONE` | 实时模糊 + tint/噪点/饱和 | +/// | `Acrylic` | controller 成功时清零,否则 state 4 | `DWMSBT_NONE` | 实时 Acrylic | /// /// `Mica` / `Mica Alt` 使用公开 DWM 属性。Nebula 不读取 /// `SPI_GETDESKWALLPAPER` 或 `TranscodedWallpaper`;显示器选择、壁纸排布、模糊和 /// 色调全部交给系统合成器。Windows 不支持该属性时退回 Acrylic,避免透明空洞。 +/// Acrylic 在 Windows 11 22H2+ 优先使用可用的 DesktopAcrylicController;缺少 +/// Windows App Runtime 或绑定失败时保留 AccentPolicy 回退。控制器只随窗口和 +/// 材质档位变化创建/释放,不跟随透明度滑块或焦点重建。 /// /// 两条通道**必须互斥**:同时开 Acrylic 与 system backdrop 时 DWM 的行为未 /// 定义(实测表现为 backdrop 赢,Acrylic 被吞)。所以每档都要把另一条显式 @@ -494,7 +502,7 @@ fn apply_windows_accent_policy( } let apply_accent = |mut accent: AccentPolicy, phase: &str| { - let Some(set_attribute) = set_attribute else { return }; + let Some(set_attribute) = set_attribute else { return false }; let mut data = WindowCompositionAttributeData { attribute: 19, // WCA_ACCENT_POLICY data: &mut accent as *mut _ as *mut core::ffi::c_void, @@ -503,7 +511,9 @@ fn apply_windows_accent_policy( // SAFETY: hwnd 来自当前存活的 GPUI 窗口,数据在调用期间保持有效。 if unsafe { set_attribute(hwnd, &mut data) } == 0 { log::warn!("SetWindowCompositionAttribute({phase}) failed"); + return false; } + true }; let disabled_accent = AccentPolicy { @@ -520,9 +530,11 @@ fn apply_windows_accent_policy( // 必须先移除旧 WCA 层。反过来先写 DWMSBT 时,Aero/Acrylic 的 // AccentPolicy 会阻止 DWM 接纳新材质,事后再清也不会自动重算 frame。 - if system_material_requested { - apply_accent(disabled_accent, "clear-before-system-backdrop"); - } + let accent_cleared = if system_material_requested || blur == BlurModeName::Acrylic { + apply_accent(disabled_accent, "clear-before-system-backdrop") + } else { + false + }; let blur_behind = DWM_BLURBEHIND { dwFlags: DWM_BB_ENABLE, @@ -550,6 +562,17 @@ fn apply_windows_accent_policy( let system_material_available = system_material_requested && backdrop_result.is_some_and(|result| result >= 0); + let acrylic_requested = blur == BlurModeName::Acrylic + || (matches!(blur, BlurModeName::Mica | BlurModeName::MicaAlt) + && !system_material_available + && appearance != WindowBackgroundAppearance::Transparent); + let controller_available = acrylic_requested + && windows_build_number() >= 22_621 + && accent_cleared + && backdrop_result.is_some_and(|result| result >= 0) + && blur_behind_result >= 0 + && crate::platform::acrylic::apply(window.window_handle().window_id(), hwnd as isize); + let accent = match blur { BlurModeName::Acrylic => AccentPolicy { state: 4, // ACCENT_ENABLE_ACRYLICBLURBEHIND @@ -576,7 +599,7 @@ fn apply_windows_accent_policy( BlurModeName::Mica | BlurModeName::MicaAlt | BlurModeName::None => disabled_accent, }; - if !(system_material_requested && system_material_available) { + if !controller_available && !(system_material_requested && system_material_available) { apply_accent(accent, "final"); } @@ -813,3 +836,20 @@ fn image_corners(bounds: Bounds, image: Bounds, radius: Pixels) bottom_right: if right && bottom { radius } else { px(0.0) }, } } + +/// Initialize only the visual state needed by native material acceptance tests. +#[cfg(test)] +pub(crate) fn test_install_visual_effects(cx: &mut App, opacity: f32, blur: BlurModeName) { + cx.set_global(VisualEffects { + opacity, + blur, + wallpaper: None, + generation: Arc::new(AtomicU64::new(0)), + loading: false, + }); +} + +#[cfg(test)] +pub(crate) fn test_apply_window_effects(cx: &mut App) { + apply_window_effects(cx); +} diff --git a/nebula_app/src/platform/acrylic.rs b/nebula_app/src/platform/acrylic.rs new file mode 100644 index 000000000..c8be51068 --- /dev/null +++ b/nebula_app/src/platform/acrylic.rs @@ -0,0 +1,32 @@ +//! Optional native Acrylic lifecycle behind a platform-neutral shell interface. +//! Windows owns the material; other platforms retain their existing GPUI backdrop. + +#[cfg(windows)] +mod bindings; +#[cfg(windows)] +mod composition; +#[cfg(windows)] +mod controller; +#[cfg(all(test, windows))] +mod gpui_tests; +#[cfg(windows)] +mod runtime; +#[cfg(all(test, windows))] +mod tests; +#[cfg(windows)] +mod transitions; + +#[cfg(all(test, windows))] +pub(crate) use controller::test_snapshot; +#[cfg(windows)] +pub(crate) use controller::{RunGuard, apply, init, remove}; + +#[cfg(not(windows))] +#[derive(Default)] +pub(crate) struct RunGuard; + +#[cfg(not(windows))] +pub(crate) fn init(_: &mut gpui::App) {} + +#[cfg(not(windows))] +pub(crate) fn remove(_: gpui::WindowId) {} diff --git a/nebula_app/src/platform/acrylic/bindings.rs b/nebula_app/src/platform/acrylic/bindings.rs new file mode 100644 index 000000000..d25abee0e --- /dev/null +++ b/nebula_app/src/platform/acrylic/bindings.rs @@ -0,0 +1,154 @@ +//! Narrow Windows App SDK 1.8 ABI, absent from the OS-only `windows` crate. +//! Interface identities and slot order come from Microsoft.UI.winmd 1.8. +//! Use local activation factories: no SDK COM pointer may outlive our runtime lease. + +use std::ffi::c_void; + +use windows::UI::Color; +use windows::UI::Composition::CompositionTarget; +use windows::Win32::System::WinRT::{RoActivateInstance, RoGetActivationFactory}; +use windows_core::{HRESULT, HSTRING, IInspectable_Vtbl, Interface, Result}; + +windows_core::imp::define_interface!(Acrylic, AcrylicVtbl, 0x7c20a6af_8eb3_5f08_bdfc_6d35e35dfe45); +#[repr(C)] +pub struct AcrylicVtbl { + base: IInspectable_Vtbl, + get_fallback: unsafe extern "system" fn(*mut c_void, *mut Color) -> HRESULT, + set_fallback: unsafe extern "system" fn(*mut c_void, Color) -> HRESULT, + get_luminosity: unsafe extern "system" fn(*mut c_void, *mut f32) -> HRESULT, + set_luminosity: unsafe extern "system" fn(*mut c_void, f32) -> HRESULT, + get_tint_color: unsafe extern "system" fn(*mut c_void, *mut Color) -> HRESULT, + set_tint_color: unsafe extern "system" fn(*mut c_void, Color) -> HRESULT, + get_tint: unsafe extern "system" fn(*mut c_void, *mut f32) -> HRESULT, + set_tint: unsafe extern "system" fn(*mut c_void, f32) -> HRESULT, +} + +windows_core::imp::define_interface!(Statics, StaticsVtbl, 0xa9e8f790_79ef_5416_9b67_6bcfe867c8b7); +#[repr(C)] +pub struct StaticsVtbl { + base: IInspectable_Vtbl, + is_supported: unsafe extern "system" fn(*mut c_void, *mut bool) -> HRESULT, +} + +windows_core::imp::define_interface!( + Configuration, + ConfigurationVtbl, + 0xebcce1b9_0e0c_5431_ab0e_00f3f0669962 +); +#[repr(C)] +pub struct ConfigurationVtbl { + base: IInspectable_Vtbl, + get_high_contrast_color: unsafe extern "system" fn(*mut c_void, *mut *mut c_void) -> HRESULT, + set_high_contrast_color: unsafe extern "system" fn(*mut c_void, *mut c_void) -> HRESULT, + get_high_contrast: unsafe extern "system" fn(*mut c_void, *mut bool) -> HRESULT, + set_high_contrast: unsafe extern "system" fn(*mut c_void, bool) -> HRESULT, + get_input_active: unsafe extern "system" fn(*mut c_void, *mut bool) -> HRESULT, + set_input_active: unsafe extern "system" fn(*mut c_void, bool) -> HRESULT, + get_theme: unsafe extern "system" fn(*mut c_void, *mut i32) -> HRESULT, + set_theme: unsafe extern "system" fn(*mut c_void, i32) -> HRESULT, +} + +windows_core::imp::define_interface!( + Controller, + ControllerVtbl, + 0x5632d76c_0b74_5b52_aa33_80262068aeb2 +); +#[repr(C)] +pub struct ControllerVtbl { + base: IInspectable_Vtbl, + set_window_target: + unsafe extern "system" fn(*mut c_void, WindowId, *mut c_void, *mut bool) -> HRESULT, + set_core_target: + unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *mut bool) -> HRESULT, +} + +#[repr(C)] +struct WindowId { + value: u64, +} + +windows_core::imp::define_interface!( + WithTargets, + WithTargetsVtbl, + 0x9c56fe7c_98eb_5f89_ad97_dad57fc30c8c +); +#[repr(C)] +pub struct WithTargetsVtbl { + base: IInspectable_Vtbl, + get_state: unsafe extern "system" fn(*mut c_void, *mut i32) -> HRESULT, + add_target: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut bool) -> HRESULT, + remove_all_targets: unsafe extern "system" fn(*mut c_void) -> HRESULT, + remove_target: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut bool) -> HRESULT, + set_configuration: unsafe extern "system" fn(*mut c_void, *mut c_void) -> HRESULT, + add_state_changed: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut i64) -> HRESULT, + remove_state_changed: unsafe extern "system" fn(*mut c_void, i64) -> HRESULT, +} + +const CLASS: &str = "Microsoft.UI.Composition.SystemBackdrops.DesktopAcrylicController"; + +impl Acrylic { + pub(super) fn new() -> Result { + unsafe { + let factory: Statics = RoGetActivationFactory(&HSTRING::from(CLASS))?; + let mut supported = false; + (factory.vtable().is_supported)(factory.as_raw(), &mut supported).ok()?; + if !supported { + return Err(windows_core::Error::new( + HRESULT(0x80004001_u32 as i32), + "Acrylic unsupported", + )); + } + RoActivateInstance(&HSTRING::from(CLASS))?.cast() + } + } + + pub(super) fn attach(&self, hwnd: isize, target: &CompositionTarget) -> Result<()> { + let controller: Controller = self.cast()?; + let mut attached = false; + unsafe { + (controller.vtable().set_window_target)( + controller.as_raw(), + WindowId { value: hwnd as u64 }, + target.as_raw(), + &mut attached, + ) + .ok()?; + } + if !attached { + return Err(windows_core::Error::new( + HRESULT(0x80004005_u32 as i32), + "Acrylic target rejected", + )); + } + Ok(()) + } + + pub(super) fn configure(&self) -> Result { + unsafe { + let config: Configuration = RoActivateInstance(&HSTRING::from( + "Microsoft.UI.Composition.SystemBackdrops.SystemBackdropConfiguration", + ))? + .cast()?; + (config.vtable().set_input_active)(config.as_raw(), true).ok()?; + let targets: WithTargets = self.cast()?; + // SetTarget installs its own focus policy. Override AFTER attaching, + // otherwise deactivation reinstates opaque gray. Keep OS contrast and + // transparency policies; only the focus-derived fallback is disabled. + (targets.vtable().set_configuration)(targets.as_raw(), config.as_raw()).ok()?; + (self.vtable().set_tint_color)(self.as_raw(), Color { A: 255, R: 46, G: 52, B: 64 }) + .ok()?; + (self.vtable().set_tint)(self.as_raw(), 0.0).ok()?; + (self.vtable().set_luminosity)(self.as_raw(), 0.0).ok()?; + Ok(config) + } + } + + pub(super) fn close(&self) { + match self.cast::().and_then(|object| object.Close()) { + Ok(()) => {}, + Err(error) => { + log::warn!(target: "nebula", "closing Acrylic controller failed: {error}") + }, + } + } +} diff --git a/nebula_app/src/platform/acrylic/composition.rs b/nebula_app/src/platform/acrylic/composition.rs new file mode 100644 index 000000000..ecf1173f4 --- /dev/null +++ b/nebula_app/src/platform/acrylic/composition.rs @@ -0,0 +1,206 @@ +//! STA-affine composition resources. No background worker or per-frame updates. + +use std::marker::PhantomData; +use std::rc::Rc; +use std::time::{Duration, Instant}; + +use windows::System::{DispatcherQueue, DispatcherQueueController}; +use windows::UI::Composition::Compositor; +use windows::UI::Composition::Desktop::DesktopWindowTarget; +use windows::Win32::Foundation::HWND; +use windows::Win32::System::WinRT::Composition::ICompositorDesktopInterop; +use windows::Win32::System::WinRT::{ + CreateDispatcherQueueController, DQTAT_COM_NONE, DQTYPE_THREAD_CURRENT, DispatcherQueueOptions, + RO_INIT_SINGLETHREADED, RoInitialize, RoUninitialize, +}; +use windows_core::{HRESULT, Interface, Result}; +use windows_sys::Win32::Graphics::Dwm::{DWMWA_USE_HOSTBACKDROPBRUSH, DwmSetWindowAttribute}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + DispatchMessageW, IsWindow, MSG, PM_REMOVE, PeekMessageW, TranslateMessage, WM_QUIT, +}; + +use super::bindings::{Acrylic, Configuration}; +use super::runtime::Runtime; +use super::transitions::Transitions; + +struct Apartment; +impl Drop for Apartment { + fn drop(&mut self) { + unsafe { RoUninitialize() }; + } +} + +pub(super) struct Context { + compositor: Option, + queue: Option, + // Drop order: SDK objects/queue, runtime package lease, then our own STA ref. + _runtime: Runtime, + _apartment: Apartment, + _thread: PhantomData>, +} + +impl Context { + pub(super) fn new() -> Result { + unsafe { RoInitialize(RO_INIT_SINGLETHREADED)? }; + let apartment = Apartment; + let runtime = Runtime::load()?; + let queue = if DispatcherQueue::GetForCurrentThread().is_ok() { + None + } else { + Some(unsafe { + CreateDispatcherQueueController(DispatcherQueueOptions { + dwSize: std::mem::size_of::() as u32, + threadType: DQTYPE_THREAD_CURRENT, + apartmentType: DQTAT_COM_NONE, + })? + }) + }; + // Delay fallible compositor activation until State owns this context; + // even a failed attach must drain an owned queue at application shutdown. + Ok(Self { + compositor: None, + queue, + _runtime: runtime, + _apartment: apartment, + _thread: PhantomData, + }) + } + + pub(super) fn attach(&mut self, hwnd: isize) -> Result { + if self.compositor.is_none() { + self.compositor = Some(Compositor::new()?); + } + let compositor = self.compositor.as_ref().unwrap(); + let host = HostBackdrop::new(hwnd)?; + let interop: ICompositorDesktopInterop = compositor.cast()?; + // GPUI owns the topmost target; the material occupies the lower target. + let target = unsafe { interop.CreateDesktopWindowTarget(HWND(hwnd as _), false)? }; + let mut backdrop = + Backdrop { transitions: None, controller: None, config: None, target, _host: host }; + let root = compositor.CreateContainerVisual()?; + let mut relative_size = root.RelativeSizeAdjustment()?; + relative_size.X = 1.0; + relative_size.Y = 1.0; + root.SetRelativeSizeAdjustment(relative_size)?; + backdrop.target.SetRoot(&root)?; + backdrop.controller = Some(Acrylic::new()?); + let controller = backdrop.controller.as_ref().unwrap(); + controller.attach(hwnd, &backdrop.target.cast()?)?; + backdrop.config = Some(controller.configure()?); + backdrop.transitions = Some(Transitions::new(hwnd, backdrop.target.cast()?)?); + Ok(backdrop) + } + + /// Called outside GPUI's App borrow, AFTER Application::run returns. Never + /// pump messages in a window-close callback or on_app_quit (re-entrancy). + pub(super) fn shutdown(mut self) -> bool { + if let Some(compositor) = self.compositor.take() { + if let Err(error) = compositor.Close() { + log::warn!(target: "nebula", "closing Acrylic compositor failed: {error}"); + } + } + let Some(queue) = self.queue.as_ref() else { return true }; + let shutdown = match queue.ShutdownQueueAsync() { + Ok(shutdown) => shutdown, + Err(error) => { + log::warn!(target: "nebula", "Acrylic queue shutdown failed: {error}"); + // Keep package resolution and our STA alive for outstanding + // callbacks until process exit. This is not a live-window leak. + std::mem::forget(self); + return false; + }, + }; + let deadline = Instant::now() + Duration::from_secs(2); + while shutdown.Status().is_ok_and(|status| status.0 == 0) && Instant::now() < deadline { + let mut message: MSG = unsafe { std::mem::zeroed() }; + // The outer application loop has ended; WM_QUIT needs no repost. + unsafe { + while Instant::now() < deadline + && PeekMessageW(&mut message, std::ptr::null_mut(), 0, 0, PM_REMOVE) != 0 + { + if message.message != WM_QUIT { + TranslateMessage(&message); + DispatchMessageW(&message); + } + } + } + std::thread::sleep(Duration::from_millis(1)); + } + if shutdown.Status().is_ok_and(|status| status.0 == 1) { + if let Err(error) = shutdown.GetResults() { + log::warn!(target: "nebula", "Acrylic queue shutdown result: {error}"); + std::mem::forget(shutdown); + std::mem::forget(self); + return false; + } + true + } else { + log::warn!(target: "nebula", "Acrylic queue did not drain; retaining runtime until process exit"); + std::mem::forget(shutdown); + std::mem::forget(self); + false + } + } +} + +pub(super) struct Backdrop { + transitions: Option, + controller: Option, + config: Option, + target: DesktopWindowTarget, + _host: HostBackdrop, +} + +#[cfg(test)] +impl Backdrop { + pub(super) fn has_live_full_size_root(&self) -> bool { + self.target + .Root() + .and_then(|root| root.RelativeSizeAdjustment()) + .is_ok_and(|size| size.X == 1.0 && size.Y == 1.0) + } +} + +impl Drop for Backdrop { + fn drop(&mut self) { + // The HWND callback must stop using its target before the SDK closes it. + self.transitions.take(); + if let Some(controller) = self.controller.take() { + controller.close(); + } + self.config.take(); + if let Err(error) = self.target.Close() { + log::warn!(target: "nebula", "closing Acrylic desktop target failed: {error}"); + } + } +} + +struct HostBackdrop(isize); +impl HostBackdrop { + fn new(hwnd: isize) -> Result { + Self::set(hwnd, true)?; + Ok(Self(hwnd)) + } + + fn set(hwnd: isize, enabled: bool) -> Result<()> { + let value = i32::from(enabled); + unsafe { + HRESULT(DwmSetWindowAttribute( + hwnd as _, + DWMWA_USE_HOSTBACKDROPBRUSH as u32, + &value as *const _ as _, + std::mem::size_of_val(&value) as u32, + )) + .ok() + } + } +} +impl Drop for HostBackdrop { + fn drop(&mut self) { + if unsafe { IsWindow(self.0 as _) } != 0 { + if let Err(error) = Self::set(self.0, false) { + log::warn!(target: "nebula", "clearing Acrylic host backdrop failed: {error}"); + } + } + } +} diff --git a/nebula_app/src/platform/acrylic/controller.rs b/nebula_app/src/platform/acrylic/controller.rs new file mode 100644 index 000000000..ba247e35f --- /dev/null +++ b/nebula_app/src/platform/acrylic/controller.rs @@ -0,0 +1,94 @@ +use std::cell::RefCell; +use std::collections::HashMap; +use std::marker::PhantomData; +use std::rc::Rc; + +use super::composition::{Backdrop, Context}; + +#[derive(Default)] +struct State { + windows: HashMap, + context: Option, + unavailable: bool, + #[cfg(test)] + attachments: usize, +} + +thread_local! { + static STATE: RefCell = RefCell::new(State::default()); +} + +/// Owns final queue drain outside the App's shutdown borrow. Must surround run. +#[derive(Default)] +pub(crate) struct RunGuard(PhantomData>); + +impl Drop for RunGuard { + fn drop(&mut self) { + let mut state = STATE.with(|state| std::mem::take(&mut *state.borrow_mut())); + state.windows.clear(); + if let Some(context) = state.context.take() { + context.shutdown(); + } + } +} + +pub(crate) fn init(cx: &mut gpui::App) { + cx.on_window_closed(|_, id| remove(id)).detach(); + cx.on_app_quit(|_| { + STATE.with(|state| state.borrow_mut().windows.clear()); + async {} + }) + .detach(); +} + +pub(crate) fn remove(id: gpui::WindowId) { + STATE.with(|state| { + state.borrow_mut().windows.remove(&id); + }); +} + +/// Called only for a new HWND or material change, never an opacity/frame update. +pub(crate) fn apply(id: gpui::WindowId, hwnd: isize) -> bool { + STATE.with(|state| { + let mut state = state.borrow_mut(); + if state.windows.contains_key(&id) { + return true; + } + if state.unavailable { + return false; + } + if state.context.is_none() { + match Context::new() { + Ok(context) => state.context = Some(context), + Err(error) => { + state.unavailable = true; + log::info!(target: "nebula", "Desktop Acrylic unavailable; using Accent fallback: {error}"); + return false; + }, + } + } + match state.context.as_mut().unwrap().attach(hwnd) { + Ok(backdrop) => { + state.windows.insert(id, backdrop); + #[cfg(test)] + { + state.attachments += 1; + } + log::debug!(target: "nebula", "Desktop Acrylic attached to HWND {hwnd:#x}"); + true + }, + Err(error) => { + log::warn!(target: "nebula", "Desktop Acrylic attach failed; using Accent fallback: {error}"); + false + }, + } + }) +} + +#[cfg(test)] +pub(crate) fn test_snapshot() -> (usize, usize) { + STATE.with(|state| { + let state = state.borrow(); + (state.windows.len(), state.attachments) + }) +} diff --git a/nebula_app/src/platform/acrylic/gpui_tests.rs b/nebula_app/src/platform/acrylic/gpui_tests.rs new file mode 100644 index 000000000..726ff01c5 --- /dev/null +++ b/nebula_app/src/platform/acrylic/gpui_tests.rs @@ -0,0 +1,114 @@ +//! Opt-in real GPUI/WinRT lifecycle acceptance; no terminal, settings or user data. + +use crate::gpui_shell::wallpaper::{ + VisualEffects, test_apply_window_effects as apply_window_effects, test_install_visual_effects, +}; +use crate::platform::acrylic; +use gpui::{App, AppContext, AsyncApp, Context, Render, WindowHandle, WindowOptions}; +use gpui::{IntoElement, Styled, Window, WindowBackgroundAppearance, div}; +use nebula_settings::BlurModeName; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; +use std::time::Duration; + +struct EmptyWindow; +impl Render for EmptyWindow { + fn render(&mut self, _: &mut Window, _: &mut Context<'_, Self>) -> impl IntoElement { + div().size_full() + } +} + +fn open(cx: &mut App) -> WindowHandle { + cx.open_window( + WindowOptions { + window_background: WindowBackgroundAppearance::Transparent, + ..Default::default() + }, + |_, cx| cx.new(|_| EmptyWindow), + ) + .unwrap() +} + +async fn settle(cx: &AsyncApp, expected: usize) -> Result<(), String> { + cx.background_executor().timer(Duration::from_millis(180)).await; + let actual = acrylic::test_snapshot().0; + if actual != expected { + return Err(format!("expected {expected} native backdrops, observed {actual}")); + } + Ok(()) +} + +async fn exercise(first: WindowHandle, cx: &AsyncApp) -> Result<(), String> { + settle(cx, 1).await?; + let second = cx.update(|cx| { + let window = open(cx); + apply_window_effects(cx); + window + }); + settle(cx, 2).await?; + for mode in [ + BlurModeName::Aero, + BlurModeName::Acrylic, + BlurModeName::Mica, + BlurModeName::Acrylic, + BlurModeName::MicaAlt, + BlurModeName::Acrylic, + BlurModeName::None, + BlurModeName::Acrylic, + ] { + cx.update(|cx| { + cx.global_mut::().blur = mode; + apply_window_effects(cx); + }); + settle(cx, if mode == BlurModeName::Acrylic { 2 } else { 0 }).await?; + } + let before = acrylic::test_snapshot(); + for value in 0..=20 { + cx.update(|cx| { + cx.global_mut::().opacity = value as f32 / 20.0; + apply_window_effects(cx); + }); + } + settle(cx, 2).await?; + if acrylic::test_snapshot() != before { + return Err("opacity refresh recreated native resources".into()); + } + cx.update(|cx| first.update(cx, |_, window, _| window.remove_window())) + .map_err(|error| error.to_string())?; + settle(cx, 1).await?; + cx.update(|cx| second.update(cx, |_, window, _| window.refresh())) + .map_err(|error| error.to_string())?; + Ok(()) +} + +#[test] +#[ignore = "opens real GPUI windows; requires Windows 11 and Windows App Runtime 1.8"] +fn native_acrylic_gpui_material_switches_and_window_lifecycle() { + let result = Rc::new(RefCell::new(None)); + let shared_result = result.clone(); + let timed_out = Rc::new(Cell::new(false)); + let watchdog = timed_out.clone(); + let guard = acrylic::RunGuard::default(); + gpui_platform::application().run(move |cx| { + acrylic::init(cx); + test_install_visual_effects(cx, 0.4, BlurModeName::Acrylic); + let first = open(cx); + apply_window_effects(cx); + cx.spawn(async move |cx| { + *shared_result.borrow_mut() = Some(exercise(first, cx).await); + cx.update(|cx| cx.quit()); + }) + .detach(); + cx.spawn(async move |cx| { + cx.background_executor().timer(Duration::from_secs(15)).await; + watchdog.set(true); + cx.update(|cx| cx.quit()); + }) + .detach(); + }); + drop(guard); + assert!(!timed_out.get(), "normal GPUI quit must finish before the watchdog"); + assert_eq!(result.borrow_mut().take(), Some(Ok(()))); + assert_eq!(acrylic::test_snapshot().0, 0); + assert!(windows::System::DispatcherQueue::GetForCurrentThread().is_err()); +} diff --git a/nebula_app/src/platform/acrylic/runtime.rs b/nebula_app/src/platform/acrylic/runtime.rs new file mode 100644 index 000000000..ea900e41f --- /dev/null +++ b/nebula_app/src/platform/acrylic/runtime.rs @@ -0,0 +1,105 @@ +//! Optional, process-scoped Windows App Runtime package graph lease. +//! +//! Resolve the Windows 11 API dynamically so older Windows can still load Pebrel. +//! No bootstrap DLL, installation, filesystem probing or global package mutation. + +use std::ffi::c_void; +use std::ptr::{null, null_mut}; + +use windows_core::{Error, HRESULT, Result}; +use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress}; +use windows_sys::Win32::System::Memory::{GetProcessHeap, HeapFree}; + +type Create = unsafe extern "system" fn( + *const c_void, + *const u16, + u64, + i32, + i32, + *const u16, + u32, + *mut *mut u16, +) -> i32; +type Add = unsafe extern "system" fn(*const u16, i32, u32, *mut *mut c_void, *mut *mut u16) -> i32; +type Remove = unsafe extern "system" fn(*mut c_void) -> i32; +type Delete = unsafe extern "system" fn(*const u16) -> i32; + +pub(super) struct Runtime { + context: *mut c_void, + id: *mut u16, + remove: Remove, + delete: Delete, +} + +impl Runtime { + pub(super) fn load() -> Result { + Self::load_family(windows_core::w!("Microsoft.WindowsAppRuntime.1.8_8wekyb3d8bbwe")) + } + + fn load_family(family: windows_core::PCWSTR) -> Result { + // SAFETY: kernelbase is an OS module already loaded for this process. Each + // export has the signature in the Windows SDK's appmodel.h (22621+). + unsafe { + let module = GetModuleHandleW(windows_core::w!("kernelbase.dll").as_ptr()); + let proc = |name: &'static std::ffi::CStr| { + GetProcAddress(module, name.as_ptr().cast()).ok_or_else(Error::from_win32) + }; + if module.is_null() { + return Err(Error::from_win32()); + } + let create: Create = std::mem::transmute(proc(c"TryCreatePackageDependency")?); + let add: Add = std::mem::transmute(proc(c"AddPackageDependency")?); + let remove: Remove = std::mem::transmute(proc(c"RemovePackageDependency")?); + let delete: Delete = std::mem::transmute(proc(c"DeletePackageDependency")?); + let mut lease = Self { context: null_mut(), id: null_mut(), remove, delete }; + // Pin the minimum runtime actually validated, allowing newer patches + // in the same 1.8 family. Process lifetime; default architecture. + HRESULT(create( + null(), + family.as_ptr(), + (8000_u64 << 48) | (946_u64 << 32) | (1701_u64 << 16), + 0, + 0, + null(), + 0, + &mut lease.id, + )) + .ok()?; + let mut full_name = null_mut(); + let result = HRESULT(add(lease.id, 0, 0, &mut lease.context, &mut full_name)); + if !full_name.is_null() { + if let Ok(name) = windows_core::PCWSTR(full_name).to_string() { + log::debug!(target: "nebula", "Acrylic runtime: {name}"); + } + HeapFree(GetProcessHeap(), 0, full_name.cast()); + } + result.ok()?; + Ok(lease) + } + } +} + +#[cfg(test)] +#[test] +fn absent_runtime_is_a_recoverable_error() { + assert!( + Runtime::load_family(windows_core::w!("Pebrel.MissingAcrylicRuntime_8wekyb3d8bbwe")) + .is_err() + ); +} + +impl Drop for Runtime { + fn drop(&mut self) { + // Release owned SDK objects before removing their activation context. + // Removing the graph entry does not unload already loaded runtime DLLs. + unsafe { + if !self.context.is_null() { + let _ = (self.remove)(self.context); + } + if !self.id.is_null() { + let _ = (self.delete)(self.id); + HeapFree(GetProcessHeap(), 0, self.id.cast()); + } + } + } +} diff --git a/nebula_app/src/platform/acrylic/tests.rs b/nebula_app/src/platform/acrylic/tests.rs new file mode 100644 index 000000000..4b2ca69da --- /dev/null +++ b/nebula_app/src/platform/acrylic/tests.rs @@ -0,0 +1,225 @@ +use super::composition::Context; +use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + CreateWindowExW, DestroyWindow, DispatchMessageW, PM_REMOVE, PeekMessageW, TranslateMessage, + WS_EX_NOREDIRECTIONBITMAP, WS_OVERLAPPEDWINDOW, +}; + +struct TestWindow(isize); +impl TestWindow { + fn new() -> Self { + let hwnd = unsafe { + CreateWindowExW( + WS_EX_NOREDIRECTIONBITMAP, + windows_core::w!("STATIC").as_ptr(), + windows_core::w!("Pebrel Acrylic lifecycle test").as_ptr(), + WS_OVERLAPPEDWINDOW, + 0, + 0, + 320, + 240, + std::ptr::null_mut(), + std::ptr::null_mut(), + GetModuleHandleW(std::ptr::null()), + std::ptr::null(), + ) + }; + assert!(!hwnd.is_null()); + Self(hwnd as isize) + } +} +impl Drop for TestWindow { + fn drop(&mut self) { + assert_ne!(unsafe { DestroyWindow(self.0 as _) }, 0); + } +} + +#[test] +#[ignore = "requires interactive Windows 11 and Windows App Runtime 1.8 >= 8000.946.1701.0"] +fn native_targets_rollback_switch_independently_and_drain_before_sta_exit() { + // Real COM/WinRT calls protect ABI, failure rollback, two HWND ownership and + // shutdown. This does not substitute for GPUI focus/edge screenshot checks. + let mut context = Context::new().expect("required native runtime"); + let first = TestWindow::new(); + let second = TestWindow::new(); + assert!(context.attach(0).is_err()); + for _ in 0..8 { + let a = context.attach(first.0).expect("first native target"); + let b = context.attach(second.0).expect("independent second target"); + assert!(a.has_live_full_size_root() && b.has_live_full_size_root()); + drop(a); + assert!(b.has_live_full_size_root()); + // Reattach the same HWND while the other remains alive (material toggle). + let a = context.attach(first.0).expect("reattach after Close"); + let mut message = unsafe { std::mem::zeroed() }; + unsafe { + while PeekMessageW(&mut message, std::ptr::null_mut(), 0, 0, PM_REMOVE) != 0 { + TranslateMessage(&message); + DispatchMessageW(&message); + } + } + drop(b); + assert!(a.has_live_full_size_root()); + drop(a); + } + drop(first); + drop(second); + assert!(context.shutdown(), "owned queue must actually complete shutdown"); + assert!(windows::System::DispatcherQueue::GetForCurrentThread().is_err()); +} + +#[test] +#[ignore = "opens a native window; requires interactive Windows 11 and Windows App Runtime 1.8"] +fn native_transition_guard_preserves_moves_restarts_deadlines_and_releases_its_hook() { + use std::time::{Duration, Instant}; + use windows::UI::Color; + use windows::UI::Composition::{Compositor, ICompositionSupportsSystemBackdrop}; + use windows::Win32::Foundation::HWND; + use windows::Win32::System::WinRT::Composition::ICompositorDesktopInterop; + use windows_core::Interface; + use windows_sys::Win32::UI::WindowsAndMessaging::{ + PM_NOREMOVE, SC_MAXIMIZE, SC_MINIMIZE, SC_RESTORE, SW_MAXIMIZE, SW_MINIMIZE, SW_RESTORE, + SW_SHOWNOACTIVATE, SWP_NOACTIVATE, SWP_NOZORDER, SendMessageW, SetWindowPos, ShowWindow, + ShowWindowAsync, WM_SYSCOMMAND, WM_TIMER, + }; + + let pump = |millis| { + let until = Instant::now() + Duration::from_millis(millis); + while Instant::now() < until { + let mut message = unsafe { std::mem::zeroed() }; + unsafe { + while PeekMessageW(&mut message, std::ptr::null_mut(), 0, 0, PM_REMOVE) != 0 { + TranslateMessage(&message); + DispatchMessageW(&message); + } + } + std::thread::sleep(Duration::from_millis(2)); + } + }; + let context = Context::new().unwrap(); + let window = TestWindow::new(); + let compositor = Compositor::new().unwrap(); + let interop: ICompositorDesktopInterop = compositor.cast().unwrap(); + let target = unsafe { interop.CreateDesktopWindowTarget(HWND(window.0 as _), false).unwrap() }; + let root = compositor.CreateContainerVisual().unwrap(); + target.SetRoot(&root).unwrap(); + let support: ICompositionSupportsSystemBackdrop = target.cast().unwrap(); + let original = + compositor.CreateColorBrushWithColor(Color { A: 255, R: 40, G: 70, B: 90 }).unwrap(); + support.SetSystemBackdrop(&original).unwrap(); + let guard = super::transitions::Transitions::new(window.0, support.clone()).unwrap(); + unsafe { + ShowWindow(window.0 as _, SW_SHOWNOACTIVATE); + SetWindowPos( + window.0 as _, + std::ptr::null_mut(), + 100, + 100, + 360, + 260, + SWP_NOACTIVATE | SWP_NOZORDER, + ); + } + assert_eq!( + support.SystemBackdrop().unwrap(), + original.cast().unwrap(), + "ordinary geometry keeps the material" + ); + + unsafe { SendMessageW(window.0 as _, WM_SYSCOMMAND, SC_MAXIMIZE as usize, 0) }; + assert!(support.SystemBackdrop().is_err(), "maximization removes the stale sample"); + // Make a WM_TIMER from the old transition pending without dispatching it. + std::thread::sleep(Duration::from_millis(340)); + let mut message = unsafe { std::mem::zeroed() }; + assert_ne!( + unsafe { PeekMessageW(&mut message, window.0 as _, WM_TIMER, WM_TIMER, PM_NOREMOVE) }, + 0 + ); + unsafe { SendMessageW(window.0 as _, WM_SYSCOMMAND, SC_RESTORE as usize, 0) }; + pump(70); + assert!( + support.SystemBackdrop().is_err(), + "an old queued timer must not end the new transition" + ); + pump(320); + assert_eq!(support.SystemBackdrop().unwrap(), original.cast().unwrap()); + + // GPUI's titlebar takes the ShowWindow path, without WM_SYSCOMMAND. + for action in [SW_MAXIMIZE, SW_RESTORE] { + unsafe { + ShowWindowAsync(window.0 as _, action); + } + pump(20); + assert!(support.SystemBackdrop().is_err(), "programmatic transitions also pause"); + pump(340); + assert_eq!(support.SystemBackdrop().unwrap(), original.cast().unwrap()); + } + + unsafe { SendMessageW(window.0 as _, WM_SYSCOMMAND, SC_MINIMIZE as usize, 0) }; + assert_eq!( + support.SystemBackdrop().unwrap(), + original.cast().unwrap(), + "minimize keeps native material" + ); + pump(340); + assert_eq!(support.SystemBackdrop().unwrap(), original.cast().unwrap()); + unsafe { SendMessageW(window.0 as _, WM_SYSCOMMAND, SC_RESTORE as usize, 0) }; + pump(340); + assert_eq!( + support.SystemBackdrop().unwrap(), + original.cast().unwrap(), + "restore from taskbar keeps native material" + ); + + unsafe { SendMessageW(window.0 as _, WM_SYSCOMMAND, SC_MAXIMIZE as usize, 0) }; + assert!(support.SystemBackdrop().is_err()); + let newer = compositor.CreateColorBrushWithColor(Color { A: 255, R: 0, G: 0, B: 0 }).unwrap(); + support.SetSystemBackdrop(&newer).unwrap(); + pump(340); + assert_eq!( + support.SystemBackdrop().unwrap(), + newer.cast().unwrap(), + "a newer SDK policy brush wins" + ); + + for action in [SW_MINIMIZE, SW_RESTORE] { + unsafe { + ShowWindowAsync(window.0 as _, action); + } + pump(340); + assert_eq!( + support.SystemBackdrop().unwrap(), + newer.cast().unwrap(), + "maximized taskbar transitions keep native material" + ); + } + + unsafe { SendMessageW(window.0 as _, WM_SYSCOMMAND, SC_RESTORE as usize, 0) }; + assert!(support.SystemBackdrop().is_err()); + drop(guard); + support.SetSystemBackdrop(&newer).unwrap(); + pump(340); + assert_eq!( + support.SystemBackdrop().unwrap(), + newer.cast().unwrap(), + "dropping the owner cancels pending restoration" + ); + + // Native HWND destruction can precede the Rust owner during reentrant close. + let guard = super::transitions::Transitions::new(window.0, support.clone()).unwrap(); + unsafe { SendMessageW(window.0 as _, WM_SYSCOMMAND, SC_MAXIMIZE as usize, 0) }; + assert!(support.SystemBackdrop().is_err()); + drop(window); + pump(340); + drop(guard); + drop(support); + target.Close().unwrap(); + drop(target); + drop(interop); + drop(root); + drop(original); + drop(newer); + compositor.Close().unwrap(); + drop(compositor); + assert!(context.shutdown()); +} diff --git a/nebula_app/src/platform/acrylic/transitions.rs b/nebula_app/src/platform/acrylic/transitions.rs new file mode 100644 index 000000000..a5897c85b --- /dev/null +++ b/nebula_app/src/platform/acrylic/transitions.rs @@ -0,0 +1,270 @@ +//! Keep a stale Acrylic sample out of maximize/restore-to-window animations. +//! +//! Unlike Accent, the controller's composition target remains visible while DWM +//! scales the old window representation. Temporarily clear only that backdrop; +//! the GPUI scene, pixel opacity, focus policy and Windows animation stay intact. + +use std::cell::{Cell, RefCell}; +use std::rc::Rc; +use std::time::{Duration, Instant}; + +use windows::UI::Composition::{CompositionBrush, ICompositionSupportsSystemBackdrop}; +use windows_core::{Error, Result}; +use windows_sys::Win32::Foundation::HWND; +use windows_sys::Win32::UI::Shell::{ + DefSubclassProc, GetWindowSubclass, RemoveWindowSubclass, SetWindowSubclass, +}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + ANIMATIONINFO, IsIconic, IsWindowVisible, IsZoomed, KillTimer, SC_MAXIMIZE, SC_RESTORE, + SPI_GETANIMATION, SetTimer, SystemParametersInfoW, WM_NCDESTROY, WM_SETTINGCHANGE, + WM_SYSCOMMAND, WM_TIMER, WM_WINDOWPOSCHANGING, +}; + +// WM_WINDOWPOSCHANGED precedes the compositor animation's completion. Windows +// exposes no per-HWND completion event here. This bounded, nonblocking settling +// interval covers the native transition measured in our acceptance probes; it is +// not a claim to observe DWM completion. Repeated transitions extend the deadline. +const SETTLE: Duration = Duration::from_millis(300); + +#[derive(Clone, Copy, PartialEq, Eq)] +struct ShowState { + maximized: bool, + minimized: bool, +} + +impl ShowState { + fn read(hwnd: HWND) -> Self { + Self { + maximized: unsafe { IsZoomed(hwnd) != 0 }, + minimized: unsafe { IsIconic(hwnd) != 0 }, + } + } + + fn changes_for(self, command: usize) -> bool { + match command as u32 & 0xfff0 { + SC_MAXIMIZE => !self.maximized && !self.minimized, + SC_RESTORE => self.maximized && !self.minimized, + _ => false, + } + } +} + +struct State { + target: ICompositionSupportsSystemBackdrop, + saved: RefCell>, + show: Cell, + deadline: Cell>, + attached: Cell, + native_ref: Cell, +} + +/// Owned by one Backdrop, on its HWND's thread; no global registry or worker. +pub(super) struct Transitions { + hwnd: isize, + state: Rc, +} + +impl Transitions { + pub(super) fn new(hwnd: isize, target: ICompositionSupportsSystemBackdrop) -> Result { + let state = Rc::new(State { + target, + saved: RefCell::new(None), + show: Cell::new(ShowState::read(hwnd as _)), + deadline: Cell::new(None), + attached: Cell::new(false), + native_ref: Cell::new(false), + }); + let id = Rc::as_ptr(&state) as usize; + let native = Rc::into_raw(state.clone()); + // SAFETY: the subclass owns a strong reference until successful removal + // or WM_NCDESTROY. Each invocation also takes an Rc for nested teardown. + if unsafe { SetWindowSubclass(hwnd as _, Some(window_proc), id, id) } == 0 { + let error = Error::from_win32(); + unsafe { + drop(Rc::from_raw(native)); + } + return Err(error); + } + state.native_ref.set(true); + state.attached.set(true); + Ok(Self { hwnd, state }) + } +} + +impl Drop for Transitions { + fn drop(&mut self) { + self.state.detach(self.hwnd as _, Rc::as_ptr(&self.state) as usize, false); + } +} + +impl State { + fn detach(&self, hwnd: HWND, id: usize, destroying: bool) { + self.attached.set(false); + if self.native_ref.get() { + let mut data = 0; + let removed = unsafe { + KillTimer(hwnd, id); + RemoveWindowSubclass(hwnd, Some(window_proc), id) != 0 + || destroying + || GetWindowSubclass(hwnd, Some(window_proc), id, &mut data) == 0 + }; + if removed && self.native_ref.replace(false) { + // The caller still holds the owner or callback Rc here. + unsafe { + Rc::decrement_strong_count(self as *const State); + } + } else { + // Keep an inert failed-to-remove callback alive until destruction. + log::warn!(target: "nebula", "Acrylic transition hook removal failed; retaining it until HWND destruction"); + } + } + self.deadline.set(None); + let saved = self.saved.borrow_mut().take(); + drop(saved); + } + + fn cancel(&self, hwnd: HWND, id: usize) { + unsafe { + KillTimer(hwnd, id); + } + self.deadline.set(None); + self.resume(); + } + + fn pause(&self, hwnd: HWND, id: usize) { + if !self.attached.get() || unsafe { IsWindowVisible(hwnd) } == 0 { + return; + } + if !animations_enabled() { + self.cancel(hwnd, id); + return; + } + // Arm before clearing; a failed timer must not leave a live window clear. + if unsafe { SetTimer(hwnd, id, SETTLE.as_millis() as u32, None) } == 0 { + log::warn!(target: "nebula", "Acrylic transition timer failed; retaining the normal material"); + self.cancel(hwnd, id); + return; + } + self.deadline.set(Some(Instant::now() + SETTLE)); + let needs_brush = self.saved.borrow().is_none(); + if needs_brush { + let Ok(brush) = self.target.SystemBackdrop() else { return }; + if !self.attached.get() { + return; + } + match self.target.SetSystemBackdrop(None::<&CompositionBrush>) { + Ok(()) if self.attached.get() => { + let previous = self.saved.replace(Some(brush)); + drop(previous); + }, + Ok(()) => {}, + Err(error) => { + log::warn!(target: "nebula", "pausing Acrylic transition failed: {error}") + }, + } + } + } + + fn resume(&self) { + let saved = self.saved.borrow_mut().take(); + if let Some(brush) = saved { + if !self.attached.get() { + return; + } + // Null WinRT interfaces map to Error::empty (code 0). A real COM + // error does not prove that the SDK's current material is empty. + match self.target.SystemBackdrop() { + Err(error) if error.code().0 == 0 && self.attached.get() => { + if let Err(error) = self.target.SetSystemBackdrop(&brush) { + log::warn!(target: "nebula", "resuming Acrylic transition failed: {error}"); + } + }, + Err(error) => { + log::warn!(target: "nebula", "reading Acrylic transition material failed: {error}") + }, + // A newer SDK brush, including an accessibility fallback, wins. + Ok(_) => {}, + } + } + } + + fn on_timer(&self, hwnd: HWND, id: usize) { + if !self.attached.get() { + return; + } + unsafe { KillTimer(hwnd, id) }; + let Some(deadline) = self.deadline.get() else { return }; + if let Some(remaining) = deadline.checked_duration_since(Instant::now()) { + // KillTimer does not remove queued WM_TIMER messages. A stale message + // from an earlier transition must not reveal the backdrop too soon. + let millis = remaining.as_millis().saturating_add(1).min(u32::MAX as u128) as u32; + if unsafe { SetTimer(hwnd, id, millis, None) } != 0 { + return; + } + // On resource failure, a usable material is preferable to leaving + // the window permanently clear. The original artifact can recur. + log::warn!(target: "nebula", "Acrylic transition timer rearm failed; restoring material"); + } + self.deadline.set(None); + self.resume(); + } +} + +fn animations_enabled() -> bool { + let mut animation = + ANIMATIONINFO { cbSize: std::mem::size_of::() as u32, iMinAnimate: 1 }; + unsafe { + if SystemParametersInfoW( + SPI_GETANIMATION, + animation.cbSize, + &mut animation as *mut _ as _, + 0, + ) != 0 + && animation.iMinAnimate == 0 + { + return false; + } + } + true +} + +unsafe extern "system" fn window_proc( + hwnd: HWND, + message: u32, + wparam: usize, + lparam: isize, + id: usize, + data: usize, +) -> isize { + if !matches!( + message, + WM_SYSCOMMAND | WM_WINDOWPOSCHANGING | WM_TIMER | WM_NCDESTROY | WM_SETTINGCHANGE + ) { + return unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }; + } + // SAFETY: the installed subclass retains this raw Rc allocation. + // No mutable borrow or borrowed state crosses DefSubclassProc/COM callbacks. + let state = unsafe { + Rc::increment_strong_count(data as *const State); + Rc::from_raw(data as *const State) + }; + if message == WM_NCDESTROY { + state.detach(hwnd, id, true); + } else if message == WM_TIMER && wparam == id { + state.on_timer(hwnd, id); + return 0; + } else if message == WM_SETTINGCHANGE && state.attached.get() && !animations_enabled() { + state.cancel(hwnd, id); + } else if message == WM_WINDOWPOSCHANGING { + let show = ShowState::read(hwnd); + let previous = state.show.replace(show); + // Taskbar minimize/restore retains the native material and animation. + // Pausing before minimize would add a visible flash before shrinking. + if !previous.minimized && !show.minimized && previous.maximized != show.maximized { + state.pause(hwnd, id); + } + } else if message == WM_SYSCOMMAND && ShowState::read(hwnd).changes_for(wparam) { + state.pause(hwnd, id); + } + unsafe { DefSubclassProc(hwnd, message, wparam, lparam) } +} diff --git a/nebula_app/src/platform/mod.rs b/nebula_app/src/platform/mod.rs index a82c44aed..4b832d60e 100644 --- a/nebula_app/src/platform/mod.rs +++ b/nebula_app/src/platform/mod.rs @@ -9,6 +9,8 @@ //! 切模块 + 模块内 `#[cfg]` 分派」,只保留真正值钱的两点:单一入口,以及 //! 能力探测(让 UI 隐藏入口,而不是让功能在别的平台报错)。 +#[cfg(feature = "gpui-shell")] +pub(crate) mod acrylic; pub(crate) mod ai_session_identity; pub mod capabilities; pub mod credentials; From ba31b0d9c3225758121588068ba763bbf46ccb71 Mon Sep 17 00:00:00 2001 From: "Harvey Z." <39295864+zhbjerry@users.noreply.github.com> Date: Sat, 26 Sep 2026 18:45:28 +0800 Subject: [PATCH 13/14] fix(gpui): restore configurable macOS shortcuts and normal quit (#248) Restore configurable macOS Command aliases, preserve RenameTab rebinding and dispatch Command-Q through the normal quit path. Register Command aliases through the existing runtime platform entry without changing platform budgets or validation rules. Fixes #238. --- .../2026-09-21-macos-command-key-aliases.md | 116 ++++++++++++++ nebula_app/src/display/keymap.rs | 133 +++++++++++++++- .../gpui_shell/workspace/keyboard_bindings.rs | 65 ++++---- .../workspace/keyboard_bindings/tests.rs | 145 ++++++++++++++++++ 4 files changed, 424 insertions(+), 35 deletions(-) create mode 100644 architecture/notes/nebula_app/gpui_shell/2026-09-21-macos-command-key-aliases.md diff --git a/architecture/notes/nebula_app/gpui_shell/2026-09-21-macos-command-key-aliases.md b/architecture/notes/nebula_app/gpui_shell/2026-09-21-macos-command-key-aliases.md new file mode 100644 index 000000000..1055e1a32 --- /dev/null +++ b/architecture/notes/nebula_app/gpui_shell/2026-09-21-macos-command-key-aliases.md @@ -0,0 +1,116 @@ +# macOS command-key aliases + +## Status + +Implemented for issue #238. + +## Context + +The GPUI shell registered a macOS ⌘ shortcut set that existed nowhere else. +`bind_macos_command_keys` hand-wrote roughly two dozen bindings after +`default_workspace_bindings`, while `display::keymap::default_shortcuts()` — the +table that `clear_action` / `reset_action`, the settings keymap page and the +keybind reload path read — knew nothing about them. Half of those keys also +appear in the config macOS platform table (`config/bindings/defaults.rs`); the +other half only existed in the shell. + +Two user-visible consequences followed. Clearing the Shell picker row wrote only +`Ctrl+K:ReceiveChar`, so the static ⌘K binding kept consuming the key and the +panel still opened. `Action::Quit`, declared for macOS as `"q", SUPER`, fell into +the `_ => None` arm of `workspace_binding_in_context`, so ⌘Q did nothing at all +(GPUI installs no application menu). The display layer also rendered the super +modifier as `Win+`, so the settings page and the lines the app wrote into +`pebrel_settings.txt` showed `Ctrl+Win+F` / `Win+F` on macOS. + +## Evidence + +- Issue #238 reproduction, with the settings file the released build wrote: + `keybind=Ctrl+Win+F:ReceiveChar`, `keybind=Ctrl+K:ReceiveChar`, + `keybind=shift+win+k:ReceiveChar` — the unbind persisted, yet ⌘K still opened + the picker. +- `display::keymap` regressions (`clearing_releases_the_macos_command_alias`, + `macos_command_aliases_round_trip_through_storage`, + `super_modifier_renders_per_platform`) and shell regressions + (`every_macos_command_alias_binds_a_gpui_action`, + `released_cmd_k_is_swallowed_by_no_action`). +- GPUI keymap semantics: a no-action binding for a keystroke suppresses matching + bindings from equal or weaker sources, and a keystroke with no remaining + binding falls through to the view's key handler — that is why a cleared ⌘ key + reaches the terminal instead of being eaten. +- Manual acceptance on macOS 26 (arm64, debug build, window driven through + accessibility): default ⌘K opens the picker; clearing the row writes both + `Ctrl+K:ReceiveChar` and `cmd+k:ReceiveChar` and releases ⌘K and Ctrl+K without + a restart; restoring the row brings ⌘K back; ⌘Q quits with `clean_exit` true. + +## Decision + +`display::keymap::MACOS_COMMAND_ALIASES` is the single authority for the shell's +⌘ set. `init()` derives the static gpui bindings from it, and +`default_shortcuts()` adds it to the unbind/restore vocabulary on macOS, deduped +against entries the config table already provides for the same action and key. +The alias table writes `cmd+…` into `keybind=` lines. Existing files and shortcut +capture can still use `win+…`, and manually edited files can use `super+…` or a +different modifier order. The GPUI adapter parses and canonicalizes its binding +strings before comparing overrides and restored defaults. Display spelling must +not determine a shortcut's runtime identity. + +`Action::Quit` maps to a `QuitApp` action whose handler defers +`windowing::quit_all`, the same path as tray quit, so ⌘Q saves the session and +drafts before stopping PTYs. `mods_prefix` renders the super modifier per +platform, which also corrects the spelling of lines the app writes. + +## Rejected alternatives + +- Showing the ⌘ aliases on the settings keymap page (reverse-looking-up the + alias table in `effective_combo`) changes about twenty keycaps on macOS, the + shadowing verdicts other rows derive from them, and needs its own visual + acceptance. The page keeps showing the config table's Ctrl key. +- Moving the ⌘ set into the config macOS platform table would feed the legacy + terminal shell UI-only actions and keep the ⌘K collision, which the table + already resolves differently (`Esc("\x0c")` plus `ClearHistory`). +- Comparing raw display/storage spellings fails for equivalent `Win+…`, + `Cmd+…` and `super+…` keys. Display text is not a canonical identity; + `Ctrl++`-style display spellings also do not parse back as storage strings. +- Mapping the removed static ⌘ bindings to `ReceiveChar` from `init()` was not + needed: the user keybind table already injects the no-action binding. + +## Consequences + +- Cleared actions now also write `keybind=cmd+…:ReceiveChar` lines. Users coming + from an earlier build must clear the row once more, because their existing file + predates the alias vocabulary and holds no line for the ⌘ half. +- The keymap page still shows Ctrl keys for actions whose macOS binding set + includes ⌘. Releasing them works; seeing them does not. +- ⌘K after unbinding does not clear the screen. The GPUI shell has no + clear-screen action (`Action::Esc` and `Action::ClearHistory` are unmapped) and + the terminal encoder ignores pure ⌘ combinations, so the key is released but + inert. Out of scope here; `Ctrl+L` still passes through to the shell. +- ⌘B and ⌘, stay static bindings: they have no editable keymap row, so there is + nothing to clear. + +## Validation + +`cargo fmt --all -- --check`, `python3 scripts/check_architecture.py --base +f7ca0ec`, `python3 scripts/check_platform_cfg.py` (budget unchanged at 484) and +the `display::keymap` / `keyboard_bindings` unit suites pass; the two new +released-key tests fail without the change. Manual acceptance is listed under +Evidence. The alias table is shared data; runtime registration uses the existing +`Platform::current()` entry and remains macOS-only. The two macOS restore +regressions remain platform-gated. This avoids duplicating platform compile +branches in the UI adapter without increasing the current cfg budget. +A cross-platform GPUI dispatch regression confirms that sharing the table does +not register Command shortcuts on Windows/Linux. + +The 2026-09-23 review reproduced two restore failures through GPUI keyboard +dispatch: recording Cmd+K then resetting the row, and resetting the old +`Ctrl+Win+F:ReceiveChar` override from #238. Both failed before canonicalization. +Regression coverage includes those paths and equivalent modifier spellings/order. + +## Supersedes + +None. + +## Revisit when + +The keymap page should show platform-native keycaps, or macOS ⌘K should be +assigned to a clear-screen action instead of the Shell picker. diff --git a/nebula_app/src/display/keymap.rs b/nebula_app/src/display/keymap.rs index b7442e0f3..5b3cb3758 100644 --- a/nebula_app/src/display/keymap.rs +++ b/nebula_app/src/display/keymap.rs @@ -88,6 +88,52 @@ pub(crate) const READONLY_ROWS: &[(&str, &str, &str)] = &[ ("贴入 AI 修复建议", "Paste AI fix suggestion", "Ctrl+."), ]; +/// macOS 的 ⌘ 命令键别名:`(存储写法, 动作)`。 +/// +/// GPUI 壳在配置表之外**追加**一整套 ⌘ 绑定:配置表的 macOS 段只覆盖其中 +/// 一半,另一半(⌘K、⌘D、⌘⇧P…)是壳自己加的。这张表是那套绑定的唯一权威: +/// `init()` 按它注册静态绑定,解绑与恢复按它写回 `keybind=` 行。留在表外 +/// 就成了影子绑定——`clear_action` 不知道它,于是出现「⌘K 解绑后仍然弹出 +/// Shell 选择器」(#238)。 +/// +/// 表里的写法会写进设置文件,超级键写 `cmd`(macOS 的读法)。历史配置和 +/// 录制结果仍可使用 `win` / `super`;GPUI 适配层按解析后的按键规范化, +/// 覆盖与恢复默认不依赖这些别名或修饰键顺序的逐字相等。 +/// +/// 这张表只进 [`default_shortcuts`](解绑/恢复口径),不进 `effective_combo` +/// 的键帽反查:设置页仍按配置表的 Ctrl 键显示。 +/// +/// 别名表是共享数据;实际注册由平台层入口限定为 macOS,便于跨平台核验分派。 +pub(crate) const MACOS_COMMAND_ALIASES: &[(&str, Action)] = &[ + ("cmd+t", Action::CreateNewTab), + ("cmd+n", Action::CreateNewWindow), + // ⌘W 关标签页是 GPUI 壳的实际行为;配置表的 macOS 段把 ⌘W 记作 Quit, + // 这里必须压过它,否则解绑恢复会把 ⌘W 还给退出。 + ("cmd+w", Action::CloseTab), + ("shift+cmd+p", Action::ToggleCommandPalette), + ("cmd+k", Action::ToggleShellPicker), + ("shift+cmd+f", Action::ToggleFilesPanel), + ("cmd+d", Action::SplitRight), + ("shift+cmd+d", Action::SplitDown), + ("shift+cmd+enter", Action::ToggleZoom), + ("alt+cmd+left", Action::FocusPaneLeft), + ("alt+cmd+right", Action::FocusPaneRight), + ("alt+cmd+up", Action::FocusPaneUp), + ("alt+cmd+down", Action::FocusPaneDown), + ("shift+cmd+]", Action::SelectNextTab), + ("shift+cmd+[", Action::SelectPreviousTab), + ("shift+cmd+g", Action::ToggleGitPanel), + ("cmd+plus", Action::IncreaseFontSize), + ("cmd+=", Action::IncreaseFontSize), + ("cmd+minus", Action::DecreaseFontSize), + ("cmd+digit0", Action::ResetFontSize), + ("cmd+c", Action::Copy), + ("cmd+v", Action::Paste), + ("ctrl+cmd+f", Action::ToggleFullscreen), + ("shift+cmd+o", Action::OpenQuickJump), + ("cmd+q", Action::Quit), +]; + pub(crate) fn action_label( row: &(Action, &'static str, &'static str), language: super::UiLanguage, @@ -118,13 +164,33 @@ fn cached_defaults() -> &'static [KeyBinding] { } pub(crate) fn default_shortcuts() -> Vec<(String, Action)> { - cached_defaults() + let mut shortcuts: Vec<(String, Action)> = cached_defaults() .iter() .filter_map(|binding| { display_combo(binding.mods, &binding.trigger) .map(|combo| (combo, binding.action.clone())) }) - .collect() + .collect(); + // macOS 的 ⌘ 键也算默认键:`clear_action` / `reset_action` 按这份表决定要 + // 解掉、要还回哪些键,不带上它就会漏掉 ⌘ 那一半(#238)。 + #[cfg(target_os = "macos")] + { + let mut extra: Vec<(String, Action)> = Vec::new(); + for (combo, action) in MACOS_COMMAND_ALIASES { + let parsed = parse_combo(combo); + // 配置表已经给了同一动作的同一个键(⌘T、⌘C、⌘Q…)就不重复追加: + // 解绑会把每条 combo 都写进设置文件,重复条目只会多留一行废话。 + let covered = shortcuts + .iter() + .chain(extra.iter()) + .any(|(known, candidate)| candidate == action && parse_combo(known) == parsed); + if !covered { + extra.push(((*combo).to_owned(), action.clone())); + } + } + shortcuts.extend(extra); + } + shortcuts } /// Editing one action moves its shortcut: old keys pass through to the terminal. @@ -335,7 +401,10 @@ pub(crate) fn mods_prefix(mods: ModifiersState) -> String { out.push_str("Alt+"); } if mods.super_key() { - out.push_str("Win+"); + // macOS 的超级键是 ⌘。键帽必须写 Cmd+,否则设置页会出现 + // `Ctrl+Win+F`(全屏)、`Win+F`(搜索)这类用户认不出的组合(#238)。 + // 存储侧不受影响:`win+` / `super+` / `cmd+` 同等解析。 + out.push_str(if cfg!(target_os = "macos") { "Cmd+" } else { "Win+" }); } out } @@ -805,4 +874,62 @@ mod tests { ); } } + + /// 超级键键帽随平台渲染:macOS 是 ⌘,其它平台是 Win。 + #[test] + fn super_modifier_renders_per_platform() { + let expected = if cfg!(target_os = "macos") { "Cmd+" } else { "Win+" }; + assert_eq!(mods_prefix(ModifiersState::SUPER), expected); + assert_eq!( + mods_prefix(ModifiersState::CONTROL | ModifiersState::SUPER), + format!("Ctrl+{expected}") + ); + } + + /// 别名条目要能在存储格式里往返:`clear_action` 把表里的写法逐字写进 + /// 设置文件,解析层必须读回同一个组合。 + #[cfg(target_os = "macos")] + #[test] + fn macos_command_aliases_round_trip_through_storage() { + for (combo, _) in MACOS_COMMAND_ALIASES { + let (mods, key) = parse_combo(combo).unwrap_or_else(|| panic!("{combo} 解析失败")); + assert!(mods.super_key(), "{combo} 必须是 ⌘ 组合"); + let canonical = + canonical_combo(mods, &key).unwrap_or_else(|| panic!("{combo} 无法写成存储格式")); + assert_eq!(parse_combo(&canonical), Some((mods, key)), "{combo} 存储往返不一致"); + } + } + + /// #238:macOS 上 Shell 选择器除了配置表的 Ctrl+K 还有一条壳自带的 + /// ⌘K。解绑必须把两条都解掉,否则静态默认绑定继续抢键,用户看到的就是 + /// 「解绑了但 ⌘K 照样弹面板」。 + #[cfg(target_os = "macos")] + #[test] + fn clearing_releases_the_macos_command_alias() { + let action = Action::ToggleShellPicker; + // 设置页仍按配置表的 Ctrl+K 展示:别名只进解绑口径,不进键帽反查。 + assert_eq!(effective_combo(&action, &[]), Some(("Ctrl+K".to_owned(), false))); + let mut raw = Vec::new(); + clear_action(&mut raw, &action); + // 解绑使用表里的写法;旧配置和录制结果的等价拼写由 GPUI 层规范化。 + assert!( + raw.iter().any(|(combo, _)| combo == "cmd+k"), + "⌘K 必须按表里的写法逐字写回,实际 {raw:?}" + ); + // Ctrl+K 来自配置表、⌘K 来自别名表,两条都要落成 ReceiveChar。 + for combo in ["ctrl+k", "cmd+k"] { + let parsed = parse_combo(combo); + assert!( + raw.iter().any(|(candidate, name)| parse_combo(candidate) == parsed + && parse_action(name) == Some(Action::ReceiveChar)), + "{combo} 必须落成 ReceiveChar,否则运行时解不掉静态默认绑定" + ); + } + assert_eq!(effective_combo(&action, &build_bindings(&raw)), None, "解绑后不应再有有效键"); + reset_action(&mut raw, &action); + assert!( + effective_combo(&action, &build_bindings(&raw)).is_some(), + "恢复要把两组默认键都还回来" + ); + } } diff --git a/nebula_app/src/gpui_shell/workspace/keyboard_bindings.rs b/nebula_app/src/gpui_shell/workspace/keyboard_bindings.rs index 1ccd710e7..f1ce80d6d 100644 --- a/nebula_app/src/gpui_shell/workspace/keyboard_bindings.rs +++ b/nebula_app/src/gpui_shell/workspace/keyboard_bindings.rs @@ -44,22 +44,30 @@ pub(super) const STATIC_DEFAULT_COMBOS: &[&str] = &[ /// 存储格式 combo(`ctrl+shift+t`)→ gpui 绑定串(`ctrl-shift-t`)。键名 /// 两套体系同构(小写命名键 + 单字符);digitN 折回数字,plus/minus 折回 /// `+`/`-`(`+` 是存储分隔符,必须先占位再替换)。 +/// 最后由 GPUI 解析并规范化修饰键别名和顺序,保证旧 Win+、新 Cmd+ 和 +/// 录制结果在覆盖/恢复默认时具有同一个运行时身份。 pub(super) fn gpui_binding_combo(combo: &str) -> String { - combo + let combo = combo .to_ascii_lowercase() .replace("plus", "\u{1}") .replace("minus", "\u{2}") .replace('+', "-") .replace("digit", "") .replace('\u{1}', "+") - .replace('\u{2}', "-") + .replace('\u{2}', "-"); + gpui::Keystroke::parse(&combo).map(|key| key.unparse()).unwrap_or(combo) } /// 注册工作区快捷键;在 `gpui_component::init` 之后调用一次。 pub(super) fn init(cx: &mut App) { cx.bind_keys(default_workspace_bindings()); - #[cfg(target_os = "macos")] - bind_macos_command_keys(cx); + // 平台判定复用已有入口;共享表不意味着给其他平台注册 ⌘ 快捷键。 + if crate::platform::Platform::current() == crate::platform::Platform::MacOS { + bind_macos_command_keys(cx); + } + // 退出不属于任何视图,挂全局兜底:⌘Q 与用户自定义的 `keybind=…:Quit` + // 都落到与托盘退出同一条「先落盘会话与草稿,再停 PTY」的路径。 + cx.on_action(|_: &QuitApp, cx: &mut App| cx.defer(super::windowing::quit_all)); } /// 工作区静态默认键位表;与 [`STATIC_DEFAULT_COMBOS`] 互为镜像。 @@ -132,37 +140,23 @@ pub(super) fn default_workspace_bindings() -> Vec { /// 追加而非替换有两个原因:Ctrl+Shift 组合在 Mac 终端里没有别的含义,留着 /// 不碍事;而 ⌘C/⌘V 必须存在,否则 Mac 用户第一反应就是「复制粘贴坏了」。 /// 终端里的 Ctrl+C 仍然是 SIGINT——这里只绑 ⌘,不碰 Ctrl 的语义。 -#[cfg(target_os = "macos")] +/// +/// 键位来自 `display::keymap::MACOS_COMMAND_ALIASES`:设置页的反查、解绑与 +/// 恢复读的是同一张表,两处不会再各自漂移。注册必须留在这里、且早于用户 +/// 自定义键,这样 `clear_action` 注入的 NoAction 才压得住静态默认绑定。 fn bind_macos_command_keys(cx: &mut App) { - cx.bind_keys([ - KeyBinding::new("cmd-t", NewTerminal, None), - KeyBinding::new("cmd-n", NewWindow, None), - KeyBinding::new("cmd-w", CloseActiveTerminal, None), + let mut bindings: Vec = crate::display::keymap::MACOS_COMMAND_ALIASES + .iter() + .filter_map(|(combo, action)| workspace_binding_in_context(combo, action, None)) + .collect(); + // 剩下这些没有对应的 `config::Action`,或者需要单独的作用域。 + bindings.extend([ KeyBinding::new("cmd-b", ToggleSidebar, None), KeyBinding::new("cmd-,", OpenSettings, None), - KeyBinding::new("cmd-shift-p", ToggleCommandPalette, None), - KeyBinding::new("cmd-k", ToggleShellPicker, None), - KeyBinding::new("cmd-shift-f", ToggleFileTree, None), - KeyBinding::new("cmd-d", SplitRight, None), - KeyBinding::new("cmd-shift-d", SplitDown, None), - KeyBinding::new("cmd-shift-enter", ToggleZoom, None), - KeyBinding::new("cmd-alt-left", FocusPaneLeft, None), - KeyBinding::new("cmd-alt-right", FocusPaneRight, None), - KeyBinding::new("cmd-alt-up", FocusPaneUp, None), - KeyBinding::new("cmd-alt-down", FocusPaneDown, None), - KeyBinding::new("cmd-shift-]", SelectNextTab, None), - KeyBinding::new("cmd-shift-[", SelectPreviousTab, None), - KeyBinding::new("cmd-shift-g", ToggleGitPanel, None), - KeyBinding::new("cmd-=", IncreaseFontSize, None), - KeyBinding::new("cmd-+", IncreaseFontSize, None), - KeyBinding::new("cmd--", DecreaseFontSize, None), - KeyBinding::new("cmd-0", ResetFontSize, None), - KeyBinding::new("cmd-c", CopySelection, Some(crate::gpui_shell::terminal::KEY_CONTEXT)), - KeyBinding::new("cmd-v", PasteClipboard, Some(crate::gpui_shell::terminal::KEY_CONTEXT)), + // 设置页与对话框的输入框自带 ⌘V,作用域必须和终端分开。 KeyBinding::new("cmd-v", gpui_component::input::Paste, Some("Input")), - KeyBinding::new("cmd-ctrl-f", ToggleFullscreen, None), - KeyBinding::new("cmd-shift-o", OpenQuickJump, None), ]); + cx.bind_keys(bindings); } /// Typed GPUI adapter for the shared numbered/last-tab actions. The existing @@ -173,6 +167,12 @@ pub(super) struct SelectTab { index: Option, } +/// 退出应用,macOS 上绑 ⌘Q(`Action::Quit` 的 GPUI 侧落点)。处理注册在 +/// [`init`] 的全局兜底上,与绑定同一处维护。 +#[derive(Clone, Debug, PartialEq, gpui::Action)] +#[action(namespace = nebula_workspace, no_json)] +pub(super) struct QuitApp; + impl SelectTab { fn from_config(action: &crate::config::Action) -> Option { use crate::config::Action; @@ -250,8 +250,9 @@ fn workspace_binding_in_context( )), Action::ToggleFullscreen => Some(KeyBinding::new(&combo, ToggleFullscreen, scope)), Action::OpenQuickJump => Some(KeyBinding::new(&combo, OpenQuickJump, scope)), - // Mask the app action. ReceiveChar entries from the editor allow - // the terminal input handler to encode the released key. + // macOS 的退出键走与托盘退出同一条路径:先落盘会话与草稿,再停 PTY。 + Action::Quit => Some(KeyBinding::new(&combo, QuitApp, scope)), + // 屏蔽应用动作后,ReceiveChar 仍交给终端编码,保留改键释放旧键的语义。 Action::None | Action::ReceiveChar => Some(KeyBinding::new(&combo, gpui::NoAction, scope)), _ => None, } diff --git a/nebula_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs b/nebula_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs index 3929aeca4..9c9a03533 100644 --- a/nebula_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs +++ b/nebula_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs @@ -1,4 +1,90 @@ use super::*; + +#[test] +fn command_aliases_and_modifier_order_share_one_runtime_identity() { + let expected = gpui_binding_combo("shift+cmd+k"); + for combo in ["Shift+Win+K", "cmd+shift+k", "super+shift+k"] { + assert_eq!(gpui_binding_combo(combo), expected, "{combo}"); + } + assert_ne!(gpui_binding_combo("cmd+k"), expected); + assert_ne!(gpui_binding_combo("ctrl+shift+k"), expected); +} + +mod macos_command_keys { + use super::*; + + /// #238:别名表里的每条都必须落到 gpui 绑定上。表和运行时各写一份时, + /// 设置页显示的键可能按下去没有反应;合一之后这条守住两边不再漂移。 + #[test] + fn every_macos_command_alias_binds_a_gpui_action() { + for (combo, action) in crate::display::keymap::MACOS_COMMAND_ALIASES { + assert!( + workspace_binding_in_context(combo, action, None).is_some(), + "{combo} → {action:?} 没有对应的 gpui 绑定" + ); + } + // ⌘Q 必须落到退出动作,否则退出键不会走保存会话与草稿的路径。 + let quit = workspace_binding_in_context("cmd+q", &crate::config::Action::Quit, None) + .expect("⌘Q 必须有绑定"); + assert!(quit.action().as_any().is::(), "⌘Q 必须绑定 QuitApp"); + } + + #[test] + fn command_close_and_quit_dispatch_to_distinct_actions() { + use gpui::{KeyContext, Keymap, Keystroke}; + // 合并后仍按共享别名表分派,防止配置中的 ⌘W/Quit 抢走关闭标签页动作。 + let bindings = crate::display::keymap::MACOS_COMMAND_ALIASES + .iter() + .filter_map(|(combo, action)| workspace_binding_in_context(combo, action, None)) + .collect(); + let keymap = Keymap::new(bindings); + for context in ["Root", crate::gpui_shell::terminal::KEY_CONTEXT] { + let contexts = [KeyContext::parse(context).unwrap()]; + for (combo, quit) in [("cmd-w", false), ("cmd-q", true)] { + let input = [Keystroke::parse(combo).unwrap()]; + let (bindings, pending) = keymap.bindings_for_input(&input, &contexts); + assert!(!pending); + let action = bindings.first().expect("命令键必须有明确动作").action(); + if quit { + assert!(action.as_any().is::()); + } else { + assert!(action.as_any().is::()); + } + } + } + } + + /// #238:⌘K 被解绑后,用户注入的 NoAction 必须压得住静态默认绑定。 + #[test] + fn released_cmd_k_is_swallowed_by_no_action() { + use crate::config::Action; + use gpui::{KeyContext, Keymap, Keystroke}; + let contexts = [ + KeyContext::parse("Root").unwrap(), + KeyContext::parse(crate::gpui_shell::terminal::KEY_CONTEXT).unwrap(), + ]; + let input = [Keystroke::parse("cmd-k").unwrap()]; + // 反向对照:只有静态默认键时 ⌘K 必须命中 Shell 选择器,否则本用例空跑。 + let default = + custom_workspace_binding("cmd+k", &Action::ToggleShellPicker).expect("静态默认键"); + let (bindings, pending) = + Keymap::new(vec![default.clone()]).bindings_for_input(&input, &contexts); + assert!(!pending, "对照组必须命中"); + assert!(bindings[0].action().as_any().is::()); + // `update_keybinds` 在两个作用域各注入一条 NoAction,这里照抄运行时形状。 + let clear = workspace_binding_in_context("cmd+k", &Action::ReceiveChar, None).unwrap(); + let clear_terminal = workspace_binding_in_context( + "cmd+k", + &Action::ReceiveChar, + Some(crate::gpui_shell::terminal::KEY_CONTEXT), + ) + .unwrap(); + let released = Keymap::new(vec![default, clear, clear_terminal]); + let (bindings, pending) = released.bindings_for_input(&input, &contexts); + assert!(bindings.is_empty() && !pending, "解绑后不应有任何应用动作消费 ⌘K"); + } +} + #[test] fn cleared_shortcut_reaches_terminal_and_can_be_restored_without_restart() { use crate::config::Action; @@ -120,6 +206,65 @@ mod dispatch { }); } + #[gpui::test] + fn command_shortcut_registration_follows_runtime_platform(cx: &mut TestAppContext) { + let (_directory, workspace, mut cx) = open_workspace(1, cx); + press("cmd-k", &mut cx); + assert_eq!( + workspace.read_with(&cx, |workspace, _| workspace.shell_picker_open), + crate::platform::Platform::current() == crate::platform::Platform::MacOS, + "共享别名表只应在 macOS 注册原生命令键" + ); + } + + #[gpui::test] + #[cfg(target_os = "macos")] + fn recorded_command_key_can_restore_default(cx: &mut TestAppContext) { + use crate::display::keymap; + let (_directory, workspace, mut cx) = open_workspace(1, cx); + press("cmd-k", &mut cx); + assert!(workspace.read_with(&cx, |workspace, _| workspace.shell_picker_open)); + press("escape", &mut cx); + let keymap::CaptureOutcome::Bind(combo) = + keymap::capture_gpui(&Keystroke::parse("cmd-k").unwrap()) + else { + panic!("expected captured shortcut") + }; + assert_eq!(combo, "win+k"); + let mut raw = vec![(combo, "ToggleShellPicker".into())]; + workspace.update(&mut cx, |workspace, cx| workspace.update_keybinds(raw.clone(), cx)); + press("cmd-k", &mut cx); + assert!(workspace.read_with(&cx, |workspace, _| workspace.shell_picker_open)); + press("escape", &mut cx); + keymap::reset_action(&mut raw, &crate::config::Action::ToggleShellPicker); + workspace.update(&mut cx, |workspace, cx| workspace.update_keybinds(raw, cx)); + press("cmd-k", &mut cx); + assert!( + workspace.read_with(&cx, |workspace, _| workspace.shell_picker_open), + "Reset after recording Cmd+K must restore its default action" + ); + } + + #[gpui::test] + #[cfg(target_os = "macos")] + fn old_fullscreen_unbind_can_restore_default(cx: &mut TestAppContext) { + use crate::display::keymap; + let (_directory, workspace, mut cx) = open_workspace(1, cx); + for combo in ["Ctrl+Cmd+F", "Ctrl+Win+F", "super+ctrl+f"] { + let mut raw = vec![(combo.into(), "ReceiveChar".into())]; + workspace.update(&mut cx, |workspace, cx| workspace.update_keybinds(raw.clone(), cx)); + press("ctrl-cmd-f", &mut cx); + assert!(!cx.update(|window, _| window.is_fullscreen())); + keymap::reset_action(&mut raw, &crate::config::Action::ToggleFullscreen); + assert!(raw.is_empty()); + workspace.update(&mut cx, |workspace, cx| workspace.update_keybinds(raw, cx)); + press("ctrl-cmd-f", &mut cx); + assert!(cx.update(|window, _| window.is_fullscreen()), "reset failed for {combo}"); + press("ctrl-cmd-f", &mut cx); + assert!(!cx.update(|window, _| window.is_fullscreen())); + } + } + #[gpui::test] fn digits_switch_real_tabs_and_focus_in_both_tab_layouts(cx: &mut TestAppContext) { let (_directory, workspace, mut cx) = open_workspace(10, cx); From 7b0cedb5f9222e70d45292939bc662e5eacc903a Mon Sep 17 00:00:00 2001 From: Tennoji Rina <184329099+keys-cherish@users.noreply.github.com> Date: Sat, 26 Sep 2026 21:38:18 +0800 Subject: [PATCH 14/14] fix: keep update dialog opaque at low terminal opacity (#305) Use the existing opaque settings panel surface for the update dialog without changing terminal transparency or update actions. Cover the modal with light and dark themes, shell opacity values, and visible layout checks. --- .../src/gpui_shell/workspace/update_dialog.rs | 88 ++++++++++++++++++- 1 file changed, 87 insertions(+), 1 deletion(-) diff --git a/nebula_app/src/gpui_shell/workspace/update_dialog.rs b/nebula_app/src/gpui_shell/workspace/update_dialog.rs index 979520395..c519c93c2 100644 --- a/nebula_app/src/gpui_shell/workspace/update_dialog.rs +++ b/nebula_app/src/gpui_shell/workspace/update_dialog.rs @@ -11,6 +11,12 @@ use crate::update_download::DownloadStatus; const UPDATE_DIALOG_IDLE_HEIGHT: f32 = 250.0; const UPDATE_DIALOG_STATUS_HEIGHT: f32 = 280.0; +fn update_dialog_frame(dialog: Dialog, window: &Window, estimated_height: f32, cx: &App) -> Dialog { + // 默认 Dialog 继承终端壳的透明背景;更新内容需像设置页一样遮住底层文字。 + center_modal_dialog(dialog, window, estimated_height) + .bg(crate::gpui_shell::theme::settings_panel_bg(cx)) +} + struct UpdateNotification; /// 自动检查只在右下角提示,不抢终端焦点;默认常驻,也遵循通知时长设置。 @@ -394,7 +400,7 @@ pub(crate) fn open_update_dialog( let primary = Button::new("ok").label(primary_text).primary(); footer = footer.child(DialogAction::new().child(primary)); - center_modal_dialog(dialog, window, estimated_height) + update_dialog_frame(dialog, window, estimated_height, cx) .close_button(true) // 保留新 Dialog 的遮罩点击取消;它与 Esc、取消按钮共用 on_cancel。 .overlay_closable(true) @@ -452,3 +458,83 @@ fn format_bytes(bytes: u64) -> String { format!("{bytes} B") } } + +#[cfg(all(test, feature = "gpui-test-support"))] +mod tests { + use super::*; + use gpui::TestAppContext; + use gpui_component::{Theme, ThemeMode}; + + struct DialogProbe; + + impl Render for DialogProbe { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + // 滚动组件依赖当前视图;沿用真实模态层,避免裸绘制 Dialog 缺失实体上下文。 + div().size_full().children(Root::render_dialog_layer(window, cx)) + } + } + + #[gpui::test] + fn update_dialog_stays_opaque_without_changing_terminal_opacity(cx: &mut TestAppContext) { + cx.update(|cx| { + gpui_component::init(cx); + cx.set_reduce_motion(true); + }); + let (_, cx) = cx.add_window_view(|window, cx| { + let view = cx.new(|_| DialogProbe); + Root::new(view, window, cx) + }); + cx.simulate_resize(size(px(800.0), px(600.0))); + for name in [nebula_settings::ThemeName::LinenLight, nebula_settings::ThemeName::Nord] { + cx.update(|window, cx| { + let mut runtime = nebula_settings::RuntimeSettings::from_raw( + &nebula_settings::RawSettings::default(), + ); + runtime.theme = name; + runtime.follow_system_theme = false; + cx.set_global(crate::gpui_shell::config::Settings::load_with_runtime( + name, runtime, + )); + let mode = if crate::gpui_shell::theme::resolved_skin(cx).is_light { + ThemeMode::Light + } else { + ThemeMode::Dark + }; + Theme::change(mode, Some(window), cx); + }); + for alpha in [0.0, 0.2, 0.75, 1.0] { + for height in [UPDATE_DIALOG_IDLE_HEIGHT, UPDATE_DIALOG_STATUS_HEIGHT] { + let shell = cx.update(|window, cx| { + let panel = crate::gpui_shell::theme::settings_panel_bg(cx); + let shell = panel.opacity(alpha); + let theme = Theme::global_mut(cx); + theme.background = shell; + theme.tokens.background = shell.into(); + window.open_dialog(cx, move |dialog, window, cx| { + let mut dialog = update_dialog_frame(dialog, window, height, cx); + assert_eq!(panel.a, 1.0); + assert_eq!(dialog.style().background, Some(panel.into())); + assert_eq!(cx.theme().background, shell); + assert_eq!(cx.theme().tokens.background, shell.into()); + dialog.title("Update").child( + div() + .debug_selector(|| "update-dialog-body".to_owned()) + .child("Version details"), + ) + }); + shell + }); + cx.run_until_parked(); + cx.update(|window, cx| { + let _ = window.draw(cx); + assert_eq!(cx.theme().background, shell); + assert_eq!(cx.theme().tokens.background, shell.into()); + }); + let bounds = cx.debug_bounds("update-dialog-body").expect("rendered dialog"); + assert!(bounds.size.width > px(0.0) && bounds.size.height > px(0.0)); + cx.update(|window, cx| window.close_dialog(cx)); + } + } + } + } +}