Skip to main content

eframe/web/
backend.rs

1use std::collections::BTreeMap;
2
3use egui::mutex::Mutex;
4
5use crate::epi;
6
7use super::percent_decode;
8
9// ----------------------------------------------------------------------------
10
11/// Data gathered between frames.
12#[derive(Default)]
13pub(crate) struct WebInput {
14    /// Required because we don't get a position on touchend
15    pub primary_touch: Option<egui::TouchId>,
16
17    /// Helps to track the delta scale from gesture events
18    pub accumulated_scale: f32,
19
20    /// Helps to track the delta rotation from gesture events
21    pub accumulated_rotation: f32,
22
23    /// The last modifier state we sent to egui.
24    ///
25    /// The web has no dedicated modifier event, so we derive the state from each DOM event and
26    /// emit [`egui::Event::ModifiersChanged`] when it changes (see [`Self::set_modifiers`]).
27    pub modifiers: egui::Modifiers,
28
29    /// The raw input to `egui`.
30    pub raw: egui::RawInput,
31}
32
33impl WebInput {
34    pub fn new_frame(&mut self, canvas_size: egui::Vec2) -> egui::RawInput {
35        let mut raw_input = egui::RawInput {
36            screen_rect: Some(egui::Rect::from_min_size(Default::default(), canvas_size)),
37            time: Some(super::now_sec()),
38            ..self.raw.take()
39        };
40        let viewport = raw_input
41            .viewports
42            .entry(egui::ViewportId::ROOT)
43            .or_default();
44        viewport.native_pixels_per_point = Some(super::native_pixels_per_point());
45
46        // A hidden browser tab is effectively occluded.
47        let hidden = web_sys::window()
48            .and_then(|w| w.document())
49            .is_some_and(|doc| doc.hidden());
50        viewport.occluded = Some(hidden);
51
52        raw_input
53    }
54
55    /// On alt-tab, or user clicking another HTML element.
56    pub fn set_focus(&mut self, focused: bool) {
57        if self.raw.focused == focused {
58            return;
59        }
60
61        // log::debug!("on_web_page_focus_change: {focused}");
62        self.modifiers = egui::Modifiers::default(); // Avoid sticky modifier keys on alt-tab:
63        self.raw.focused = focused;
64        self.raw.events.push(egui::Event::WindowFocused(focused));
65        self.primary_touch = None;
66    }
67
68    /// Update the modifier state, emitting [`egui::Event::ModifiersChanged`] if it changed.
69    ///
70    /// Call before pushing the DOM event itself so egui sees the new modifier state first.
71    pub fn set_modifiers(&mut self, modifiers: egui::Modifiers) {
72        if self.modifiers != modifiers {
73            self.modifiers = modifiers;
74            self.raw
75                .events
76                .push(egui::Event::ModifiersChanged(modifiers));
77        }
78    }
79}
80
81// ----------------------------------------------------------------------------
82
83/// Stores when to do the next repaint.
84pub(crate) struct NeedRepaint {
85    /// Time in seconds when the next repaint should happen.
86    next_repaint: Mutex<f64>,
87
88    /// Rate limit for repaint. 0 means "unlimited". The rate may still be limited by vsync.
89    max_fps: u32,
90}
91
92impl NeedRepaint {
93    pub fn new(max_fps: Option<u32>) -> Self {
94        Self {
95            next_repaint: Mutex::new(f64::NEG_INFINITY), // start with a repaint
96            max_fps: max_fps.unwrap_or(0),
97        }
98    }
99}
100
101impl NeedRepaint {
102    /// Returns the time (in [`now_sec`] scale) when
103    /// we should next repaint.
104    pub fn when_to_repaint(&self) -> f64 {
105        *self.next_repaint.lock()
106    }
107
108    /// Unschedule repainting.
109    pub fn clear(&self) {
110        *self.next_repaint.lock() = f64::INFINITY;
111    }
112
113    pub fn repaint_after(&self, num_seconds: f64) {
114        let mut time = super::now_sec() + num_seconds;
115        time = self.round_repaint_time_to_rate(time);
116        let mut repaint_time = self.next_repaint.lock();
117        *repaint_time = repaint_time.min(time);
118    }
119
120    /// Request a repaint. Depending on the presence of rate limiting, this may not be instant.
121    pub fn repaint(&self) {
122        let time = self.round_repaint_time_to_rate(super::now_sec());
123        let mut repaint_time = self.next_repaint.lock();
124        *repaint_time = repaint_time.min(time);
125    }
126
127    pub fn repaint_asap(&self) {
128        *self.next_repaint.lock() = f64::NEG_INFINITY;
129    }
130
131    pub fn needs_repaint(&self) -> bool {
132        self.when_to_repaint() <= super::now_sec()
133    }
134
135    fn round_repaint_time_to_rate(&self, time: f64) -> f64 {
136        if self.max_fps == 0 {
137            time
138        } else {
139            let interval = 1.0 / self.max_fps as f64;
140            (time / interval).ceil() * interval
141        }
142    }
143}
144
145// ----------------------------------------------------------------------------
146
147/// The User-Agent of the user's browser.
148pub fn user_agent() -> Option<String> {
149    web_sys::window()?.navigator().user_agent().ok()
150}
151
152/// Get the [`epi::Location`] from the browser.
153pub fn web_location() -> epi::Location {
154    let location = web_sys::window().unwrap().location();
155
156    let hash = percent_decode(&location.hash().unwrap_or_default());
157
158    let query = location
159        .search()
160        .unwrap_or_default()
161        .strip_prefix('?')
162        .unwrap_or_default()
163        .to_owned();
164
165    epi::Location {
166        // TODO(emilk): should we really percent-decode the url? 🤷‍♂️
167        url: percent_decode(&location.href().unwrap_or_default()),
168        protocol: percent_decode(&location.protocol().unwrap_or_default()),
169        host: percent_decode(&location.host().unwrap_or_default()),
170        hostname: percent_decode(&location.hostname().unwrap_or_default()),
171        port: percent_decode(&location.port().unwrap_or_default()),
172        hash,
173        query_map: parse_query_map(&query),
174        query,
175        origin: percent_decode(&location.origin().unwrap_or_default()),
176    }
177}
178
179/// query is percent-encoded
180fn parse_query_map(query: &str) -> BTreeMap<String, Vec<String>> {
181    let mut map: BTreeMap<String, Vec<String>> = Default::default();
182
183    for pair in query.split('&') {
184        if !pair.is_empty() {
185            if let Some((key, value)) = pair.split_once('=') {
186                map.entry(percent_decode(key))
187                    .or_default()
188                    .push(percent_decode(value));
189            } else {
190                map.entry(percent_decode(pair))
191                    .or_default()
192                    .push(String::new());
193            }
194        }
195    }
196
197    map
198}
199
200// TODO(emilk): this test is never acgtually run, because this whole module is wasm32 only 🤦‍♂️
201#[test]
202fn test_parse_query() {
203    assert_eq!(parse_query_map(""), BTreeMap::default());
204    assert_eq!(parse_query_map("foo"), BTreeMap::from_iter([("foo", "")]));
205    assert_eq!(
206        parse_query_map("foo=bar"),
207        BTreeMap::from_iter([("foo", "bar")])
208    );
209    assert_eq!(
210        parse_query_map("foo=bar&baz=42"),
211        BTreeMap::from_iter([("foo", "bar"), ("baz", "42")])
212    );
213    assert_eq!(
214        parse_query_map("foo&baz=42"),
215        BTreeMap::from_iter([("foo", ""), ("baz", "42")])
216    );
217    assert_eq!(
218        parse_query_map("foo&baz&&"),
219        BTreeMap::from_iter([("foo", ""), ("baz", "")])
220    );
221    assert_eq!(
222        parse_query_map("badger=data.rrd%3Fparam1%3Dfoo%26param2%3Dbar&mushroom=snake"),
223        BTreeMap::from_iter([
224            ("badger", "data.rrd?param1=foo&param2=bar"),
225            ("mushroom", "snake")
226        ])
227    );
228}