Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,7 @@ nonminimal_bool = "allow"

[patch.crates-io]
async-process = { git = "https://github.com/zed-industries/async-process.git", rev = "0b6d6713570af61806e1e5cb40e0f757cb93fd9d" }
async-task = { git = "https://github.com/zed-industries/async-task.git", rev = "015845a19fc31752c02367567d3b8900a406f9da" }
# Keep the waker identity fix until it is released: https://github.com/smol-rs/async-task/pull/108
async-task = { git = "https://github.com/smol-rs/async-task", rev = "41fd3359c75e221bd8b187a8ee361aa309c1714c" }
calloop = { git = "https://github.com/zed-industries/calloop", rev = "3759371fee14c40066d64777e2a36b6ffcc22590" }
khronos-egl = { git = "https://github.com/zed-industries/khronos-egl", rev = "42214b36347b108fd9630ca6254b96dde59e04fe" }
222 changes: 222 additions & 0 deletions crates/gpui/examples/svg_animation.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
#![cfg_attr(target_family = "wasm", no_main)]

//! Compares SVGs animated with [`Svg::with_timed_transformation`], which
//! moves them in the already painted scene, against the same SVGs animated by
//! re-rendering with `with_animation`. It shows spinners and pulsing rings.
//!
//! The header counts how many times the view has rendered. With the retained
//! scene the count stays put while the SVGs keep animating; when re-rendering
//! it climbs once per frame. Pass `--rerender` to start in that mode, and
//! `--max-fps <n>` to cap how often the retained scene is presented.

#[path = "example_support/fonts.rs"]
mod example_support;

use std::{cell::Cell, time::Duration};

use gpui::{
Animation, AnimationExt as _, App, Bounds, Context, Easing, TimedTransformation,
Transformation, Window, WindowBounds, WindowOptions, div, ease_out_quint, percentage,
prelude::*, px, rgb, size, svg,
};
use gpui_platform::application;

const ARROW_CIRCLE_SVG: &str = concat!(
env!("CARGO_MANIFEST_DIR"),
"/examples/image/arrow_circle.svg"
);

const RING_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><circle cx="8" cy="8" r="5" fill="none" stroke="black" stroke-width="1.5"/></svg>"#;

const SPINNER_COUNT: usize = 100;
const PULSE_COUNT: usize = 100;
const SPIN_PERIOD: Duration = Duration::from_secs(2);
const PULSE_PERIOD: Duration = Duration::from_millis(1750);

#[derive(Clone, Copy, PartialEq)]
enum Mode {
RetainedScene,
Rerender,
}

struct SvgAnimationExample {
mode: Mode,
max_fps: Option<f32>,
render_count: Cell<u64>,
}

impl SvgAnimationExample {
fn timed(&self, transformation: TimedTransformation) -> TimedTransformation {
match self.max_fps {
Some(max_fps) => transformation.with_max_fps(max_fps),
None => transformation,
}
}

fn pulse(&self, index: usize) -> impl IntoElement {
let ring = svg().size_4().data(RING_SVG).text_color(rgb(0x16a34a));
let ring = match self.mode {
Mode::RetainedScene => ring
.with_timed_transformation(
self.timed(
TimedTransformation::new(PULSE_PERIOD)
.from(Transformation::alpha(0.6))
.to(Transformation::scale(size(1.5, 1.5)).with_alpha(0.))
.with_scale_easing(Easing::EaseOutQuint),
),
)
.into_any_element(),
Mode::Rerender => ring
.with_animation(
("pulse", index),
Animation::new(PULSE_PERIOD).repeat_synced(),
|svg, delta| {
let scale = 1. + 0.5 * ease_out_quint()(delta);
svg.with_transformation(
Transformation::scale(size(scale, scale))
.with_alpha(0.6 * (1. - delta)),
)
},
)
.into_any_element(),
};
div()
.size_6()
.flex()
.items_center()
.justify_center()
.child(div().absolute().size_1p5().rounded_full().bg(rgb(0x16a34a)))
.child(ring)
}

fn spinner(&self, index: usize) -> impl IntoElement {
let spinner = svg()
.size_6()
.external_path(ARROW_CIRCLE_SVG)
.text_color(rgb(0x3b82f6));
match self.mode {
Mode::RetainedScene => spinner
.with_timed_transformation(self.timed(TimedTransformation::rotation(
SPIN_PERIOD,
Transformation::default(),
)))
.into_any_element(),
Mode::Rerender => spinner
.with_animation(
("spinner", index),
Animation::new(SPIN_PERIOD).repeat_synced(),
|svg, delta| svg.with_transformation(Transformation::rotate(percentage(delta))),
)
.into_any_element(),
}
}
}

