1use std::time::Duration;
31
32use egui::{Align2, Id, LayerId, Order, Shape, Ui};
33use egui_pop_core::icon::Icon;
34use egui_pop_core::kit::{Kit, State};
35use egui_pop_core::overlay;
36use egui_pop_core::placeholder::EmptyState;
37use egui_pop_core::strings;
38use egui_pop_model::context::{Envelope, Request};
39use serde_json::{Value as Json, json};
40use web_time::Instant;
41
42use crate::app::AppHandle;
43use crate::strings as txt;
44
45pub const DEFAULT_DELAY: Duration = Duration::from_secs(2);
47
48const MIN_PASSES: u32 = 3;
51
52#[derive(Debug, Default)]
55pub(crate) struct WindowWatch {
56 empty: Option<(Instant, u32)>,
58 shown: bool,
60}
61
62#[derive(Debug)]
65pub(crate) struct Closed {
66 id: String,
67 since: Instant,
68 seen: u32,
70 said: bool,
72}
73
74#[derive(Debug)]
78struct Orphan {
79 since: Instant,
80 passes: u32,
81 said: bool,
82}
83
84thread_local! {
85 static ORPHANS: std::cell::RefCell<std::collections::BTreeMap<egui::ViewportId, Orphan>> =
87 const { std::cell::RefCell::new(std::collections::BTreeMap::new()) };
88}
89
90pub(crate) struct Mark(Vec<(LayerId, usize)>);
92
93pub(crate) fn mark(ui: &Ui) -> Mark {
95 let ctx = ui.ctx();
96 let mut layers: Vec<LayerId> = ctx.memory(|m| m.layer_ids().collect());
97 for l in [ui.layer_id(), LayerId::background()] {
98 if !layers.contains(&l) {
99 layers.push(l);
100 }
101 }
102 Mark(layers.into_iter().map(|l| (l, shapes(ctx, l))).collect())
103}
104
105pub(crate) fn painted_since(ctx: &egui::Context, mark: &Mark) -> bool {
108 let layers: Vec<LayerId> = ctx.memory(|m| m.layer_ids().collect());
109 let from = |l: LayerId| mark.0.iter().find(|(m, _)| *m == l).map_or(0, |(_, n)| *n);
110 mark.0
111 .iter()
112 .map(|(l, _)| *l)
113 .chain(
114 layers
115 .into_iter()
116 .filter(|l| mark.0.iter().all(|(m, _)| m != l)),
117 )
118 .any(|l| has_content(ctx, l, from(l), None, &[]))
119}
120
121struct LastPage {
125 title: String,
126 shapes: Option<Vec<(LayerId, Vec<egui::epaint::ClippedShape>)>>,
129}
130
131thread_local! {
132 static LAST_PAGES: std::cell::RefCell<std::collections::BTreeMap<egui::ViewportId, LastPage>> =
134 const { std::cell::RefCell::new(std::collections::BTreeMap::new()) };
135}
136
137pub(crate) fn closing(viewport: egui::ViewportId, title: String) {
140 LAST_PAGES.with_borrow_mut(|p| {
141 p.insert(
142 viewport,
143 LastPage {
144 title,
145 shapes: None,
146 },
147 )
148 });
149}
150
151pub(crate) fn keep_last_page(ctx: &egui::Context, viewport: egui::ViewportId) {
154 let layers: Vec<LayerId> = ctx.memory(|m| m.layer_ids().collect());
155 let shapes: Vec<(LayerId, Vec<egui::epaint::ClippedShape>)> = ctx.graphics(|g| {
156 layers
157 .iter()
158 .filter_map(|l| {
159 let list = g.get(*l)?;
160 let shapes: Vec<_> = list.all_entries().cloned().collect();
161 (!shapes.is_empty()).then_some((*l, shapes))
162 })
163 .collect()
164 });
165 LAST_PAGES.with_borrow_mut(|p| {
166 if let Some(page) = p.get_mut(&viewport) {
167 page.shapes = Some(shapes);
168 }
169 });
170}
171
172pub(crate) fn closed_for_good(viewport: egui::ViewportId) {
175 LAST_PAGES.with_borrow_mut(|p| p.remove(&viewport));
176}
177
178fn draw_last_page(ui: &mut Ui, viewport: egui::ViewportId) -> bool {
182 let Some((title, shapes)) = LAST_PAGES.with_borrow(|p| {
183 p.get(&viewport)
184 .map(|l| (l.title.clone(), l.shapes.clone()))
185 }) else {
186 return false;
187 };
188 let ctx = ui.ctx().clone();
189 match shapes {
190 Some(shapes) => ctx.graphics_mut(|g| {
191 for (layer, shapes) in shapes {
192 let list = g.entry(layer);
193 for s in shapes {
194 list.add(s.clip_rect, s.shape);
195 }
196 }
197 }),
198 None => {
199 let t = egui_pop_core::theme::Tokens::of(&ctx);
200 let rect = ui.max_rect();
201 ui.painter().rect_filled(rect, 0.0, t.surface.canvas);
202 ui.painter().text(
203 rect.center(),
204 Align2::CENTER_CENTER,
205 title,
206 egui::FontId::proportional(14.0),
207 t.text.muted,
208 );
209 }
210 }
211 true
212}
213
214pub(crate) fn orphan_pass(ui: &mut Ui, viewport: egui::ViewportId, why: &str) {
222 let ctx = ui.ctx().clone();
223 let drawn = draw_last_page(ui, viewport);
224 let now = Instant::now();
225 let say = ORPHANS.with_borrow_mut(|o| {
226 let e = o.entry(viewport).or_insert(Orphan {
227 since: now,
228 passes: 0,
229 said: false,
230 });
231 e.passes += 1;
232 if e.passes == 1 {
233 if drawn {
234 log::debug!(
235 target: "egui_pop",
236 "a pass of viewport {viewport:?} after its window went ({why}): it draws \
237 the window's last page until the backend drops it"
238 );
239 } else {
240 log::info!(
244 target: "egui_pop",
245 "a pass of viewport {viewport:?} after its window went ({why}): it paints \
246 nothing, and the window is asked to hide and close"
247 );
248 }
249 }
250 let due = !e.said && e.passes >= MIN_PASSES && now.duration_since(e.since) >= DEFAULT_DELAY;
251 if due {
252 e.said = true;
253 }
254 due.then_some((e.passes, now.duration_since(e.since)))
255 });
256 if let Some((passes, since)) = say {
257 let title = ctx
258 .input(|i| i.viewport().title.clone())
259 .unwrap_or_default();
260 log::error!(
261 target: "egui_pop",
262 "the window of viewport {viewport:?} (title {title:?}) outlived its close for \
263 {passes} passes ({:.1} s): {why}; it is closed",
264 since.as_secs_f32()
265 );
266 }
267 ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false));
268 ctx.send_viewport_cmd(egui::ViewportCommand::Close);
269 ctx.request_repaint_of(egui::ViewportId::ROOT);
270 ctx.request_repaint_after(DEFAULT_DELAY);
271}
272
273pub(crate) fn forget_orphan(viewport: egui::ViewportId) {
276 ORPHANS.with_borrow_mut(|o| o.remove(&viewport));
277 LAST_PAGES.with_borrow_mut(|p| p.remove(&viewport));
278}
279
280#[derive(Debug)]
282pub(crate) struct Guard {
283 focus_hole: bool,
285 pass_start: Option<(LayerId, usize)>,
288 start: Option<(LayerId, usize)>,
291 first_said: bool,
293 placeholders: Vec<(LayerId, std::ops::Range<usize>)>,
297 empty: Option<(Instant, u32)>,
299 shown: bool,
301 delay: Option<Duration>,
303 windows: std::collections::BTreeMap<egui::ViewportId, WindowWatch>,
305 closed: std::collections::BTreeMap<egui::ViewportId, Closed>,
307}
308
309impl Default for Guard {
310 fn default() -> Self {
311 Guard {
312 focus_hole: false,
313 pass_start: None,
314 start: None,
315 first_said: false,
316 placeholders: Vec::new(),
317 empty: None,
318 shown: false,
319 delay: Some(DEFAULT_DELAY),
320 windows: std::collections::BTreeMap::new(),
321 closed: std::collections::BTreeMap::new(),
322 }
323 }
324}
325
326fn is_content(shape: &Shape) -> bool {
330 match shape {
331 Shape::Noop | Shape::LineSegment { .. } => false,
332 Shape::Rect(r) => r.brush.is_some(),
333 Shape::Vec(v) => v.iter().any(is_content),
334 _ => true,
335 }
336}
337
338fn shapes(ctx: &egui::Context, layer: LayerId) -> usize {
340 ctx.graphics(|g| g.get(layer).map_or(0, |l| l.next_idx().0))
341}
342
343fn has_content(
346 ctx: &egui::Context,
347 layer: LayerId,
348 from: usize,
349 to: Option<usize>,
350 skip: &[(LayerId, std::ops::Range<usize>)],
351) -> bool {
352 let skipped = |i: usize| skip.iter().any(|(l, r)| *l == layer && r.contains(&i));
353 ctx.graphics(|g| {
354 g.get(layer).is_some_and(|l| {
355 l.all_entries()
356 .enumerate()
357 .take(to.unwrap_or(usize::MAX))
358 .skip(from)
359 .any(|(i, s)| !skipped(i) && is_content(&s.shape))
360 })
361 })
362}
363
364impl AppHandle {
365 pub fn set_empty_window_delay(&self, delay: Option<Duration>) {
370 let mut g = self.0.paint_guard.borrow_mut();
371 g.delay = delay;
372 g.empty = None;
373 }
374
375 pub fn empty_window(&self) -> bool {
378 self.0.paint_guard.borrow().shown
379 }
380
381 pub fn focus_screen_hole(&self) -> bool {
384 self.0.paint_guard.borrow().focus_hole
385 }
386
387 pub(crate) fn hidden_by_focus_screen(&self) -> bool {
390 crate::admin::focus_screen(self) && !self.0.paint_guard.borrow().focus_hole
391 }
392
393 pub(crate) fn mark_pass_start(&self, ui: &Ui) {
396 let layer = ui.layer_id();
397 let mut g = self.0.paint_guard.borrow_mut();
398 g.pass_start = Some((layer, shapes(ui.ctx(), layer)));
399 g.start = None;
400 g.placeholders.clear();
401 }
402
403 pub(crate) fn placeholder(&self, ui: &mut Ui, add: impl FnOnce(&mut Ui)) {
408 let layer = ui.layer_id();
409 let from = shapes(ui.ctx(), layer);
410 add(ui);
411 let to = shapes(ui.ctx(), layer);
412 self.0
413 .paint_guard
414 .borrow_mut()
415 .placeholders
416 .push((layer, from..to));
417 }
418
419 pub(crate) fn mark_shell_start(&self, ui: &Ui) {
422 let layer = ui.layer_id();
423 self.0.paint_guard.borrow_mut().start = Some((layer, shapes(ui.ctx(), layer)));
424 }
425
426 pub(crate) fn end_shell_pass(&self, ui: &Ui) {
429 let ctx = ui.ctx();
430 let admin = self.service(&crate::admin::ADMIN);
431 let focus = admin.as_ref().is_some_and(|a| a.focus_screen());
432 let page = admin.as_ref().is_some_and(|a| a.take_page_drawn());
433 let hole = focus && !page;
434 let was = std::mem::replace(&mut self.0.paint_guard.borrow_mut().focus_hole, hole);
435 if hole && !was {
436 let state = self.screen_state(ctx);
437 log::warn!(
438 target: "egui_pop",
439 "a wizard holds the main window as a focus screen and no page of it was drawn: \
440 the shell is drawn instead; {state}"
441 );
442 self.publish("egui_pop", None, "window.focus_hole", state);
443 ctx.request_repaint();
444 } else if was && !hole {
445 log::info!(target: "egui_pop", "the focus screen's hole is closed");
446 }
447 self.watch_empty(ui, page);
448 self.check_invariants_in_pass(ctx);
451 }
452
453 fn watch_empty(&self, ui: &Ui, page: bool) {
454 let ctx = ui.ctx();
455 let (pass_start, start, delay, shown, first_said, skip) = {
456 let mut g = self.0.paint_guard.borrow_mut();
457 let first = std::mem::replace(&mut g.first_said, true);
458 let skip = std::mem::take(&mut g.placeholders);
459 (
460 g.pass_start.take(),
461 g.start.take(),
462 g.delay,
463 g.shown,
464 first,
465 skip,
466 )
467 };
468 let Some((layer, from)) = start.or(pass_start) else {
472 return;
473 };
474 let title_bar = match (pass_start, start) {
476 (Some((_, a)), Some((_, b))) => Some(has_content(ctx, layer, a, Some(b), &skip)),
477 _ => None,
478 };
479 let content = has_content(ctx, layer, from, None, &skip);
480 if !first_said {
481 log::info!(
482 target: "egui_pop",
483 "the main window's first pass: content painted: {content}, title bar painted: \
484 {title_bar:?}, shell drawn: {}; {}",
485 start.is_some(),
486 self.screen_state(ctx)
487 );
488 }
489 let Some(delay) = delay else {
490 return;
491 };
492 let painted = page || !overlay::stack(ctx).is_empty() || content;
493 if painted {
494 let mut g = self.0.paint_guard.borrow_mut();
495 g.empty = None;
496 if shown {
497 g.shown = false;
498 drop(g);
499 log::info!(target: "egui_pop", "the main window paints again");
500 self.invariant_holds(
501 crate::window_invariants::PAINTS,
502 crate::windows::WindowId::MAIN,
503 );
504 }
505 return;
506 }
507 let now = Instant::now();
508 let (since, passes) = {
509 let mut g = self.0.paint_guard.borrow_mut();
510 let e = g.empty.get_or_insert((now, 0));
511 e.1 += 1;
512 *e
513 };
514 if !shown {
515 if passes < MIN_PASSES || now.duration_since(since) < delay {
516 ctx.request_repaint_after(delay.max(Duration::from_millis(50)));
518 return;
519 }
520 self.0.paint_guard.borrow_mut().shown = true;
521 let mut state = self.screen_state(ctx);
522 state["title_bar_painted"] = json!(title_bar);
523 state["shell_drawn"] = json!(start.is_some());
524 log::error!(
525 target: "egui_pop",
526 "the main window painted nothing (title bar painted: {title_bar:?}, shell \
527 drawn: {}) for {passes} passes ({:.1} s): the fallback page is shown; {state}",
528 start.is_some(),
529 now.duration_since(since).as_secs_f32()
530 );
531 self.publish("egui_pop", None, "window.painted_nothing", state);
532 self.painted_nothing(
533 crate::windows::WindowId::MAIN,
534 passes,
535 now.duration_since(since),
536 );
537 }
538 self.fallback_page(ctx);
539 }
540
541 pub fn screen_state(&self, ctx: &egui::Context) -> Json {
545 let admin = self.service(&crate::admin::ADMIN);
546 let stack = crate::contexts::state(self).map(|s| {
547 json!({
548 "places": s.places.iter().map(|e| e.frame.to_string()).collect::<Vec<_>>(),
549 "modes": s.modes.iter().map(|m| m.frame.to_string()).collect::<Vec<_>>(),
550 })
551 });
552 let overlays: Vec<String> = overlay::stack(ctx)
553 .iter()
554 .map(|o| o.label.clone())
555 .collect();
556 let areas: Vec<Json> = {
557 let wb = self.workbench_mut();
558 wb.areas()
559 .into_iter()
560 .map(|a| {
561 json!({
562 "area": crate::workbench::area_name(a),
563 "panels": wb.panels_in(a).iter().map(ToString::to_string).collect::<Vec<_>>(),
564 })
565 })
566 .collect()
567 };
568 json!({
569 "contexts": stack,
570 "settings": {
571 "open": admin.as_ref().is_some_and(|a| a.is_open()),
572 "wizard": admin.as_ref().and_then(|a| a.wizard_flow()).is_some(),
573 "focus_screen": admin.as_ref().is_some_and(|a| a.focus_screen()),
574 "in_window": crate::admin::in_window(self),
575 },
576 "overlays": overlays,
577 "zen": self.zen(),
578 "own_frame": crate::frame::own_frame(self),
579 "root_has_content": self.root_has_content(),
580 "areas": areas,
581 })
582 }
583
584 pub(crate) fn watch_app_window(
591 &self,
592 ctx: &egui::Context,
593 id: &crate::windows::WindowId,
594 painted: bool,
595 ) -> bool {
596 let viewport = ctx.viewport_id();
597 let delay = self.0.paint_guard.borrow().delay;
598 let Some(delay) = delay else {
599 return false;
600 };
601 let painted = painted || !overlay::stack(ctx).is_empty();
602 let now = Instant::now();
603 let (since, passes, shown) = {
604 let mut g = self.0.paint_guard.borrow_mut();
605 let w = g.windows.entry(viewport).or_default();
606 if painted {
607 let was = std::mem::take(&mut w.shown);
608 w.empty = None;
609 drop(g);
610 if was {
611 log::info!(target: "egui_pop", "the window `{id}` paints again");
612 self.invariant_holds(crate::window_invariants::PAINTS, id.as_str());
613 }
614 return false;
615 }
616 let e = w.empty.get_or_insert((now, 0));
617 e.1 += 1;
618 (e.0, e.1, w.shown)
619 };
620 if shown {
621 return true;
622 }
623 if passes < MIN_PASSES || now.duration_since(since) < delay {
624 ctx.request_repaint_after(delay.max(Duration::from_millis(50)));
626 return false;
627 }
628 if let Some(w) = self.0.paint_guard.borrow_mut().windows.get_mut(&viewport) {
629 w.shown = true;
630 }
631 let mut state = self.screen_state(ctx);
632 let info = self.windows().into_iter().find(|w| w.viewport == viewport);
633 state["window"] = json!({
634 "id": id,
635 "viewport": format!("{viewport:?}"),
636 "title": info.as_ref().map(|w| w.title.clone()),
637 "focused": info.as_ref().and_then(|w| w.focused),
638 "geometry": info.as_ref().and_then(|w| w.geometry),
639 "minimized": ctx.input(|i| i.viewport().minimized),
640 });
641 log::error!(
642 target: "egui_pop",
643 "the window `{id}` ({viewport:?}) painted nothing for {passes} passes ({:.1} s): the \
644 fallback page is shown; {state}",
645 now.duration_since(since).as_secs_f32()
646 );
647 self.publish("egui_pop", None, "window.painted_nothing", state);
648 self.painted_nothing(id.as_str(), passes, now.duration_since(since));
649 true
650 }
651
652 fn painted_nothing(&self, window: &str, passes: u32, since: Duration) {
655 let owner = self
656 .windows_list()
657 .into_iter()
658 .find(|w| w.id == window)
659 .map(|w| w.owner)
660 .unwrap_or_default();
661 self.invariant_broken(crate::window_invariants::painted_nothing(
662 window,
663 &owner,
664 format!(
665 "shown, painted nothing for {passes} passes ({:.1} s)",
666 since.as_secs_f32()
667 ),
668 ));
669 }
670
671 pub(crate) fn app_window_fallback(&self, ctx: &egui::Context) -> bool {
675 let mut close = false;
676 egui::Area::new(Id::unique(("egui_pop.empty_app_window", ctx.viewport_id())))
677 .order(Order::Foreground)
678 .anchor(Align2::CENTER_CENTER, egui::Vec2::ZERO)
679 .show(ctx, |ui| {
680 ui.set_max_width(420.0);
681 Kit::of(ctx)
682 .fault_card
683 .show(ui, State::REST, egui::Shadow::NONE, |ui| {
684 close = EmptyState::new(
685 Icon::Warning,
686 strings::tr(ctx, &txt::EMPTY_WINDOW_TITLE),
687 )
688 .text(strings::tr(ctx, &txt::EMPTY_WINDOW_BODY))
689 .action(strings::tr(ctx, &strings::CLOSE))
690 .show(ui);
691 });
692 });
693 if close {
694 log::info!(target: "egui_pop", "empty window: closed from its fallback page");
695 }
696 close
697 }
698
699 pub(crate) fn app_window_closed(&self, viewport: egui::ViewportId, id: &str) {
702 let mut g = self.0.paint_guard.borrow_mut();
703 g.windows.remove(&viewport);
704 g.closed.insert(
705 viewport,
706 Closed {
707 id: id.to_string(),
708 since: Instant::now(),
709 seen: 0,
710 said: false,
711 },
712 );
713 drop(g);
714 self.invariant_holds(crate::window_invariants::PAINTS, id);
716 }
717
718 pub(crate) fn closed_window_id(&self, viewport: egui::ViewportId) -> Option<String> {
721 self.0
722 .paint_guard
723 .borrow()
724 .closed
725 .get(&viewport)
726 .map(|c| c.id.clone())
727 }
728
729 pub(crate) fn app_window_opened(&self, viewport: egui::ViewportId) {
732 let mut g = self.0.paint_guard.borrow_mut();
733 g.windows.remove(&viewport);
734 g.closed.remove(&viewport);
735 drop(g);
736 forget_orphan(viewport);
737 }
738
739 pub(crate) fn watch_closed_windows(&self, ctx: &egui::Context) -> Vec<egui::ViewportId> {
745 let live: Vec<egui::ViewportId> = ctx.input(|i| i.raw.viewports.keys().copied().collect());
746 let now = Instant::now();
747 let (late, waiting) = {
748 let mut g = self.0.paint_guard.borrow_mut();
749 g.closed.retain(|v, _| live.contains(v));
751 let Some(delay) = g.delay else {
752 return Vec::new();
753 };
754 let mut late = Vec::new();
755 for (v, c) in &mut g.closed {
756 c.seen += 1;
757 if !c.said && c.seen >= 2 && now.duration_since(c.since) >= delay {
760 late.push((*v, c.id.clone(), now.duration_since(c.since)));
761 c.said = true;
762 }
763 }
764 (late, g.closed.values().any(|c| !c.said))
765 };
766 if waiting {
767 ctx.request_repaint_after(self.0.paint_guard.borrow().delay.unwrap_or(DEFAULT_DELAY));
768 }
769 late.into_iter()
770 .map(|(v, id, since)| {
771 let state = self.screen_state(ctx);
772 log::error!(
773 target: "egui_pop",
774 "the window `{id}` ({v:?}) is closed, yet its system window is still there \
775 {:.1} s later: it is hidden; {state}",
776 since.as_secs_f32()
777 );
778 self.publish(
779 "egui_pop",
780 None,
781 "window.outlived",
782 json!({ "window": id, "viewport": format!("{v:?}") }),
783 );
784 v
785 })
786 .collect()
787 }
788
789 fn fallback_page(&self, ctx: &egui::Context) {
792 let deep = crate::contexts::state(self).is_some_and(|s| s.depth() > 0);
793 let mut reset = false;
794 let mut back = false;
795 egui::Area::new(Id::unique("egui_pop.empty_window"))
796 .order(Order::Foreground)
797 .anchor(Align2::CENTER_CENTER, egui::Vec2::ZERO)
798 .show(ctx, |ui| {
799 ui.set_max_width(420.0);
800 Kit::of(ctx)
801 .fault_card
802 .show(ui, State::REST, egui::Shadow::NONE, |ui| {
803 reset = EmptyState::new(
804 Icon::Warning,
805 strings::tr(ctx, &txt::EMPTY_WINDOW_TITLE),
806 )
807 .text(strings::tr(ctx, &txt::EMPTY_WINDOW_BODY))
808 .action(strings::tr(ctx, &txt::EMPTY_WINDOW_RESET))
809 .show(ui);
810 if deep {
811 ui.vertical_centered(|ui| {
812 back = ui
813 .button(strings::tr(ctx, &txt::EMPTY_WINDOW_BACK))
814 .clicked();
815 });
816 }
817 });
818 });
819 if reset {
820 log::info!(target: "egui_pop", "empty window: the arrangement is reset");
821 if let Some(a) = self.service(&crate::admin::ADMIN) {
824 a.close(self);
825 }
826 if self.zen() {
828 self.run(crate::workbench::CMD_LEAVE_ZEN, Json::Null);
829 }
830 self.run(crate::arrangements::CMD_RESET, Json::Null);
831 }
832 if back {
833 log::info!(target: "egui_pop", "empty window: back to the first place");
834 let _ = crate::contexts::request(
835 self,
836 Envelope::new(Request::Jump { depth: 0 }),
837 &egui_pop_model::commands::Origin::User,
838 );
839 }
840 }
841}