1use std::cell::{Cell, RefCell};
81use std::collections::BTreeMap;
82use std::fmt;
83use std::rc::Rc;
84
85use egui_pop_core::binding::SharedStore;
86use egui_pop_core::{focus, lock, strings};
87use egui_pop_model::clock::ManualClock;
88use egui_pop_model::commands::Origin;
89use egui_pop_model::ids::{OwnerId, StepId};
90use egui_pop_model::values::{self, Store};
91use serde::Serialize;
92use serde_json::{Value as Json, json};
93
94pub use egui_pop_model::history::{
95 APP, At, CAP, Features, Jump, Label, Line, MERGE_WINDOW, MergeMark, Preview, PreviewChange,
96 Refusal, RefusalKind, Replaced, Request, SETTINGS, ScopeId, ScopeInfo, Snapshot, StepInfo,
97 may_undo_out_of_order, merges, newest, plan_jump,
98};
99
100use crate::app::{AppHandle, STEP_REDO, STEP_UNDO};
101use crate::host::{Pending, source_of};
102use crate::steps::Outcome;
103
104pub const STEP_JUMP: StepId = StepId::from_static("edit.jump");
107
108pub const STEP_RESTORE: StepId = StepId::from_static("edit.restore");
111
112pub const STEP_UNDO_STEP: StepId = StepId::from_static("edit.undo_step");
115
116pub const STEP_TARGET: StepId = StepId::from_static("pop.history.target");
124
125pub const NOTHING_FOCUSED: &str = "none";
129
130#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
133#[serde(rename_all = "snake_case")]
134pub enum Routing {
135 #[default]
138 Newest,
139 Focus,
145}
146
147#[derive(Debug)]
149pub enum Answer {
150 Done(Result<Walked, Refusal>),
152 Later(Pending),
154}
155
156#[derive(Clone, Debug, PartialEq, Serialize)]
158pub struct Walked {
159 pub scope: ScopeId,
160 pub steps: Vec<StepInfo>,
163 pub rev: u64,
165 pub head: u64,
167 pub dry_run: bool,
169}
170
171pub trait History {
173 fn scopes(&self) -> Vec<ScopeInfo>;
175
176 fn line(&self, scope: &ScopeId) -> Option<Line>;
178
179 fn rev(&self, scope: &ScopeId) -> u64 {
181 self.line(scope).map_or(0, |l| l.rev)
182 }
183
184 fn tips(&self, scope: &ScopeId) -> Option<Line> {
187 self.line(scope).map(|l| tips_of(&l))
188 }
189
190 fn undo(&mut self, request: &Request, origin: &Origin) -> Answer;
192
193 fn redo(&mut self, request: &Request, origin: &Origin) -> Answer;
195
196 fn jump(&mut self, request: &Request, to: u64, origin: &Origin) -> Answer;
198
199 fn group(&mut self, _origin: &Origin, _label: &Label) -> Option<u64> {
202 None
203 }
204
205 fn close(&mut self, _group: u64, _keep: bool) {}
207
208 fn in_progress(&self, _scope: &ScopeId) -> Option<Label> {
211 None
212 }
213
214 fn features(&self, _scope: &ScopeId) -> Features {
217 Features::default()
218 }
219
220 fn snapshots(&self, _scope: &ScopeId) -> Vec<Snapshot> {
222 Vec::new()
223 }
224
225 fn snapshot(
229 &mut self,
230 request: &Request,
231 _name: &str,
232 _origin: &Origin,
233 ) -> Result<Snapshot, Refusal> {
234 Err(unsupported(&request.scope, "snapshots"))
235 }
236
237 fn restore(&mut self, request: &Request, _snapshot: u64, _origin: &Origin) -> Answer {
239 Answer::Done(Err(unsupported(&request.scope, "snapshots")))
240 }
241
242 fn forget(&mut self, request: &Request, _snapshot: u64) -> Result<(), Refusal> {
244 Err(unsupported(&request.scope, "snapshots"))
245 }
246
247 fn undo_step(&mut self, request: &Request, _step: u64, _origin: &Origin) -> Answer {
251 Answer::Done(Err(unsupported(&request.scope, "undoing one step")))
252 }
253
254 fn replaced(&self, _scope: &ScopeId) -> Vec<Replaced> {
258 Vec::new()
259 }
260
261 fn preview(&mut self, _scope: &ScopeId, _at: Option<At>) -> Option<Preview> {
266 None
267 }
268}
269
270pub fn unsupported(scope: &ScopeId, what: &str) -> Refusal {
272 Refusal::new(
273 RefusalKind::Unsupported,
274 format!("the history `{scope}` does not support {what}"),
275 )
276}
277
278#[derive(Clone)]
281pub struct StoreHistory {
282 store: SharedStore,
283 scopes: Vec<ScopeInfo>,
284}
285
286impl fmt::Debug for StoreHistory {
287 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288 f.debug_struct("StoreHistory")
289 .field("scopes", &self.scopes)
290 .finish_non_exhaustive()
291 }
292}
293
294impl StoreHistory {
295 pub fn new(store: SharedStore) -> Self {
297 Self::with_scopes(store, vec![ScopeInfo::new(APP, "Application")])
298 }
299
300 pub fn with_scopes(store: SharedStore, scopes: Vec<ScopeInfo>) -> Self {
302 Self { store, scopes }
303 }
304
305 fn known(&self, scope: &ScopeId) -> Result<(), Refusal> {
306 if self.scopes.iter().any(|s| s.id == *scope) {
307 Ok(())
308 } else {
309 Err(unknown(scope))
310 }
311 }
312
313 fn answer(
314 &self,
315 request: &Request,
316 f: impl FnOnce(&mut Store) -> Result<Vec<StepInfo>, Refusal>,
317 ) -> Answer {
318 Answer::Done(self.known(&request.scope).and_then(|()| {
319 let mut s = lock(&self.store);
320 request.check(s.history_rev(&request.scope))?;
321 if let Some(label) = s.gesture_open(&request.scope) {
322 return Err(in_progress(label));
323 }
324 let steps = f(&mut s)?;
325 let line = store_line(&s, &request.scope);
326 Ok(Walked {
327 scope: request.scope.clone(),
328 steps,
329 rev: line.rev,
330 head: line.head_id(),
331 dry_run: request.dry_run,
332 })
333 }))
334 }
335}
336
337impl History for StoreHistory {
338 fn scopes(&self) -> Vec<ScopeInfo> {
339 let cap = lock(&self.store).history_cap();
340 self.scopes
341 .iter()
342 .cloned()
343 .map(|mut s| {
344 s.cap = cap;
345 s
346 })
347 .collect()
348 }
349
350 fn line(&self, scope: &ScopeId) -> Option<Line> {
351 self.known(scope).ok()?;
352 Some(store_line(&lock(&self.store), scope))
353 }
354
355 fn rev(&self, scope: &ScopeId) -> u64 {
356 lock(&self.store).history_rev(scope)
357 }
358
359 fn tips(&self, scope: &ScopeId) -> Option<Line> {
360 self.known(scope).ok()?;
361 let s = lock(&self.store);
362 Some(Line {
363 undo: s
364 .undo_steps_in(scope)
365 .last()
366 .map(|st| step_info(scope, st))
367 .into_iter()
368 .collect(),
369 redo: s
370 .redo_steps_in(scope)
371 .last()
372 .map(|st| step_info(scope, st))
373 .into_iter()
374 .collect(),
375 rev: s.history_rev(scope),
376 })
377 }
378
379 fn undo(&mut self, request: &Request, origin: &Origin) -> Answer {
380 self.answer(request, |s| store_walk(s, request, origin, false))
381 }
382
383 fn redo(&mut self, request: &Request, origin: &Origin) -> Answer {
384 self.answer(request, |s| store_walk(s, request, origin, true))
385 }
386
387 fn jump(&mut self, request: &Request, to: u64, origin: &Origin) -> Answer {
388 self.answer(request, |s| store_jump(s, request, to, origin))
389 }
390
391 fn group(&mut self, origin: &Origin, label: &Label) -> Option<u64> {
392 Some(lock(&self.store).begin_group(origin.clone(), &label.text).0)
393 }
394
395 fn close(&mut self, group: u64, keep: bool) {
396 let mut s = lock(&self.store);
397 let g = values::GestureId(group);
398 if keep {
399 s.end(g);
400 } else {
401 s.cancel(g);
402 }
403 }
404
405 fn in_progress(&self, scope: &ScopeId) -> Option<Label> {
406 lock(&self.store).gesture_open(scope).map(Label::text)
407 }
408
409 fn features(&self, scope: &ScopeId) -> Features {
410 if self.known(scope).is_ok() {
411 Features::all()
412 } else {
413 Features::default()
414 }
415 }
416
417 fn snapshots(&self, scope: &ScopeId) -> Vec<Snapshot> {
418 if self.known(scope).is_err() {
419 return Vec::new();
420 }
421 lock(&self.store).snapshots_in(scope)
422 }
423
424 fn snapshot(
425 &mut self,
426 request: &Request,
427 name: &str,
428 origin: &Origin,
429 ) -> Result<Snapshot, Refusal> {
430 self.known(&request.scope)?;
431 let mut s = lock(&self.store);
432 request.check(s.history_rev(&request.scope))?;
433 s.take_snapshot(&request.scope, name, origin, request.dry_run)
434 }
435
436 fn restore(&mut self, request: &Request, snapshot: u64, origin: &Origin) -> Answer {
437 self.answer(request, |s| {
438 let step = s.restore_snapshot(&request.scope, snapshot, origin, request.dry_run)?;
439 Ok(step
440 .map(|st| step_info(&request.scope, &st))
441 .into_iter()
442 .collect())
443 })
444 }
445
446 fn forget(&mut self, request: &Request, snapshot: u64) -> Result<(), Refusal> {
447 self.known(&request.scope)?;
448 let mut s = lock(&self.store);
449 request.check(s.history_rev(&request.scope))?;
450 let there = s
451 .snapshots_in(&request.scope)
452 .iter()
453 .any(|x| x.id == snapshot);
454 if !there {
455 return Err(Refusal::new(
456 RefusalKind::Nothing,
457 format!("no snapshot {snapshot} in `{}`", request.scope),
458 ));
459 }
460 if !request.dry_run {
461 s.forget_snapshot(&request.scope, snapshot);
462 }
463 Ok(())
464 }
465
466 fn undo_step(&mut self, request: &Request, step: u64, origin: &Origin) -> Answer {
467 self.answer(request, |s| {
468 let st = s.undo_step_in(&request.scope, step, origin, request.dry_run)?;
469 Ok(vec![step_info(&request.scope, &st)])
470 })
471 }
472
473 fn replaced(&self, scope: &ScopeId) -> Vec<Replaced> {
474 if self.known(scope).is_err() {
475 return Vec::new();
476 }
477 lock(&self.store)
478 .replaced_in(scope)
479 .into_iter()
480 .map(|(after, st)| Replaced {
481 step: step_info(scope, st),
482 after,
483 })
484 .collect()
485 }
486
487 fn preview(&mut self, scope: &ScopeId, at: Option<At>) -> Option<Preview> {
488 self.known(scope).ok()?;
489 let at = at?;
490 let s = lock(&self.store);
491 let changes = s
492 .values_at(scope, at)?
493 .into_iter()
494 .map(|(path, now, then)| {
495 let d = s.get(&path).map(|e| &e.descriptor);
496 PreviewChange {
497 what: d.map_or_else(|| path.clone(), |d| d.label.clone()),
498 then: value_text(d, &then),
499 now: value_text(d, &now),
500 }
501 })
502 .collect();
503 Some(Preview {
504 shown: false,
505 changes,
506 })
507 }
508}
509
510fn value_text(d: Option<&values::Descriptor>, v: &values::Value) -> String {
513 let number = |x: f64, d: &values::Descriptor| {
514 let x = x * d.display_scale;
515 let text = format!("{x:.*}", d.precision as usize);
516 match &d.unit {
517 Some(u) => format!("{text} {u}"),
518 None => text,
519 }
520 };
521 match (d, v) {
522 (Some(d), values::Value::Float(x)) => number(*x, d),
523 (Some(d), values::Value::Int(x)) => number(*x as f64, d),
524 (_, values::Value::Text(t) | values::Value::Choice(t)) => t.clone(),
525 _ => v.to_json().to_string(),
526 }
527}
528
529pub fn tips_of(line: &Line) -> Line {
531 Line {
532 undo: line.head().cloned().into_iter().collect(),
533 redo: line.next().cloned().into_iter().collect(),
534 rev: line.rev,
535 }
536}
537
538fn unknown(scope: &ScopeId) -> Refusal {
539 Refusal::new(RefusalKind::Unknown, format!("no history `{scope}`"))
540}
541
542fn in_progress(label: &str) -> Refusal {
543 Refusal::new(RefusalKind::Held, format!("“{label}” is in progress"))
544}
545
546fn refused(r: values::Refused) -> Refusal {
547 let kind = match r {
548 values::Refused::Held { .. } => RefusalKind::Held,
549 _ => RefusalKind::Owner,
550 };
551 Refusal::new(kind, r.to_string())
552}
553
554fn not_writer(s: &Store, step: &values::Step, by: &OwnerId) -> Result<(), Refusal> {
558 let Some((path, e)) = step
559 .changes
560 .iter()
561 .find(|(p, _, _)| !s.may_write(p, by))
562 .and_then(|(p, _, _)| s.get(p).map(|e| (p, e)))
563 else {
564 return Ok(());
565 };
566 Err(refused(values::Refused::NotWriter {
567 path: path.clone(),
568 by: by.clone(),
569 owner: e.owner.clone(),
570 current: e.value.clone(),
571 }))
572}
573
574fn step_info(scope: &ScopeId, step: &values::Step) -> StepInfo {
576 StepInfo {
577 id: step.id,
578 scope: scope.clone(),
579 label: Label::text(&step.label),
580 origin: step.origin.clone(),
581 group: step.group,
582 place: step.place.clone(),
583 at: step.at,
584 in_progress: false,
585 }
586}
587
588pub fn store_line(store: &Store, scope: &ScopeId) -> Line {
590 Line {
591 undo: store
592 .undo_steps_in(scope)
593 .iter()
594 .map(|s| step_info(scope, s))
595 .collect(),
596 redo: store
597 .redo_steps_in(scope)
598 .iter()
599 .map(|s| step_info(scope, s))
600 .collect(),
601 rev: store.history_rev(scope),
602 }
603}
604
605fn store_walk(
606 s: &mut Store,
607 request: &Request,
608 origin: &Origin,
609 redo: bool,
610) -> Result<Vec<StepInfo>, Refusal> {
611 let scope = &request.scope;
612 let by = origin.writer();
615 if request.dry_run {
616 let step = s.check_walk(scope, redo).map_err(refused)?;
617 if let Some(st) = step {
618 not_writer(s, st, &by)?;
619 }
620 return Ok(step.map(|st| step_info(scope, st)).into_iter().collect());
621 }
622 let step = if redo {
623 s.redo_in_by(scope, origin, &by)
624 } else {
625 s.undo_in_by(scope, origin, &by)
626 }
627 .map_err(refused)?;
628 Ok(step.map(|st| step_info(scope, &st)).into_iter().collect())
629}
630
631fn store_jump(
632 s: &mut Store,
633 request: &Request,
634 to: u64,
635 origin: &Origin,
636) -> Result<Vec<StepInfo>, Refusal> {
637 let scope = &request.scope;
638 let line = store_line(s, scope);
639 let jump = match plan_jump(&line, to) {
640 Ok(j) => j,
641 Err(e) => {
643 return match s
644 .jump_replaced(scope, to, origin, request.dry_run)
645 .map_err(refused)?
646 {
647 Some(steps) => Ok(steps.iter().map(|st| step_info(scope, st)).collect()),
648 None if s.replaced_in(scope).iter().any(|(_, st)| st.id == to) => {
649 Err(Refusal::new(
650 RefusalKind::Owner,
651 "its line left from a step that is replaced too: go to that line first",
652 ))
653 }
654 None => Err(e),
655 };
656 }
657 };
658 let walked = walked_by(&line, jump);
659 if request.dry_run {
660 let list = if jump.redo {
661 s.redo_steps_in(scope)
662 } else {
663 s.undo_steps_in(scope)
664 };
665 for st in list.iter().rev().take(jump.count) {
667 if let Some((p, _, _)) = st.changes.iter().find(|(p, _, _)| s.held_by(p).is_some()) {
668 return Err(Refusal::new(
669 RefusalKind::Held,
670 format!("`{p}` is held by a gesture in progress"),
671 ));
672 }
673 }
674 let by = origin.writer();
676 for st in list.iter().rev().take(jump.count) {
677 not_writer(s, st, &by)?;
678 }
679 return Ok(walked);
680 }
681 s.jump_in_by(scope, to, origin, &origin.writer())
682 .map_err(refused)?;
683 Ok(walked)
684}
685
686fn walked_by(line: &Line, jump: Jump) -> Vec<StepInfo> {
688 let list = if jump.redo { &line.redo } else { &line.undo };
689 list.iter().rev().take(jump.count).cloned().collect()
690}
691
692pub trait LocalScope {
697 fn info(&self) -> ScopeInfo;
699
700 fn line(&self, app: &AppHandle) -> Line;
702
703 fn undo(&self, app: &AppHandle, origin: &Origin) -> Result<Option<StepInfo>, Refusal>;
705
706 fn redo(&self, app: &AppHandle, origin: &Origin) -> Result<Option<StepInfo>, Refusal>;
708
709 fn in_progress(&self, _app: &AppHandle) -> Option<Label> {
711 None
712 }
713}
714
715#[derive(Clone, Debug)]
719pub struct StoreScope {
720 info: ScopeInfo,
721}
722
723impl StoreScope {
724 pub fn new(scope: ScopeId, title: &str) -> Self {
725 let mut info = ScopeInfo::new(scope, title);
726 info.local = true;
727 Self { info }
728 }
729
730 fn walk(
731 &self,
732 app: &AppHandle,
733 origin: &Origin,
734 redo: bool,
735 ) -> Result<Option<StepInfo>, Refusal> {
736 let store = app.store();
737 let mut s = lock(&store);
738 if let Some(label) = s.gesture_open(&self.info.id) {
739 return Err(in_progress(label));
740 }
741 let by = origin.writer();
742 let step = if redo {
743 s.redo_in_by(&self.info.id, origin, &by)
744 } else {
745 s.undo_in_by(&self.info.id, origin, &by)
746 }
747 .map_err(refused)?;
748 Ok(step.map(|st| step_info(&self.info.id, &st)))
749 }
750}
751
752impl LocalScope for StoreScope {
753 fn info(&self) -> ScopeInfo {
754 self.info.clone()
755 }
756
757 fn line(&self, app: &AppHandle) -> Line {
758 store_line(&lock(&app.store()), &self.info.id)
759 }
760
761 fn undo(&self, app: &AppHandle, origin: &Origin) -> Result<Option<StepInfo>, Refusal> {
762 self.walk(app, origin, false)
763 }
764
765 fn redo(&self, app: &AppHandle, origin: &Origin) -> Result<Option<StepInfo>, Refusal> {
766 self.walk(app, origin, true)
767 }
768
769 fn in_progress(&self, app: &AppHandle) -> Option<Label> {
770 lock(&app.store())
771 .gesture_open(&self.info.id)
772 .map(Label::text)
773 }
774}
775
776type Registered = (OwnerId, String, Rc<dyn LocalScope>);
778
779#[derive(Default)]
782pub(crate) struct Kept {
783 locals: RefCell<Vec<Registered>>,
784 undone: RefCell<Vec<ScopeId>>,
785 revs: RefCell<BTreeMap<ScopeId, u64>>,
786 focused: Cell<Option<egui::Id>>,
787 clock: RefCell<Option<ManualClock>>,
788 previewing: RefCell<Option<Previewing>>,
789 routing: Cell<Routing>,
790 targets: RefCell<Vec<(OwnerId, String, ScopeId)>>,
792 last_focused: RefCell<Vec<(egui::ViewportId, ScopeId)>>,
794 rule: Cell<&'static str>,
797}
798
799struct Previewing {
802 scope: ScopeId,
803 at: At,
804 answer: Option<Preview>,
805 pass: u64,
806 view: Option<egui::Id>,
807}
808
809pub(crate) fn register(app: &AppHandle, owner: &OwnerId, surface: &str, scope: Rc<dyn LocalScope>) {
811 let kept = app.local::<Kept>();
812 let mut locals = kept.locals.borrow_mut();
813 locals.retain(|(_, s, _)| s != surface);
814 locals.push((owner.clone(), surface.into(), scope));
815}
816
817pub(crate) fn declare_target(app: &AppHandle, owner: &OwnerId, surface: &str, scope: ScopeId) {
820 let kept = app.local::<Kept>();
821 let mut targets = kept.targets.borrow_mut();
822 targets.retain(|(_, s, _)| s != surface);
823 targets.push((owner.clone(), surface.into(), scope));
824}
825
826pub(crate) fn remove_owner(app: &AppHandle, owner: &OwnerId) {
829 let kept = app.local::<Kept>();
830 kept.locals.borrow_mut().retain(|(o, _, _)| o != owner);
831 kept.targets.borrow_mut().retain(|(o, _, _)| o != owner);
832}
833
834pub fn with_owner<R>(app: &AppHandle, f: impl FnOnce(&mut dyn History) -> R) -> Option<R> {
837 app.with_host_mut(|h| {
838 let store = h.store();
839 match h.history() {
840 Some(owner) => f(owner),
841 None => f(&mut StoreHistory::new(store)),
842 }
843 })
844}
845
846#[derive(Clone)]
848pub enum Target {
849 Local(Rc<dyn LocalScope>),
851 Owner(ScopeId),
853}
854
855impl fmt::Debug for Target {
856 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
857 match self {
858 Target::Local(l) => write!(f, "Local({})", l.info().id),
859 Target::Owner(s) => write!(f, "Owner({s})"),
860 }
861 }
862}
863
864impl Target {
865 pub fn scope(&self) -> ScopeId {
867 match self {
868 Target::Local(l) => l.info().id,
869 Target::Owner(s) => s.clone(),
870 }
871 }
872
873 pub fn line(&self, app: &AppHandle) -> Option<Line> {
875 match self {
876 Target::Local(l) => Some(l.line(app)),
877 Target::Owner(s) => with_owner(app, |h| h.line(s)).flatten(),
878 }
879 }
880}
881
882fn focused_local(app: &AppHandle) -> Option<Rc<dyn LocalScope>> {
884 let chain = focus::chain_names(&app.egui());
885 let kept = app.local::<Kept>();
886 let locals = kept.locals.borrow();
887 chain.iter().rev().find_map(|name| {
888 locals
889 .iter()
890 .find(|(_, s, _)| s == name)
891 .map(|(_, _, l)| l.clone())
892 })
893}
894
895pub fn set_routing(app: &AppHandle, routing: Routing) {
897 let kept = app.local::<Kept>();
898 if kept.routing.replace(routing) != routing {
899 kept.last_focused.borrow_mut().clear();
900 }
901}
902
903pub fn routing(app: &AppHandle) -> Routing {
905 app.local::<Kept>().routing.get()
906}
907
908pub fn focused_scope(app: &AppHandle) -> Option<ScopeId> {
913 let chain = focus::chain_names(&app.egui());
914 if chain.is_empty() {
915 return None;
916 }
917 let scopes = with_owner(app, |h| h.scopes()).unwrap_or_default();
918 let kept = app.local::<Kept>();
919 let targets = kept.targets.borrow();
920 let names = crate::app::names_surface;
921 chain.iter().rev().find_map(|name| {
922 targets
923 .iter()
924 .find(|(_, s, id)| names(s, name) && scopes.iter().any(|i| i.id == *id))
925 .map(|(_, _, id)| id.clone())
926 .or_else(|| {
927 scopes
928 .iter()
929 .filter(|s| !s.local)
930 .find(|s| s.focus.iter().any(|f| names(f, name)))
931 .map(|s| s.id.clone())
932 })
933 })
934}
935
936pub fn last_focused(app: &AppHandle) -> Option<ScopeId> {
939 let window = window_of(app);
940 app.local::<Kept>()
941 .last_focused
942 .borrow()
943 .iter()
944 .find(|(w, _)| *w == window)
945 .map(|(_, s)| s.clone())
946}
947
948fn window_of(app: &AppHandle) -> egui::ViewportId {
950 crate::app::pass_in_progress(&app.egui()).map_or_else(|| app.active_window(), |(v, _)| v)
951}
952
953fn keep_focused(app: &AppHandle, scope: ScopeId) {
955 let window = window_of(app);
956 let kept = app.local::<Kept>();
957 let mut last = kept.last_focused.borrow_mut();
958 last.retain(|(w, _)| *w != window);
959 last.push((window, scope));
960}
961
962fn shown(app: &AppHandle) -> Vec<String> {
964 focus::scopes(&app.egui())
965 .into_iter()
966 .map(|r| r.name)
967 .collect()
968}
969
970fn is_active(info: &ScopeInfo, shown: &[String]) -> bool {
973 info.focus.is_empty()
974 || info
975 .focus
976 .iter()
977 .any(|f| shown.iter().any(|s| crate::app::names_surface(f, s)))
978}
979
980fn active_lines(app: &AppHandle) -> Vec<Line> {
983 let shown = shown(app);
984 with_owner(app, |h| {
985 h.scopes()
986 .iter()
987 .filter(|s| is_active(s, &shown))
988 .filter_map(|s| h.tips(&s.id))
989 .collect()
990 })
991 .unwrap_or_default()
992}
993
994pub fn hover(app: &AppHandle, scope: &ScopeId, at: At) -> Option<Preview> {
1001 hovered(app, None, scope, at)
1002}
1003
1004pub fn hover_in(app: &AppHandle, view: egui::Id, scope: &ScopeId, at: At) -> Option<Preview> {
1008 hovered(app, Some(view), scope, at)
1009}
1010
1011pub fn rows_drawn(app: &AppHandle, view: egui::Id) {
1017 let ctx = app.egui();
1018 let left = app
1019 .local::<Kept>()
1020 .previewing
1021 .borrow()
1022 .as_ref()
1023 .is_some_and(|p| p.view == Some(view) && p.pass != ctx.cumulative_pass_nr());
1024 if left {
1025 end_preview(app);
1026 ctx.request_repaint();
1028 }
1029}
1030
1031fn hovered(app: &AppHandle, view: Option<egui::Id>, scope: &ScopeId, at: At) -> Option<Preview> {
1032 let kept = app.local::<Kept>();
1033 let pass = app.egui().cumulative_pass_nr();
1034 if let Some(p) = kept.previewing.borrow_mut().as_mut()
1035 && p.scope == *scope
1036 && p.at == at
1037 {
1038 p.pass = pass;
1039 p.view = view;
1040 return p.answer.clone();
1041 }
1042 let before = kept.previewing.borrow_mut().take();
1043 if let Some(b) = before
1044 && b.scope != *scope
1045 {
1046 preview(app, &b.scope, None);
1047 }
1048 let answer = preview(app, scope, Some(at));
1049 *kept.previewing.borrow_mut() = Some(Previewing {
1050 scope: scope.clone(),
1051 at,
1052 answer: answer.clone(),
1053 pass,
1054 view,
1055 });
1056 answer
1057}
1058
1059pub fn previewing(app: &AppHandle) -> Option<(ScopeId, At)> {
1061 let kept = app.local::<Kept>();
1062 let p = kept.previewing.borrow();
1063 p.as_ref().map(|p| (p.scope.clone(), p.at))
1064}
1065
1066pub fn end_preview(app: &AppHandle) {
1069 let before = app.local::<Kept>().previewing.borrow_mut().take();
1070 if let Some(b) = before {
1071 preview(app, &b.scope, None);
1072 }
1073}
1074
1075pub fn active(app: &AppHandle) -> Vec<ScopeId> {
1077 let shown = shown(app);
1078 with_owner(app, |h| {
1079 h.scopes()
1080 .into_iter()
1081 .filter(|s| is_active(s, &shown))
1082 .map(|s| s.id)
1083 .collect()
1084 })
1085 .unwrap_or_default()
1086}
1087
1088pub fn target(app: &AppHandle, redo: bool) -> Option<Target> {
1093 if let Some(l) = focused_local(app) {
1094 return Some(Target::Local(l));
1095 }
1096 if egui_pop_core::overlay::modal_open(&app.egui()) {
1099 return None;
1100 }
1101 let (picked, rule) = match routing(app) {
1102 Routing::Newest => (by_newest(app, &active_lines(app), redo), "newest"),
1103 Routing::Focus => by_focus(app),
1104 };
1105 app.local::<Kept>().rule.set(rule);
1106 hooked(app, picked, redo, rule)
1107}
1108
1109fn by_focus(app: &AppHandle) -> (Option<ScopeId>, &'static str) {
1114 if let Some(s) = focused_scope(app) {
1115 keep_focused(app, s.clone());
1116 return (Some(s), "focus");
1117 }
1118 let sticky = last_focused(app)
1119 .filter(|s| with_owner(app, |h| h.scopes().iter().any(|i| i.id == *s)).unwrap_or(false));
1120 match sticky {
1121 Some(s) => (Some(s), "last_focused"),
1122 None => (None, NOTHING_FOCUSED),
1123 }
1124}
1125
1126pub fn needs_view(app: &AppHandle, redo: bool) -> bool {
1132 if routing(app) != Routing::Focus
1133 || focused_local(app).is_some()
1134 || egui_pop_core::overlay::modal_open(&app.egui())
1135 || by_focus(app).1 != NOTHING_FOCUSED
1136 {
1137 return false;
1138 }
1139 with_owner(app, |h| {
1140 h.scopes().iter().any(|s| {
1141 h.tips(&s.id).is_some_and(|l| {
1142 if redo {
1143 l.next().is_some()
1144 } else {
1145 l.head().is_some()
1146 }
1147 })
1148 })
1149 })
1150 .unwrap_or(false)
1151}
1152
1153fn say_nothing_focused(app: &AppHandle, redo: bool, origin: &Origin) {
1158 let ctx = app.egui();
1159 let key = if redo {
1160 &crate::strings::HISTORY_NOTHING_FOCUSED_REDO
1161 } else {
1162 &crate::strings::HISTORY_NOTHING_FOCUSED
1163 };
1164 let text = strings::tr(&ctx, key);
1165 if matches!(origin, Origin::User | Origin::Device(_)) {
1168 if let Some(t) = app.service(&crate::toasts::TOASTS) {
1169 t.notify(crate::toasts::Toast::info(&text));
1170 }
1171 egui_pop_core::a11y::announce(&ctx, text.clone(), egui_pop_core::a11y::Politeness::Polite);
1172 }
1173 app.publish(
1174 &source_of(origin),
1175 None,
1176 "history.refused",
1177 json!({ "scope": Json::Null, "kind": "nothing_focused", "reason": text, "redo": redo }),
1178 );
1179}
1180
1181fn hooked(
1184 app: &AppHandle,
1185 picked: Option<ScopeId>,
1186 redo: bool,
1187 rule: &'static str,
1188) -> Option<Target> {
1189 let args = json!({ "scope": picked, "redo": redo, "rule": rule });
1190 let out = app.step_with(&STEP_TARGET, args, true, |_, args| Ok(args.clone()));
1191 let scope = match out {
1192 Outcome::Done(Ok(v)) => v
1193 .get("scope")
1194 .and_then(Json::as_str)
1195 .and_then(|s| ScopeId::new(s).ok()),
1196 Outcome::Vetoed { .. } => None,
1198 Outcome::Done(Err(_)) => picked,
1199 }?;
1200 Some(scope_target(app, &scope).unwrap_or(Target::Owner(scope)))
1201}
1202
1203fn by_newest(app: &AppHandle, lines: &[Line], redo: bool) -> Option<ScopeId> {
1207 if !redo {
1208 return newest(lines)
1209 .cloned()
1210 .or_else(|| lines.first().and_then(scope_of));
1211 }
1212 let undone = app.local::<Kept>().undone.borrow().clone();
1213 let can = |s: &ScopeId| {
1214 lines
1215 .iter()
1216 .any(|l| l.next().is_some_and(|n| n.scope == *s))
1217 };
1218 undone
1219 .iter()
1220 .rev()
1221 .find(|s| can(s))
1222 .cloned()
1223 .or_else(|| lines.iter().find_map(|l| l.next().map(|n| n.scope.clone())))
1224 .or_else(|| lines.first().and_then(scope_of))
1225}
1226
1227fn scope_of(line: &Line) -> Option<ScopeId> {
1228 line.undo
1229 .first()
1230 .or(line.redo.first())
1231 .map(|s| s.scope.clone())
1232}
1233
1234pub fn scope_target(app: &AppHandle, scope: &ScopeId) -> Option<Target> {
1236 let kept = app.local::<Kept>();
1237 if let Some(l) = kept
1238 .locals
1239 .borrow()
1240 .iter()
1241 .find(|(_, _, l)| l.info().id == *scope)
1242 {
1243 return Some(Target::Local(l.2.clone()));
1244 }
1245 with_owner(app, |h| h.scopes().iter().any(|s| s.id == *scope))
1246 .unwrap_or(false)
1247 .then(|| Target::Owner(scope.clone()))
1248}
1249
1250pub fn scopes(app: &AppHandle) -> Vec<ScopeInfo> {
1252 let mut out: Vec<ScopeInfo> = app
1253 .local::<Kept>()
1254 .locals
1255 .borrow()
1256 .iter()
1257 .map(|(_, _, l)| l.info())
1258 .collect();
1259 out.extend(with_owner(app, |h| h.scopes()).unwrap_or_default());
1260 out
1261}
1262
1263pub fn line(app: &AppHandle, scope: &ScopeId) -> Option<Line> {
1265 scope_target(app, scope)?.line(app)
1266}
1267
1268pub fn can_undo(app: &AppHandle) -> bool {
1270 head_label(app, false).is_some()
1271}
1272
1273pub fn can_redo(app: &AppHandle) -> bool {
1275 head_label(app, true).is_some()
1276}
1277
1278pub fn undo_label(app: &AppHandle) -> Option<String> {
1280 head_label(app, false)
1281}
1282
1283pub fn redo_label(app: &AppHandle) -> Option<String> {
1285 head_label(app, true)
1286}
1287
1288fn head_label(app: &AppHandle, redo: bool) -> Option<String> {
1289 let line = match target(app, redo)? {
1290 Target::Owner(s) => with_owner(app, |h| h.tips(&s)).flatten()?,
1291 t @ Target::Local(_) => t.line(app)?,
1292 };
1293 let step = if redo { line.next() } else { line.head() }?;
1294 Some(label_text(&app.egui(), &step.label))
1295}
1296
1297pub fn label_text(ctx: &egui::Context, label: &Label) -> String {
1300 match &label.key {
1301 Some(key) => {
1302 let args: Vec<(&str, &str)> = label
1303 .args
1304 .iter()
1305 .map(|(k, v)| (k.as_str(), v.as_str()))
1306 .collect();
1307 strings::lookup_args(ctx, key, &label.text, &args)
1308 }
1309 None => label.text.clone(),
1310 }
1311}
1312
1313#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1316pub enum Walk {
1317 Undo,
1318 Redo,
1319 Jump(u64),
1320 Restore(u64),
1322 UndoStep(u64),
1324}
1325
1326fn walk(
1328 app: &AppHandle,
1329 target: &Target,
1330 what: Walk,
1331 request: &Request,
1332 origin: &Origin,
1333) -> Result<Option<Walked>, Refusal> {
1334 match target {
1335 Target::Owner(scope) => {
1336 let mut request = request.clone();
1337 request.scope = scope.clone();
1338 let answer = with_owner(app, |h| {
1339 if let Some(label) = h.in_progress(scope) {
1340 return Answer::Done(Err(in_progress(&label.text)));
1341 }
1342 match what {
1343 Walk::Undo => h.undo(&request, origin),
1344 Walk::Redo => h.redo(&request, origin),
1345 Walk::Jump(to) => h.jump(&request, to, origin),
1346 Walk::Restore(id) => h.restore(&request, id, origin),
1347 Walk::UndoStep(id) => h.undo_step(&request, id, origin),
1348 }
1349 })
1350 .ok_or_else(|| Refusal::new(RefusalKind::Owner, "the host is dispatching a command"))?;
1351 match answer {
1352 Answer::Done(r) => r.map(Some),
1353 Answer::Later(_) => Ok(None),
1354 }
1355 }
1356 Target::Local(l) => {
1357 let info = l.info();
1358 let line = l.line(app);
1359 request.check(line.rev)?;
1360 if let Some(label) = l.in_progress(app) {
1361 return Err(in_progress(&label.text));
1362 }
1363 let (redo, count) = match what {
1364 Walk::Undo => (false, usize::from(line.head().is_some())),
1365 Walk::Redo => (true, usize::from(line.next().is_some())),
1366 Walk::Jump(to) => {
1367 let j = plan_jump(&line, to)?;
1368 (j.redo, j.count)
1369 }
1370 Walk::Restore(_) => return Err(unsupported(&info.id, "snapshots")),
1371 Walk::UndoStep(_) => return Err(unsupported(&info.id, "undoing one step")),
1372 };
1373 let mut steps = Vec::new();
1374 if request.dry_run {
1375 steps = walked_by(&line, Jump { redo, count });
1376 } else {
1377 for _ in 0..count {
1378 let step = if redo {
1379 l.redo(app, origin)?
1380 } else {
1381 l.undo(app, origin)?
1382 };
1383 match step {
1384 Some(s) => steps.push(s),
1385 None => break,
1386 }
1387 }
1388 }
1389 let after = l.line(app);
1390 Ok(Some(Walked {
1391 scope: info.id,
1392 steps,
1393 rev: after.rev,
1394 head: after.head_id(),
1395 dry_run: request.dry_run,
1396 }))
1397 }
1398 }
1399}
1400
1401pub fn undo(app: &AppHandle, origin: &Origin) -> Outcome {
1403 let t = target(app, false);
1404 if t.is_none() && app.local::<Kept>().rule.get() == NOTHING_FOCUSED {
1405 say_nothing_focused(app, false, origin);
1406 }
1407 run(app, t, Walk::Undo, None, origin)
1408}
1409
1410pub fn redo(app: &AppHandle, origin: &Origin) -> Outcome {
1412 let t = target(app, true);
1413 if t.is_none() && app.local::<Kept>().rule.get() == NOTHING_FOCUSED {
1414 say_nothing_focused(app, true, origin);
1415 }
1416 run(app, t, Walk::Redo, None, origin)
1417}
1418
1419pub fn undo_in(app: &AppHandle, scope: &ScopeId, origin: &Origin) -> Outcome {
1421 let t = scope_target(app, scope).unwrap_or_else(|| Target::Owner(scope.clone()));
1422 run(app, Some(t), Walk::Undo, None, origin)
1423}
1424
1425pub fn redo_in(app: &AppHandle, scope: &ScopeId, origin: &Origin) -> Outcome {
1427 let t = scope_target(app, scope).unwrap_or_else(|| Target::Owner(scope.clone()));
1428 run(app, Some(t), Walk::Redo, None, origin)
1429}
1430
1431pub fn jump(app: &AppHandle, scope: &ScopeId, to: u64, origin: &Origin) -> Outcome {
1434 let t = scope_target(app, scope).unwrap_or_else(|| Target::Owner(scope.clone()));
1435 run(app, Some(t), Walk::Jump(to), None, origin)
1436}
1437
1438pub fn restore(app: &AppHandle, scope: &ScopeId, snapshot: u64, origin: &Origin) -> Outcome {
1441 let t = scope_target(app, scope).unwrap_or_else(|| Target::Owner(scope.clone()));
1442 run(app, Some(t), Walk::Restore(snapshot), None, origin)
1443}
1444
1445pub fn undo_step(app: &AppHandle, scope: &ScopeId, step: u64, origin: &Origin) -> Outcome {
1448 let t = scope_target(app, scope).unwrap_or_else(|| Target::Owner(scope.clone()));
1449 run(app, Some(t), Walk::UndoStep(step), None, origin)
1450}
1451
1452pub fn features(app: &AppHandle, scope: &ScopeId) -> Features {
1454 match scope_target(app, scope) {
1455 Some(Target::Owner(s)) => with_owner(app, |h| h.features(&s)).unwrap_or_default(),
1456 _ => Features::default(),
1457 }
1458}
1459
1460pub fn snapshots(app: &AppHandle, scope: &ScopeId) -> Vec<Snapshot> {
1462 match scope_target(app, scope) {
1463 Some(Target::Owner(s)) => with_owner(app, |h| h.snapshots(&s)).unwrap_or_default(),
1464 _ => Vec::new(),
1465 }
1466}
1467
1468pub fn replaced(app: &AppHandle, scope: &ScopeId) -> Vec<Replaced> {
1470 match scope_target(app, scope) {
1471 Some(Target::Owner(s)) => with_owner(app, |h| h.replaced(&s)).unwrap_or_default(),
1472 _ => Vec::new(),
1473 }
1474}
1475
1476pub fn take_snapshot(
1481 app: &AppHandle,
1482 scope: Option<&ScopeId>,
1483 name: &str,
1484 if_rev: Option<u64>,
1485 dry_run: bool,
1486 origin: &Origin,
1487) -> Result<Snapshot, Refusal> {
1488 let scope = owner_scope(app, scope)?;
1489 let request = Request {
1490 scope: scope.clone(),
1491 if_rev,
1492 dry_run,
1493 };
1494 let taken = with_owner(app, |h| h.snapshot(&request, name, origin)).ok_or_else(busy)?;
1495 match &taken {
1496 Ok(snap) if !dry_run => app.publish(
1497 &source_of(origin),
1498 None,
1499 "history.snapshot_taken",
1500 json!({ "scope": scope, "snapshot": snap.id, "name": snap.name }),
1501 ),
1502 Ok(_) => {}
1503 Err(r) => refused_published(app, origin, &scope, r),
1504 }
1505 taken
1506}
1507
1508pub fn forget_snapshot(
1511 app: &AppHandle,
1512 scope: Option<&ScopeId>,
1513 snapshot: u64,
1514 if_rev: Option<u64>,
1515 dry_run: bool,
1516 origin: &Origin,
1517) -> Result<(), Refusal> {
1518 let scope = owner_scope(app, scope)?;
1519 let request = Request {
1520 scope: scope.clone(),
1521 if_rev,
1522 dry_run,
1523 };
1524 let done = with_owner(app, |h| h.forget(&request, snapshot)).ok_or_else(busy)?;
1525 match &done {
1526 Ok(()) if !dry_run => app.publish(
1527 &source_of(origin),
1528 None,
1529 "history.snapshot_deleted",
1530 json!({ "scope": scope, "snapshot": snapshot }),
1531 ),
1532 Ok(()) => {}
1533 Err(r) => refused_published(app, origin, &scope, r),
1534 }
1535 done
1536}
1537
1538pub fn preview(app: &AppHandle, scope: &ScopeId, at: Option<At>) -> Option<Preview> {
1541 match scope_target(app, scope) {
1542 Some(Target::Owner(s)) => with_owner(app, |h| h.preview(&s, at)).flatten(),
1543 _ => None,
1544 }
1545}
1546
1547fn owner_scope(app: &AppHandle, scope: Option<&ScopeId>) -> Result<ScopeId, Refusal> {
1550 let t = match scope {
1551 Some(s) => scope_target(app, s).ok_or_else(|| unknown(s))?,
1552 None => {
1553 target(app, false).ok_or_else(|| Refusal::new(RefusalKind::Nothing, "no history"))?
1554 }
1555 };
1556 match t {
1557 Target::Owner(s) => Ok(s),
1558 Target::Local(l) => Err(unsupported(&l.info().id, "snapshots")),
1559 }
1560}
1561
1562fn busy() -> Refusal {
1563 Refusal::new(RefusalKind::Owner, "the host is dispatching a command")
1564}
1565
1566fn refused_published(app: &AppHandle, origin: &Origin, scope: &ScopeId, r: &Refusal) {
1567 app.publish(
1568 &source_of(origin),
1569 None,
1570 "history.refused",
1571 json!({ "scope": scope, "kind": r.kind, "reason": r.reason }),
1572 );
1573}
1574
1575pub fn ask(
1581 app: &AppHandle,
1582 what: Walk,
1583 scope: Option<&ScopeId>,
1584 if_rev: Option<u64>,
1585 dry_run: bool,
1586 origin: &Origin,
1587) -> Outcome {
1588 let t = match scope {
1589 Some(s) => Some(scope_target(app, s).unwrap_or_else(|| Target::Owner(s.clone()))),
1590 None => target(app, what == Walk::Redo),
1591 };
1592 let request = Request {
1593 scope: t.as_ref().map_or(APP, Target::scope),
1594 if_rev,
1595 dry_run,
1596 };
1597 run(app, t, what, Some(request), origin)
1598}
1599
1600fn run(
1603 app: &AppHandle,
1604 target: Option<Target>,
1605 what: Walk,
1606 asked: Option<Request>,
1607 origin: &Origin,
1608) -> Outcome {
1609 let (if_rev, dry_run) = asked.map_or((None, false), |r| (r.if_rev, r.dry_run));
1610 let (step, key, done, failed) = match what {
1611 Walk::Undo => (&STEP_UNDO, "undone", "edit.undone", "edit.undo_failed"),
1612 Walk::Redo => (&STEP_REDO, "redone", "edit.redone", "edit.redo_failed"),
1613 Walk::Jump(_) => (&STEP_JUMP, "jumped", "edit.jumped", "edit.jump_failed"),
1614 Walk::Restore(_) => (
1615 &STEP_RESTORE,
1616 "restored",
1617 "edit.restored",
1618 "edit.restore_failed",
1619 ),
1620 Walk::UndoStep(_) => (
1621 &STEP_UNDO_STEP,
1622 "undone",
1623 "edit.step_undone",
1624 "edit.undo_step_failed",
1625 ),
1626 };
1627 let ctx = app.egui();
1628 let line = target.as_ref().and_then(|t| t.line(app));
1629 let label = match what {
1630 Walk::Restore(id) => target
1631 .as_ref()
1632 .map(Target::scope)
1633 .and_then(|s| snapshots(app, &s).into_iter().find(|x| x.id == id))
1634 .map(|x| x.name),
1635 _ => line
1636 .as_ref()
1637 .and_then(|l| match what {
1638 Walk::Undo => l.head(),
1639 Walk::Redo => l.next(),
1640 Walk::UndoStep(id) => l.undo.iter().find(|s| s.id == id),
1641 _ => None,
1642 })
1643 .map(|s| label_text(&ctx, &s.label)),
1644 };
1645 let scope = target.as_ref().map(Target::scope);
1646 let mut args = json!({
1647 "label": label,
1648 "origin": source_of(origin),
1649 "scope": scope,
1650 });
1651 match what {
1652 Walk::Jump(to) => args["to"] = json!(to),
1653 Walk::Restore(id) => args["snapshot"] = json!(id),
1654 Walk::UndoStep(id) => args["step"] = json!(id),
1655 Walk::Undo | Walk::Redo => {}
1656 }
1657 if let Some(rev) = if_rev {
1658 args["if_rev"] = json!(rev);
1659 }
1660 if dry_run {
1661 args["dry_run"] = json!(true);
1662 }
1663 let refusal: Rc<RefCell<Option<Refusal>>> = Rc::default();
1664 let walked: Rc<RefCell<Option<Walked>>> = Rc::default();
1665 let (r2, w2) = (refusal.clone(), walked.clone());
1666 let who = origin.clone();
1667 let outcome = app.step(step, args, move |app, args| {
1668 let asked = args
1670 .get("scope")
1671 .and_then(Json::as_str)
1672 .and_then(|s| ScopeId::new(s).ok());
1673 let target = match (&asked, target) {
1674 (Some(a), Some(t)) if t.scope() == *a => Some(t),
1675 (Some(a), _) => scope_target(app, a),
1676 (None, t) => t,
1677 };
1678 let Some(target) = target else {
1679 return Ok(json!({ key: Json::Null }));
1680 };
1681 let mut request = Request::new(target.scope());
1682 request.if_rev = if_rev;
1683 request.dry_run = dry_run;
1684 match walk(app, &target, what, &request, &who) {
1685 Ok(Some(w)) => {
1686 let name = w.steps.last().map(|s| label_text(&app.egui(), &s.label));
1687 let skipped = lock(&app.store()).take_skipped_in(&w.scope);
1690 let mut out = json!({
1691 key: name,
1692 "scope": w.scope,
1693 "steps": w.steps,
1694 "rev": w.rev,
1695 "head": w.head,
1696 });
1697 if w.dry_run {
1698 out["dry_run"] = json!(true);
1699 }
1700 if !skipped.is_empty() {
1701 out["skipped"] = json!(skipped);
1702 }
1703 *w2.borrow_mut() = Some(w);
1704 Ok(out)
1705 }
1706 Ok(None) => Ok(json!({ key: Json::Null, "scope": target.scope(), "pending": true })),
1707 Err(r) => {
1708 let reason = r.reason.clone();
1709 *r2.borrow_mut() = Some(r);
1710 Err(reason)
1711 }
1712 }
1713 });
1714 let source = source_of(origin);
1715 let skipped: Vec<String> = match &outcome {
1716 Outcome::Done(Ok(v)) => serde_json::from_value(v["skipped"].clone()).unwrap_or_default(),
1717 _ => Vec::new(),
1718 };
1719 match &outcome {
1720 Outcome::Done(Ok(v)) => {
1721 if !v[key].is_null() && !dry_run {
1722 app.publish(
1723 &source,
1724 None,
1725 done,
1726 json!({ "label": v[key], "scope": v["scope"] }),
1727 );
1728 }
1729 }
1730 Outcome::Done(Err(e)) => {
1731 app.publish(&source, None, failed, json!({ "label": label, "error": e }));
1732 }
1733 Outcome::Vetoed { by, reason } => {
1734 app.publish(
1735 &source,
1736 None,
1737 failed,
1738 json!({ "label": label, "vetoed_by": by, "reason": reason }),
1739 );
1740 *refusal.borrow_mut() = Some(Refusal::new(RefusalKind::Vetoed, reason.clone()));
1741 }
1742 }
1743 if let Some(r) = refusal.borrow_mut().take() {
1744 app.publish(
1745 &source,
1746 None,
1747 "history.refused",
1748 json!({ "scope": scope, "kind": r.kind, "reason": r.reason }),
1749 );
1750 }
1751 if let Some(w) = walked.borrow_mut().take()
1752 && !w.dry_run
1753 && !w.steps.is_empty()
1754 {
1755 let kept = app.local::<Kept>();
1756 {
1757 let mut undone = kept.undone.borrow_mut();
1758 undone.retain(|s| *s != w.scope);
1759 if matches!(what, Walk::Undo | Walk::Jump(_)) {
1760 undone.push(w.scope.clone());
1761 }
1762 }
1763 kept.revs.borrow_mut().insert(w.scope.clone(), w.rev);
1764 changed(app, &w.scope, w.rev, w.head, &skipped);
1765 }
1766 outcome
1767}
1768
1769fn changed(app: &AppHandle, scope: &ScopeId, rev: u64, head: u64, skipped: &[String]) {
1773 let mut data = json!({ "scope": scope, "rev": rev, "head": head });
1774 if !skipped.is_empty() {
1775 data["skipped"] = json!(skipped);
1776 }
1777 app.publish("egui_pop", None, "history.changed", data);
1778}
1779
1780pub(crate) fn pass(app: &AppHandle) {
1784 let ctx = app.egui();
1785 let kept = app.local::<Kept>();
1786 let store = app.store();
1787 {
1788 let mut clock = kept.clock.borrow_mut();
1789 let mut s = lock(&store);
1790 if clock.is_none() && !s.has_clock() {
1791 let c = ManualClock::default();
1792 s.set_clock(Some(c.shared()));
1793 *clock = Some(c);
1794 }
1795 if let Some(c) = clock.as_ref() {
1796 c.set(ctx.input(|i| i.time));
1797 }
1798 let focused = focus::focused(&ctx);
1799 if kept.focused.replace(focused) != focused {
1800 s.seal();
1801 }
1802 }
1803 if kept.routing.get() == Routing::Focus
1807 && let Some(s) = focused_scope(app)
1808 {
1809 keep_focused(app, s);
1810 }
1811 let mut skipped: BTreeMap<ScopeId, Vec<String>> = BTreeMap::new();
1813 for s in lock(&store).take_skipped() {
1814 skipped.entry(s.history).or_default().push(s.path);
1815 }
1816 let moved: Vec<(ScopeId, u64, u64)> = {
1817 let revs = kept.revs.borrow();
1818 with_owner(app, |h| {
1819 h.scopes()
1820 .into_iter()
1821 .filter_map(|s| {
1822 let rev = h.rev(&s.id);
1823 (revs.get(&s.id).copied().unwrap_or(0) != rev || skipped.contains_key(&s.id))
1824 .then(|| (s.id.clone(), rev, h.line(&s.id).map_or(0, |l| l.head_id())))
1825 })
1826 .collect()
1827 })
1828 .unwrap_or_default()
1829 };
1830 for (id, rev, head) in moved {
1831 kept.revs.borrow_mut().insert(id.clone(), rev);
1832 let paths = skipped.remove(&id).unwrap_or_default();
1833 changed(app, &id, rev, head, &paths);
1834 }
1835 for (id, paths) in skipped {
1838 let (rev, head) = {
1839 let s = lock(&store);
1840 (s.history_rev(&id), store_line(&s, &id).head_id())
1841 };
1842 changed(app, &id, rev, head, &paths);
1843 }
1844 let stale = kept
1850 .previewing
1851 .borrow()
1852 .as_ref()
1853 .is_some_and(|p| p.pass + 1 < ctx.cumulative_pass_nr());
1854 if stale {
1855 end_preview(app);
1856 }
1857}
1858
1859pub(crate) fn snapshot(app: &AppHandle) -> Json {
1862 let active = active(app);
1863 let scopes: Vec<Json> = scopes(app)
1864 .into_iter()
1865 .map(|s| {
1866 let l = line(app, &s.id).unwrap_or_default();
1867 json!({
1868 "scope": s,
1869 "active": s.local || active.contains(&s.id),
1870 "rev": l.rev,
1871 "head": l.head_id(),
1872 "undo": l.undo.len(),
1873 "redo": l.redo.len(),
1874 })
1875 })
1876 .collect();
1877 json!({
1878 "can_undo": can_undo(app),
1879 "undo": undo_label(app),
1880 "undo_scope": target(app, false).map(|t| t.scope()),
1881 "can_redo": can_redo(app),
1882 "redo": redo_label(app),
1883 "redo_scope": target(app, true).map(|t| t.scope()),
1884 "routing": routing(app),
1885 "last_focused": last_focused(app),
1886 "scopes": scopes,
1887 })
1888}