File indexing completed on 2024-05-12 03:47:46

0001 /*
0002     File                 : PropertyChangeCommand.h
0003     Project              : SciDAVis / LabPlot
0004     Description          : Generic undo command changing a single variable.
0005     --------------------------------------------------------------------
0006     SPDX-FileCopyrightText: 2010 Knut Franke <Knut.Franke*gmx.net (use @ for *)>
0007     SPDX-License-Identifier: GPL-2.0-or-later
0008 */
0009 
0010 #ifndef PROPERTY_CHANGE_COMMAND_H
0011 #define PROPERTY_CHANGE_COMMAND_H
0012 
0013 #include <QUndoCommand>
0014 
0015 /**
0016  * \class PropertyChangeCommand
0017  * \brief Generic undo command changing a single variable.
0018  *
0019  * Given a pointer to a variable (usually a member of the class instantiating the command, or of
0020  * its private implementation class) and a new value, assigns the value to the variable. A backup
0021  * of the old value is made, so that undo/redo can switch back and forth between the two values.
0022  * The value type needs to support copy construction and assignment.
0023  */
0024 
0025 template<class T>
0026 class PropertyChangeCommand : public QUndoCommand {
0027 public:
0028     PropertyChangeCommand(const QString& text, T* property, const T& new_value)
0029         : m_property(property)
0030         , m_other_value(new_value) {
0031         setText(text);
0032     }
0033 
0034     void redo() override {
0035         T tmp = *m_property;
0036         *m_property = m_other_value;
0037         m_other_value = tmp;
0038     }
0039 
0040     void undo() override {
0041         redo();
0042     }
0043 
0044     int id() const override {
0045         return reinterpret_cast<std::intptr_t>(m_property);
0046     }
0047 
0048     bool mergeWith(const QUndoCommand* other) override {
0049         if (other->id() != id())
0050             return false;
0051 
0052         if (std::is_same<T, bool>::value)
0053             *m_property = *(static_cast<const PropertyChangeCommand*>(other)->m_property);
0054         else
0055             *m_property += *(static_cast<const PropertyChangeCommand*>(other)->m_property);
0056 
0057         return true;
0058     }
0059 
0060     T* m_property;
0061 
0062 private:
0063     T m_other_value;
0064 };
0065 
0066 #endif // ifndef PROPERTY_CHANGE_COMMAND_H