1use std::collections::HashMap;
49
50use egui::{Context, FocusDirection, Id, Key, LayerId, Modifiers, Rect, Response, Ui};
51use egui_pop_model::tab::{self as model, TabEntry};
52use serde::Serialize;
53
54use crate::state::{lock, pass, shared};
55
56#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
58#[serde(rename_all = "lowercase")]
59pub enum ScopeKind {
60 Panel,
62 Modal,
64}
65
66#[derive(Clone, Debug, Default, PartialEq, Eq)]
68pub struct TabStop {
69 index: Option<i32>,
70 group: Option<String>,
71 skip: bool,
72}
73
74impl TabStop {
75 pub fn new() -> Self {
76 Self::default()
77 }
78
79 pub fn index(mut self, index: i32) -> Self {
81 self.index = Some(index);
82 self
83 }
84
85 pub fn group(mut self, group: impl Into<String>) -> Self {
87 self.group = Some(group.into());
88 self
89 }
90
91 pub fn skip(mut self, skip: bool) -> Self {
93 self.skip = skip;
94 self
95 }
96
97 pub fn group_name(&self) -> Option<&str> {
99 self.group.as_deref()
100 }
101
102 pub fn explicit_index(&self) -> Option<i32> {
104 self.index
105 }
106}
107
108#[derive(Clone, Debug, PartialEq, Serialize)]
110pub struct StopRecord {
111 #[serde(skip)]
112 pub id: Id,
113 pub entry: TabEntry,
114}
115
116#[derive(Clone, Debug, PartialEq, Serialize)]
118pub struct ScopeRecord {
119 pub name: String,
120 pub kind: ScopeKind,
121 #[serde(skip)]
122 pub layer: LayerId,
123 #[serde(skip)]
124 pub rect: Rect,
125 pub stops: Vec<StopRecord>,
126}
127
128impl ScopeRecord {
129 pub fn order(&self) -> Vec<Id> {
131 let entries: Vec<TabEntry> = self.stops.iter().map(|s| s.entry.clone()).collect();
132 model::order(&entries, false)
133 .into_iter()
134 .map(|i| self.stops[i].id)
135 .collect()
136 }
137
138 fn has_stops(&self) -> bool {
139 self.stops.iter().any(|s| !s.entry.skip)
140 }
141}
142
143#[derive(Debug, Default)]
144struct State {
145 pass: u64,
146 building: Vec<ScopeRecord>,
147 open: Vec<usize>,
148 last: Vec<ScopeRecord>,
149 remembered: HashMap<String, Id>,
151 installed: bool,
152}
153
154fn state(ctx: &Context) -> std::sync::Arc<std::sync::Mutex<State>> {
155 shared::<State>(ctx, "core.tab")
156}
157
158fn rotate(ctx: &Context, s: &mut State) {
159 let now = pass(ctx);
160 if s.pass != now {
161 s.pass = now;
162 s.last = std::mem::take(&mut s.building);
163 s.open.clear();
164 }
165}
166
167pub fn scope<R>(ui: &mut Ui, name: &str, kind: ScopeKind, add: impl FnOnce(&mut Ui) -> R) -> R {
169 install(ui.ctx());
170 let st = state(ui.ctx());
171 let index = {
172 let mut s = lock(&st);
173 rotate(ui.ctx(), &mut s);
174 s.building.push(ScopeRecord {
175 name: name.into(),
176 kind,
177 layer: ui.layer_id(),
178 rect: Rect::NOTHING,
179 stops: Vec::new(),
180 });
181 let i = s.building.len() - 1;
182 s.open.push(i);
183 i
184 };
185 let (inner, rect) = ui
186 .scope(|ui| {
187 let inner = add(ui);
188 (inner, ui.min_rect())
189 })
190 .inner;
191 let mut s = lock(&st);
192 if let Some(r) = s.building.get_mut(index) {
193 r.rect = rect;
194 }
195 s.open.pop();
196 inner
197}
198
199pub fn stop(ui: &Ui, response: &Response, stop: TabStop) {
203 let st = state(ui.ctx());
204 let mut s = lock(&st);
205 rotate(ui.ctx(), &mut s);
206 let Some(&i) = s.open.last() else {
207 return;
208 };
209 let r = response.rect;
210 let entry = TabEntry {
211 rect: [r.left(), r.top(), r.width(), r.height()],
212 index: stop.index,
213 group: stop.group,
214 skip: stop.skip || !response.enabled(),
215 };
216 s.building[i].stops.push(StopRecord {
217 id: response.id,
218 entry,
219 });
220}
221
222#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
224#[serde(rename_all = "lowercase")]
225pub enum Axis {
226 Horizontal,
228 Vertical,
230 Own,
234}
235
236pub fn roving<R>(ui: &mut Ui, name: &str, axis: Axis, add: impl FnOnce(&mut Ui) -> R) -> R {
271 crate::roving::show(ui, name, axis, add)
272}
273
274pub fn parts<R>(ui: &mut Ui, name: &str, owner: Id, add: impl FnOnce(&mut Ui) -> R) -> R {
284 crate::roving::parts(ui, name, owner, add)
285}
286
287pub fn rovings(ctx: &Context) -> Vec<(String, Vec<Id>)> {
290 crate::roving::groups(ctx)
291}
292
293pub fn scopes(ctx: &Context) -> Vec<ScopeRecord> {
295 let st = state(ctx);
296 let mut s = lock(&st);
297 rotate(ctx, &mut s);
298 s.last.clone()
299}
300
301pub fn order(ctx: &Context, name: &str) -> Vec<Id> {
303 scopes(ctx)
304 .iter()
305 .find(|r| r.name == name)
306 .map(ScopeRecord::order)
307 .unwrap_or_default()
308}
309
310#[derive(Clone, Debug)]
312pub(crate) struct PanelHop {
313 pub first: Id,
315 pub target: Id,
317 pub here: bool,
319}
320
321pub(crate) fn panel_hops(ctx: &Context) -> Vec<PanelHop> {
323 let focused = ctx.memory(|m| m.focused());
324 let at = focused.and_then(|f| {
325 let r = crate::focus::peek_response(ctx, f)?;
326 Some((r.layer_id, r.rect.center()))
327 });
328 let st = state(ctx);
329 let mut s = lock(&st);
330 rotate(ctx, &mut s);
331 let drawn = s.last.iter().filter(|sc| sc.kind == ScopeKind::Panel);
332 drawn
333 .filter_map(|sc| {
334 let order = sc.order();
335 let target = s
336 .remembered
337 .get(&sc.name)
338 .filter(|r| order.contains(r))
339 .or(order.first())?;
340 let holds = focused.is_some_and(|f| sc.stops.iter().any(|x| x.id == f));
341 let lies = at.is_some_and(|(layer, pos)| sc.layer == layer && sc.rect.contains(pos));
342 Some(PanelHop {
343 first: sc.stops.first()?.id,
344 target: *target,
345 here: holds || lies,
346 })
347 })
348 .collect()
349}
350
351pub(crate) fn modal_drawn(ctx: &Context) -> bool {
353 let st = state(ctx);
354 let mut s = lock(&st);
355 rotate(ctx, &mut s);
356 s.last
357 .iter()
358 .any(|sc| sc.kind == ScopeKind::Modal && sc.has_stops())
359}
360
361pub fn install(ctx: &Context) {
363 let st = state(ctx);
364 let mut s = lock(&st);
365 if !s.installed {
366 s.installed = true;
367 drop(s);
368 ctx.add_plugin(TabPlugin);
369 }
370}
371
372#[derive(Debug)]
375struct TabPlugin;
376
377impl egui::plugin::Plugin for TabPlugin {
378 fn debug_name(&self) -> &'static str {
379 "egui_pop_core::tab"
380 }
381
382 fn on_begin_pass(&mut self, ui: &mut Ui) {
383 begin_pass(ui.ctx());
384 }
385}
386
387fn pressed(ctx: &Context, key: Key) -> Option<bool> {
389 ctx.input(|i| {
390 i.events.iter().find_map(|e| match e {
391 egui::Event::Key {
392 key: k,
393 pressed: true,
394 modifiers,
395 ..
396 } if *k == key && (modifiers.is_none() || modifiers.shift_only()) => {
397 Some(modifiers.shift)
398 }
399 _ => None,
400 })
401 })
402}
403
404fn focus(ctx: &Context, target: Id, key: Key, back: bool) {
405 ctx.memory_mut(|m| {
406 m.request_focus(target);
407 m.move_focus(FocusDirection::None);
408 });
409 let mods = if back {
410 Modifiers::SHIFT
411 } else {
412 Modifiers::NONE
413 };
414 ctx.input_mut(|i| i.consume_key(mods, key));
415}
416
417fn begin_pass(ctx: &Context) {
418 let st = state(ctx);
419 let mut s = lock(&st);
420 rotate(ctx, &mut s);
421 let focused = ctx.memory(|m| m.focused());
422 let at = focused.and_then(|f| {
424 s.last
425 .iter()
426 .enumerate()
427 .find_map(|(i, sc)| sc.stops.iter().position(|x| x.id == f).map(|j| (i, j)))
428 });
429 if let Some((i, _)) = at
430 && s.last[i].kind == ScopeKind::Panel
431 && let Some(f) = focused
432 {
433 let name = s.last[i].name.clone();
434 s.remembered.insert(name, f);
435 }
436 if let Some(back) = pressed(ctx, Key::Tab)
437 && let Some((i, j)) = at
438 {
439 let sc = &s.last[i];
440 let entries: Vec<TabEntry> = sc.stops.iter().map(|x| x.entry.clone()).collect();
441 let order = model::order(&entries, false);
442 let cycle = sc.kind == ScopeKind::Modal;
443 if let Some(k) = model::next(&order, Some(j), back, cycle) {
444 let target = sc.stops[k].id;
445 drop(s);
446 focus(ctx, target, Key::Tab, back);
447 return;
448 }
449 }
450 if let Some(back) = pressed(ctx, Key::F6) {
451 if crate::focus::has_regions(ctx) {
453 return;
454 }
455 let modal = s
456 .last
457 .iter()
458 .any(|sc| sc.kind == ScopeKind::Modal && sc.has_stops())
459 || crate::overlay::modal_open(ctx);
460 if modal {
461 return;
462 }
463 let panels: Vec<usize> = (0..s.last.len())
464 .filter(|&i| s.last[i].kind == ScopeKind::Panel && s.last[i].has_stops())
465 .collect();
466 if panels.is_empty() {
467 return;
468 }
469 let current = at.map(|(i, _)| i).or_else(|| {
470 let f = focused?;
471 let r = crate::focus::peek_response(ctx, f)?;
472 panels.iter().copied().find(|&p| {
473 s.last[p].layer == r.layer_id && s.last[p].rect.contains(r.rect.center())
474 })
475 });
476 let pos = current.and_then(|c| panels.iter().position(|&p| p == c));
477 let n = panels.len();
478 let next = match pos {
479 None if back => panels[n - 1],
480 None => panels[0],
481 Some(p) if back => panels[(p + n - 1) % n],
482 Some(p) => panels[(p + 1) % n],
483 };
484 let sc = &s.last[next];
485 let order = sc.order();
486 let target = s
487 .remembered
488 .get(&sc.name)
489 .copied()
490 .filter(|r| order.contains(r))
491 .or_else(|| order.first().copied());
492 if let Some(target) = target {
493 drop(s);
494 focus(ctx, target, Key::F6, back);
495 }
496 }
497}