1use std::collections::HashMap;
56use std::sync::{Arc, Mutex};
57
58use egui::{Context, Id, Pos2, Rect, Response, Stroke, StrokeKind, Ui, ViewportId, vec2};
59use serde::{Deserialize, Serialize};
60
61use crate::hover_card::{Card, HoverCard};
62use crate::pointer::DragKind;
63use crate::state::{lock, shared};
64use crate::theme::Tokens;
65
66#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
68#[serde(rename_all = "kebab-case")]
69#[non_exhaustive]
70pub enum AreaKind {
71 Display,
73 Navigate,
76 Edit,
78}
79
80impl AreaKind {
81 pub fn as_str(self) -> &'static str {
83 match self {
84 AreaKind::Display => "display",
85 AreaKind::Navigate => "navigate",
86 AreaKind::Edit => "edit",
87 }
88 }
89}
90
91#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
93#[serde(rename_all = "kebab-case")]
94#[non_exhaustive]
95pub enum GripAxis {
96 Horizontal,
98 Vertical,
100 Free,
102}
103
104#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
107#[non_exhaustive]
108pub struct Grip {
109 pub at: Pos2,
111 pub axis: GripAxis,
112}
113
114impl Grip {
115 pub fn new(at: Pos2, axis: GripAxis) -> Grip {
116 Grip { at, axis }
117 }
118
119 pub fn horizontal(at: Pos2) -> Grip {
121 Grip::new(at, GripAxis::Horizontal)
122 }
123
124 pub fn vertical(at: Pos2) -> Grip {
126 Grip::new(at, GripAxis::Vertical)
127 }
128
129 pub fn free(at: Pos2) -> Grip {
131 Grip::new(at, GripAxis::Free)
132 }
133
134 pub fn rect(&self) -> Rect {
136 let size = match self.axis {
137 GripAxis::Horizontal => vec2(GRIP_THIN, GRIP_LONG),
138 GripAxis::Vertical => vec2(GRIP_LONG, GRIP_THIN),
139 GripAxis::Free => vec2(GRIP_THIN + 2.0, GRIP_THIN + 2.0),
140 };
141 Rect::from_center_size(self.at, size)
142 }
143}
144
145const GRIP_THIN: f32 = 7.0;
147const GRIP_LONG: f32 = 18.0;
149
150#[derive(Clone, Debug, PartialEq)]
152#[non_exhaustive]
153pub struct AreaSpec {
154 pub id: String,
155 pub kind: AreaKind,
156 pub control: Option<String>,
158 pub value: Option<String>,
160 pub path: Option<String>,
163 pub grips: Vec<Grip>,
164 pub cursor: Option<DragKind>,
166}
167
168impl AreaSpec {
169 pub fn new(id: impl Into<String>, kind: AreaKind) -> AreaSpec {
170 AreaSpec {
171 id: id.into(),
172 kind,
173 control: None,
174 value: None,
175 path: None,
176 grips: Vec::new(),
177 cursor: None,
178 }
179 }
180
181 pub fn display(id: impl Into<String>) -> AreaSpec {
183 AreaSpec::new(id, AreaKind::Display)
184 }
185
186 pub fn navigate(id: impl Into<String>) -> AreaSpec {
188 AreaSpec::new(id, AreaKind::Navigate)
189 }
190
191 pub fn edit(id: impl Into<String>, control: impl Into<String>) -> AreaSpec {
193 let mut a = AreaSpec::new(id, AreaKind::Edit);
194 a.control = Some(control.into());
195 a
196 }
197
198 pub fn value(mut self, value: impl Into<String>) -> AreaSpec {
200 self.value = Some(value.into());
201 self
202 }
203
204 pub fn path(mut self, path: impl Into<String>) -> AreaSpec {
206 self.path = Some(path.into());
207 self
208 }
209
210 pub fn grip(mut self, grip: Grip) -> AreaSpec {
212 self.grips.push(grip);
213 self
214 }
215
216 pub fn cursor(mut self, kind: DragKind) -> AreaSpec {
219 self.cursor = Some(kind);
220 self
221 }
222
223 pub fn card(&self) -> Card {
226 match (self.kind, &self.control) {
227 (AreaKind::Edit, Some(control)) => {
228 let text = match &self.value {
229 Some(v) => format!("**{control}** {v}"),
230 None => format!("**{control}**"),
231 };
232 Card::new().text(text)
233 }
234 _ => Card::new(),
235 }
236 }
237}
238
239#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
241#[non_exhaustive]
242pub struct AreaRecord {
243 pub id: String,
244 pub kind: AreaKind,
245 #[serde(default, skip_serializing_if = "Option::is_none")]
246 pub control: Option<String>,
247 #[serde(default, skip_serializing_if = "Option::is_none")]
248 pub value: Option<String>,
249 #[serde(default, skip_serializing_if = "Option::is_none")]
250 pub path: Option<String>,
251 pub rect: Rect,
253 #[serde(default, skip_serializing_if = "Option::is_none")]
255 pub panel: Option<String>,
256 pub window: String,
258 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
260 pub inert: bool,
261 #[serde(default, skip_serializing_if = "Vec::is_empty")]
263 pub grips: Vec<Grip>,
264}
265
266#[derive(Clone, Debug)]
268struct Scope {
269 panel: String,
270 inert: bool,
271}
272
273#[derive(Debug, Default)]
275struct Window {
276 drawing: bool,
278 current: Vec<AreaRecord>,
280 last: Vec<AreaRecord>,
282 scopes: Vec<Scope>,
284}
285
286#[derive(Debug, Default)]
287struct State {
288 windows: HashMap<ViewportId, Window>,
289}
290
291fn state(ctx: &Context) -> Arc<Mutex<State>> {
292 shared::<State>(ctx, "core.areas")
293}
294
295struct Hook;
297
298impl egui::Plugin for Hook {
299 fn debug_name(&self) -> &'static str {
300 "egui_pop_areas"
301 }
302
303 fn on_begin_pass(&mut self, ui: &mut Ui) {
304 let viewport = ui.ctx().viewport_id();
305 let st = state(ui.ctx());
306 let mut s = lock(&st);
307 let w = s.windows.entry(viewport).or_default();
308 w.last = std::mem::take(&mut w.current);
309 w.drawing = true;
310 w.scopes.clear();
311 }
312
313 fn on_end_pass(&mut self, ui: &mut Ui) {
314 let viewport = ui.ctx().viewport_id();
315 let st = state(ui.ctx());
316 if let Some(w) = lock(&st).windows.get_mut(&viewport) {
317 w.drawing = false;
318 }
319 }
320}
321
322pub fn scope<R>(ui: &mut Ui, panel: &str, inert: bool, add: impl FnOnce(&mut Ui) -> R) -> R {
326 let ctx = ui.ctx().clone();
327 let viewport = ctx.viewport_id();
328 let st = state(&ctx);
329 lock(&st)
330 .windows
331 .entry(viewport)
332 .or_default()
333 .scopes
334 .push(Scope {
335 panel: panel.to_owned(),
336 inert,
337 });
338 struct Pop(Arc<Mutex<State>>, ViewportId);
340 impl Drop for Pop {
341 fn drop(&mut self) {
342 if let Some(w) = lock(&self.0).windows.get_mut(&self.1) {
343 w.scopes.pop();
344 }
345 }
346 }
347 let _pop = Pop(st, viewport);
348 add(ui)
349}
350
351pub fn inert(ui: &Ui) -> bool {
354 let ctx = ui.ctx();
355 let viewport = ctx.viewport_id();
356 lock(&state(ctx))
357 .windows
358 .get(&viewport)
359 .and_then(|w| w.scopes.last())
360 .is_some_and(|s| s.inert)
361}
362
363pub fn register(ui: &Ui, response: &Response, area: AreaSpec) -> bool {
368 let ctx = ui.ctx().clone();
369 ctx.add_plugin(Hook);
370 let viewport = ctx.viewport_id();
371 let st = state(&ctx);
372 let (panel, inert) = {
373 let s = lock(&st);
374 let scope = s.windows.get(&viewport).and_then(|w| w.scopes.last());
375 (
376 scope.map(|s| s.panel.clone()),
377 area.kind == AreaKind::Edit && scope.is_some_and(|s| s.inert),
378 )
379 };
380 let edits = area.kind == AreaKind::Edit && !inert;
381 if edits {
382 let active = response.hovered() || response.dragged() || response.has_focus();
383 for g in &area.grips {
384 paint_grip(ui, g, active);
385 }
386 if let Some(kind) = area.cursor {
387 crate::pointer::drag_cursor(response, kind);
388 }
389 let card = if response.dragged() {
391 Card::new()
392 } else {
393 area.card()
394 };
395 HoverCard::new(("egui_pop.area", response.id)).show(ui, response, &card);
396 }
397 let record = AreaRecord {
398 id: area.id,
399 kind: area.kind,
400 control: area.control,
401 value: area.value,
402 path: area.path,
403 rect: response.rect,
404 panel,
405 window: format!("{viewport:?}"),
406 inert,
407 grips: if edits { area.grips } else { Vec::new() },
408 };
409 lock(&st)
410 .windows
411 .entry(viewport)
412 .or_default()
413 .current
414 .push(record);
415 inert
416}
417
418pub fn paint_grip(ui: &Ui, grip: &Grip, active: bool) {
422 let t = Tokens::of(ui.ctx());
423 let fill = t.surface.raised;
424 let border = if active {
425 t.accent.default
426 } else {
427 t.border.strong
428 };
429 let line = t.text.muted;
430 let rect = grip.rect();
431 let painter = ui.painter();
432 let radius = rect.width().min(rect.height()) / 2.0;
433 painter.rect_filled(rect, radius, fill);
434 painter.rect_stroke(rect, radius, Stroke::new(1.0, border), StrokeKind::Inside);
435 let ridge = Stroke::new(1.0, line);
437 match grip.axis {
438 GripAxis::Horizontal => {
439 for dy in [-2.0, 2.0] {
440 let y = rect.center().y + dy;
441 painter.line_segment(
442 [
443 Pos2::new(rect.left() + 2.0, y),
444 Pos2::new(rect.right() - 2.0, y),
445 ],
446 ridge,
447 );
448 }
449 }
450 GripAxis::Vertical => {
451 for dx in [-2.0, 2.0] {
452 let x = rect.center().x + dx;
453 painter.line_segment(
454 [
455 Pos2::new(x, rect.top() + 2.0),
456 Pos2::new(x, rect.bottom() - 2.0),
457 ],
458 ridge,
459 );
460 }
461 }
462 GripAxis::Free => {
463 painter.circle_filled(rect.center(), 1.5, line);
464 }
465 }
466}
467
468pub fn list(ctx: &Context) -> Vec<AreaRecord> {
471 let st = state(ctx);
472 let s = lock(&st);
473 let mut windows: Vec<_> = s.windows.iter().collect();
474 windows.sort_by_key(|(id, _)| (**id != ViewportId::ROOT, format!("{id:?}")));
475 windows
476 .into_iter()
477 .flat_map(|(_, w)| if w.drawing { &w.last } else { &w.current })
478 .cloned()
479 .collect()
480}
481
482pub fn find(ctx: &Context, id: &str) -> Option<AreaRecord> {
484 list(ctx).into_iter().find(|a| a.id == id)
485}
486
487pub fn card_id(widget: Id) -> Id {
490 HoverCard::new(("egui_pop.area", widget)).id()
491}
492
493#[cfg(test)]
494mod tests {
495 use super::*;
496
497 #[test]
498 fn an_edit_card_names_the_control_and_its_value() {
499 let a = AreaSpec::edit("h", "Exposure").value("+0.30 EV");
500 assert_eq!(a.card().plain_text(), "Exposure +0.30 EV");
501 assert!(AreaSpec::display("w").card().is_empty());
502 assert_eq!(AreaKind::Navigate.as_str(), "navigate");
503 }
504
505 #[test]
506 fn a_grip_is_tall_when_dragged_sideways() {
507 let g = Grip::horizontal(Pos2::new(10.0, 10.0));
508 assert!(g.rect().height() > g.rect().width());
509 assert_eq!(g.rect().center(), Pos2::new(10.0, 10.0));
510 }
511}