1use std::collections::BTreeMap;
2
3use egui::mutex::Mutex;
4
5use crate::epi;
6
7use super::percent_decode;
8
9#[derive(Default)]
13pub(crate) struct WebInput {
14 pub primary_touch: Option<egui::TouchId>,
16
17 pub accumulated_scale: f32,
19
20 pub accumulated_rotation: f32,
22
23 pub modifiers: egui::Modifiers,
28
29 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 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 pub fn set_focus(&mut self, focused: bool) {
57 if self.raw.focused == focused {
58 return;
59 }
60
61 self.modifiers = egui::Modifiers::default(); self.raw.focused = focused;
64 self.raw.events.push(egui::Event::WindowFocused(focused));
65 self.primary_touch = None;
66 }
67
68 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
81pub(crate) struct NeedRepaint {
85 next_repaint: Mutex<f64>,
87
88 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), max_fps: max_fps.unwrap_or(0),
97 }
98 }
99}
100
101impl NeedRepaint {
102 pub fn when_to_repaint(&self) -> f64 {
105 *self.next_repaint.lock()
106 }
107
108 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 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
145pub fn user_agent() -> Option<String> {
149 web_sys::window()?.navigator().user_agent().ok()
150}
151
152pub 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 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
179fn 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#[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¶m2=bar"),
225 ("mushroom", "snake")
226 ])
227 );
228}