1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
//! **Low-level undo-redo functionality.**
//!
//! It is an implementation of the action pattern, where all modifications are done
//! by creating objects of actions that applies the modifications. All actions knows
//! how to undo the changes it applies, and by using the provided data structures
//! it is easy to apply, undo, and redo changes made to a target.
//!
//! # Features
//!
//! * [Action](trait.Action.html) provides the base functionality for all actions.
//! * [Record](record/struct.Record.html) provides basic undo-redo functionality.
//! * [Timeline](timeline/struct.Timeline.html) provides basic undo-redo functionality using a fixed size.
//! * [History](history/struct.History.html) provides non-linear undo-redo functionality that allows you to jump between different branches.
//! * Queues wraps a record or history and extends them with queue functionality.
//! * Checkpoints wraps a record or history and extends them with checkpoint functionality.
//! * Actions can be merged into a single action by implementing the
//!   [merge](trait.Action.html#method.merge) method on the action.
//!   This allows smaller actions to be used to build more complex operations, or smaller incremental changes to be
//!   merged into larger changes that can be undone and redone in a single step.
//! * The target can be marked as being saved to disk and the data-structures can track the saved state and notify
//!   when it changes.
//! * The amount of changes being tracked can be configured by the user so only the `N` most recent changes are stored.
//! * Configurable display formatting using the display structure.
//! * The library can be used as `no_std`.
//!
//! # Cargo Feature Flags
//!
//! * `alloc`: Enables the use of the alloc crate, enabled by default.
//! * `arrayvec`: Required for the timeline module, enabled by default.
//! * `chrono`: Enables time stamps and time travel.
//! * `serde`: Enables serialization and deserialization.
//! * `colored`: Enables colored output when visualizing the display structures.
//!
//! # Examples
//!
//! ```rust
//! use undo::{Action, History};
//!
//! struct Add(char);
//!
//! impl Action for Add {
//!     type Target = String;
//!     type Output = ();
//!     type Error = &'static str;
//!
//!     fn apply(&mut self, s: &mut String) -> undo::Result<Add> {
//!         s.push(self.0);
//!         Ok(())
//!     }
//!
//!     fn undo(&mut self, s: &mut String) -> undo::Result<Add> {
//!         self.0 = s.pop().ok_or("s is empty")?;
//!         Ok(())
//!     }
//! }
//!
//! fn main() -> undo::Result<Add> {
//!     let mut target = String::new();
//!     let mut history = History::new();
//!     history.apply(&mut target, Add('a'))?;
//!     history.apply(&mut target, Add('b'))?;
//!     history.apply(&mut target, Add('c'))?;
//!     assert_eq!(target, "abc");
//!     history.undo(&mut target).unwrap()?;
//!     history.undo(&mut target).unwrap()?;
//!     history.undo(&mut target).unwrap()?;
//!     assert_eq!(target, "");
//!     history.redo(&mut target).unwrap()?;
//!     history.redo(&mut target).unwrap()?;
//!     history.redo(&mut target).unwrap()?;
//!     assert_eq!(target, "abc");
//!     Ok(())
//! }
//! ```

#![no_std]
#![doc(html_root_url = "https://docs.rs/undo")]
#![deny(missing_docs)]
#![forbid(unsafe_code)]
#![cfg_attr(not(feature = "alloc"), allow(dead_code))]

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "alloc")]
mod format;
#[cfg(feature = "alloc")]
pub mod history;
#[cfg(feature = "alloc")]
pub mod record;
#[cfg(feature = "arrayvec")]
pub mod timeline;

use crate::format::Format;
#[cfg(feature = "chrono")]
use chrono::{DateTime, Utc};
use core::fmt;
#[cfg(feature = "serde")]
use serde_crate::{Deserialize, Serialize};

#[cfg(feature = "arrayvec")]
pub use self::timeline::Timeline;
#[cfg(feature = "alloc")]
pub use self::{history::History, record::Record};

/// A specialized Result type for undo-redo operations.
pub type Result<A> = core::result::Result<<A as Action>::Output, <A as Action>::Error>;

