| 1 | // Copyright (C) 2024 Christian Ehrlicher <ch.ehrlicher@gmx.de> |
|---|---|
| 2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only |
| 3 | |
| 4 | #ifndef QPAINTERSTATEGUARD_H |
| 5 | #define QPAINTERSTATEGUARD_H |
| 6 | |
| 7 | #include <QtCore/qtclasshelpermacros.h> |
| 8 | #include <QtGui/qpainter.h> |
| 9 | |
| 10 | QT_BEGIN_NAMESPACE |
| 11 | |
| 12 | class QPainterStateGuard |
| 13 | { |
| 14 | Q_DISABLE_COPY(QPainterStateGuard) |
| 15 | public: |
| 16 | enum class InitialState : quint8 { |
| 17 | Save, |
| 18 | NoSave, |
| 19 | }; |
| 20 | |
| 21 | QPainterStateGuard(QPainterStateGuard &&other) noexcept |
| 22 | : m_painter(std::exchange(obj&: other.m_painter, new_val: nullptr)) |
| 23 | , m_level(std::exchange(obj&: other.m_level, new_val: 0)) |
| 24 | {} |
| 25 | QT_MOVE_ASSIGNMENT_OPERATOR_IMPL_VIA_MOVE_AND_SWAP(QPainterStateGuard) |
| 26 | void swap(QPainterStateGuard &other) noexcept |
| 27 | { |
| 28 | qt_ptr_swap(lhs&: m_painter, rhs&: other.m_painter); |
| 29 | std::swap(a&: m_level, b&: other.m_level); |
| 30 | } |
| 31 | |
| 32 | Q_NODISCARD_CTOR |
| 33 | explicit QPainterStateGuard(QPainter *painter, InitialState state = InitialState::Save) |
| 34 | : m_painter(painter) |
| 35 | { |
| 36 | verifyPainter(); |
| 37 | if (state == InitialState::Save) |
| 38 | save(); |
| 39 | } |
| 40 | |
| 41 | ~QPainterStateGuard() |
| 42 | { |
| 43 | while (m_level > 0) |
| 44 | restore(); |
| 45 | } |
| 46 | |
| 47 | void save() |
| 48 | { |
| 49 | verifyPainter(); |
| 50 | m_painter->save(); |
| 51 | ++m_level; |
| 52 | } |
| 53 | |
| 54 | void restore() |
| 55 | { |
| 56 | verifyPainter(); |
| 57 | Q_ASSERT(m_level > 0); |
| 58 | --m_level; |
| 59 | m_painter->restore(); |
| 60 | } |
| 61 | |
| 62 | private: |
| 63 | void verifyPainter() |
| 64 | { |
| 65 | Q_ASSERT(m_painter); |
| 66 | } |
| 67 | |
| 68 | QPainter *m_painter; |
| 69 | int m_level = 0; |
| 70 | }; |
| 71 | |
| 72 | QT_END_NAMESPACE |
| 73 | |
| 74 | #endif // QPAINTERSTATEGUARD_H |
| 75 |