impl Render for SvgAnimationExample {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.render_count.set(self.render_count.get() + 1);
let mode = self.mode;
let mode_label = match mode {
Mode::RetainedScene => "retained scene (with_timed_transformation)",
Mode::Rerender => "re-render (with_animation)",
};

div()
.flex()
.flex_col()
.size_full()
.bg(gpui::white())
.text_color(gpui::black())
.p_4()
.gap_3()
.child(
div()
.flex()
.flex_row()
.items_center()
.gap_4()
.child(
div()
.id("toggle-mode")
.px_3()
.py_1()
.rounded_md()
.bg(rgb(0xe5e7eb))
.cursor_pointer()
.child(format!("Mode: {mode_label}"))
.on_click(cx.listener(|this, _, _, cx| {
this.mode = match this.mode {
Mode::RetainedScene => Mode::Rerender,
Mode::Rerender => Mode::RetainedScene,
};
cx.notify();
})),
)
.child(format!("Renders: {}", self.render_count.get())),
)
.child(
div()
.flex()
.flex_row()
.flex_wrap()
.gap_2()
.children((0..SPINNER_COUNT).map(|index| self.spinner(index))),
)
.child(
div()
.flex()
.flex_row()
.flex_wrap()
.gap_2()
.children((0..PULSE_COUNT).map(|index| self.pulse(index))),
)
}
}

fn run_example() {
application().run(|cx: &mut App| {
if !example_support::load_fonts(cx) {
return;
}
let options = WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
None,
size(px(720.), px(480.)),
cx,
))),
..Default::default()
};
cx.open_window(options, |_, cx| {
cx.activate(false);
let mode = if std::env::args().any(|arg| arg == "--rerender") {
Mode::Rerender
} else {
Mode::RetainedScene
};
let mut arguments = std::env::args();
let max_fps = arguments
.by_ref()
.find(|argument| argument == "--max-fps")
.and_then(|_| arguments.next())
.and_then(|max_fps| max_fps.parse().ok());
cx.new(|_| SvgAnimationExample {
mode,
max_fps,
render_count: Cell::new(0),
})
})
.expect("failed to open window");
});
}

#[cfg(not(target_family = "wasm"))]
fn main() {
run_example();
}

