From d1673eefdd9628d9ace62c1f4c129dcdcf3e9d18 Mon Sep 17 00:00:00 2001 From: Dongcheng Lin Date: Sun, 15 Nov 2026 01:12:07 +0900 Subject: [PATCH] feat(app): add chrome motion with a reduce motion preference --- crates/app/Cargo.toml | 2 +- crates/app/src/ui/canvas/board.rs | 18 +- crates/app/src/ui/command_exec_tests.rs | 4 +- crates/app/src/ui/mod.rs | 78 ++++++- crates/app/src/ui/motion.rs | 219 ++++++++++++++++++ crates/app/src/ui/motion_tests.rs | 78 +++++++ crates/app/src/ui/panel_chrome.rs | 12 +- crates/app/src/ui/properties/presentations.rs | 6 + crates/app/src/ui/properties/tests.rs | 4 +- crates/app/src/ui/ribbon.rs | 117 +++++++++- crates/app/src/ui/settings_dialog/chrome.rs | 9 +- crates/app/src/ui/switcher.rs | 76 ++---- crates/core/src/properties/app_preferences.rs | 66 +++++- .../src/properties/app_preferences_tests.rs | 40 +++- crates/core/src/settings/model.rs | 14 ++ .../src/content/docs/reference/preferences.md | 4 + .../docs/zh-cn/reference/preferences.md | 3 + 17 files changed, 653 insertions(+), 97 deletions(-) create mode 100644 crates/app/src/ui/motion.rs create mode 100644 crates/app/src/ui/motion_tests.rs diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml index b4fcef01..63c7ec4d 100644 --- a/crates/app/Cargo.toml +++ b/crates/app/Cargo.toml @@ -54,7 +54,7 @@ libc.workspace = true [target.'cfg(target_os = "macos")'.dependencies] muda.workspace = true objc2 = "0.6" -objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSApplication", "NSColor", "NSColorSpace", "NSHapticFeedback", "NSWindow", "objc2-core-foundation"] } +objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSAccessibility", "NSApplication", "NSColor", "NSColorSpace", "NSHapticFeedback", "NSWindow", "NSWorkspace", "objc2-core-foundation"] } objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSObject", "NSAppleEventManager", "NSAppleEventDescriptor", "NSNotification", "NSString", "NSURL"] } [target.'cfg(windows)'.build-dependencies] diff --git a/crates/app/src/ui/canvas/board.rs b/crates/app/src/ui/canvas/board.rs index 8e91e3aa..19b60893 100644 --- a/crates/app/src/ui/canvas/board.rs +++ b/crates/app/src/ui/canvas/board.rs @@ -70,17 +70,17 @@ pub(crate) fn freeze_board_for_gesture(app: &mut PlotiumApp) { /// Seed the fit springs from the live camera. fn seed_board_fit_springs(app: &mut PlotiumApp, ctx: &egui::Context) { - crate::ui::switcher::seed_spring( + crate::ui::motion::seed_spring( ctx, viewport_local_id(ctx, FIT_ZOOM_ID), app.session.board.zoom, ); - crate::ui::switcher::seed_spring( + crate::ui::motion::seed_spring( ctx, viewport_local_id(ctx, FIT_CENTER_X_ID), app.session.board.world_center[0], ); - crate::ui::switcher::seed_spring( + crate::ui::motion::seed_spring( ctx, viewport_local_id(ctx, FIT_CENTER_Y_ID), app.session.board.world_center[1], @@ -153,19 +153,15 @@ pub(crate) fn drive_board_fit( let ctx = ui.ctx(); let dt = ui.input(|i| i.stable_dt); let before = app.session.board; - app.session.board.zoom = crate::ui::switcher::animate_spring( - ctx, - viewport_local_id(ctx, FIT_ZOOM_ID), - target.zoom, - dt, - ); - app.session.board.world_center[0] = crate::ui::switcher::animate_spring( + app.session.board.zoom = + crate::ui::motion::spring(ctx, viewport_local_id(ctx, FIT_ZOOM_ID), target.zoom, dt); + app.session.board.world_center[0] = crate::ui::motion::spring( ctx, viewport_local_id(ctx, FIT_CENTER_X_ID), target.world_center[0], dt, ); - app.session.board.world_center[1] = crate::ui::switcher::animate_spring( + app.session.board.world_center[1] = crate::ui::motion::spring( ctx, viewport_local_id(ctx, FIT_CENTER_Y_ID), target.world_center[1], diff --git a/crates/app/src/ui/command_exec_tests.rs b/crates/app/src/ui/command_exec_tests.rs index b7eaff52..e95a889c 100644 --- a/crates/app/src/ui/command_exec_tests.rs +++ b/crates/app/src/ui/command_exec_tests.rs @@ -44,7 +44,7 @@ fn zoom_to_fit_command_seeds_springs_from_the_live_camera() { ("board_fit_center_y", -900.0), ] { let key = crate::ui::viewport_local_id(&ctx, id); - crate::ui::switcher::animate_spring(&ctx, key, stale, 0.0); + crate::ui::motion::spring(&ctx, key, stale, 0.0); } execute_without_clipboard(CommandId::ZoomToFit, &mut app, &ctx); @@ -59,7 +59,7 @@ fn zoom_to_fit_command_seeds_springs_from_the_live_camera() { ("board_fit_center_y", -40.0), ] { let key = crate::ui::viewport_local_id(&ctx, id); - let seeded = crate::ui::switcher::animate_spring(&ctx, key, live, 0.0); + let seeded = crate::ui::motion::spring(&ctx, key, live, 0.0); assert_eq!(seeded, live); } assert_eq!(app.session.status, "Fit all 1 board frame to view."); diff --git a/crates/app/src/ui/mod.rs b/crates/app/src/ui/mod.rs index ff69898c..8deeb860 100644 --- a/crates/app/src/ui/mod.rs +++ b/crates/app/src/ui/mod.rs @@ -31,6 +31,7 @@ pub(crate) mod file_dialogs; pub(crate) mod file_drop; pub(crate) mod import_feedback; mod menus; +pub(crate) mod motion; #[cfg(target_os = "macos")] pub(crate) mod native_documents; #[cfg(target_os = "macos")] @@ -117,6 +118,7 @@ pub fn render( *last_window_title = Some(title); } sync_chrome_theme(&ctx, app.settings.appearance.theme); + motion::sync(&ctx, app.settings.appearance.reduce_motion); clipboard_table_paste.begin_frame(app, &ctx); canvas::refresh_spotlight(app, &ctx); file_dialogs::image_import::poll(app, &ctx); @@ -553,25 +555,85 @@ pub(super) enum ModalKind { Dialog, } -/// Every modal goes through here so backdrop depth, anchoring, and future -/// theming decisions live in one place instead of at each call site. -pub(super) fn modal(ctx: &egui::Context, id: &str, kind: ModalKind) -> egui::Modal { +/// Every modal goes through here so backdrop depth, anchoring, and the +/// opening animation live in one place instead of at each call site. +pub(super) fn modal(ctx: &egui::Context, id: &str, kind: ModalKind) -> ChromeModal { let id = egui::Id::new(id); - match kind { - ModalKind::Palette => egui::Modal::new(id) - .backdrop_color(Color32::TRANSPARENT) - .area( + let (modal, backdrop) = match kind { + ModalKind::Palette => ( + egui::Modal::new(id).area( egui::Modal::default_area(id) .anchor(egui::Align2::CENTER_TOP, Vec2::new(0.0, 96.0)), ), + Color32::TRANSPARENT, + ), ModalKind::Dialog => { let alpha = if ctx.theme() == egui::Theme::Dark { 100 } else { 48 }; - egui::Modal::new(id).backdrop_color(Color32::from_black_alpha(alpha)) + (egui::Modal::new(id), Color32::from_black_alpha(alpha)) } + }; + ChromeModal { + id, + modal: modal + .backdrop_color(Color32::TRANSPARENT) + .frame(egui::Frame::NONE), + backdrop, + } +} + +/// An `egui::Modal` that fades in and grows slightly from its centre when it +/// opens. The backdrop is painted here rather than by egui so it still covers +/// the window while the layer is scaled. +pub(super) struct ChromeModal { + id: egui::Id, + modal: egui::Modal, + backdrop: Color32, +} + +impl ChromeModal { + pub(super) fn show( + self, + ctx: &egui::Context, + content: impl FnOnce(&mut Ui) -> T, + ) -> egui::ModalResponse { + let Self { + id, + mut modal, + backdrop, + } = self; + modal.area = modal.area.fade_in(false); + let layer = modal.area.layer(); + let t = motion::appear(ctx, id); + let rect_id = viewport_local_id(ctx, "modal_rect").with(id); + let pivot = ctx + .data(|data| data.get_temp::(rect_id)) + .map(|rect| rect.center()); + let transform = match pivot { + Some(pivot) if t < 1.0 => { + motion::scale_about(pivot, egui::lerp(motion::APPEAR_SCALE_FROM..=1.0, t)) + } + _ => egui::emath::TSTransform::IDENTITY, + }; + ctx.set_transform_layer(layer, transform); + modal.show(ctx, |ui| { + if backdrop.a() > 0 { + let cover = transform.inverse() * ui.ctx().content_rect(); + egui::Painter::new(ui.ctx().clone(), layer, cover).rect_filled( + cover, + 0.0, + backdrop.gamma_multiply(t), + ); + } + ui.multiply_opacity(t); + let shown = egui::Frame::popup(ui.style()).show(ui, content); + ui.ctx() + .data_mut(|data| data.insert_temp(rect_id, shown.response.rect)); + shown.inner + }) } } diff --git a/crates/app/src/ui/motion.rs b/crates/app/src/ui/motion.rs new file mode 100644 index 00000000..caf3f1f2 --- /dev/null +++ b/crates/app/src/ui/motion.rs @@ -0,0 +1,219 @@ +//! Chrome motion: durations, spring parameters, and the reduced-motion policy. +//! +//! Every animation state is keyed per viewport, so two windows showing the +//! same canvas never drive one another's springs. Animations request repaints +//! only while they are moving, and only for the viewport that owns them. + +use egui::{Color32, Id}; +use plotium_core::settings::ReduceMotion; + +/// Hover colour transitions. Presses show at once. +pub(crate) const HOVER_SECONDS: f32 = 0.10; +/// Dialog and command palette fade-in. +pub(crate) const APPEAR_SECONDS: f32 = 0.16; +/// Scale a dialog grows from while it fades in. +pub(crate) const APPEAR_SCALE_FROM: f32 = 0.96; +/// Spring period in seconds and damping ratio for sliding selections and +/// board camera glides. +const SPRING_RESPONSE: f32 = 0.34; +const SPRING_DAMPING: f32 = 0.82; +/// How often the platform accessibility setting is re-read while frames run. +const SYSTEM_POLL_SECONDS: f64 = 2.0; + +const POLICY_ID: &str = "plotium_motion_reduced"; +const SYSTEM_ID: &str = "plotium_motion_system"; + +/// Applies the preference once per frame. The platform setting is re-read +/// every few seconds so a change in the system settings takes effect without +/// restarting. +pub(crate) fn sync(ctx: &egui::Context, preference: ReduceMotion) { + let reduced = match preference { + ReduceMotion::On => true, + ReduceMotion::Off => false, + ReduceMotion::System => system_reduce_motion_cached(ctx), + }; + let applied = ctx.data(|data| data.get_temp::(Id::new(POLICY_ID))); + if applied == Some(reduced) { + return; + } + let defaults = egui::Style::default(); + for theme in [egui::Theme::Light, egui::Theme::Dark] { + ctx.style_mut_of(theme, |style| { + if reduced { + style.animation_time = 0.0; + style.scroll_animation = egui::style::ScrollAnimation::none(); + } else { + style.animation_time = defaults.animation_time; + style.scroll_animation = defaults.scroll_animation; + } + }); + } + ctx.data_mut(|data| data.insert_temp(Id::new(POLICY_ID), reduced)); +} + +pub(crate) fn reduced(ctx: &egui::Context) -> bool { + ctx.data(|data| data.get_temp::(Id::new(POLICY_ID))) + .unwrap_or(false) +} + +fn system_reduce_motion_cached(ctx: &egui::Context) -> bool { + let now = ctx.input(|input| input.time); + let cached = ctx.data(|data| data.get_temp::<(f64, bool)>(Id::new(SYSTEM_ID))); + if let Some((read_at, value)) = cached + && now - read_at < SYSTEM_POLL_SECONDS + && now >= read_at + { + return value; + } + let value = system_reduce_motion(); + ctx.data_mut(|data| data.insert_temp(Id::new(SYSTEM_ID), (now, value))); + value +} + +#[cfg(target_os = "macos")] +fn system_reduce_motion() -> bool { + objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion() +} + +#[cfg(windows)] +fn system_reduce_motion() -> bool { + use windows_sys::Win32::UI::WindowsAndMessaging::{ + SPI_GETCLIENTAREAANIMATION, SystemParametersInfoW, + }; + + let mut animations: windows_sys::core::BOOL = 1; + // SAFETY: SPI_GETCLIENTAREAANIMATION writes one BOOL through the pointer. + let ok = unsafe { + SystemParametersInfoW( + SPI_GETCLIENTAREAANIMATION, + 0, + (&raw mut animations).cast(), + 0, + ) + }; + if ok == 0 { + static WARNED: std::sync::Once = std::sync::Once::new(); + WARNED.call_once(|| { + log::warn!( + "could not read the Windows animation setting: {}", + std::io::Error::last_os_error() + ) + }); + return false; + } + animations == 0 +} + +#[cfg(not(any(target_os = "macos", windows)))] +fn system_reduce_motion() -> bool { + false +} + +#[derive(Clone, Copy)] +struct Spring { + pos: f32, + vel: f32, +} + +/// A damped spring integrated once per frame. Re-targeting mid-flight carries +/// the momentum, so a quick re-click redirects the glide instead of snapping. +/// With reduced motion the value lands on `target` immediately. +pub(crate) fn spring(ctx: &egui::Context, id: Id, target: f32, dt: f32) -> f32 { + if reduced(ctx) { + ctx.data_mut(|d| { + d.insert_temp( + id, + Spring { + pos: target, + vel: 0.0, + }, + ) + }); + return target; + } + let omega = std::f32::consts::TAU / SPRING_RESPONSE; + let k = omega * omega; + let c = 2.0 * SPRING_DAMPING * omega; + let mut s = ctx + .data_mut(|d| d.get_temp::(id)) + .unwrap_or(Spring { + pos: target, + vel: 0.0, + }); + let dt = dt.clamp(0.0, 1.0 / 30.0); + let accel = -k * (s.pos - target) - c * s.vel; + s.vel += accel * dt; + s.pos += s.vel * dt; + if (s.pos - target).abs() < 5e-4 && s.vel.abs() < 5e-4 { + s.pos = target; + s.vel = 0.0; + } else { + ctx.request_repaint(); + } + ctx.data_mut(|d| d.insert_temp(id, s)); + s.pos +} + +/// Seed a spring's stored position without disturbing its velocity, so the next +/// `spring` call glides from `pos` (the current value) rather than snapping to +/// a fresh target. Preserving velocity lets a re-seed mid-flight keep momentum. +pub(crate) fn seed_spring(ctx: &egui::Context, id: Id, pos: f32) { + let vel = ctx + .data_mut(|d| d.get_temp::(id)) + .map_or(0.0, |s| s.vel); + ctx.data_mut(|d| d.insert_temp(id, Spring { pos, vel })); +} + +/// Hover emphasis from 0 to 1. It animates only for a moment after the +/// pointer enters or leaves, so an idle hover costs no frames. +pub(crate) fn hover(ctx: &egui::Context, id: Id, hovered: bool) -> f32 { + let seconds = if reduced(ctx) { 0.0 } else { HOVER_SECONDS }; + ctx.animate_bool_with_time(id.with("hover").with(ctx.viewport_id()), hovered, seconds) +} + +/// Eased progress from 0 to 1 since the surface `id` started showing. A +/// surface counts as newly shown when it was absent on the previous pass. +pub(crate) fn appear(ctx: &egui::Context, id: Id) -> f32 { + let key = id.with("appear").with(ctx.viewport_id()); + let pass = ctx.cumulative_pass_nr(); + let now = ctx.input(|input| input.time); + let started = ctx.data_mut(|data| { + let started = match data.get_temp::<(u64, f64)>(key) { + Some((last_pass, started)) if last_pass + 1 >= pass && started <= now => started, + _ => now, + }; + data.insert_temp(key, (pass, started)); + started + }); + if reduced(ctx) { + return 1.0; + } + let t = ((now - started) as f32 / APPEAR_SECONDS).clamp(0.0, 1.0); + if t < 1.0 { + ctx.request_repaint(); + } + egui::emath::easing::cubic_out(t) +} + +/// Scales a layer by `scale` around `pivot`, both in layer coordinates. +pub(crate) fn scale_about(pivot: egui::Pos2, scale: f32) -> egui::emath::TSTransform { + use egui::emath::TSTransform; + TSTransform::from_translation(pivot.to_vec2()) + * TSTransform::from_scaling(scale) + * TSTransform::from_translation(-pivot.to_vec2()) +} + +pub(crate) fn lerp_color(a: Color32, b: Color32, t: f32) -> Color32 { + let t = t.clamp(0.0, 1.0); + let l = |x: u8, y: u8| (x as f32 + (y as f32 - x as f32) * t).round() as u8; + Color32::from_rgba_premultiplied( + l(a.r(), b.r()), + l(a.g(), b.g()), + l(a.b(), b.b()), + l(a.a(), b.a()), + ) +} + +#[cfg(test)] +#[path = "motion_tests.rs"] +mod tests; diff --git a/crates/app/src/ui/motion_tests.rs b/crates/app/src/ui/motion_tests.rs new file mode 100644 index 00000000..74daa8ba --- /dev/null +++ b/crates/app/src/ui/motion_tests.rs @@ -0,0 +1,78 @@ +use super::*; + +fn pass(ctx: &egui::Context, time: f64, f: impl FnMut(&egui::Context)) { + let mut f = f; + let _ = ctx.run_ui( + egui::RawInput { + time: Some(time), + ..Default::default() + }, + |ui| f(ui.ctx()), + ); +} + +#[test] +fn reduced_motion_lands_springs_and_disables_egui_animation() { + let ctx = egui::Context::default(); + let id = Id::new("test_spring"); + seed_spring(&ctx, id, 0.0); + sync(&ctx, ReduceMotion::Off); + let moving = spring(&ctx, id, 10.0, 1.0 / 60.0); + assert!(moving > 0.0 && moving < 10.0, "{moving}"); + + sync(&ctx, ReduceMotion::On); + assert!(reduced(&ctx)); + assert_eq!(spring(&ctx, id, 10.0, 1.0 / 60.0), 10.0); + for theme in [egui::Theme::Light, egui::Theme::Dark] { + assert_eq!(ctx.style_of(theme).animation_time, 0.0); + } + + sync(&ctx, ReduceMotion::Off); + assert!(!reduced(&ctx)); + for theme in [egui::Theme::Light, egui::Theme::Dark] { + assert!(ctx.style_of(theme).animation_time > 0.0); + } +} + +#[test] +fn appear_restarts_after_a_surface_was_hidden() { + let ctx = egui::Context::default(); + let id = Id::new("test_surface"); + let mut seen = Vec::new(); + for time in [0.0, 0.05, 1.0] { + pass(&ctx, time, |ctx| seen.push(appear(ctx, id))); + } + assert_eq!(seen[0], 0.0); + assert!(seen[1] > 0.0 && seen[1] < 1.0, "{seen:?}"); + assert_eq!(seen[2], 1.0); + + pass(&ctx, 2.0, |_| {}); + let mut reopened = 1.0; + pass(&ctx, 3.0, |ctx| reopened = appear(ctx, id)); + assert_eq!(reopened, 0.0); + + sync(&ctx, ReduceMotion::On); + pass(&ctx, 5.0, |_| {}); + let mut reduced_open = 0.0; + pass(&ctx, 6.0, |ctx| reduced_open = appear(ctx, id)); + assert_eq!(reduced_open, 1.0); +} + +#[test] +fn hover_jumps_when_motion_is_reduced() { + let ctx = egui::Context::default(); + sync(&ctx, ReduceMotion::On); + let mut value = 0.0; + pass(&ctx, 0.0, |ctx| { + value = hover(ctx, Id::new("test_hover"), true) + }); + assert_eq!(value, 1.0); +} + +#[test] +fn scale_about_keeps_the_pivot_fixed() { + let pivot = egui::pos2(100.0, 50.0); + let transform = scale_about(pivot, 0.5); + assert_eq!(transform * pivot, pivot); + assert_eq!(transform * egui::pos2(200.0, 50.0), egui::pos2(150.0, 50.0)); +} diff --git a/crates/app/src/ui/panel_chrome.rs b/crates/app/src/ui/panel_chrome.rs index c26d2a56..4dd98b2f 100644 --- a/crates/app/src/ui/panel_chrome.rs +++ b/crates/app/src/ui/panel_chrome.rs @@ -38,9 +38,19 @@ fn button(ui: &mut Ui, label: &str) -> (Rect, Response) { egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), label) }); let visuals = ui.style().interact(&response); - if response.hovered() || response.is_pointer_button_down_on() || response.has_focus() { + let pressed = response.is_pointer_button_down_on() || response.has_focus(); + let hover = super::motion::hover(ui.ctx(), response.id, response.hovered()); + // Presses show at once; only hover enter and exit ease. + if pressed { ui.painter() .rect_filled(rect, visuals.corner_radius, visuals.weak_bg_fill); + } else if hover > 0.0 { + let hovered = &ui.visuals().widgets.hovered; + ui.painter().rect_filled( + rect, + hovered.corner_radius, + hovered.weak_bg_fill.gamma_multiply(hover), + ); } (rect, response) } diff --git a/crates/app/src/ui/properties/presentations.rs b/crates/app/src/ui/properties/presentations.rs index 4b8b4cc0..3abe5ccf 100644 --- a/crates/app/src/ui/properties/presentations.rs +++ b/crates/app/src/ui/properties/presentations.rs @@ -723,6 +723,12 @@ const OTHERS: &[PropertyPresentation] = &[ &[LocalizedText("selection colour")], APPEARANCE_PREFERENCES_HOME, ), + preference_entry( + app_preferences::REDUCE_MOTION, + "Reduce motion", + &[LocalizedText("animations")], + APPEARANCE_PREFERENCES_HOME, + ), preference_entry( app_preferences::INCLUDE_VIEW_SNAPSHOTS, "Embed view snapshots", diff --git a/crates/app/src/ui/properties/tests.rs b/crates/app/src/ui/properties/tests.rs index 8812b16c..3b343336 100644 --- a/crates/app/src/ui/properties/tests.rs +++ b/crates/app/src/ui/properties/tests.rs @@ -319,8 +319,8 @@ fn migrated_preferences_keep_their_real_section_density() { ), ( SettingsCategory::Appearance.section_id(), - 3, - "theme, GPU, and the accent override row", + 4, + "theme, GPU, the accent override, and reduce motion rows", ), ( SettingsCategory::Processing.section_id(), diff --git a/crates/app/src/ui/ribbon.rs b/crates/app/src/ui/ribbon.rs index a40471ce..9d3d0809 100644 --- a/crates/app/src/ui/ribbon.rs +++ b/crates/app/src/ui/ribbon.rs @@ -183,11 +183,87 @@ fn titlebar_interaction(response: &egui::Response) { fn task_tab_buttons(ui: &mut Ui, selected: WorkflowTab) -> [(WorkflowTab, egui::Response); 6] { ui.spacing_mut().item_spacing.x = super::ribbon_chrome::TASK_TAB_SPACING; - WorkflowTab::ALL.map(|tab| { - let response = - ui.selectable_label(selected == tab, crate::typography::headline(tab.label())); - (tab, response) - }) + let ctx = ui.ctx().clone(); + let selected_index = tab_index(selected); + let dt = ui.input(|input| input.stable_dt); + let pill = super::motion::spring( + &ctx, + super::viewport_local_id(&ctx, "ribbon_task_tab_pill"), + selected_index as f32, + dt, + ); + // Backgrounds are painted under the labels once every tab rect is known. + let background = ui.painter().add(egui::Shape::Noop); + let visuals = ui.visuals().clone(); + // Hide the frame stroke but keep its width: egui sizes button padding + // around the stroke, so dropping it would resize a hovered tab. + let widgets = &mut ui.visuals_mut().widgets; + for state in [ + &mut widgets.inactive, + &mut widgets.hovered, + &mut widgets.active, + &mut widgets.open, + ] { + state.bg_stroke.color = egui::Color32::TRANSPARENT; + } + let tabs = WorkflowTab::ALL.map(|tab| { + let emphasis = (1.0 - (pill - tab_index(tab) as f32).abs()).clamp(0.0, 1.0); + let next_id = ui.next_auto_id(); + let hovered = ui + .ctx() + .read_response(next_id) + .is_some_and(|response| response.hovered()); + let hover = super::motion::hover(&ctx, next_id, hovered && tab != selected); + let idle = super::motion::lerp_color( + visuals.widgets.inactive.text_color(), + visuals.widgets.hovered.text_color(), + hover, + ); + let color = super::motion::lerp_color(idle, visuals.selection.stroke.color, emphasis); + let response = ui.add( + Button::new(crate::typography::headline(tab.label()).color(color)) + .selected(selected == tab) + .fill(egui::Color32::TRANSPARENT), + ); + (tab, response, hover) + }); + ui.visuals_mut().widgets = visuals.widgets.clone(); + + let mut shapes = Vec::new(); + let radius = visuals.widgets.inactive.corner_radius; + for (tab, response, hover) in &tabs { + if *tab != selected && *hover > 0.0 { + shapes.push(egui::Shape::rect_filled( + response.rect, + radius, + visuals.widgets.hovered.weak_bg_fill.gamma_multiply(*hover), + )); + } + } + let last = (tabs.len() - 1) as f32; + let lower = pill.floor().clamp(0.0, last) as usize; + let upper = pill.ceil().clamp(0.0, last) as usize; + let blend = (pill - lower as f32).clamp(0.0, 1.0); + let from = tabs[lower].1.rect; + let to = tabs[upper].1.rect; + let pill_rect = egui::Rect::from_min_max( + egui::pos2(egui::lerp(from.left()..=to.left(), blend), from.top()), + egui::pos2(egui::lerp(from.right()..=to.right(), blend), from.bottom()), + ); + shapes.push(egui::Shape::rect_filled( + pill_rect, + radius, + visuals.selection.bg_fill, + )); + ui.painter().set(background, egui::Shape::Vec(shapes)); + tabs.map(|(tab, response, _)| (tab, response)) +} + +fn tab_index(tab: WorkflowTab) -> usize { + WorkflowTab::ALL + .iter() + .position(|candidate| *candidate == tab) + .unwrap_or(0) } fn render_chrome_controls( @@ -551,6 +627,37 @@ mod tests { rects.expect("the task tab row was rendered") } + #[test] + fn hovering_a_task_tab_keeps_every_tab_in_place() { + let ctx = crate::typography::test_context(); + let expected = task_tab_rects(&ctx, WorkflowTab::Data, RibbonDensity::Full); + for (index, rect) in expected.iter().enumerate() { + let mut rects = None; + for _ in 0..2 { + let _ = ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + vec2(900.0, 120.0), + )), + events: vec![egui::Event::PointerMoved(rect.center())], + ..Default::default() + }, + |ui| { + rects = Some( + ui.horizontal(|ui| { + task_tab_buttons(ui, WorkflowTab::Data) + .map(|(_, response)| response.rect) + }) + .inner, + ); + }, + ); + } + assert_eq!(rects, Some(expected), "hovering tab {index}"); + } + } + #[test] fn task_tab_geometry_is_stable_across_selection_and_command_density() { let ctx = crate::typography::test_context(); diff --git a/crates/app/src/ui/settings_dialog/chrome.rs b/crates/app/src/ui/settings_dialog/chrome.rs index 83f50529..8a4d41d0 100644 --- a/crates/app/src/ui/settings_dialog/chrome.rs +++ b/crates/app/src/ui/settings_dialog/chrome.rs @@ -123,11 +123,12 @@ pub(crate) fn sync_chrome_theme(ctx: &egui::Context, mode: ThemeMode) { pub(super) fn rail_row(ui: &mut Ui, cat: SettingsCategory, selected: bool) -> Response { let width = ui.available_width(); let (rect, resp) = ui.allocate_exact_size(vec2(width, 30.0), Sense::click()); + let hover = crate::ui::motion::hover(ui.ctx(), resp.id, resp.hovered() && !selected); let visuals = ui.visuals(); - let color = if selected || resp.hovered() { + let color = if selected { visuals.strong_text_color() } else { - visuals.text_color() + crate::ui::motion::lerp_color(visuals.text_color(), visuals.strong_text_color(), hover) }; if selected { ui.painter().rect_filled( @@ -135,11 +136,11 @@ pub(super) fn rail_row(ui: &mut Ui, cat: SettingsCategory, selected: bool) -> Re visuals.widgets.active.corner_radius, visuals.selection.bg_fill, ); - } else if resp.hovered() { + } else if hover > 0.0 { ui.painter().rect_filled( rect, visuals.widgets.hovered.corner_radius, - visuals.widgets.hovered.bg_fill, + visuals.widgets.hovered.bg_fill.gamma_multiply(hover), ); } let cy = rect.center().y; diff --git a/crates/app/src/ui/switcher.rs b/crates/app/src/ui/switcher.rs index 15c3f749..0d8916fa 100644 --- a/crates/app/src/ui/switcher.rs +++ b/crates/app/src/ui/switcher.rs @@ -1,65 +1,10 @@ +use super::motion; use egui::{Color32, CornerRadius, Id, Pos2, Rect, Sense, Stroke, Ui, Vec2}; use plotium_core::state::PrimaryView; -const PILL_SPRING_RESPONSE: f32 = 0.34; -const PILL_SPRING_DAMPING: f32 = 0.82; const TRACK_HEIGHT: f32 = 34.0; const SEGMENT_INSET: f32 = 3.0; -#[derive(Clone, Copy)] -struct Spring { - pos: f32, - vel: f32, -} - -/// A critically-ish damped spring integrated once per frame, keyed in egui's -/// frame-local store by `id`. Re-targeting mid-flight carries the momentum, so a -/// quick re-click redirects the glide instead of snapping. -pub(crate) fn animate_spring(ctx: &egui::Context, id: Id, target: f32, dt: f32) -> f32 { - let omega = std::f32::consts::TAU / PILL_SPRING_RESPONSE.max(1e-4); - let k = omega * omega; - let c = 2.0 * PILL_SPRING_DAMPING * omega; - let mut s = ctx - .data_mut(|d| d.get_temp::(id)) - .unwrap_or(Spring { - pos: target, - vel: 0.0, - }); - let dt = dt.clamp(0.0, 1.0 / 30.0); - let accel = -k * (s.pos - target) - c * s.vel; - s.vel += accel * dt; - s.pos += s.vel * dt; - if (s.pos - target).abs() < 5e-4 && s.vel.abs() < 5e-4 { - s.pos = target; - s.vel = 0.0; - } else { - ctx.request_repaint(); - } - ctx.data_mut(|d| d.insert_temp(id, s)); - s.pos -} - -/// Seed a spring's stored position without disturbing its velocity, so the next -/// `animate_spring` glides from `pos` (the current value) rather than snapping to -/// a fresh target. Preserving velocity lets a re-seed mid-flight keep momentum. -pub(crate) fn seed_spring(ctx: &egui::Context, id: Id, pos: f32) { - let vel = ctx - .data_mut(|d| d.get_temp::(id)) - .map_or(0.0, |s| s.vel); - ctx.data_mut(|d| d.insert_temp(id, Spring { pos, vel })); -} - -fn lerp_color(a: Color32, b: Color32, t: f32) -> Color32 { - let t = t.clamp(0.0, 1.0); - let l = |x: u8, y: u8| (x as f32 + (y as f32 - x as f32) * t).round() as u8; - Color32::from_rgba_unmultiplied( - l(a.r(), b.r()), - l(a.g(), b.g()), - l(a.b(), b.b()), - l(a.a(), b.a()), - ) -} - /// A segmented control with a sliding, spring-animated selection pill. Returns /// `true` if the selection changed this frame. pub fn segmented(ui: &mut Ui, current: &mut PrimaryView) -> bool { @@ -92,9 +37,9 @@ pub fn segmented(ui: &mut Ui, current: &mut PrimaryView) -> bool { let active_index = views.iter().position(|v| v == current).unwrap_or(0); let dt = ui.input(|i| i.stable_dt); - let pill_pos = animate_spring( + let pill_pos = motion::spring( ui.ctx(), - Id::new("primary_view_pill"), + super::viewport_local_id(ui.ctx(), "primary_view_pill"), active_index as f32, dt, ); @@ -135,14 +80,23 @@ pub fn segmented(ui: &mut Ui, current: &mut PrimaryView) -> bool { let selected = *current == *view; let label_t = (1.0 - (pill_pos - index as f32).abs()).clamp(0.0, 1.0); - if !selected && label_t < 0.5 && response.hovered() { - painter.rect_filled(rect, segment_radius, Color32::from_white_alpha(10)); + let hover = motion::hover( + ui.ctx(), + response.id, + !selected && label_t < 0.5 && response.hovered(), + ); + if hover > 0.0 { + painter.rect_filled( + rect, + segment_radius, + Color32::from_white_alpha(10).gamma_multiply(hover), + ); } let galley = painter.layout_no_wrap( view.label().to_owned(), crate::typography::headline_font(), - lerp_color(text_muted, text_strong, label_t), + motion::lerp_color(text_muted, text_strong, label_t), ); painter.galley( Pos2::new( diff --git a/crates/core/src/properties/app_preferences.rs b/crates/core/src/properties/app_preferences.rs index be389ab9..20c6e1f7 100644 --- a/crates/core/src/properties/app_preferences.rs +++ b/crates/core/src/properties/app_preferences.rs @@ -8,7 +8,9 @@ use super::{ PropertyTransaction, PropertyValue, ResolvedProperty, ResolvedSchema, ScopeKind, Tier, ValueCopies, ValueSchema, definition, }; -use crate::settings::{GraphicsPowerPreference, MAX_PROJECT_BACKUP_GENERATIONS, ThemeMode}; +use crate::settings::{ + GraphicsPowerPreference, MAX_PROJECT_BACKUP_GENERATIONS, ReduceMotion, ThemeMode, +}; use crate::state::PlotiumApp; use crate::update::{UpdateChannel, UpdateChannelSetting}; use plotium_figure::Color; @@ -25,6 +27,7 @@ pub const PROJECT_BACKUP_GENERATIONS: PropertyId = pub const THEME: PropertyId = PropertyId("settings.appearance.theme"); pub const GRAPHICS_POWER: PropertyId = PropertyId("settings.appearance.graphics_power"); pub const ACCENT_COLOR: PropertyId = PropertyId("settings.appearance.accent.color"); +pub const REDUCE_MOTION: PropertyId = PropertyId("settings.appearance.reduce_motion"); pub const INCLUDE_VIEW_SNAPSHOTS: PropertyId = PropertyId("settings.export.include_view_snapshots"); pub const TRIM_TO_VISIBLE_CONTENT: PropertyId = PropertyId("settings.export.trim_to_visible_content"); @@ -37,6 +40,9 @@ pub const THEME_LIGHT: &str = "light"; pub const THEME_DARK: &str = "dark"; pub const GRAPHICS_LOW_POWER: &str = "low_power"; pub const GRAPHICS_HIGH_PERFORMANCE: &str = "high_performance"; +pub const REDUCE_MOTION_SYSTEM: &str = "system"; +pub const REDUCE_MOTION_ON: &str = "on"; +pub const REDUCE_MOTION_OFF: &str = "off"; pub const UPDATE_AUTO: &str = "auto"; pub const UPDATE_STABLE: &str = "stable"; pub const UPDATE_BETA: &str = "beta"; @@ -56,6 +62,18 @@ const GRAPHICS_VARIANTS: &[EnumVariant] = &[ EnumVariant::new(GRAPHICS_LOW_POWER, "Power saving"), EnumVariant::new(GRAPHICS_HIGH_PERFORMANCE, "High performance"), ]; +const REDUCE_MOTION_VARIANTS: &[EnumVariant] = &[ + EnumVariant::new(REDUCE_MOTION_SYSTEM, "Follow system"), + EnumVariant::new(REDUCE_MOTION_ON, "On"), + EnumVariant::new(REDUCE_MOTION_OFF, "Off"), +]; +/// Linux exposes no reliable reduced-motion setting, so the default plays +/// animations there. +const REDUCE_MOTION_VARIANTS_UNREADABLE: &[EnumVariant] = &[ + EnumVariant::new(REDUCE_MOTION_SYSTEM, "Default (off)"), + EnumVariant::new(REDUCE_MOTION_ON, "On"), + EnumVariant::new(REDUCE_MOTION_OFF, "Off"), +]; const UPDATE_VARIANTS: &[EnumVariant] = &[ EnumVariant::new(UPDATE_AUTO, "Follow build"), EnumVariant::new(UPDATE_STABLE, "Stable"), @@ -170,6 +188,15 @@ pub(crate) const DEFINITIONS: &[PropertyDefinition] = &[ "Canvas accent", &["selection colour", "guide color", "accent color"], ), + app_definition( + REDUCE_MOTION, + ValueSchema::Enum { + variants: REDUCE_MOTION_VARIANTS, + }, + DefaultPolicy::Fixed(PropertyValue::Enum(REDUCE_MOTION_SYSTEM)), + "Reduce motion", + &["animations", "interface motion", "accessibility motion"], + ), app_definition( INCLUDE_VIEW_SNAPSHOTS, ValueSchema::Bool, @@ -287,6 +314,16 @@ fn fixed_default(definition: &'static PropertyDefinition) -> Option ResolvedSchema { + if definition.id == REDUCE_MOTION { + let variants = if system_reduce_motion_is_readable() { + REDUCE_MOTION_VARIANTS + } else { + REDUCE_MOTION_VARIANTS_UNREADABLE + }; + return ResolvedSchema::Enum { + variants: variants.iter().collect(), + }; + } if definition.id == UPDATE_CHANNEL { let variants = match UpdateChannel::built_in() { UpdateChannel::Stable => UPDATE_VARIANTS_STABLE, @@ -338,6 +375,7 @@ fn value_of(app: &PlotiumApp, id: PropertyId) -> Result PropertyValue::Enum(reduce_motion_key(settings.appearance.reduce_motion)), INCLUDE_VIEW_SNAPSHOTS => PropertyValue::Bool(settings.export.include_view_snapshots), TRIM_TO_VISIBLE_CONTENT => PropertyValue::Bool(settings.export.trim_to_visible_content), SCALE_CONTENT => PropertyValue::Bool(settings.canvas_size.scale_content), @@ -412,6 +450,10 @@ fn write_value( (ACCENT_COLOR, PropertyValue::Color(value)) => { settings.appearance.canvas_accent = Some([value.r, value.g, value.b]) } + (REDUCE_MOTION, PropertyValue::Enum(value)) => { + settings.appearance.reduce_motion = + reduce_motion(value).expect("validated reduce motion") + } (INCLUDE_VIEW_SNAPSHOTS, PropertyValue::Bool(value)) => { settings.export.include_view_snapshots = value } @@ -465,6 +507,28 @@ fn graphics(value: &str) -> Option { } } +/// Whether the desktop can read a platform reduced-motion setting. +pub const fn system_reduce_motion_is_readable() -> bool { + cfg!(any(target_os = "macos", windows)) +} + +fn reduce_motion_key(value: ReduceMotion) -> &'static str { + match value { + ReduceMotion::System => REDUCE_MOTION_SYSTEM, + ReduceMotion::On => REDUCE_MOTION_ON, + ReduceMotion::Off => REDUCE_MOTION_OFF, + } +} + +fn reduce_motion(value: &str) -> Option { + match value { + REDUCE_MOTION_SYSTEM => Some(ReduceMotion::System), + REDUCE_MOTION_ON => Some(ReduceMotion::On), + REDUCE_MOTION_OFF => Some(ReduceMotion::Off), + _ => None, + } +} + fn update_key(value: UpdateChannelSetting) -> &'static str { match value { UpdateChannelSetting::Auto => UPDATE_AUTO, diff --git a/crates/core/src/properties/app_preferences_tests.rs b/crates/core/src/properties/app_preferences_tests.rs index 7fa312b6..3aa856da 100644 --- a/crates/core/src/properties/app_preferences_tests.rs +++ b/crates/core/src/properties/app_preferences_tests.rs @@ -126,7 +126,7 @@ fn backup_bound_rejects_the_value_and_names_the_actual_limit() { } #[test] -fn all_thirteen_app_preferences_reset_through_their_catalog_definitions() { +fn all_fourteen_app_preferences_reset_through_their_catalog_definitions() { let mut settings = Settings::default(); settings.general.snap_enabled = false; settings.general.equal_scale_homonuclear_2d_imports = false; @@ -135,6 +135,7 @@ fn all_thirteen_app_preferences_reset_through_their_catalog_definitions() { settings.appearance.theme = ThemeMode::Dark; settings.appearance.graphics_power = GraphicsPowerPreference::HighPerformance; settings.appearance.canvas_accent = Some([12, 34, 56]); + settings.appearance.reduce_motion = ReduceMotion::On; settings.export.include_view_snapshots = true; settings.export.trim_to_visible_content = true; settings.canvas_size.scale_content = true; @@ -150,6 +151,7 @@ fn all_thirteen_app_preferences_reset_through_their_catalog_definitions() { THEME, GRAPHICS_POWER, ACCENT_COLOR, + REDUCE_MOTION, INCLUDE_VIEW_SNAPSHOTS, TRIM_TO_VISIBLE_CONTENT, SCALE_CONTENT, @@ -175,6 +177,10 @@ fn all_thirteen_app_preferences_reset_through_their_catalog_definitions() { defaults.appearance.graphics_power ); assert_eq!(app.settings.appearance.canvas_accent, None); + assert_eq!( + app.settings.appearance.reduce_motion, + defaults.appearance.reduce_motion + ); assert_eq!(app.settings.export, defaults.export); assert_eq!( app.settings.canvas_size.scale_content, @@ -210,3 +216,35 @@ fn snap_catalog_and_legacy_setter_share_one_authoritative_value_and_clear_guides AggregateValue::Uniform(PropertyValue::Bool(true)) ); } + +#[test] +fn reduce_motion_preference_round_trips_and_labels_the_platform_default() { + let mut app = PlotiumApp::new_with_settings(Settings::default()); + commit( + &mut app, + REDUCE_MOTION, + PropertyValue::Enum(REDUCE_MOTION_ON), + ); + assert_eq!(app.settings.appearance.reduce_motion, ReduceMotion::On); + + let resolved = app + .resolve_property(&PropertyAddress::new(app.app_target(), REDUCE_MOTION)) + .expect("reduce motion reads"); + assert_eq!( + resolved.value, + AggregateValue::Uniform(PropertyValue::Enum(REDUCE_MOTION_ON)) + ); + let ResolvedSchema::Enum { variants } = resolved.schema else { + panic!("reduce motion is an enum"); + }; + let default_label = variants + .iter() + .find(|variant| variant.id == REDUCE_MOTION_SYSTEM) + .map(|variant| variant.canonical_label); + let expected = if system_reduce_motion_is_readable() { + "Follow system" + } else { + "Default (off)" + }; + assert_eq!(default_label, Some(expected)); +} diff --git a/crates/core/src/settings/model.rs b/crates/core/src/settings/model.rs index ea0f3e35..941d108f 100644 --- a/crates/core/src/settings/model.rs +++ b/crates/core/src/settings/model.rs @@ -97,6 +97,20 @@ pub struct AppearanceSettings { /// Optional editor-chrome accent. Figure colours and exports are unaffected. #[serde(default)] pub canvas_accent: Option<[u8; 3]>, + #[serde(default)] + pub reduce_motion: ReduceMotion, +} + +/// Whether interface animations are replaced by immediate changes. `System` +/// follows the platform accessibility setting where one can be read. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "snake_case")] +pub enum ReduceMotion { + On, + Off, + #[serde(other)] + #[default] + System, } /// Graphics policy applied at the next application start. Platform-specific diff --git a/docs/src/content/docs/reference/preferences.md b/docs/src/content/docs/reference/preferences.md index d857dec6..30133d92 100644 --- a/docs/src/content/docs/reference/preferences.md +++ b/docs/src/content/docs/reference/preferences.md @@ -50,6 +50,10 @@ saved preferences except your recent-files list. AI connection preferences are d chrome theme. Snap guides keep a contrasting color of their own so they stay distinct, and figure content and exported colors are never affected. +- **Reduce motion** — replaces interface animations, such as sliding tab + highlights, dialog fades, and zoom-to-fit glides, with immediate changes. + **Follow system** uses the macOS or Windows accessibility setting. On Linux, + where no system setting can be read, the default keeps animations on. - **UI scale** — the size of all interface text and controls, per display. Automatic picks a physically legible size from the display's reported pixel density; the manual choices and the `Ctrl` + `+` / `Ctrl` + `-` shortcuts diff --git a/docs/src/content/docs/zh-cn/reference/preferences.md b/docs/src/content/docs/zh-cn/reference/preferences.md index b69eca3e..7c982a9e 100644 --- a/docs/src/content/docs/zh-cn/reference/preferences.md +++ b/docs/src/content/docs/zh-cn/reference/preferences.md @@ -39,6 +39,9 @@ AI 连接启用状态和权限会持久保存,详见下文。 预览的颜色。可自选颜色,也可用 **Follow theme** 跟随系统强调色(macOS 和 Windows)或应用主题。吸附参考线始终使用另一种对比色以便区分;图形 内容和导出配色不受影响。 +- **Reduce motion**——让标签高亮滑动、对话框淡入、适应视图的平移缩放等界面 + 动画改为直接切换。**Follow system** 跟随 macOS 或 Windows 的辅助功能设置。 + Linux 上读取不到系统设置,默认保留动画。 - **UI scale**——界面文字和控件的大小,按显示器分别设置。自动模式根据 显示器报告的像素密度选择物理上可读的尺寸;手动选项和 `Ctrl` + `+` / `Ctrl` + `-` 快捷键只覆盖当前显示器。