1use egui::{RichText, Ui};
64use egui_pop_core::state::Slot;
65use egui_pop_core::strings;
66use egui_pop_core::theme::Tokens;
67use egui_pop_core::ui::UiPop as _;
68use egui_pop_core::widgets;
69use egui_pop_model::commands::{CommandSpec, Origin};
70use egui_pop_model::ids::{CommandId, PanelId, PluginId};
71use egui_pop_model::panels::{Area, PanelSpec};
72use serde_json::{Value as Json, json};
73
74use crate::app::AppHandle;
75use crate::history::{self, At, Line, ScopeId, StepInfo, Walk};
76use crate::host::source_of;
77use crate::steps::Outcome;
78use crate::strings as txt;
79use crate::toasts;
80use crate::{Ctx, Plugin, PluginError};
81
82pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.history");
84
85pub const PANEL_HISTORY: PanelId = PanelId::from_static("egui_pop.history");
87
88pub const CMD_LIST: CommandId = CommandId::from_static("history.list");
90pub const CMD_READ: CommandId = CommandId::from_static("history.read");
92pub const CMD_UNDO: CommandId = CommandId::from_static("history.undo");
94pub const CMD_REDO: CommandId = CommandId::from_static("history.redo");
96pub const CMD_JUMP: CommandId = CommandId::from_static("history.jump");
98pub const CMD_SNAPSHOT: CommandId = CommandId::from_static("history.snapshot");
100pub const CMD_RESTORE: CommandId = CommandId::from_static("history.restore");
102pub const CMD_DROP_SNAPSHOT: CommandId = CommandId::from_static("history.drop_snapshot");
104pub const CMD_UNDO_STEP: CommandId = CommandId::from_static("history.undo_step");
106
107const CHOSEN: Slot<ScopeId> = Slot::new("egui_pop.history.scope");
109
110const SHOW_REPLACED: Slot<bool> = Slot::new("egui_pop.history.replaced");
112
113#[derive(Clone, Debug)]
115pub struct HistoryPlugin {
116 panel: bool,
117}
118
119impl Default for HistoryPlugin {
120 fn default() -> Self {
121 Self { panel: true }
122 }
123}
124
125impl HistoryPlugin {
126 pub fn without_panel(mut self) -> Self {
129 self.panel = false;
130 self
131 }
132}
133
134impl Plugin for HistoryPlugin {
135 fn id(&self) -> PluginId {
136 PLUGIN
137 }
138
139 fn title(&self) -> String {
140 "History".into()
141 }
142
143 fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
144 let category = "Edit";
145 ctx.command(
146 CommandSpec::new(CMD_LIST, "List the histories", category)
147 .description("Every history (its scope: id, title, whether it is local or durable, its cap), whether it is active in the window, its revision, head and counts, and where Undo and Redo go now with what they would do.")
148 .hidden()
149 .read_only(),
150 |call| Ok(history::snapshot(call.app)),
151 )?
152 .command(
153 CommandSpec::new(CMD_READ, "Read a history", category)
154 .description("A history's steps (`scope`; none: where Undo goes now): `undo`, oldest first, and `redo`, the next one last; each step's id, label and its text in the interface's language, origin, group, place and time; the history's revision and head; its `snapshots`, the `replaced` steps its owner keeps (each with the step it came `after`) and the `features` its owner supports.")
155 .args(json!({ "scope": "app" }))
156 .hidden()
157 .read_only(),
158 |call| {
159 let scope = scope_arg(call.app, call.args, Walk::Undo)?;
160 let line = history::line(call.app, &scope)
161 .ok_or_else(|| format!("no history `{scope}`"))?;
162 Ok(read(call.app, &scope, &line))
163 },
164 )?
165 .command(
166 CommandSpec::new(CMD_UNDO, "Undo in a history", category)
167 .icon("undo")
168 .description("Undoes the last step of a history (`scope`; none: where Undo goes now), refused unless its revision is still `if_rev`; with `dry_run`, only says what it would undo.")
169 .args(json!({ "scope": "app", "if_rev": null, "dry_run": false }))
170 .hidden(),
171 |call| walk(call.app, call.args, Walk::Undo, call.origin),
172 )?
173 .command(
174 CommandSpec::new(CMD_REDO, "Redo in a history", category)
175 .icon("redo")
176 .description("Redoes the last undone step of a history (`scope`; none: where Redo goes now), refused unless its revision is still `if_rev`; with `dry_run`, only says what it would redo.")
177 .args(json!({ "scope": "app", "if_rev": null, "dry_run": false }))
178 .hidden(),
179 |call| walk(call.app, call.args, Walk::Redo, call.origin),
180 )?
181 .command(
182 CommandSpec::new(CMD_JUMP, "Jump in a history", category)
183 .icon("history")
184 .description("Brings a history (`scope`) to one of its steps (`to`, its id; 0: the start) by undos or redos, all or nothing, refused unless its revision is still `if_rev`; with `dry_run`, only says which steps it would walk.")
185 .args(json!({ "scope": "app", "to": 0, "if_rev": null, "dry_run": false }))
186 .hidden(),
187 |call| {
188 let to = call.args["to"]
189 .as_u64()
190 .ok_or_else(|| "`to` is missing: a step's id, or 0".to_string())?;
191 walk(call.app, call.args, Walk::Jump(to), call.origin)
192 },
193 )?
194 .command(
195 CommandSpec::new(CMD_SNAPSHOT, "Take a snapshot", category)
196 .description("Pins a history's current state (`scope`; none: where Undo goes now) under `name` (none: numbered), refused unless its revision is still `if_rev`, or when its owner has no snapshots; with `dry_run`, only says what it would take.")
197 .args(json!({ "scope": "app", "name": "Before the agent", "if_rev": null, "dry_run": false }))
198 .hidden(),
199 |call| {
200 let (scope, if_rev, dry_run) = request_args(call.args)?;
201 let name = match call.args.get("name").and_then(Json::as_str) {
202 Some(n) => n.to_string(),
203 None => next_name(call.app, scope.as_ref()),
204 };
205 let snap = history::take_snapshot(
206 call.app,
207 scope.as_ref(),
208 &name,
209 if_rev,
210 dry_run,
211 call.origin,
212 )
213 .map_err(|r| r.reason)?;
214 let mut out = json!({ "snapshot": snap });
215 if dry_run {
216 out["dry_run"] = json!(true);
217 }
218 Ok(out)
219 },
220 )?
221 .command(
222 CommandSpec::new(CMD_RESTORE, "Restore a snapshot", category)
223 .description("Brings a history (`scope`; none: where Undo goes now) back to one of its snapshots (`snapshot`, its id) as one new step an undo takes back, refused unless its revision is still `if_rev`; with `dry_run`, only says what it would change.")
224 .args(json!({ "scope": "app", "snapshot": 1, "if_rev": null, "dry_run": false }))
225 .hidden(),
226 |call| {
227 let id = id_arg(call.args, "snapshot", "a snapshot's id")?;
228 walk(call.app, call.args, Walk::Restore(id), call.origin)
229 },
230 )?
231 .command(
232 CommandSpec::new(CMD_DROP_SNAPSHOT, "Delete a snapshot", category)
233 .description("Deletes one of a history's snapshots (`scope`; none: where Undo goes now; `snapshot`, its id), refused unless its revision is still `if_rev`; with `dry_run`, only checks it is there.")
234 .args(json!({ "scope": "app", "snapshot": 1, "if_rev": null, "dry_run": false }))
235 .hidden(),
236 |call| {
237 let id = id_arg(call.args, "snapshot", "a snapshot's id")?;
238 let (scope, if_rev, dry_run) = request_args(call.args)?;
239 history::forget_snapshot(call.app, scope.as_ref(), id, if_rev, dry_run, call.origin)
240 .map_err(|r| r.reason)?;
241 Ok(json!({ "deleted": id, "dry_run": dry_run }))
242 },
243 )?
244 .command(
245 CommandSpec::new(CMD_UNDO_STEP, "Undo one step", category)
246 .description("Undoes one step of a history (`scope`; none: where Undo goes now; `step`, its id) out of order: the newest as an undo does, an older one by a new step putting its values back, refused when a later step changed one of them or when its owner does not allow it, and unless its revision is still `if_rev`; with `dry_run`, only checks it.")
247 .args(json!({ "scope": "app", "step": 3, "if_rev": null, "dry_run": false }))
248 .hidden(),
249 |call| {
250 let id = id_arg(call.args, "step", "a step's id")?;
251 walk(call.app, call.args, Walk::UndoStep(id), call.origin)
252 },
253 )?;
254 if self.panel {
255 ctx.panel(
256 PanelSpec::new(PANEL_HISTORY, "History", Area::EndSide)
257 .min_size(160.0)
258 .default_size(240.0)
259 .icon("history")
260 .closed(),
261 |ui, app| {
262 ui.scroll_area(
263 egui::ScrollArea::vertical().auto_shrink([false, false]),
264 |ui| show(ui, app),
265 );
266 },
267 )?;
268 }
269 Ok(())
270 }
271}
272
273fn scope_arg(app: &AppHandle, args: &Json, what: Walk) -> Result<ScopeId, String> {
275 match args.get("scope").and_then(Json::as_str) {
276 Some(s) => ScopeId::new(s).map_err(|e| format!("`scope`: {e}")),
277 None => history::target(app, what == Walk::Redo)
278 .map(|t| t.scope())
279 .ok_or_else(|| "no history to read".to_string()),
280 }
281}
282
283fn request_args(args: &Json) -> Result<(Option<ScopeId>, Option<u64>, bool), String> {
286 let scope = match args.get("scope").and_then(Json::as_str) {
287 Some(s) => Some(ScopeId::new(s).map_err(|e| format!("`scope`: {e}"))?),
288 None => None,
289 };
290 Ok((
291 scope,
292 args.get("if_rev").and_then(Json::as_u64),
293 args["dry_run"] == true,
294 ))
295}
296
297fn id_arg(args: &Json, name: &str, what: &str) -> Result<u64, String> {
299 args[name]
300 .as_u64()
301 .ok_or_else(|| format!("`{name}` is missing: {what}"))
302}
303
304fn next_name(app: &AppHandle, scope: Option<&ScopeId>) -> String {
306 let scope = scope
307 .cloned()
308 .or_else(|| history::target(app, false).map(|t| t.scope()));
309 let n = scope.map_or(0, |s| history::snapshots(app, &s).len()) + 1;
310 strings::tr_with(&app.egui(), &txt::HISTORY_SNAPSHOT_NAME, &[("n", n.into())])
311}
312
313fn walk(app: &AppHandle, args: &Json, what: Walk, origin: &Origin) -> Result<Json, String> {
316 let (scope, if_rev, dry_run) = request_args(args)?;
317 match history::ask(app, what, scope.as_ref(), if_rev, dry_run, origin) {
318 Outcome::Done(r) => r,
319 Outcome::Vetoed { by, reason } => Err(format!("vetoed by {by}: {reason}")),
320 }
321}
322
323fn step_json(ctx: &egui::Context, step: &StepInfo) -> Json {
325 let mut v = json!(step);
326 v["text"] = json!(history::label_text(ctx, &step.label));
327 v
328}
329
330fn read(app: &AppHandle, scope: &ScopeId, line: &Line) -> Json {
332 let ctx = app.egui();
333 let replaced: Vec<Json> = history::replaced(app, scope)
334 .iter()
335 .map(|r| {
336 let mut v = step_json(&ctx, &r.step);
337 v["after"] = json!(r.after);
338 v
339 })
340 .collect();
341 json!({
342 "scope": scope,
343 "rev": line.rev,
344 "head": line.head_id(),
345 "undo": line.undo.iter().map(|s| step_json(&ctx, s)).collect::<Vec<_>>(),
346 "redo": line.redo.iter().map(|s| step_json(&ctx, s)).collect::<Vec<_>>(),
347 "snapshots": history::snapshots(app, scope),
348 "replaced": replaced,
349 "features": history::features(app, scope),
350 })
351}
352
353pub fn shown_scope(app: &AppHandle) -> Option<ScopeId> {
356 let all = history::scopes(app);
357 let ctx = app.egui();
358 CHOSEN
359 .get(&ctx)
360 .filter(|s| all.iter().any(|i| i.id == *s))
361 .or_else(|| history::target(app, false).map(|t| t.scope()))
362 .filter(|s| all.iter().any(|i| i.id == *s))
363 .or_else(|| all.first().map(|s| s.id.clone()))
364}
365
366pub fn choose(app: &AppHandle, scope: ScopeId) {
368 CHOSEN.set(&app.egui(), scope);
369}
370
371pub fn row_text(ctx: &egui::Context, step: &StepInfo) -> String {
374 let label = history::label_text(ctx, &step.label);
375 match step.origin {
376 Origin::User => label,
377 _ => strings::tr_args(
378 ctx,
379 &txt::HISTORY_BY,
380 &[("label", &label), ("origin", &source_of(&step.origin))],
381 ),
382 }
383}
384
385enum Act {
387 Jump(u64),
388 Restore(u64),
389 Forget(u64),
390 UndoStep(u64),
391 Snapshot,
392}
393
394fn previewed(
397 response: egui::Response,
398 app: &AppHandle,
399 view: egui::Id,
400 scope: &ScopeId,
401 at: At,
402 hint: &str,
403) -> egui::Response {
404 if !response.hovered() {
405 return response.on_hover_text(hint);
406 }
407 let preview = history::hover_in(app, view, scope, at);
408 let changes = preview.map(|p| p.changes).unwrap_or_default();
409 if changes.is_empty() {
410 return response.on_hover_text(hint);
411 }
412 response.on_hover_ui(|ui| {
413 ui.label(hint);
414 ui.separator();
415 let ctx = ui.ctx().clone();
416 for c in &changes {
417 ui.label(strings::tr_args(
418 &ctx,
419 &txt::HISTORY_PREVIEW_CHANGE,
420 &[("what", &c.what), ("then", &c.then), ("now", &c.now)],
421 ));
422 }
423 })
424}
425
426pub fn show(ui: &mut Ui, app: &AppHandle) {
433 let view = ui.scope_id();
434 rows(ui, app, view);
435 history::rows_drawn(app, view);
437}
438
439fn rows(ui: &mut Ui, app: &AppHandle, view: egui::Id) {
440 let ctx = ui.ctx().clone();
441 let all = history::scopes(app);
442 let Some(scope) = shown_scope(app) else {
443 ui.weak(strings::tr(&ctx, &txt::HISTORY_NONE));
444 return;
445 };
446 if all.len() > 1 {
447 ui.horizontal_wrapped(|ui| {
448 for s in &all {
449 if ui
450 .add(widgets::SelectableRow::new(s.id == scope, s.title.as_str()))
451 .clicked()
452 {
453 choose(app, s.id.clone());
454 }
455 }
456 });
457 ui.separator();
458 }
459 let line = history::line(app, &scope).unwrap_or_default();
460 let features = history::features(app, &scope);
461 let snapshots = history::snapshots(app, &scope);
462 let replaced = history::replaced(app, &scope);
463 let muted = Tokens::of(&ctx).text.muted;
464 let hint = strings::tr(&ctx, &txt::HISTORY_JUMP);
465 let mut act = None;
466 if features.snapshots || !snapshots.is_empty() {
467 ui.label(RichText::new(strings::tr(&ctx, &txt::HISTORY_SNAPSHOTS)).strong());
468 let restore_hint = strings::tr(&ctx, &txt::HISTORY_RESTORE_HINT);
469 let pending_hint = format!(
470 "{restore_hint}\n{}",
471 strings::tr(&ctx, &txt::HISTORY_SNAPSHOT_PENDING_HINT)
472 );
473 for snap in &snapshots {
474 let (text, hint) = if snap.pending {
476 let name = strings::tr_args(
477 &ctx,
478 &txt::HISTORY_SNAPSHOT_PENDING,
479 &[("name", &snap.name)],
480 );
481 (RichText::new(name).italics(), &pending_hint)
482 } else {
483 (RichText::new(snap.name.as_str()), &restore_hint)
484 };
485 let r = ui.add(widgets::SelectableRow::new(false, text));
486 let r = previewed(r, app, view, &scope, At::Snapshot(snap.id), hint);
487 if r.clicked() {
488 act = Some(Act::Restore(snap.id));
489 }
490 egui_pop_core::pointer::claim::context_menu(&r, |ui| {
491 if ui
492 .button(strings::tr(&ctx, &txt::HISTORY_RESTORE))
493 .clicked()
494 {
495 act = Some(Act::Restore(snap.id));
496 ui.close();
497 }
498 if ui
499 .button(strings::tr(&ctx, &txt::HISTORY_DELETE_SNAPSHOT))
500 .clicked()
501 {
502 act = Some(Act::Forget(snap.id));
503 ui.close();
504 }
505 });
506 }
507 if features.snapshots
508 && ui
509 .button(strings::tr(&ctx, &txt::HISTORY_TAKE_SNAPSHOT))
510 .clicked()
511 {
512 act = Some(Act::Snapshot);
513 }
514 ui.separator();
515 }
516 let show_replaced = !replaced.is_empty() && SHOW_REPLACED.get(&ctx).unwrap_or(false);
517 let mut drawn_replaced = vec![false; replaced.len()];
518 let mut replaced_after = |ui: &mut Ui, after: Option<u64>, act: &mut Option<Act>| {
520 if !show_replaced {
521 return;
522 }
523 for (i, r) in replaced.iter().enumerate() {
524 if drawn_replaced[i] || after.is_some_and(|a| a != r.after) {
525 continue;
526 }
527 drawn_replaced[i] = true;
528 let label = history::label_text(&ctx, &r.step.label);
529 let text = strings::tr_args(&ctx, &txt::HISTORY_REPLACED, &[("label", &label)]);
530 let text = RichText::new(text).color(muted).italics();
531 let row = ui.add(widgets::SelectableRow::new(false, text));
532 if previewed(row, app, view, &scope, At::Step(r.step.id), &hint).clicked() {
533 *act = Some(Act::Jump(r.step.id));
534 }
535 }
536 };
537 let start = strings::tr(&ctx, &txt::HISTORY_START);
538 let r = ui.add(widgets::SelectableRow::new(
539 line.undo.is_empty(),
540 start.as_str(),
541 ));
542 if previewed(r, app, view, &scope, At::Step(0), &hint).clicked() && !line.undo.is_empty() {
543 act = Some(Act::Jump(0));
544 }
545 replaced_after(ui, Some(0), &mut act);
546 let head = line.head_id();
547 let undo_this = strings::tr(&ctx, &txt::HISTORY_UNDO_THIS);
548 for step in &line.undo {
549 let here = step.id == head;
550 let r = ui.add(widgets::SelectableRow::new(here, row_text(&ctx, step)));
551 let r = previewed(r, app, view, &scope, At::Step(step.id), &hint);
552 if r.clicked() && !here {
553 act = Some(Act::Jump(step.id));
554 }
555 if features.undo_step {
556 egui_pop_core::pointer::claim::context_menu(&r, |ui| {
557 if ui.button(undo_this.as_str()).clicked() {
558 act = Some(Act::UndoStep(step.id));
559 ui.close();
560 }
561 });
562 }
563 replaced_after(ui, Some(step.id), &mut act);
564 }
565 for step in line.redo.iter().rev() {
566 let text = RichText::new(row_text(&ctx, step)).color(muted);
567 let r = ui.add(widgets::SelectableRow::new(false, text));
568 if previewed(r, app, view, &scope, At::Step(step.id), &hint).clicked() {
569 act = Some(Act::Jump(step.id));
570 }
571 replaced_after(ui, Some(step.id), &mut act);
572 }
573 replaced_after(ui, None, &mut act);
575 if !replaced.is_empty() {
576 let mut on = SHOW_REPLACED.get(&ctx).unwrap_or(false);
577 if widgets::checkbox(ui, &mut on, strings::tr(&ctx, &txt::HISTORY_SHOW_REPLACED)).changed()
578 {
579 SHOW_REPLACED.set(&ctx, on);
580 }
581 }
582 if let Some(act) = act {
583 run_act(app, &scope, act);
584 }
585}
586
587fn run_act(app: &AppHandle, scope: &ScopeId, act: Act) {
590 history::end_preview(app);
591 let user = Origin::User;
592 let refusal = match act {
593 Act::Jump(to) => outcome_error(history::jump(app, scope, to, &user)),
594 Act::Restore(id) => outcome_error(history::restore(app, scope, id, &user)),
595 Act::UndoStep(id) => outcome_error(history::undo_step(app, scope, id, &user)),
596 Act::Forget(id) => history::forget_snapshot(app, Some(scope), id, None, false, &user)
597 .err()
598 .map(|r| r.reason),
599 Act::Snapshot => {
600 let name = next_name(app, Some(scope));
601 history::take_snapshot(app, Some(scope), &name, None, false, &user)
602 .err()
603 .map(|r| r.reason)
604 }
605 };
606 if let Some(reason) = refusal
607 && let Some(toasts) = app.service(&toasts::TOASTS)
608 {
609 toasts.notify(toasts::Toast::warning(&reason));
610 }
611}
612
613fn outcome_error(outcome: Outcome) -> Option<String> {
614 match outcome {
615 Outcome::Done(Ok(_)) => None,
616 Outcome::Done(Err(e)) => Some(e),
617 Outcome::Vetoed { reason, .. } => Some(reason),
618 }
619}