| OLD | NEW |
| (Empty) |
| 1 // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file | |
| 2 // for details. All rights reserved. Use of this source code is governed by a | |
| 3 // BSD-style license that can be found in the LICENSE file. | |
| 4 | |
| 5 /** | |
| 6 * A stack of [Command]s with a current position that supports [execute], [undo]
, and [redo] | |
| 7 * methods. Calling [execute] destroys any previously "undone" commands beyond
the current | |
| 8 * position. Attempting to undo beyond the first command or redo beyond the las
t command are | |
| 9 * treated as no-ops. | |
| 10 */ | |
| 11 class UndoStack { | |
| 12 | |
| 13 int _undoPosition; | |
| 14 List<Command> _undoStack; | |
| 15 | |
| 16 UndoStack() { | |
| 17 this._undoStack = new List<Command>(); | |
| 18 this._undoPosition = -1; | |
| 19 } | |
| 20 | |
| 21 /** | |
| 22 * Return [:true:] if there is a command on the stack that can be "redone." | |
| 23 */ | |
| 24 bool canRedo() => _undoPosition < _undoStack.length - 1; | |
| 25 | |
| 26 /** | |
| 27 * Return [:true:] if there is a command on the stack that can be "undone." | |
| 28 */ | |
| 29 bool canUndo() => _undoPosition >= 0; | |
| 30 | |
| 31 /** | |
| 32 * Execute a command and make it the next "undoable" command. | |
| 33 * Any commands that have previously been "undone" will be removed from the st
ack. | |
| 34 */ | |
| 35 void execute(Command command) { | |
| 36 int pos = ++_undoPosition; | |
| 37 if (pos == _undoStack.length) { | |
| 38 _undoStack.add(command); | |
| 39 } else { | |
| 40 _undoStack[pos] = command; | |
| 41 // Remove susequent commands on the stack | |
| 42 _undoStack.length = pos + 1; | |
| 43 } | |
| 44 command.execute(); | |
| 45 } | |
| 46 | |
| 47 /** | |
| 48 * Redo the most recently "undone" command, or do nothing if there is none. | |
| 49 */ | |
| 50 void redo() { | |
| 51 if (_undoPosition < _undoStack.length - 1) { | |
| 52 ++_undoPosition; | |
| 53 Command command = _undoStack[_undoPosition]; | |
| 54 print("Redo ${command.description}"); | |
| 55 command.execute(); | |
| 56 } | |
| 57 } | |
| 58 | |
| 59 /** | |
| 60 * Undo the most recent command, or do nothing if there is none. | |
| 61 */ | |
| 62 void undo() { | |
| 63 if (_undoPosition >= 0) { | |
| 64 Command command = _undoStack[_undoPosition]; | |
| 65 _undoPosition--; | |
| 66 print("Undo ${command.description}"); | |
| 67 command.unexecute(); | |
| 68 } | |
| 69 } | |
| 70 } | |
| OLD | NEW |