-
-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathundo.go
More file actions
355 lines (316 loc) · 10.4 KB
/
undo.go
File metadata and controls
355 lines (316 loc) · 10.4 KB
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
// Copyright (c) 2021, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
Package undo package provides a generic undo / redo functionality based on `[]string`
representations of any kind of state representation (typically JSON dump of the 'document'
state). It stores the compact diffs from one state change to the next, with raw copies saved
at infrequent intervals to tradeoff cost of computing diffs.
In addition to state (which is optional on any given step), a description of the action
and arbitrary string-encoded data can be saved with each record. Thus, for cases
where the state doesn't change, you can just save some data about the action sufficient
to undo / redo it.
A new record must be saved of the state just *before* an action takes place
and the nature of the action taken.
Thus, undoing the action restores the state to that prior state.
Redoing the action means restoring the state *after* the action.
This means that the first Undo action must save the current state
before doing the undo.
The Index is always on the last state saved, which will then be the one
that would be undone for an undo action.
*/
package undo
import (
"log"
"strings"
"sync"
"cogentcore.org/core/text/lines"
)
// DefaultRawInterval is interval for saving raw state -- need to do this
// at some interval to prevent having it take too long to compute patches
// from all the diffs.
var DefaultRawInterval = 50
// Record is one undo record, associated with one action that changed state from one to next.
// The state saved in this record is the state *before* the action took place.
// The state is either saved as a Raw value or as a diff Patch to the previous state.
type Record struct {
// description of this action, for user to see
Action string
// action data, encoded however you want -- some undo records can just be about this action data that can be interpreted to Undo / Redo a non-state-changing action
Data string
// if present, then direct save of full state -- do this at intervals to speed up computing prior states
Raw []string
// patch to get from previous record to this one
Patch lines.Patch
// this record is an UndoSave, when Undo first called from end of stack
UndoSave bool
}
// Init sets the action and data in a record -- overwriting any prior values
func (rc *Record) Init(action, data string) {
rc.Action = action
rc.Data = data
rc.Patch = nil
rc.Raw = nil
rc.UndoSave = false
}
// Stack is the undo stack manager that manages the undo and redo process.
type Stack struct {
// Index is the current index in the undo records.
// This is the record that will be undone if user hits undo.
Index int
// Records is the list of saved state / action records.
Records []*Record
// RawInterval is the interval for saving raw data.
// Need to do this at some interval to prevent having it take too long
// to compute patches from all the diffs.
RawInterval int
// Mu mutex that protects updates. Diff computation runs as a separate
// goroutine so it is instant from perspective of UI.
Mu sync.Mutex
}
// RecState returns the state for given index, reconstructing from diffs
// as needed. Must be called under lock.
func (us *Stack) RecState(idx int) []string {
stidx := 0
var cdt []string
for i := idx; i >= 0; i-- {
r := us.Records[i]
if r.Raw != nil {
stidx = i
cdt = r.Raw
break
}
}
for i := stidx + 1; i <= idx; i++ {
r := us.Records[i]
if r.Patch != nil {
cdt = r.Patch.Apply(cdt)
}
}
return cdt
}
// Save saves a new action as next action to be undone, with given action
// data and current full state of the system (either of which are optional).
// The state must be available for saving -- we do not copy in case we save the
// full raw copy.
func (us *Stack) Save(action, data string, state []string) {
us.Mu.Lock() // we start lock
if us.Records == nil {
if us.RawInterval == 0 {
us.RawInterval = DefaultRawInterval
}
us.Records = make([]*Record, 1)
us.Index = 0
nr := &Record{Action: action, Data: data, Raw: state}
us.Records[0] = nr
us.Mu.Unlock()
return
}
// recs will be [old..., Index] after this
us.Index++
var nr *Record
if len(us.Records) > us.Index {
us.Records = us.Records[:us.Index+1]
nr = us.Records[us.Index]
} else if len(us.Records) == us.Index {
nr = &Record{}
us.Records = append(us.Records, nr)
} else {
log.Printf("undo.Stack error: index: %d > len(um.Recs): %d\n", us.Index, len(us.Records))
us.Index = len(us.Records)
nr = &Record{}
us.Records = append(us.Records, nr)
}
nr.Init(action, data)
if state == nil {
us.Mu.Unlock()
return
}
go us.SaveState(nr, us.Index, state) // fork off save -- it will unlock when done
// now we return straight away, with lock still held
}
// MustSaveUndoStart returns true if the current state must be saved as the start of
// the first Undo action when at the end of the stack. If this returns true, then
// call SaveUndoStart. It sets a special flag on the record.
func (us *Stack) MustSaveUndoStart() bool {
return us.Index == len(us.Records)-1
}
// SaveUndoStart saves the current state -- call if MustSaveUndoStart is true.
// Sets a special flag for this record, and action, data are empty.
// Does NOT increment the index, so next undo is still as expected.
func (us *Stack) SaveUndoStart(state []string) {
us.Mu.Lock()
nr := &Record{UndoSave: true}
us.Records = append(us.Records, nr)
us.SaveState(nr, us.Index+1, state) // do it now because we need to immediately do Undo, does unlock
}
// SaveReplace replaces the current Undo record with new state,
// instead of creating a new record. This is useful for when
// you have a stream of the same type of manipulations
// and just want to save the last (it is better to handle that case
// up front as saving the state can be relatively expensive, but
// in some cases it is not possible).
func (us *Stack) SaveReplace(action, data string, state []string) {
us.Mu.Lock()
nr := us.Records[us.Index]
go us.SaveState(nr, us.Index, state)
}
// SaveState saves given record of state at given index
func (us *Stack) SaveState(nr *Record, idx int, state []string) {
if idx%us.RawInterval == 0 {
nr.Raw = state
us.Mu.Unlock()
return
}
prv := us.RecState(idx - 1)
dif := lines.DiffLines(prv, state)
nr.Patch = dif.ToPatch(state)
us.Mu.Unlock()
}
// HasUndoAvail returns true if there is at least one undo record available.
// This does NOT get the lock -- may rarely be inaccurate but is used for
// gui enabling so not such a big deal.
func (us *Stack) HasUndoAvail() bool {
return us.Index >= 0
}
// HasRedoAvail returns true if there is at least one redo record available.
// This does NOT get the lock -- may rarely be inaccurate but is used for
// GUI enabling so not such a big deal.
func (us *Stack) HasRedoAvail() bool {
return us.Index < len(us.Records)-2
}
// Undo returns the action, action data, and state at the current index
// and decrements the index to the previous record.
// This state is the state just prior to the action.
// If already at the start (Index = -1) then returns empty everything
// Before calling, first check MustSaveUndoStart() -- if false, then you need
// to call SaveUndoStart() so that the state just before Undoing can be redone!
func (us *Stack) Undo() (action, data string, state []string) {
us.Mu.Lock()
if us.Index < 0 || us.Index >= len(us.Records) {
us.Mu.Unlock()
return
}
rec := us.Records[us.Index]
action = rec.Action
data = rec.Data
state = us.RecState(us.Index)
us.Index--
us.Mu.Unlock()
return
}
// UndoTo returns the action, action data, and state at the given index
// and decrements the index to the previous record.
// If idx is out of range then returns empty everything
func (us *Stack) UndoTo(idx int) (action, data string, state []string) {
us.Mu.Lock()
if idx < 0 || idx >= len(us.Records) {
us.Mu.Unlock()
return
}
rec := us.Records[idx]
action = rec.Action
data = rec.Data
state = us.RecState(idx)
us.Index = idx - 1
us.Mu.Unlock()
return
}
// Redo returns the action, data at the *next* index, and the state at the
// index *after that*.
// returning nil if already at end of saved records.
func (us *Stack) Redo() (action, data string, state []string) {
us.Mu.Lock()
if us.Index >= len(us.Records)-2 {
us.Mu.Unlock()
return
}
us.Index++
rec := us.Records[us.Index] // action being redone is this one
action = rec.Action
data = rec.Data
state = us.RecState(us.Index + 1) // state is the one *after* it
us.Mu.Unlock()
return
}
// RedoTo returns the action, action data, and state at the given index,
// returning nil if already at end of saved records.
func (us *Stack) RedoTo(idx int) (action, data string, state []string) {
us.Mu.Lock()
if idx >= len(us.Records)-1 || idx <= 0 {
us.Mu.Unlock()
return
}
us.Index = idx
rec := us.Records[idx]
action = rec.Action
data = rec.Data
state = us.RecState(idx + 1)
us.Mu.Unlock()
return
}
// Reset resets the undo state
func (us *Stack) Reset() {
us.Mu.Lock()
us.Records = nil
us.Index = 0
us.Mu.Unlock()
}
// UndoList returns the list actions in order from the most recent back in time
// suitable for a menu of actions to undo.
func (us *Stack) UndoList() []string {
al := make([]string, us.Index)
for i := us.Index; i >= 0; i-- {
al[us.Index-i] = us.Records[i].Action
}
return al
}
// RedoList returns the list actions in order from the current forward to end
// suitable for a menu of actions to redo
func (us *Stack) RedoList() []string {
nl := len(us.Records)
if us.Index >= nl-2 {
return nil
}
st := us.Index + 1
n := (nl - 1) - st
al := make([]string, n)
for i := st; i < nl-1; i++ {
al[i-st] = us.Records[i].Action
}
return al
}
// MemUsed reports the amount of memory used for record
func (rc *Record) MemUsed() int {
mem := 0
if rc.Raw != nil {
for _, s := range rc.Raw {
mem += len(s)
}
} else {
for _, pr := range rc.Patch {
for _, s := range pr.Blines {
mem += len(s)
}
}
}
return mem
}
// MemStats reports the memory usage statistics.
// if details is true, each record is reported.
func (us *Stack) MemStats(details bool) string {
sb := strings.Builder{}
// TODO(kai): add this back once we figure out how to do core.FileSize
/*
sum := 0
for i, r := range um.Recs {
mem := r.MemUsed()
sum += mem
if details {
sb.WriteString(fmt.Sprintf("%d\t%s\tmem:%s\n", i, r.Action, core.FileSize(mem).String()))
}
}
sb.WriteString(fmt.Sprintf("Total: %s\n", core.FileSize(sum).String()))
*/
return sb.String()
}