use std::any::TypeId;
use std::cell::Cell;
use std::collections::HashMap;
use std::fmt::{self, Debug};
use std::rc::Rc;
use std::time::Duration;
use waft_embedder::TargetPlatform;
use waft_foundation::{
App, ChangeNotifier, ChangeNotifierData, Handle, Listener, OptionRetained, Timer,
ValueListenable, ValueNotifier,
};
use waft_services::{UndoDirection, UndoManager, UndoManagerClient};
use crate::framework::{
BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
};
use crate::widgets::actions::{Actions, AnyAction, CallbackAction};
use crate::widgets::focus_manager::FocusNodeRef;
use crate::widgets::text_editing_intents::{RedoTextIntent, UndoTextIntent};
use waft_foundation::ListenableObject;
use waft_foundation::Ref;
pub type UndoHistoryOnTriggered<T> = Rc<dyn Fn(&mut App, T)>;
pub type ShouldChangeUndoStack<T> = Rc<dyn Fn(Option<&T>, &T) -> bool>;
pub type UndoStackModifier<T> = Rc<dyn Fn(T) -> T>;
pub struct UndoHistory<
T: Clone + PartialEq + 'static,
V: ValueListenable<T> + Clone + PartialEq + 'static = Ref<ValueNotifier<T>>,
> {
pub key: Option<KeyRef>,
pub should_change_undo_stack: Option<ShouldChangeUndoStack<T>>,
pub value: V,
pub on_triggered: UndoHistoryOnTriggered<T>,
pub focus_node: FocusNodeRef,
pub undo_stack_modifier: Option<UndoStackModifier<T>>,
pub controller: Option<Ref<UndoHistoryController>>,
pub child: WidgetRef,
}
impl<T: Clone + PartialEq + 'static, V: ValueListenable<T> + Clone + PartialEq + 'static>
UndoHistory<T, V>
{
pub fn new<K>(
value: V,
on_triggered: impl Fn(&mut App, T) + 'static,
focus_node: FocusNodeRef,
child: impl IntoWidget<K>,
) -> UndoHistory<T, V> {
UndoHistory {
key: None,
should_change_undo_stack: None,
value,
on_triggered: Rc::new(on_triggered),
focus_node,
undo_stack_modifier: None,
controller: None,
child: child.into_widget(),
}
}
pub fn key(mut self, key: KeyRef) -> UndoHistory<T, V> {
self.key = Some(key);
self
}
pub fn should_change_undo_stack(
mut self,
should_change_undo_stack: impl Fn(Option<&T>, &T) -> bool + 'static,
) -> UndoHistory<T, V> {
self.should_change_undo_stack = Some(Rc::new(should_change_undo_stack));
self
}
pub fn undo_stack_modifier(
mut self,
undo_stack_modifier: impl Fn(T) -> T + 'static,
) -> UndoHistory<T, V> {
self.undo_stack_modifier = Some(Rc::new(undo_stack_modifier));
self
}
pub fn controller(mut self, controller: Ref<UndoHistoryController>) -> UndoHistory<T, V> {
self.controller = Some(controller);
self
}
}
impl<T: Clone + PartialEq + 'static, V: ValueListenable<T> + Clone + PartialEq + 'static> Debug
for UndoHistory<T, V>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("UndoHistory")
.field("child", &self.child)
.finish_non_exhaustive()
}
}
impl<T: Clone + PartialEq + 'static, V: ValueListenable<T> + Clone + PartialEq + 'static>
StatefulWidget for UndoHistory<T, V>
{
type State = UndoHistoryState<T, V>;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_state(&self) -> UndoHistoryState<T, V> {
UndoHistoryState {
state: StateData::new(),
stack: UndoStack::new(),
throttle_timer: None,
throttle_arg: None,
during_trigger: Rc::new(Cell::new(false)),
last_value: None,
controller: None,
}
}
}
pub struct UndoHistoryState<
T: Clone + PartialEq + 'static,
V: ValueListenable<T> + Clone + PartialEq + 'static = Ref<ValueNotifier<T>>,
> {
state: StateData<UndoHistory<T, V>>,
stack: UndoStack<T>,
throttle_timer: Option<Timer>,
throttle_arg: Option<T>,
during_trigger: Rc<Cell<bool>>,
last_value: Option<T>,
controller: Option<Ref<UndoHistoryController>>,
}
struct DuringTriggerGuard {
flag: Rc<Cell<bool>>,
}
impl DuringTriggerGuard {
fn enter(flag: &Rc<Cell<bool>>) -> DuringTriggerGuard {
flag.set(true);
DuringTriggerGuard {
flag: Rc::clone(flag),
}
}
}
impl Drop for DuringTriggerGuard {
fn drop(&mut self) {
self.flag.set(false);
}
}
impl<T: Clone + PartialEq + 'static, V: ValueListenable<T> + Clone + PartialEq + 'static>
UndoHistoryState<T, V>
{
fn effective_controller(self: Handle<Self>, app: &mut App) -> Handle<UndoHistoryController> {
if let Some(controller) = self.widget(app).controller.handle() {
return controller;
}
if let Some(controller) = app.get(self).controller.handle() {
return controller;
}
let controller = UndoHistoryController::new(app);
let handle = controller.handle();
app.get_mut(self).controller = Some(controller);
handle
}
pub fn undo(self: Handle<Self>, app: &mut App) {
if app.get(self).stack.current_value().is_none() {
return;
}
if app
.get(self)
.throttle_timer
.is_some_and(|timer| timer.is_active(app))
{
if let Some(timer) = app.get(self).throttle_timer {
timer.cancel(app); }
let next = app.get(self).stack.current_value().cloned();
self.update(app, next);
} else {
let next = app.get_mut(self).stack.undo().cloned();
self.update(app, next);
}
self.update_state(app);
}
pub fn redo(self: Handle<Self>, app: &mut App) {
let next = app.get_mut(self).stack.redo().cloned();
self.update(app, next);
self.update_state(app);
}
pub fn can_undo(self: Handle<Self>, app: &App) -> bool {
app.get(self).stack.can_undo()
}
pub fn can_redo(self: Handle<Self>, app: &App) -> bool {
app.get(self).stack.can_redo()
}
fn update_state(self: Handle<Self>, app: &mut App) {
let can_undo = self.can_undo(app);
let can_redo = self.can_redo(app);
let controller = self.effective_controller(app);
controller.set_value(
app,
UndoHistoryValue::new()
.can_undo(can_undo)
.can_redo(can_redo),
);
if app.platform().target_platform() != TargetPlatform::IOS {
return;
}
if UndoManager::client(app) == Some(self.as_undo_manager_client()) {
UndoManager::set_undo_state(app, can_undo, can_redo);
}
}
fn undo_from_intent(self: Handle<Self>, app: &mut App) {
self.undo(app);
}
fn redo_from_intent(self: Handle<Self>, app: &mut App) {
self.redo(app);
}
fn update(self: Handle<Self>, app: &mut App, next_value: Option<T>) {
let Some(next_value) = next_value else {
return;
};
if app.get(self).last_value.as_ref() == Some(&next_value) {
return;
}
app.get_mut(self).last_value = Some(next_value.clone());
let flag = Rc::clone(&app.get(self).during_trigger);
let _guard = DuringTriggerGuard::enter(&flag);
let on_triggered = Rc::clone(&self.widget(app).on_triggered);
on_triggered(app, next_value.clone());
debug_assert!(self.widget(app).value.value(app) == &next_value);
}
fn push(self: Handle<Self>, app: &mut App) {
let current = self.widget(app).value.value(app).clone();
if app.get(self).last_value.as_ref() == Some(¤t) {
return;
}
if app.get(self).during_trigger.get() {
return;
}
if let Some(should_change) = self.widget(app).should_change_undo_stack.clone()
&& !should_change(app.get(self).last_value.as_ref(), ¤t)
{
return;
}
let next_value = if let Some(modifier) = self.widget(app).undo_stack_modifier.clone() {
modifier(current)
} else {
current
};
if app.get(self).last_value.as_ref() == Some(&next_value) {
return;
}
app.get_mut(self).last_value = Some(next_value.clone());
let timer = self.throttled_push(app, next_value);
app.get_mut(self).throttle_timer = Some(timer);
}
fn handle_focus(self: Handle<Self>, app: &mut App) {
let focus_node = self.widget(app).focus_node.handle();
if !focus_node.has_focus(app) {
if UndoManager::client(app) == Some(self.as_undo_manager_client()) {
UndoManager::set_client(app, None);
}
return;
}
UndoManager::set_client(app, Some(self.as_undo_manager_client()));
self.update_state(app);
}
fn throttled_push(self: Handle<Self>, app: &mut App, current_arg: T) -> Timer {
app.get_mut(self).throttle_arg = Some(current_arg);
if let Some(timer) = app.get(self).throttle_timer
&& timer.is_active(app)
{
return timer;
}
Timer::new(
app,
K_THROTTLE_DURATION,
Listener::handle_method(self, Self::throttled_push_fire),
)
}
fn throttled_push_fire(self: Handle<Self>, app: &mut App) {
let arg = app
.get_mut(self)
.throttle_arg
.take()
.expect("throttled push stores the arg");
app.get_mut(self).throttle_timer = None;
app.get_mut(self).stack.push(arg);
self.update_state(app);
}
}
impl<T: Clone + PartialEq + 'static, V: ValueListenable<T> + Clone + PartialEq + 'static>
UndoManagerClient for UndoHistoryState<T, V>
{
fn handle_platform_undo(self: Handle<Self>, app: &mut App, direction: UndoDirection) {
match direction {
UndoDirection::Undo => self.undo(app),
UndoDirection::Redo => self.redo(app),
}
}
fn undo(self: Handle<Self>, app: &mut App) {
UndoHistoryState::undo(self, app);
}
fn redo(self: Handle<Self>, app: &mut App) {
UndoHistoryState::redo(self, app);
}
fn can_undo(self: Handle<Self>, app: &App) -> bool {
UndoHistoryState::can_undo(self, app)
}
fn can_redo(self: Handle<Self>, app: &App) -> bool {
UndoHistoryState::can_redo(self, app)
}
}
impl<T: Clone + PartialEq + 'static, V: ValueListenable<T> + Clone + PartialEq + 'static> State
for UndoHistoryState<T, V>
{
type Widget = UndoHistory<T, V>;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
self.push(app);
let value = self.widget(app).value.clone();
value.add_listener(app, Listener::handle_method(self, Self::push));
self.handle_focus(app);
let focus_node = self.widget(app).focus_node.handle();
focus_node.add_listener(app, Listener::handle_method(self, Self::handle_focus));
let controller = self.effective_controller(app);
controller
.on_undo(app)
.add_listener(app, Listener::handle_method(self, Self::undo));
let controller = self.effective_controller(app);
controller
.on_redo(app)
.add_listener(app, Listener::handle_method(self, Self::redo));
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &UndoHistory<T, V>) {
let value = self.widget(app).value.clone();
if value != old_widget.value {
app.get_mut(self).stack.clear();
old_widget
.value
.remove_listener(app, &Listener::handle_method(self, Self::push));
value.add_listener(app, Listener::handle_method(self, Self::push));
}
let focus_node = self.widget(app).focus_node.handle();
if focus_node != old_widget.focus_node {
old_widget
.focus_node
.remove_listener(app, &Listener::handle_method(self, Self::handle_focus));
focus_node.add_listener(app, Listener::handle_method(self, Self::handle_focus));
}
if self.widget(app).controller != old_widget.controller {
let controller = self.effective_controller(app);
controller
.on_undo(app)
.remove_listener(app, &Listener::handle_method(self, Self::undo));
let controller = self.effective_controller(app);
controller
.on_redo(app)
.remove_listener(app, &Listener::handle_method(self, Self::redo));
if let Some(controller) = app.get(self).controller.handle() {
controller.dispose(app);
}
app.get_mut(self).controller = None;
let controller = self.effective_controller(app);
controller
.on_undo(app)
.add_listener(app, Listener::handle_method(self, Self::undo));
let controller = self.effective_controller(app);
controller
.on_redo(app)
.add_listener(app, Listener::handle_method(self, Self::redo));
}
}
fn dispose(self: Handle<Self>, app: &mut App) {
if UndoManager::client(app) == Some(self.as_undo_manager_client()) {
UndoManager::set_client(app, None);
}
let value = self.widget(app).value.clone();
value.remove_listener(app, &Listener::handle_method(self, Self::push));
let focus_node = self.widget(app).focus_node.handle();
focus_node.remove_listener(app, &Listener::handle_method(self, Self::handle_focus));
let controller = self.effective_controller(app);
controller
.on_undo(app)
.remove_listener(app, &Listener::handle_method(self, Self::undo));
let controller = self.effective_controller(app);
controller
.on_redo(app)
.remove_listener(app, &Listener::handle_method(self, Self::redo));
if let Some(controller) = app.get(self).controller.handle() {
controller.dispose(app);
}
if let Some(timer) = app.get(self).throttle_timer {
timer.cancel(app);
}
}
fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
let child = self.widget(app).child.clone();
let undo_default = CallbackAction::<UndoTextIntent>::new(
app,
Rc::new({
let this = self;
move |app, _intent| {
this.undo_from_intent(app);
None
}
}),
);
let redo_default = CallbackAction::<RedoTextIntent>::new(
app,
Rc::new({
let this = self;
move |app, _intent| {
this.redo_from_intent(app);
None
}
}),
);
let undo = AnyAction::overridable(app, undo_default.into_erased(), context);
let redo = AnyAction::overridable(app, redo_default.into_erased(), context);
Actions::new(
HashMap::from([
(TypeId::of::<UndoTextIntent>(), undo),
(TypeId::of::<RedoTextIntent>(), redo),
]),
child,
)
.into_widget()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct UndoHistoryValue {
pub can_undo: bool,
pub can_redo: bool,
}
impl UndoHistoryValue {
pub const EMPTY: UndoHistoryValue = UndoHistoryValue {
can_undo: false,
can_redo: false,
};
pub const fn new() -> UndoHistoryValue {
UndoHistoryValue::EMPTY
}
pub const fn can_undo(mut self, can_undo: bool) -> UndoHistoryValue {
self.can_undo = can_undo;
self
}
pub const fn can_redo(mut self, can_redo: bool) -> UndoHistoryValue {
self.can_redo = can_redo;
self
}
}
impl Default for UndoHistoryValue {
fn default() -> UndoHistoryValue {
UndoHistoryValue::EMPTY
}
}
pub struct UndoHistoryController {
change_notifier: ChangeNotifierData,
value: UndoHistoryValue,
on_undo: Ref<ChangeNotifierData>,
on_redo: Ref<ChangeNotifierData>,
}
impl Debug for UndoHistoryController {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("UndoHistoryController")
.field("value", &self.value)
.finish()
}
}
impl UndoHistoryController {
pub fn new(app: &mut App) -> Ref<UndoHistoryController> {
Self::from_value(app, UndoHistoryValue::EMPTY)
}
pub fn from_value(app: &mut App, value: UndoHistoryValue) -> Ref<UndoHistoryController> {
let on_undo = app.create(ChangeNotifierData::new());
let on_redo = app.create(ChangeNotifierData::new());
app.create(UndoHistoryController {
change_notifier: ChangeNotifierData::new(),
value,
on_undo,
on_redo,
})
}
pub fn value(self: Handle<Self>, app: &App) -> &UndoHistoryValue {
&app.get(self).value
}
pub fn set_value(self: Handle<Self>, app: &mut App, new_value: UndoHistoryValue) {
if app.get(self).value == new_value {
return;
}
app.get_mut(self).value = new_value;
self.notify_listeners(app);
}
pub fn on_undo(self: Handle<Self>, app: &App) -> Handle<ChangeNotifierData> {
app.get(self).on_undo.handle()
}
pub fn on_redo(self: Handle<Self>, app: &App) -> Handle<ChangeNotifierData> {
app.get(self).on_redo.handle()
}
pub fn undo(self: Handle<Self>, app: &mut App) {
if !self.value(app).can_undo {
return;
}
let on_undo = self.on_undo(app);
on_undo.notify_listeners(app);
}
pub fn redo(self: Handle<Self>, app: &mut App) {
if !self.value(app).can_redo {
return;
}
let on_redo = self.on_redo(app);
on_redo.notify_listeners(app);
}
pub fn dispose(self: Handle<Self>, app: &mut App) {
let on_undo = self.on_undo(app);
let on_redo = self.on_redo(app);
ChangeNotifierData::dispose(app, on_undo);
ChangeNotifierData::dispose(app, on_redo);
ChangeNotifierData::dispose(app, self);
}
}
impl ChangeNotifier for UndoHistoryController {
fn change_notifier_data(&self) -> &ChangeNotifierData {
&self.change_notifier
}
fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
&mut self.change_notifier
}
}
struct UndoStack<T> {
list: Vec<T>,
index: i32,
}
const K_THROTTLE_DURATION: Duration = Duration::from_millis(500);
impl<T: PartialEq> UndoStack<T> {
fn new() -> UndoStack<T> {
UndoStack {
list: Vec::new(),
index: -1,
}
}
fn current_value(&self) -> Option<&T> {
if self.list.is_empty() {
None
} else {
Some(&self.list[self.index as usize])
}
}
fn can_undo(&self) -> bool {
!self.list.is_empty() && self.index > 0
}
fn can_redo(&self) -> bool {
!self.list.is_empty() && (self.index as usize) < self.list.len() - 1
}
fn push(&mut self, value: T) {
if self.list.is_empty() {
self.index = 0;
self.list.push(value);
return;
}
debug_assert!((self.index as usize) < self.list.len() && self.index >= 0);
if self.current_value() == Some(&value) {
return;
}
if (self.index as usize) != self.list.len() - 1 {
self.list.truncate((self.index as usize) + 1);
}
self.list.push(value);
self.index = self.list.len() as i32 - 1;
}
fn undo(&mut self) -> Option<&T> {
if self.list.is_empty() {
return None;
}
debug_assert!((self.index as usize) < self.list.len() && self.index >= 0);
if self.index != 0 {
self.index -= 1;
}
self.current_value()
}
fn redo(&mut self) -> Option<&T> {
if self.list.is_empty() {
return None;
}
debug_assert!((self.index as usize) < self.list.len() && self.index >= 0);
if (self.index as usize) < self.list.len() - 1 {
self.index += 1;
}
self.current_value()
}
fn clear(&mut self) {
self.list.clear();
self.index = -1;
}
}
impl<T: Debug> Debug for UndoStack<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "_UndoStack {:?}", self.list)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::widgets::focus_manager::FocusNode;
use std::cell::Cell;
use std::rc::Rc;
use std::time::Duration;
use waft_foundation::ListenableObject;
use waft_foundation::{AppCell, Listener, ValueListenable};
use crate::framework::GlobalKey;
use crate::test_harness::Harness;
use crate::widgets::basic::SizedBox;
#[test]
fn controller_starts_empty() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let controller = UndoHistoryController::new(&mut app);
assert_eq!(controller.value(&app), &UndoHistoryValue::EMPTY);
}
#[test]
fn undo_notifies_on_undo_when_can_undo() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let controller =
UndoHistoryController::from_value(&mut app, UndoHistoryValue::new().can_undo(true));
let fired = Rc::new(Cell::new(false));
let seen = Rc::clone(&fired);
controller
.on_undo(&app)
.add_listener(&mut app, Listener::new(move |_app| seen.set(true)));
controller.undo(&mut app);
assert!(fired.get());
}
#[test]
fn undo_is_a_no_op_when_empty() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let controller = UndoHistoryController::new(&mut app);
let fired = Rc::new(Cell::new(false));
let seen = Rc::clone(&fired);
controller
.on_undo(&app)
.add_listener(&mut app, Listener::new(move |_app| seen.set(true)));
controller.undo(&mut app);
assert!(!fired.get());
}
#[test]
fn stack_push_undo_redo() {
let mut stack = UndoStack::new();
stack.push("a");
stack.push("b");
stack.push("c");
assert_eq!(stack.current_value(), Some(&"c"));
assert!(stack.can_undo());
assert!(!stack.can_redo());
assert_eq!(stack.undo(), Some(&"b"));
assert!(stack.can_redo());
assert_eq!(stack.redo(), Some(&"c"));
stack.undo();
stack.push("d");
assert_eq!(stack.current_value(), Some(&"d"));
assert!(!stack.can_redo());
assert_eq!(stack.undo(), Some(&"b"));
}
#[test]
fn push_two_values_then_undo_restores() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let value = app.create(ValueNotifier::new(0i32));
let focus_node = FocusNode::new(&mut app);
let key = GlobalKey::new();
let notifier = value.handle();
let widget = UndoHistory::new(
value.clone(),
move |app, next| {
notifier.set_value(app, next);
},
focus_node.into_erased(),
SizedBox::shrink(),
)
.key(key.clone().into());
let harness = Harness::mount(&mut app, widget.into_widget());
harness.pump(&mut app);
drop(app);
cell.elapse(Duration::from_millis(500));
let mut app = cell.borrow_mut();
value.set_value(&mut app, 1);
drop(app);
cell.elapse(Duration::from_millis(500));
let mut app = cell.borrow_mut();
let state = key
.current_state::<UndoHistoryState<i32>>(&app)
.expect("the history is mounted");
assert!(state.can_undo(&app));
assert!(!state.can_redo(&app));
state.undo(&mut app);
assert_eq!(*value.value(&app), 0);
assert!(!state.can_undo(&app));
assert!(state.can_redo(&app));
state.redo(&mut app);
assert_eq!(*value.value(&app), 1);
}
}