Skip to content

developers undo redo

Tim Stair edited this page Aug 22, 2015 · 2 revisions

Developers - Undo - Redo

Undo-Redo functionality is managed via the UserAction class. The concept is reasonably simple. When a change is made there is a way to roll it back. To perform steps in either direction an Action is created that is capable of moving forward or backward.

CardMaker takes the very simple approach that if the user changes layouts the entire action stack is wiped clear.

Adding an undo - redo Action

The PushAction method accepts an action with a bool parameter. This parameter indicates whether the action is a redo or an undo.

public static void PushAction(Action<bool> zAction)

Example of an action (when an element is renamed):

UserAction.PushAction(bRedo =>
{
    string sOldName = bRedo ? sUndoName : sRedoName;
    string sNewName = bRedo ? sRedoName : sUndoName;

    RenameElement(zElement, lvItem, sOldName, sNewName);
});

The Action closure captures the current state of the variables for later recollection. Multiple renames will not cause the previous to lose track.

While not always written as such it would be best to use the Action to perform the given task at the time of its creation. See the sample below which happens to be the same code block above.

UserAction.PushAction(bRedo =>
{
    string sOldName = bRedo ? sUndoName : sRedoName;
    string sNewName = bRedo ? sRedoName : sUndoName;

    RenameElement(zElement, lvItem, sOldName, sNewName);
});
// well this call is kind of wasteful, if the Action were assigned to a variable it could just have been called with true to trigger a redo
RenameElement(zElement, lvItem, zElement.name, sName);

Undoing and Redoing

...and finally the very exciting Ctrl+z undo code:

Action<bool> undoAction = UserAction.GetUndoAction();
if (null != undoAction)
{
	undoAction(false);
}

I would show you the Ctrl+y redo code but that's a million dollar a secret.