Skip to main content

ferrochart_winit/
lib.rs

1//! Desktop host for FerroChart on winit + wgpu.
2//!
3//! - [`show`] opens a window with the defaults and shows a chart until it is
4//!   closed.
5//! - [`run`] opens a window with a wgpu surface and drives the chart: winit
6//!   events become [`InputEvent`]s, frames are built and rendered only when
7//!   [`Chart::needs_redraw`] says so (which includes kinetic scrolling), chart
8//!   events are handed to your [`ChartApp`], and [`ChartApp::update`] can ask to
9//!   be woken at a given time (e.g. for a real-time feed).
10//! - [`InputConverter`] is the event conversion on its own, for hosts that own
11//!   the event loop themselves (an egui app, a custom window).
12//!
13//! All times passed to the chart (`InputEvent::time_ms`, `build_frame`) come
14//! from one monotonic clock: milliseconds since [`run`] started.
15//!
16//! # Examples
17//!
18//! ```no_run
19//! use ferrochart_core::{Chart, ChartOptions};
20//! use ferrochart_winit::{ChartApp, WindowOptions, run};
21//!
22//! struct App;
23//! impl ChartApp for App {}
24//!
25//! run(WindowOptions::default(), Chart::new(ChartOptions::default()), App)?;
26//! # Ok::<(), ferrochart_winit::HostError>(())
27//! ```
28
29pub use {wgpu, winit};
30
31use std::sync::Arc;
32use std::time::{Duration, Instant};
33
34use ferrochart_core::Chart;
35use ferrochart_core::chart::ChartEvent;
36use ferrochart_core::frame::Invalidation;
37use ferrochart_core::geom::{Css, PointCss, SizeCss, SizePx};
38use ferrochart_core::interaction::{
39    Button, CursorIcon, GesturePhase, InputEvent, Key, Modifiers, WheelDelta,
40};
41use ferrochart_core::render::{RenderError, Renderer};
42use ferrochart_render_wgpu::{GpuContext, WgpuRenderer};
43use winit::application::ApplicationHandler;
44use winit::dpi::{LogicalSize, PhysicalSize};
45use winit::event::{ElementState, MouseButton, MouseScrollDelta, TouchPhase, WindowEvent};
46use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
47use winit::keyboard::{Key as WKey, ModifiersState, NamedKey};
48use winit::window::{Window, WindowId};
49
50/// Two presses closer than this (and [`DOUBLE_CLICK_DISTANCE`]) are a double click.
51const DOUBLE_CLICK_MS: f64 = 400.0;
52/// Maximum distance between the presses of a double click, CSS pixels.
53const DOUBLE_CLICK_DISTANCE: f32 = 4.0;
54/// Consecutive render failures after which the host stops retrying until the
55/// next input or resize (e.g. while the window is occluded).
56const MAX_RETRIES: u32 = 3;
57
58/// Errors from [`run`].
59#[derive(Debug)]
60#[non_exhaustive]
61pub enum HostError {
62    /// The winit event loop could not be created or failed.
63    EventLoop(winit::error::EventLoopError),
64    /// The window could not be created.
65    Window(winit::error::OsError),
66    /// The wgpu surface could not be created.
67    Surface(wgpu::CreateSurfaceError),
68    /// No GPU adapter/device, or the surface is unsupported.
69    Render(RenderError),
70}
71
72impl std::fmt::Display for HostError {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        match self {
75            Self::EventLoop(e) => write!(f, "event loop: {e}"),
76            Self::Window(e) => write!(f, "window: {e}"),
77            Self::Surface(e) => write!(f, "surface: {e}"),
78            Self::Render(e) => write!(f, "renderer: {e}"),
79        }
80    }
81}
82
83impl std::error::Error for HostError {}
84
85/// Window settings for [`run`].
86#[derive(Clone, Debug)]
87pub struct WindowOptions {
88    /// Window title.
89    pub title: String,
90    /// Initial inner size.
91    pub size: SizeCss,
92}
93
94impl Default for WindowOptions {
95    fn default() -> Self {
96        Self {
97            title: "FerroChart".to_owned(),
98            size: SizeCss {
99                w: 1200.0,
100                h: 720.0,
101            },
102        }
103    }
104}
105
106/// Application callbacks of [`run`]. All methods have empty defaults.
107pub trait ChartApp {
108    /// Called once per event-loop iteration before the loop sleeps. Change
109    /// the chart here (append data, `update_last`, …). Return the time
110    /// (same clock as `now_ms`) at which you want to be called again, or
111    /// `None` to sleep until the next input.
112    fn update(&mut self, chart: &mut Chart, now_ms: f64) -> Option<f64> {
113        let _ = (chart, now_ms);
114        None
115    }
116
117    /// A chart event (crosshair moved, visible range changed, need more
118    /// history, …), delivered after the frame that produced it.
119    fn on_event(&mut self, chart: &mut Chart, event: ChartEvent) {
120        let _ = (chart, event);
121    }
122
123    /// Called once the GPU renderer exists (and again if it is recreated):
124    /// register native custom series here with
125    /// [`WgpuRenderer::register_series`]. The chart learns their kinds
126    /// before the next frame.
127    fn on_renderer(&mut self, renderer: &mut WgpuRenderer) {
128        let _ = renderer;
129    }
130
131    /// Called after each rendered frame with the CPU time spent building and
132    /// submitting it, for statistics.
133    fn on_frame(&mut self, window: &Window, cpu_ms: f64) {
134        let _ = (window, cpu_ms);
135    }
136}
137
138/// Converts winit window events into [`InputEvent`]s. Keeps the state winit
139/// does not put on each event: modifiers, the pointer position, and the last
140/// press (to synthesize [`InputEvent::DoubleClick`]).
141#[derive(Clone, Copy, Debug, Default)]
142pub struct InputConverter {
143    mods: Modifiers,
144    pos: Option<PointCss>,
145    last_press: Option<(Button, PointCss, f64)>,
146}
147
148fn button(b: MouseButton) -> Option<Button> {
149    match b {
150        MouseButton::Left => Some(Button::Left),
151        MouseButton::Middle => Some(Button::Middle),
152        MouseButton::Right => Some(Button::Right),
153        _ => None,
154    }
155}
156
157fn phase(p: TouchPhase) -> GesturePhase {
158    match p {
159        TouchPhase::Started => GesturePhase::Start,
160        TouchPhase::Moved => GesturePhase::Update,
161        TouchPhase::Ended | TouchPhase::Cancelled => GesturePhase::End,
162    }
163}
164
165fn key(k: &WKey) -> Option<Key> {
166    match k {
167        WKey::Named(NamedKey::ArrowLeft) => Some(Key::ArrowLeft),
168        WKey::Named(NamedKey::ArrowRight) => Some(Key::ArrowRight),
169        WKey::Named(NamedKey::ArrowUp) => Some(Key::ArrowUp),
170        WKey::Named(NamedKey::ArrowDown) => Some(Key::ArrowDown),
171        WKey::Named(NamedKey::Home) => Some(Key::Home),
172        WKey::Named(NamedKey::End) => Some(Key::End),
173        WKey::Named(NamedKey::Escape) => Some(Key::Escape),
174        WKey::Named(NamedKey::Delete) => Some(Key::Delete),
175        WKey::Named(NamedKey::Enter) => Some(Key::Enter),
176        WKey::Character(s) => s.chars().next().map(Key::Char),
177        _ => None,
178    }
179}
180
181/// winit's positive y scrolls up (content moves down); the chart, like the
182/// DOM, uses positive y for scrolling down. Pixel deltas are physical.
183fn wheel_delta(delta: MouseScrollDelta, scale_factor: f64) -> WheelDelta {
184    match delta {
185        MouseScrollDelta::LineDelta(x, y) => WheelDelta::Lines { x: -x, y: -y },
186        MouseScrollDelta::PixelDelta(p) => WheelDelta::Pixels {
187            x: Css(-(p.x / scale_factor) as f32),
188            y: Css(-(p.y / scale_factor) as f32),
189        },
190    }
191}
192
193/// The winit cursor for a chart cursor.
194pub fn cursor_icon(c: CursorIcon) -> winit::window::CursorIcon {
195    use winit::window::CursorIcon as W;
196    match c {
197        CursorIcon::Crosshair => W::Crosshair,
198        CursorIcon::Grab => W::Grab,
199        CursorIcon::Grabbing => W::Grabbing,
200        CursorIcon::EwResize => W::EwResize,
201        CursorIcon::NsResize => W::NsResize,
202        CursorIcon::Pointer => W::Pointer,
203        CursorIcon::Move => W::Move,
204        _ => W::Default,
205    }
206}
207
208impl InputConverter {
209    /// A converter with no modifiers held and the pointer outside.
210    pub fn new() -> Self {
211        Self::default()
212    }
213
214    fn moved(&mut self, pos: PointCss, time_ms: f64, mut emit: impl FnMut(InputEvent)) {
215        self.pos = Some(pos);
216        emit(InputEvent::PointerMove {
217            id: 0,
218            pos,
219            mods: self.mods,
220            time_ms,
221        });
222    }
223
224    fn mouse(&mut self, b: Button, pressed: bool, time_ms: f64, mut emit: impl FnMut(InputEvent)) {
225        let Some(pos) = self.pos else {
226            return;
227        };
228        let mods = self.mods;
229        if !pressed {
230            emit(InputEvent::PointerUp {
231                id: 0,
232                pos,
233                button: b,
234                mods,
235                time_ms,
236            });
237            return;
238        }
239        emit(InputEvent::PointerDown {
240            id: 0,
241            pos,
242            button: b,
243            mods,
244            time_ms,
245        });
246        let double = self.last_press.is_some_and(|(lb, lp, lt)| {
247            lb == b
248                && time_ms - lt <= DOUBLE_CLICK_MS
249                && (pos.x - lp.x).abs() <= DOUBLE_CLICK_DISTANCE
250                && (pos.y - lp.y).abs() <= DOUBLE_CLICK_DISTANCE
251        });
252        if double {
253            self.last_press = None;
254            emit(InputEvent::DoubleClick { pos, button: b });
255        } else {
256            self.last_press = Some((b, pos, time_ms));
257        }
258    }
259
260    /// Converts `event` and passes the resulting chart events (zero, one or
261    /// two) to `emit`. `scale_factor` is the window's dpr; `time_ms` is the
262    /// host clock shared with `build_frame`.
263    pub fn convert(
264        &mut self,
265        event: &WindowEvent,
266        scale_factor: f64,
267        time_ms: f64,
268        mut emit: impl FnMut(InputEvent),
269    ) {
270        let mods = self.mods;
271        let css = |v: f64| (v / scale_factor) as f32;
272        match event {
273            WindowEvent::ModifiersChanged(m) => {
274                let s: ModifiersState = m.state();
275                self.mods = Modifiers {
276                    shift: s.shift_key(),
277                    ctrl: s.control_key(),
278                    alt: s.alt_key(),
279                    meta: s.super_key(),
280                };
281            }
282            WindowEvent::CursorMoved { position, .. } => {
283                self.moved(
284                    PointCss {
285                        x: css(position.x),
286                        y: css(position.y),
287                    },
288                    time_ms,
289                    emit,
290                );
291            }
292            WindowEvent::CursorLeft { .. } => {
293                self.pos = None;
294                emit(InputEvent::PointerLeave);
295            }
296            WindowEvent::MouseInput {
297                state, button: b, ..
298            } => {
299                if let Some(b) = button(*b) {
300                    self.mouse(b, *state == ElementState::Pressed, time_ms, emit);
301                }
302            }
303            WindowEvent::MouseWheel { delta, .. } => {
304                let Some(pos) = self.pos else {
305                    return;
306                };
307                emit(InputEvent::Wheel {
308                    pos,
309                    delta: wheel_delta(*delta, scale_factor),
310                    mods,
311                });
312            }
313            WindowEvent::PinchGesture {
314                delta, phase: p, ..
315            } => {
316                let Some(center) = self.pos else {
317                    return;
318                };
319                let scale = (1.0 + delta) as f32;
320                emit(InputEvent::Pinch {
321                    phase: phase(*p),
322                    center,
323                    scale: if scale.is_finite() && scale > 0.0 {
324                        scale
325                    } else {
326                        1.0
327                    },
328                });
329            }
330            WindowEvent::KeyboardInput { event, .. } => {
331                if let Some(k) = key(&event.logical_key) {
332                    emit(InputEvent::Key {
333                        key: k,
334                        pressed: event.state == ElementState::Pressed,
335                        mods,
336                    });
337                }
338            }
339            WindowEvent::Focused(false) => {
340                self.mods = Modifiers::default();
341            }
342            _ => {}
343        }
344    }
345}
346
347/// Opens a window with the default options and shows `chart` until the
348/// window is closed: [`run`] with [`WindowOptions::default`] and no
349/// callbacks.
350///
351/// # Errors
352///
353/// As [`run`].
354///
355/// # Examples
356///
357/// ```no_run
358/// use ferrochart_core::testing::random_walk;
359/// use ferrochart_core::{Chart, ChartOptions};
360///
361/// let mut chart = Chart::new(ChartOptions::default());
362/// let candles = chart.add_candlestick()?;
363/// chart.set_data(candles, random_walk(1, 500, 0, 60_000)?)?;
364/// ferrochart_winit::show(chart)?;
365/// # Ok::<(), Box<dyn std::error::Error>>(())
366/// ```
367pub fn show(chart: Chart) -> Result<(), HostError> {
368    struct NoApp;
369    impl ChartApp for NoApp {}
370    run(WindowOptions::default(), chart, NoApp)
371}
372
373/// Opens a window showing `chart` and runs until it is closed.
374///
375/// The chart is sized to the window; `app` is called back as described on
376/// [`ChartApp`].
377///
378/// # Errors
379///
380/// [`HostError`] if the event loop, window, surface or GPU device cannot be
381/// created.
382pub fn run(options: WindowOptions, chart: Chart, app: impl ChartApp) -> Result<(), HostError> {
383    let event_loop = EventLoop::new().map_err(HostError::EventLoop)?;
384    let mut host = Host {
385        options,
386        chart,
387        app,
388        clock: Instant::now(),
389        input: InputConverter::new(),
390        gpu: None,
391        error: None,
392        events: Vec::new(),
393        failures: 0,
394        wake: None,
395    };
396    event_loop
397        .run_app(&mut host)
398        .map_err(HostError::EventLoop)?;
399    host.error.map_or(Ok(()), Err)
400}
401
402struct Gpu {
403    window: Arc<Window>,
404    // Keeps the device alive alongside the renderer.
405    _ctx: GpuContext,
406    renderer: WgpuRenderer,
407}
408
409struct Host<A> {
410    options: WindowOptions,
411    chart: Chart,
412    app: A,
413    clock: Instant,
414    input: InputConverter,
415    gpu: Option<Gpu>,
416    error: Option<HostError>,
417    events: Vec<ChartEvent>,
418    failures: u32,
419    wake: Option<f64>,
420}
421
422fn physical(size: PhysicalSize<u32>) -> SizePx {
423    SizePx {
424        w: size.width as f32,
425        h: size.height as f32,
426    }
427}
428
429impl<A: ChartApp> Host<A> {
430    fn now_ms(&self) -> f64 {
431        self.clock.elapsed().as_secs_f64() * 1000.0
432    }
433
434    fn fail(&mut self, event_loop: &ActiveEventLoop, e: HostError) {
435        self.error = Some(e);
436        event_loop.exit();
437    }
438
439    fn create(&mut self, event_loop: &ActiveEventLoop) -> Result<Gpu, HostError> {
440        let attrs = Window::default_attributes()
441            .with_title(self.options.title.clone())
442            .with_inner_size(LogicalSize::new(
443                f64::from(self.options.size.w),
444                f64::from(self.options.size.h),
445            ));
446        let window = Arc::new(event_loop.create_window(attrs).map_err(HostError::Window)?);
447        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_with_display_handle(
448            Box::new(window.clone()),
449        ));
450        let surface = instance
451            .create_surface(window.clone())
452            .map_err(HostError::Surface)?;
453        let ctx = GpuContext::with_instance(instance, Some(&surface)).map_err(HostError::Render)?;
454        let size = window.inner_size();
455        let mut renderer =
456            WgpuRenderer::with_surface(&ctx, surface, physical(size)).map_err(HostError::Render)?;
457        self.app.on_renderer(&mut renderer);
458        self.resize_chart(&window);
459        Ok(Gpu {
460            window,
461            _ctx: ctx,
462            renderer,
463        })
464    }
465
466    fn resize_chart(&mut self, window: &Window) {
467        let dpr = window.scale_factor();
468        let size = window.inner_size().to_logical::<f64>(dpr);
469        self.chart.resize(
470            SizeCss {
471                w: size.width as f32,
472                h: size.height as f32,
473            },
474            dpr as f32,
475        );
476    }
477
478    fn redraw(&mut self) {
479        let now = self.now_ms();
480        let Some(gpu) = &mut self.gpu else {
481            return;
482        };
483        // Native custom series of the renderer; no-op when unchanged.
484        self.chart.set_native_kinds(gpu.renderer.native_kinds());
485        if self.chart.needs_redraw() != Invalidation::None {
486            let start = Instant::now();
487            self.chart.build_frame(now, &gpu.renderer.measurer());
488            match gpu
489                .renderer
490                .render(self.chart.frame(), &self.chart.data_view())
491            {
492                Ok(()) => {
493                    self.failures = 0;
494                    let cpu_ms = start.elapsed().as_secs_f64() * 1000.0;
495                    self.app.on_frame(&gpu.window, cpu_ms);
496                }
497                // The frame is still pending in the chart; try again (the
498                // surface was reconfigured), but not forever.
499                Err(_) => self.failures += 1,
500            }
501        }
502        self.events.extend(self.chart.drain_events());
503        for event in self.events.drain(..) {
504            self.app.on_event(&mut self.chart, event);
505        }
506    }
507
508    fn wants_frame(&self) -> bool {
509        self.chart.needs_redraw() != Invalidation::None && self.failures < MAX_RETRIES
510    }
511}
512
513impl<A: ChartApp> ApplicationHandler for Host<A> {
514    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
515        if self.gpu.is_some() {
516            return;
517        }
518        match self.create(event_loop) {
519            Ok(gpu) => {
520                gpu.window.request_redraw();
521                self.gpu = Some(gpu);
522            }
523            Err(e) => self.fail(event_loop, e),
524        }
525    }
526
527    fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
528        let Some(window) = self.gpu.as_ref().map(|g| g.window.clone()) else {
529            return;
530        };
531        match event {
532            WindowEvent::CloseRequested => event_loop.exit(),
533            WindowEvent::Resized(size) => {
534                if let Some(gpu) = &mut self.gpu {
535                    gpu.renderer.resize(physical(size));
536                }
537                self.resize_chart(&window);
538                self.failures = 0;
539            }
540            WindowEvent::ScaleFactorChanged { .. } => {
541                self.resize_chart(&window);
542                self.failures = 0;
543            }
544            WindowEvent::RedrawRequested => self.redraw(),
545            other => {
546                let now = self.now_ms();
547                let (chart, input) = (&mut self.chart, &mut self.input);
548                let mut cursor = None;
549                input.convert(&other, window.scale_factor(), now, |e| {
550                    let r = chart.handle_input(e);
551                    cursor = Some(r.cursor);
552                });
553                if let Some(c) = cursor {
554                    window.set_cursor(cursor_icon(c));
555                    self.failures = 0;
556                }
557            }
558        }
559        if self.wants_frame() {
560            window.request_redraw();
561        }
562    }
563
564    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
565        let now = self.now_ms();
566        if self.wake.is_none_or(|t| t <= now) {
567            self.wake = self.app.update(&mut self.chart, now);
568        }
569        if let Some(gpu) = &self.gpu
570            && self.wants_frame()
571        {
572            gpu.window.request_redraw();
573        }
574        event_loop.set_control_flow(match self.wake {
575            Some(t) if t.is_finite() => ControlFlow::WaitUntil(
576                self.clock + Duration::from_secs_f64((t / 1000.0).clamp(0.0, 1e9)),
577            ),
578            _ => ControlFlow::Wait,
579        });
580    }
581}
582
583#[cfg(test)]
584mod tests {
585    use super::*;
586
587    fn collect(f: impl FnOnce(&mut dyn FnMut(InputEvent))) -> Vec<InputEvent> {
588        let mut out = Vec::new();
589        f(&mut |e| out.push(e));
590        out
591    }
592
593    #[test]
594    fn wheel_direction_and_dpr_follow_the_dom_convention() {
595        assert_eq!(
596            wheel_delta(MouseScrollDelta::LineDelta(0.0, 1.0), 2.0),
597            WheelDelta::Lines { x: -0.0, y: -1.0 }
598        );
599        let px = wheel_delta(
600            MouseScrollDelta::PixelDelta(winit::dpi::PhysicalPosition::new(4.0, -20.0)),
601            2.0,
602        );
603        assert_eq!(
604            px,
605            WheelDelta::Pixels {
606                x: Css(-2.0),
607                y: Css(10.0)
608            }
609        );
610    }
611
612    #[test]
613    fn two_quick_presses_make_a_double_click() {
614        let mut c = InputConverter::new();
615        let pos = PointCss { x: 10.0, y: 10.0 };
616        let mut events = collect(|e| c.moved(pos, 0.0, e));
617        events.extend(collect(|e| c.mouse(Button::Left, true, 0.0, e)));
618        events.extend(collect(|e| c.mouse(Button::Left, false, 50.0, e)));
619        events.extend(collect(|e| c.mouse(Button::Left, true, 200.0, e)));
620        assert!(matches!(
621            events.last(),
622            Some(InputEvent::DoubleClick { .. })
623        ));
624        // A third press starts over.
625        let third = collect(|e| c.mouse(Button::Left, true, 300.0, e));
626        assert_eq!(third.len(), 1);
627        // Slow presses do not.
628        let slow = collect(|e| c.mouse(Button::Left, true, 2000.0, e));
629        assert_eq!(slow.len(), 1);
630    }
631
632    #[test]
633    fn buttons_need_a_known_pointer_position() {
634        let mut c = InputConverter::new();
635        assert!(collect(|e| c.mouse(Button::Left, true, 0.0, e)).is_empty());
636    }
637}