-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathundo_stack.hpp
68 lines (65 loc) · 1.53 KB
/
undo_stack.hpp
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
#pragma once
#include "coord.hpp"
#include <vector>
class BaseUndoCommand
{
public:
virtual ~BaseUndoCommand();
virtual void undo(Coord &cursor) = 0;
virtual void redo(Coord &cursor) = 0;
};
template <typename RedoFunc, typename UndoFunc>
class UndoCommand: public BaseUndoCommand
{
public:
UndoCommand(Coord cursor, const RedoFunc &redoFunc, const UndoFunc &undoFunc):
redoFunc_(redoFunc),
undoFunc_(undoFunc),
cursor_(cursor)
{}
virtual void undo(Coord &cursor)
{
Coord tmp = cursor_;
undoFunc_(tmp, data_);
cursor = tmp;
}
virtual void redo(Coord &cursor)
{
Coord tmp = cursor_;
data_ = redoFunc_(tmp);
cursor = tmp;
}
private:
RedoFunc redoFunc_;
UndoFunc undoFunc_;
typedef decltype(redoFunc_(*(new Coord))) Data;
Data data_;
Coord cursor_;
};
class UndoStack
{
public:
UndoStack();
~UndoStack();
template <typename RedoFunc, typename UndoFunc>
void push(Coord &cursor, const RedoFunc &redoFunc, const UndoFunc &undoFunc)
{
auto command = new UndoCommand<RedoFunc, UndoFunc>{cursor, redoFunc, undoFunc};
undoStack_.push_back(command);
command->redo(cursor);
for (auto c: redoStack_)
delete c;
redoStack_.clear();
}
void undo(Coord &cursor);
void redo(Coord &cursor);
bool canUndo() const;
bool canRedo() const;
void clean();
bool isModified() const;
void clearModified();
public:
std::vector<BaseUndoCommand *> undoStack_;
std::vector<BaseUndoCommand *> redoStack_;
std::vector<BaseUndoCommand *>::size_type originalState_;
};