File indexing completed on 2024-05-12 17:24:09

0001 // SPDX-FileCopyrightText: 2023 Carl Schwan <carl@carlschwan.eu>
0002 // SPDX-License-Identifier: MIT
0003 
0004 #include "colorgradientinterpolator.h"
0005 #include <QtQml>
0006 
0007 constexpr int stepCount = 1000;
0008 
0009 ColorGradientInterpolator::ColorGradientInterpolator(QObject *parent)
0010     : QObject(parent)
0011 {
0012     m_gradient.setEasingCurve(QEasingCurve::Linear);
0013     m_gradient.setDuration(stepCount);
0014 
0015     connect(this, &ColorGradientInterpolator::progressChanged,
0016             this, &ColorGradientInterpolator::colorChanged);
0017     connect(this, &ColorGradientInterpolator::gradientStopsChanged,
0018             this, &ColorGradientInterpolator::colorChanged);
0019 }
0020 
0021 QColor ColorGradientInterpolator::color() const
0022 {
0023     return m_gradient.currentValue().value<QColor>();
0024 }
0025 
0026 double ColorGradientInterpolator::progress() const
0027 {
0028     return m_progress;
0029 }
0030 
0031 void ColorGradientInterpolator::setProgress(const double progress)
0032 {
0033     const auto boundedProgress = qBound(0.0, progress, 1.0);
0034 
0035     if (boundedProgress == m_progress) {
0036         return;
0037     }
0038 
0039     m_progress = boundedProgress;
0040     m_gradient.setCurrentTime(m_progress * stepCount);
0041     Q_EMIT progressChanged();
0042 }
0043 
0044 QVariantList ColorGradientInterpolator::gradientStops() const
0045 {
0046     return {};
0047 }
0048 
0049 void ColorGradientInterpolator::setGradientStops(const QVariantList &gradientStops)
0050 {
0051     QVariantAnimation::KeyValues keyValues;
0052     for (const auto &gradientStop : gradientStops) {
0053         const auto map = gradientStop.toMap();
0054         bool ok = true;
0055         auto position = map[QStringLiteral("position")].toFloat(&ok);
0056         if (position > 1.0 || position < 0.0 || !ok) {
0057             qmlWarning(this) << "Invalid position given" << map[QStringLiteral("position")];
0058         }
0059 
0060         auto color = QColor(map[QStringLiteral("color")].toString());
0061         if (!color.isValid()) {
0062             qmlWarning(this) << "Invalid color given" << map[QStringLiteral("color")];
0063         }
0064 
0065         keyValues.append({ position, color });
0066     }
0067 
0068     m_gradient.setKeyValues(keyValues);
0069     Q_EMIT gradientStopsChanged();
0070 }