/// Base functionality for all actions.
pub trait Action {
    /// The target type.
    type Target;
    /// The output type.
    type Output;
    /// The error type.
    type Error;

    /// Applies the action on the target and returns `Ok` if everything went fine,
    /// and `Err` if something went wrong.
    fn apply(&mut self, target: &mut Self::Target) -> Result<Self>;

    /// Restores the state of the target as it was before the action was applied
    /// and returns `Ok` if everything went fine, and `Err` if something went wrong.
    fn undo(&mut self, target: &mut Self::Target) -> Result<Self>;

    /// Reapplies the action on the target and return `Ok` if everything went fine,
    /// and `Err` if something went wrong.
    ///
    /// The default implementation uses the [`apply`](trait.Action.html#tymethod.apply) implementation.
    fn redo(&mut self, target: &mut Self::Target) -> Result<Self> {
        self.apply(target)
    }

    /// Used for manual merging of actions.
    fn merge(&mut self, _: &mut Self) -> Merged
    where
        Self: Sized,
    {
        Merged::No
    }
}

/// Says if the action have been merged with another action.
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate")
)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
pub enum Merged {
    /// The actions have been merged.
    Yes,
    /// The actions have not been merged.
    No,
    /// The two actions cancels each other out.
    Annul,
}

/// A position in a history tree.
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate")
)]
#[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)]
struct At {
    branch: usize,
    current: usize,
}

impl At {
    const ROOT: At = At::new(0, 0);

    const fn new(branch: usize, current: usize) -> At {
        At { branch, current }
    }
}

/// The signal used for communicating state changes.
///
/// For example, if the record can no longer redo any actions, it sends a `Redo(false)`
/// signal to tell the user.
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate")
)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
pub enum Signal {
    /// Says if the structures can undo.
    Undo(bool),
    /// Says if the structures can redo.
    Redo(bool),
    /// Says if the target is in a saved state.
    Saved(bool),
}

#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate")
)]
#[derive(Clone)]
struct Slot<F> {
    #[cfg_attr(feature = "serde", serde(default = "Option::default", skip))]
    f: Option<F>,
}

impl<F: FnMut(Signal)> Slot<F> {
    fn emit(&mut self, signal: Signal) {
        if let Some(ref mut f) = self.f {
            f(signal);
        }
    }

    fn emit_if(&mut self, cond: bool, signal: Signal) {
        if cond {
            self.emit(signal);
        }
    }
}

impl<F> From<F> for Slot<F> {
    fn from(f: F) -> Slot<F> {
        Slot { f: Some(f) }
    }
}

impl<F> Default for Slot<F> {
    fn default() -> Self {
        Slot { f: None }
    }
}

impl<F> fmt::Debug for Slot<F> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.f {
            Some(_) => f.pad("Slot { .. }"),
            None => f.pad("Empty"),
        }
    }
}

#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate")
)]
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
struct Entry<A> {
    action: A,
    #[cfg(feature = "chrono")]
    timestamp: DateTime<Utc>,
}

impl<A> From<A> for Entry<A> {
    fn from(action: A) -> Self {
        Entry {
            action,
            #[cfg(feature = "chrono")]
            timestamp: Utc::now(),
        }
    }
}

impl<A: Action> Action for Entry<A> {
    type Target = A::Target;
    type Output = A::Output;
    type Error = A::Error;

    fn apply(&mut self, target: &mut Self::Target) -> Result<Self> {
        self.action.apply(target)
    }

    fn undo(&mut self, target: &mut Self::Target) -> Result<Self> {
        self.action.undo(target)
    }

    fn redo(&mut self, target: &mut Self::Target) -> Result<Self> {
        self.action.redo(target)
    }

    fn merge(&mut self, entry: &mut Self) -> Merged {
        self.action.merge(&mut entry.action)
    }
}

impl<A: fmt::Display> fmt::Display for Entry<A> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        (&self.action as &dyn fmt::Display).fmt(f)
    }
}