-
Notifications
You must be signed in to change notification settings - Fork 0
/
UndoHistory.scala
71 lines (56 loc) · 1.75 KB
/
UndoHistory.scala
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
// UndoHistory.scala
// Copyright (c) 2015 J. M. Spivey
// Modified 2017 by P.G. Jeavons
/** A mixin that can record a history of undoable changes */
trait UndoHistory {
/** A stack of undoable changes from executed actions. */
private val history =
new scala.collection.mutable.ArrayBuffer[UndoHistory.Change]
/** Index into undo stack. Elements history[0..u) have been executed
but not undone, and elements history[u..) have been undone. */
private var undoPointer = 0
/** Beep on error. */
def beep() // abstract
/** Record undo info into history */
def updateHistory(change: UndoHistory.Change) {
if (change != null) {
history.reduceToSize(undoPointer)
if (history.nonEmpty) {
val prev = history.last
if (prev.amalgamate(change)) return
}
history.append(change); undoPointer += 1
}
}
/** Reset the history, e.g. after loading a new file */
def resetHistory() {
history.clear(); undoPointer = 0
}
/** Undo the latest command. */
def undo(): Boolean = {
if (undoPointer == 0) { beep(); return false }
undoPointer -= 1
val change = history(undoPointer)
change.undo()
true
}
/** Redo the latest undone command. */
def redo(): Boolean = {
if (undoPointer == history.size) { beep(); return false }
val change = history(undoPointer)
undoPointer += 1
change.redo()
true
}
}
object UndoHistory {
/** An element of the undo history. */
abstract class Change {
/** Reset the subject to its previous state. */
def undo() // abstract
/** Reset the subject to the state after the change. */
def redo() // abstract
/** Try to amalgamate this change with another. */
def amalgamate(other: Change) = false
}
}