forked from Sneeds-Feed-and-Seed/sneedacity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUndoManager.cpp
492 lines (395 loc) · 12.9 KB
/
UndoManager.cpp
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/**********************************************************************
Sneedacity: A Digital Audio Editor
UndoManager.cpp
Dominic Mazzoni
*******************************************************************//**
\class UndoManager
\brief Works with HistoryDialog to provide the Undo functionality.
*//****************************************************************//**
\class UndoStackElem
\brief Holds one item with description and time range for the
UndoManager
*//*******************************************************************/
#include "UndoManager.h"
#include <wx/hashset.h>
#include "Clipboard.h"
#include "DBConnection.h"
#include "Diags.h"
#include "Project.h"
#include "SampleBlock.h"
#include "Sequence.h"
#include "WaveTrack.h" // temp
//#include "NoteTrack.h" // for Sonify* function declarations
#include "Diags.h"
#include "Tags.h"
#include "widgets/ProgressDialog.h"
#include <unordered_set>
wxDEFINE_EVENT(EVT_UNDO_PUSHED, wxCommandEvent);
wxDEFINE_EVENT(EVT_UNDO_MODIFIED, wxCommandEvent);
wxDEFINE_EVENT(EVT_UNDO_RENAMED, wxCommandEvent);
wxDEFINE_EVENT(EVT_UNDO_OR_REDO, wxCommandEvent);
wxDEFINE_EVENT(EVT_UNDO_RESET, wxCommandEvent);
wxDEFINE_EVENT(EVT_UNDO_PURGE, wxCommandEvent);
using SampleBlockID = long long;
static const SneedacityProject::AttachedObjects::RegisteredFactory key{
[](SneedacityProject &project)
{ return std::make_unique<UndoManager>( project ); }
};
UndoManager &UndoManager::Get( SneedacityProject &project )
{
return project.AttachedObjects::Get< UndoManager >( key );
}
const UndoManager &UndoManager::Get( const SneedacityProject &project )
{
return Get( const_cast< SneedacityProject & >( project ) );
}
UndoManager::UndoManager( SneedacityProject &project )
: mProject{ project }
{
current = -1;
saved = -1;
}
UndoManager::~UndoManager()
{
wxASSERT( stack.empty() );
}
namespace {
SpaceArray::value_type
CalculateUsage(const TrackList &tracks, SampleBlockIDSet &seen)
{
SpaceArray::value_type result = 0;
//TIMER_START( "CalculateSpaceUsage", space_calc );
InspectBlocks(
tracks,
BlockSpaceUsageAccumulator( result ),
&seen
);
return result;
}
}
void UndoManager::CalculateSpaceUsage()
{
space.clear();
space.resize(stack.size(), 0);
SampleBlockIDSet seen;
// After copies and pastes, a block file may be used in more than
// one place in one undo history state, and it may be used in more than
// one undo history state. It might even be used in two states, but not
// in another state that is between them -- as when you have state A,
// then make a cut to get state B, but then paste it back into state C.
// So be sure to count each block file once only, in the last undo item that
// contains it.
// Why the last and not the first? Because the user of the History dialog
// may DELETE undo states, oldest first. To reclaim disk space you must
// DELETE all states containing the block file. So the block file's
// contribution to space usage should be counted only in that latest state.
for (size_t nn = stack.size(); nn--;)
{
// Scan all tracks at current level
auto &tracks = *stack[nn]->state.tracks;
space[nn] = CalculateUsage(tracks, seen);
}
// Count the usage of the clipboard separately, using another set. Do not
// multiple-count any block occurring multiple times within the clipboard.
seen.clear();
mClipboardSpaceUsage = CalculateUsage(
Clipboard::Get().GetTracks(), seen);
//TIMER_STOP( space_calc );
}
wxLongLong_t UndoManager::GetLongDescription(
unsigned int n, TranslatableString *desc, TranslatableString *size)
{
wxASSERT(n < stack.size());
wxASSERT(space.size() == stack.size());
*desc = stack[n]->description;
*size = Internat::FormatSize(space[n]);
return space[n];
}
void UndoManager::GetShortDescription(unsigned int n, TranslatableString *desc)
{
wxASSERT(n < stack.size());
*desc = stack[n]->shortDescription;
}
void UndoManager::SetLongDescription(
unsigned int n, const TranslatableString &desc)
{
n -= 1;
wxASSERT(n < stack.size());
stack[n]->description = desc;
}
void UndoManager::RemoveStateAt(int n)
{
// Remove the state from the array first, and destroy it at function exit.
// Because in case of callbacks from destruction of Sample blocks, there
// might be a yield to GUI and other events might inspect the undo stack
// (such as history window update). Don't expose an inconsistent stack
// state.
auto iter = stack.begin() + n;
auto state = std::move(*iter);
stack.erase(iter);
}
//! Just to find a denominator for a progress indicator.
/*! This estimate procedure should in fact be exact */
size_t UndoManager::EstimateRemovedBlocks(size_t begin, size_t end)
{
if (begin == end)
return 0;
// Collect ids that survive
SampleBlockIDSet wontDelete;
auto f = [&](const auto &p){
InspectBlocks(*p->state.tracks, {}, &wontDelete);
};
auto first = stack.begin(), last = stack.end();
std::for_each( first, first + begin, f );
std::for_each( first + end, last, f );
if (saved >= 0)
std::for_each( first + saved, first + saved + 1, f );
InspectBlocks(TrackList::Get(mProject), {}, &wontDelete);
// Collect ids that won't survive (and are not negative pseudo ids)
SampleBlockIDSet seen, mayDelete;
std::for_each( first + begin, first + end, [&](const auto &p){
auto &tracks = *p->state.tracks;
InspectBlocks(tracks, [&]( const SampleBlock &block ){
auto id = block.GetBlockID();
if ( id > 0 && !wontDelete.count( id ) )
mayDelete.insert( id );
},
&seen);
} );
return mayDelete.size();
}
void UndoManager::RemoveStates(size_t begin, size_t end)
{
// Install a callback function that updates a progress indicator
unsigned long long nToDelete = EstimateRemovedBlocks(begin, end),
nDeleted = 0;
ProgressDialog dialog{ XO("Progress"), XO("Discarding undo/redo history"),
pdlgHideStopButton | pdlgHideCancelButton
};
auto callback = [&](const SampleBlock &){
dialog.Update(++nDeleted, nToDelete);
};
auto &trackFactory = WaveTrackFactory::Get( mProject );
auto &pSampleBlockFactory = trackFactory.GetSampleBlockFactory();
auto prevCallback =
pSampleBlockFactory->SetBlockDeletionCallback(callback);
auto cleanup = finally([&]{ pSampleBlockFactory->SetBlockDeletionCallback( prevCallback ); });
// Wrap the whole in a savepoint for better performance
Optional<TransactionScope> pTrans;
auto pConnection = ConnectionPtr::Get(mProject).mpConnection.get();
if (pConnection)
pTrans.emplace(*pConnection, "DiscardingUndoStates");
for (size_t ii = begin; ii < end; ++ii) {
RemoveStateAt(begin);
if (current > begin)
--current;
if (saved > static_cast<int>(begin))
--saved;
}
// Success, commit the savepoint
if (pTrans)
pTrans->Commit();
if (begin != end)
// wxWidgets will own the event object
mProject.QueueEvent( safenew wxCommandEvent{ EVT_UNDO_PURGE } );
// Check sanity
wxASSERT_MSG(
nDeleted == 0 || // maybe bypassing all deletions
nDeleted == nToDelete, "Block count was misestimated");
}
void UndoManager::ClearStates()
{
RemoveStates(0, stack.size());
current = -1;
saved = -1;
}
unsigned int UndoManager::GetNumStates()
{
return stack.size();
}
unsigned int UndoManager::GetCurrentState()
{
return current;
}
bool UndoManager::UndoAvailable()
{
return (current > 0);
}
bool UndoManager::RedoAvailable()
{
return (current < (int)stack.size() - 1);
}
void UndoManager::ModifyState(const TrackList * l,
const SelectedRegion &selectedRegion,
const std::shared_ptr<Tags> &tags)
{
if (current == wxNOT_FOUND) {
return;
}
// SonifyBeginModifyState();
// Delete current -- not necessary, but let's reclaim space early
stack[current]->state.tracks.reset();
// Duplicate
auto tracksCopy = TrackList::Create( nullptr );
for (auto t : *l) {
if ( t->GetId() == TrackId{} )
// Don't copy a pending added track
continue;
tracksCopy->Add(t->Duplicate());
}
// Replace
stack[current]->state.tracks = std::move(tracksCopy);
stack[current]->state.tags = tags;
stack[current]->state.selectedRegion = selectedRegion;
// SonifyEndModifyState();
// wxWidgets will own the event object
mProject.QueueEvent( safenew wxCommandEvent{ EVT_UNDO_MODIFIED } );
}
void UndoManager::RenameState( int state,
const TranslatableString &longDescription,
const TranslatableString &shortDescription)
{
if (state >= 0 && state < stack.size() ) {
auto &theState = *stack[state];
theState.description = longDescription;
theState.shortDescription = shortDescription;
// wxWidgets will own the event object
mProject.QueueEvent( safenew wxCommandEvent{ EVT_UNDO_RENAMED } );
}
}
void UndoManager::PushState(const TrackList * l,
const SelectedRegion &selectedRegion,
const std::shared_ptr<Tags> &tags,
const TranslatableString &longDescription,
const TranslatableString &shortDescription,
UndoPush flags)
{
if ( (flags & UndoPush::CONSOLIDATE) != UndoPush::NONE &&
// compare full translations not msgids!
lastAction.Translation() == longDescription.Translation() &&
mayConsolidate ) {
ModifyState(l, selectedRegion, tags);
// MB: If the "saved" state was modified by ModifyState, reset
// it so that UnsavedChanges returns true.
if (current == saved) {
saved = -1;
}
return;
}
auto tracksCopy = TrackList::Create( nullptr );
for (auto t : *l) {
if ( t->GetId() == TrackId{} )
// Don't copy a pending added track
continue;
tracksCopy->Add(t->Duplicate());
}
mayConsolidate = true;
AbandonRedo();
// Assume tags was duplicated before any changes.
// Just save a NEW shared_ptr to it.
stack.push_back(
std::make_unique<UndoStackElem>
(std::move(tracksCopy),
longDescription, shortDescription, selectedRegion, tags)
);
current++;
lastAction = longDescription;
// wxWidgets will own the event object
mProject.QueueEvent( safenew wxCommandEvent{ EVT_UNDO_PUSHED } );
}
void UndoManager::AbandonRedo()
{
if (saved > current) {
saved = -1;
}
RemoveStates( current + 1, stack.size() );
}
void UndoManager::SetStateTo(unsigned int n, const Consumer &consumer)
{
wxASSERT(n < stack.size());
current = n;
lastAction = {};
mayConsolidate = false;
consumer( *stack[current] );
// wxWidgets will own the event object
mProject.QueueEvent( safenew wxCommandEvent{ EVT_UNDO_RESET } );
}
void UndoManager::Undo(const Consumer &consumer)
{
wxASSERT(UndoAvailable());
current--;
lastAction = {};
mayConsolidate = false;
consumer( *stack[current] );
// wxWidgets will own the event object
mProject.QueueEvent( safenew wxCommandEvent{ EVT_UNDO_OR_REDO } );
}
void UndoManager::Redo(const Consumer &consumer)
{
wxASSERT(RedoAvailable());
current++;
/*
if (!RedoAvailable()) {
*sel0 = stack[current]->sel0;
*sel1 = stack[current]->sel1;
}
else {
current++;
*sel0 = stack[current]->sel0;
*sel1 = stack[current]->sel1;
current--;
}
*/
lastAction = {};
mayConsolidate = false;
consumer( *stack[current] );
// wxWidgets will own the event object
mProject.QueueEvent( safenew wxCommandEvent{ EVT_UNDO_OR_REDO } );
}
void UndoManager::VisitStates( const Consumer &consumer, bool newestFirst )
{
auto fn = [&]( decltype(stack[0]) &ptr ){ consumer( *ptr ); };
if (newestFirst)
std::for_each(stack.rbegin(), stack.rend(), fn);
else
std::for_each(stack.begin(), stack.end(), fn);
}
void UndoManager::VisitStates(
const Consumer &consumer, size_t begin, size_t end )
{
auto size = stack.size();
if (begin < end) {
end = std::min(end, size);
for (auto ii = begin; ii < end; ++ii)
consumer(*stack[ii]);
}
else {
if (size == 0)
return;
begin = std::min(begin, size - 1);
for (auto ii = begin; ii > end; --ii)
consumer(*stack[ii]);
}
}
bool UndoManager::UnsavedChanges() const
{
return (saved != current);
}
void UndoManager::StateSaved()
{
saved = current;
}
int UndoManager::GetSavedState() const
{
return saved;
}
// currently unused
//void UndoManager::Debug()
//{
// for (unsigned int i = 0; i < stack.size(); i++) {
// for (auto t : stack[i]->tracks->Any())
// wxPrintf(wxT("*%d* %s %f\n"),
// i, (i == (unsigned int)current) ? wxT("-->") : wxT(" "),
// t ? t->GetEndTime()-t->GetStartTime() : 0);
// }
//}