#[cfg(target_family = "wasm")]
#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn start() {
gpui_platform::web_init();
run_example();
}
2 changes: 1 addition & 1 deletion crates/gpui/examples/system_notifications.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ impl Render for SystemNotificationExample {
)))
.child(
button("dismiss", "Dismiss").on_click(cx.listener(|this, _, _, cx| {
cx.dismiss_system_notification(NOTIFICATION_TAG);
cx.dismiss_system_notification(NOTIFICATION_TAG).detach();
this.status = "Dismissed the notification".into();
cx.notify();
})),
Expand Down
7 changes: 5 additions & 2 deletions crates/gpui/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2097,8 +2097,11 @@ impl App {
///
/// Best-effort: some platforms cannot retract a notification once shown,
/// in which case it ages out of the notification center on its own.
pub fn dismiss_system_notification(&self, tag: &str) {
self.platform.dismiss_system_notification(tag);
/// The task completes after the platform calls return, not after any
/// asynchronous work inside the operating system. Dropping it does not
/// cancel dismissal.
pub fn dismiss_system_notification(&self, tag: &str) -> Task<()> {
self.platform.dismiss_system_notification(tag)
}

/// Registers the handler invoked when the user activates a system
Expand Down
11 changes: 10 additions & 1 deletion crates/gpui/src/app/headless_app_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::{
Context, Entity, EntityId, ForegroundExecutor, Global, Pixels, PlatformHeadlessRenderer,
PlatformTextSystem, Render, Reservation, Size, Task, TestDispatcher, TestPlatform, TextSystem,
Window, WindowBounds, WindowHandle, WindowOptions,
app::{GpuiBorrow, GpuiMode},
app::{GpuiBorrow, GpuiMode, test_context::test_window},
};
use anyhow::Result;
use image::RgbaImage;
Expand Down Expand Up @@ -130,6 +130,15 @@ impl HeadlessAppContext {
self.dispatcher.run_until_parked();
}

/// Simulates the window moving to a display with a different scale factor.
pub fn simulate_window_scale_factor_change(
&mut self,
window: AnyWindowHandle,
scale_factor: f32,
) {
test_window(&self.app, window).simulate_scale_factor_change(scale_factor);
}

/// Advances the simulated clock.
pub fn advance_clock(&self, duration: Duration) {
self.dispatcher.advance_clock(duration);
Expand Down
29 changes: 16 additions & 13 deletions crates/gpui/src/app/test_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,19 @@ use std::{
cell::RefCell, future::Future, ops::Deref, path::PathBuf, rc::Rc, sync::Arc, time::Duration,
};

pub(crate) fn test_window(app: &AppCell, window: AnyWindowHandle) -> TestWindow {
app.borrow_mut()
.windows
.get_mut(window.id)
.expect("window not found")
.as_deref_mut()
.expect("window is being updated")
.platform_window
.as_test()
.expect("window is not a TestWindow")
.clone()
}

/// A TestAppContext is provided to tests created with `#[gpui::test]`, it provides
/// an implementation of `Context` with additional methods that are useful in tests.
#[derive(Clone)]
Expand Down Expand Up @@ -670,17 +683,7 @@ impl TestAppContext {

/// Returns the `TestWindow` backing the given handle.
pub(crate) fn test_window(&self, window: AnyWindowHandle) -> TestWindow {
self.app
.borrow_mut()
.windows
.get_mut(window.id)
.unwrap()
.as_deref_mut()
.unwrap()
.platform_window
.as_test()
.unwrap()
.clone()
test_window(&self.app, window)
}

/// Returns a stream of notifications whenever the Entity is updated.
Expand Down Expand Up @@ -1424,7 +1427,7 @@ mod tests {
}]
);

cx.update(|cx| cx.dismiss_system_notification("thread-1"));
cx.update(|cx| cx.dismiss_system_notification("thread-1").detach());
assert!(cx.delivered_system_notifications().is_empty());
assert_eq!(cx.dismissed_system_notifications(), ["thread-1"]);
}
Expand Down Expand Up @@ -1499,7 +1502,7 @@ mod tests {
actions: Vec::new(),
});
cx.on_system_notification_response(|response, cx| {
cx.dismiss_system_notification(&response.tag);
cx.dismiss_system_notification(&response.tag).detach();
});
});

Expand Down
9 changes: 9 additions & 0 deletions crates/gpui/src/elements/animation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,15 @@ mod easing {
move |delta| 1.0 - (1.0 - delta).powi(5)
}

/// A heartbeat: a strong beat, a weaker one, then a rest. Starts and ends at 0 and peaks at 1.
pub fn heartbeat(delta: f32) -> f32 {
let beat = |center: f32, width: f32, height: f32| {
let x = (delta - center) / width;
height * (-x * x).exp()
};
beat(0.2, 0.06, 1.0) + beat(0.4, 0.05, 0.58)
}

/// Apply the given easing function, first in the forward direction and then in the reverse direction
pub fn bounce(easing: impl Fn(f32) -> f32) -> impl Fn(f32) -> f32 {
move |delta| {
Expand Down
Loading
Loading