1 /*
2     SPDX-FileCopyrightText: 2017 Nicolas Carion
3     SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
4 */
5 
6 #ifndef UNDOHELPER_H
7 #define UNDOHELPER_H
8 #include <functional>
9 
10 using Fun = std::function<bool(void)>;
11 
12 /** @brief this macro executes an operation after a given lambda
13  */
14 #define PUSH_LAMBDA(operation, lambda)                                                                                                                         \
15     lambda = [lambda, operation]() {                                                                                                                           \
16         bool v = lambda();                                                                                                                                     \
17         return v && operation();                                                                                                                               \
18     };
19 
20 /** @brief this macro executes an operation before a given lambda
21  */
22 #define PUSH_FRONT_LAMBDA(operation, lambda)                                                                                                                   \
23     lambda = [lambda, operation]() {                                                                                                                           \
24         bool v = operation();                                                                                                                                  \
25         return v && lambda();                                                                                                                                  \
26     };
27 
28 #include <QUndoCommand>
29 
30 /** @brief this is a generic class that takes fonctors as undo and redo actions. It just executes them when required by Qt
31   Note that QUndoStack actually executes redo() when we push the undoCommand to the stack
32   This is bad for us because we execute the command as we construct the undo Function. So to prevent it to be executed twice, there is a small hack in this
33   command that prevent redoing if it has not been undone before.
34  */
35 class FunctionalUndoCommand : public QUndoCommand
36 {
37 public:
38     FunctionalUndoCommand(Fun undo, Fun redo, const QString &text, QUndoCommand *parent = nullptr);
39     void undo() override;
40     void redo() override;
41 
42 private:
43     Fun m_undo, m_redo;
44     bool m_undone;
45 };
46 
47 #endif
48