Skip to content

armgit / krita

Public Imported from GitHub
0

Krita is a free and open source cross-platform application that offers an end-to-end solution for creating digital art files from scratch built on the KDE and Qt frameworks.

C++

Initial brush Stroke Preview implementation

Tenzin Rangdolf00afb2d204f
diff --git a/libs/ui/CMakeLists.txt b/libs/ui/CMakeLists.txt
index b9032781ba..fc4419e655 100644
--- a/libs/ui/CMakeLists.txt
+++ b/libs/ui/CMakeLists.txt
@@ -276,6 +276,8 @@ set(kritaui_LIB_SRCS
widgets/kis_pattern_chooser.cc
widgets/kis_preset_chooser.cpp
+ widgets/KisBrushStrokePreviewCache.cpp
+ widgets/KisBrushStrokePreviewGenerator.cpp
widgets/kis_progress_widget.cpp
widgets/kis_selection_options.cc
widgets/kis_scratch_pad.cpp
diff --git a/libs/ui/kis_paintop_box.cc b/libs/ui/kis_paintop_box.cc
index 861c32b0fa..e7fec81d93 100644
--- a/libs/ui/kis_paintop_box.cc
+++ b/libs/ui/kis_paintop_box.cc
@@ -65,6 +65,7 @@
#include "widgets/kis_paintop_presets_chooser_popup.h"
#include "widgets/kis_workspace_chooser.h"
#include "widgets/kis_paintop_list_widget.h"
+#include "widgets/KisBrushStrokePreviewCache.h"
#include "kis_slider_spin_box.h"
#include "KisAngleSelector.h"
#include "kis_multipliers_double_slider_spinbox.h"
@@ -285,14 +286,14 @@ KisPaintopBox::KisPaintopBox(KisViewManager *viewManager, QWidget *parent, const
slOpacity->setSingleStep(5);
slOpacity->setMinimumWidth(qMax(sliderWidth, slOpacity->sizeHint().width()));
slOpacity->setFixedHeight(buttonsize);
- slOpacity->setBlockUpdateSignalOnDrag(true);
+ slOpacity->setBlockUpdateSignalOnDrag(false);
slFlow->setRange(0, 100, 0);
slFlow->setValue(100);
slFlow->setSingleStep(5);
slFlow->setMinimumWidth(qMax(sliderWidth, slFlow->sizeHint().width()));
slFlow->setFixedHeight(buttonsize);
- slFlow->setBlockUpdateSignalOnDrag(true);
+ slFlow->setBlockUpdateSignalOnDrag(false);
slSize->setRange(0.01, KisImageConfig(true).maxBrushSize(), 2);
slSize->setValue(100);
@@ -302,7 +303,7 @@ KisPaintopBox::KisPaintopBox(KisViewManager *viewManager, QWidget *parent, const
slSize->setSuffix(i18n(" px"));
slSize->setMinimumWidth(qMax(sliderWidth, slSize->sizeHint().width()));
slSize->setFixedHeight(buttonsize);
- slSize->setBlockUpdateSignalOnDrag(true);
+ slSize->setBlockUpdateSignalOnDrag(false);
slRotation->setFlipOptionsMode(KisAngleSelector::FlipOptionsMode_MenuButton);
slRotation->setRange(-360.0, 360.0);
@@ -319,7 +320,7 @@ KisPaintopBox::KisPaintopBox(KisViewManager *viewManager, QWidget *parent, const
slPatternSize->setSuffix(i18n("x"));
slPatternSize->setMinimumWidth(qMax(sliderWidth, slPatternSize->sizeHint().width()));
slPatternSize->setFixedHeight(buttonsize);
- slPatternSize->setBlockUpdateSignalOnDrag(true);
+ slPatternSize->setBlockUpdateSignalOnDrag(false);
m_sliderChooser[i]->setMinimumWidth(qMax(sliderWidth, slPatternSize->sizeHint().width()));
@@ -1044,6 +1045,9 @@ void KisPaintopBox::slotCanvasResourceChanged(int key, const QVariant &value)
*/
m_presetsChooserPopup->canvasResourceChanged(preset);
m_presetsEditor->currentPresetChanged(preset);
+
+ // Track the current preset for settings changes in the stroke preview cache
+ KisBrushStrokePreviewCache::instance()->slotSetCurrentPreset(preset);
}
if (key == KoCanvasResource::CurrentCompositeOp) {
@@ -1088,6 +1092,10 @@ void KisPaintopBox::slotCanvasResourceChanged(int key, const QVariant &value)
m_vMirrorAction->setChecked(value.toBool());
}
+ // Notify the stroke preview cache of canvas resource changes
+ // (size, flow, opacity, rotation changes via shortcuts)
+ KisBrushStrokePreviewCache::instance()->slotCanvasResourceChanged(key, value);
+
sender()->blockSignals(false);
}
}
@@ -1421,6 +1429,7 @@ void KisPaintopBox::slotReloadPreset()
const bool result = rserver->reloadResource(preset);
KIS_SAFE_ASSERT_RECOVER_NOOP(result && "couldn't reload preset");
}
+
}
void KisPaintopBox::slotGuiChangedCurrentPreset() // Called only when UI is changed and not when preset is changed
{
@@ -1470,6 +1479,7 @@ void KisPaintopBox::slotSaveLockedOptionToPreset(KisPropertiesConfigurationSP p)
/// explicitly mark the preset as dirty since the properties
/// might have the same values (updated before)
preset->setDirty(true);
+
}
void KisPaintopBox::slotDropLockedOption(KisPropertiesConfigurationSP p)
@@ -1491,6 +1501,7 @@ void KisPaintopBox::slotDropLockedOption(KisPropertiesConfigurationSP p)
}
}
+
}
void KisPaintopBox::slotDirtyPresetToggled(bool value)
{
diff --git a/libs/ui/tests/CMakeLists.txt b/libs/ui/tests/CMakeLists.txt
index 753ae9c65a..10474decc9 100644
--- a/libs/ui/tests/CMakeLists.txt
+++ b/libs/ui/tests/CMakeLists.txt
@@ -14,6 +14,7 @@ kis_add_tests(
kis_animation_exporter_test.cpp
kis_prescaled_projection_test.cpp
kis_animation_importer_test.cpp
+ kis_brush_stroke_preview_cache_test.cpp
KisSpinBoxSplineUnitConverterTest.cpp
KisDocumentReplaceTest.cpp
KisRssReaderTest.cpp
diff --git a/libs/ui/tests/kis_brush_stroke_preview_cache_test.cpp b/libs/ui/tests/kis_brush_stroke_preview_cache_test.cpp
new file mode 100644
index 0000000000..321a7e8192
--- /dev/null
+++ b/libs/ui/tests/kis_brush_stroke_preview_cache_test.cpp
@@ -0,0 +1,119 @@
+/*
+ * SPDX-FileCopyrightText: 2026 Tenzin Rangdol <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#include "kis_brush_stroke_preview_cache_test.h"
+
+#include <QColor>
+#include <QDir>
+#include <QFile>
+#include <QImage>
+#include <QPainter>
+#include <QStandardPaths>
+
+#include "KisBrushStrokePreviewCache.h"
+#include <brushengine/kis_paintop_preset.h>
+
+namespace {
+
+QImage makeSplitImage(const QSize &size, const QColor &left, const QColor &right)
+{
+ QImage image(size, QImage::Format_ARGB32_Premultiplied);
+ image.fill(left);
+
+ QPainter painter(&image);
+ painter.fillRect(QRect(size.width() / 2, 0,
+ size.width() - size.width() / 2,
+ size.height()),
+ right);
+ return image;
+}
+
+QString cacheFilePathForPreset(int presetId)
+{
+ const QString cacheDir = QStandardPaths::writableLocation(QStandardPaths::CacheLocation)
+ + QStringLiteral("/brush_stroke_previews");
+ QDir dir(cacheDir);
+ dir.mkpath(QStringLiteral("."));
+ return dir.filePath(QString::number(presetId) + QStringLiteral(".png"));
+}
+
+} // namespace
+
+void KisBrushStrokePreviewCacheTest::initTestCase()
+{
+ QStandardPaths::setTestModeEnabled(true);
+}
+
+void KisBrushStrokePreviewCacheTest::testPlaceholderForInvalidPreset()
+{
+ KisPaintOpPresetSP preset(new KisPaintOpPreset());
+ preset->setResourceId(-1);
+
+ const QSize size(32, 16);
+ QImage preview = KisBrushStrokePreviewCache::instance()->getPreview(preset, size);
+
+ QCOMPARE(preview.size(), size);
+ QVERIFY(!preview.isNull());
+ QCOMPARE(preview.format(), QImage::Format_ARGB32_Premultiplied);
+ QCOMPARE(preview.pixelColor(0, 0).alpha(), 0);
+}
+
+void KisBrushStrokePreviewCacheTest::testScaledCacheInvalidation()
+{
+ KisBrushStrokePreviewCache *cache = KisBrushStrokePreviewCache::instance();
+
+ KisPaintOpPresetSP preset(new KisPaintOpPreset());
+ const int presetId = 12001;
+ preset->setResourceId(presetId);
+
+ const QSize sourceSize(100, 50);
+ const QSize targetSize(50, 50);
+
+ QImage firstImage = makeSplitImage(sourceSize, Qt::red, Qt::blue);
+ cache->slotLivePreviewImageReady(presetId, firstImage);
+
+ QImage firstPreview = cache->getPreview(preset, targetSize);
+ QCOMPARE(firstPreview.size(), targetSize);
+ QVERIFY(firstPreview.pixelColor(10, 25).red() > 200);
+ QVERIFY(firstPreview.pixelColor(40, 25).blue() > 200);
+
+ QImage secondImage = makeSplitImage(sourceSize, Qt::green, Qt::blue);
+ cache->slotLivePreviewImageReady(presetId, secondImage);
+
+ QImage secondPreview = cache->getPreview(preset, targetSize);
+ QCOMPARE(secondPreview.size(), targetSize);
+ QVERIFY(secondPreview.pixelColor(10, 25).green() > 200);
+ QVERIFY(secondPreview.pixelColor(40, 25).blue() > 200);
+
+ cache->invalidatePreset(presetId);
+}
+
+void KisBrushStrokePreviewCacheTest::testDiskCacheFallback()
+{
+ KisBrushStrokePreviewCache *cache = KisBrushStrokePreviewCache::instance();
+
+ KisPaintOpPresetSP preset(new KisPaintOpPreset());
+ const int presetId = 12002;
+ preset->setResourceId(presetId);
+
+ const QSize sourceSize(80, 40);
+ const QSize targetSize(40, 40);
+ QImage sourceImage = makeSplitImage(sourceSize, Qt::red, Qt::blue);
+
+ const QString filePath = cacheFilePathForPreset(presetId);
+ QFile::remove(filePath);
+ QVERIFY(sourceImage.save(filePath, "PNG"));
+
+ QImage preview = cache->getPreview(preset, targetSize);
+ QCOMPARE(preview.size(), targetSize);
+ QVERIFY(preview.pixelColor(8, 20).red() > 200);
+ QVERIFY(preview.pixelColor(30, 20).blue() > 200);
+
+ QFile::remove(filePath);
+ cache->invalidatePreset(presetId);
+}
+
+SIMPLE_TEST_MAIN(KisBrushStrokePreviewCacheTest)
diff --git a/libs/ui/tests/kis_brush_stroke_preview_cache_test.h b/libs/ui/tests/kis_brush_stroke_preview_cache_test.h
new file mode 100644
index 0000000000..af4cae4651
--- /dev/null
+++ b/libs/ui/tests/kis_brush_stroke_preview_cache_test.h
@@ -0,0 +1,23 @@
+/*
+ * SPDX-FileCopyrightText: 2026 Tenzin Rangdol <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#ifndef KIS_BRUSH_STROKE_PREVIEW_CACHE_TEST_H
+#define KIS_BRUSH_STROKE_PREVIEW_CACHE_TEST_H
+
+#include <simpletest.h>
+
+class KisBrushStrokePreviewCacheTest : public QObject
+{
+ Q_OBJECT
+
+private Q_SLOTS:
+ void initTestCase();
+ void testPlaceholderForInvalidPreset();
+ void testScaledCacheInvalidation();
+ void testDiskCacheFallback();
+};
+
+#endif // KIS_BRUSH_STROKE_PREVIEW_CACHE_TEST_H
diff --git a/libs/ui/tool/kis_resources_snapshot.cpp b/libs/ui/tool/kis_resources_snapshot.cpp
index 0eb33cb9a8..68b7a38b29 100644
--- a/libs/ui/tool/kis_resources_snapshot.cpp
+++ b/libs/ui/tool/kis_resources_snapshot.cpp
@@ -360,6 +360,11 @@ void KisResourcesSnapshot::setOpacity(qreal opacity)
m_d->opacity = opacity;
}
+void KisResourcesSnapshot::setCompositeOpId(const QString &compositeOpId)
+{
+ m_d->compositeOpId = compositeOpId;
+}
+
void KisResourcesSnapshot::setMirroring(bool horizontal, bool vertical)
{
m_d->mirrorMaskHorizontal = horizontal;
diff --git a/libs/ui/tool/kis_resources_snapshot.h b/libs/ui/tool/kis_resources_snapshot.h
index fb8eceefbe..070c811bd4 100644
--- a/libs/ui/tool/kis_resources_snapshot.h
+++ b/libs/ui/tool/kis_resources_snapshot.h
@@ -65,6 +65,8 @@ public:
bool needsSpacingUpdates() const;
void setOpacity(qreal opacity);
+ /// Override the composite op for the snapshot.
+ void setCompositeOpId(const QString &compositeOpId);
void setMirroring(bool horizontal, bool vertical);
qreal opacity() const;
QString compositeOpId() const;
diff --git a/libs/ui/widgets/KisBrushStrokePreviewCache.cpp b/libs/ui/widgets/KisBrushStrokePreviewCache.cpp
new file mode 100644
index 0000000000..8f6dafef6d
--- /dev/null
+++ b/libs/ui/widgets/KisBrushStrokePreviewCache.cpp
@@ -0,0 +1,491 @@
+/*
+ * SPDX-FileCopyrightText: 2026 Tenzin Rangdol <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#include "KisBrushStrokePreviewCache.h"
+#include "KisBrushStrokePreviewGenerator.h"
+
+#include <QDir>
+#include <QFile>
+#include <QHash>
+#include <QList>
+#include <QMutex>
+#include <QMutexLocker>
+#include <QPainter>
+#include <QPointer>
+#include <QRegularExpression>
+#include <QSaveFile>
+#include <QStandardPaths>
+#include <QTimer>
+
+#include <klocalizedstring.h>
+#include <kis_paintop_settings.h>
+#include <KisPaintOpPresetUpdateProxy.h>
+#include <KisResourceModelProvider.h>
+#include <KisResourceTypes.h>
+#include <KisResourceModel.h>
+#include <KoCanvasResourcesIds.h>
+#include <kis_signal_auto_connection.h>
+
+namespace {
+
+/// Returns preset's resource ID, or -1 if preset is null.
+inline int validPresetId(KisPaintOpPresetSP preset)
+{
+ return preset ? preset->resourceId() : -1;
+}
+
+} // namespace
+
+struct KisBrushStrokePreviewCache::Private {
+ struct CacheEntry {
+ QImage image;
+ };
+
+ mutable QMutex mutex;
+ QHash<QString, CacheEntry> cache;
+ QHash<QString, QImage> scaledCache;
+ QList<QString> accessOrder;
+ int maxCacheSize = 500;
+ KisPaintOpPresetSP currentPreset;
+ KisSignalAutoConnectionsStore presetConnections;
+ QString currentSettingsFingerprint;
+ QString diskCachePath;
+ QScopedPointer<KisBrushStrokePreviewGenerator> generator;
+ bool pendingGenerateAll {false};
+
+ /// Remove all scaled cache entries for a base key.
+ void removeScaledVariants(const QString &baseKey)
+ {
+ QMutableHashIterator<QString, QImage> it(scaledCache);
+ const QString prefix = baseKey + QLatin1Char('_');
+ while (it.hasNext()) {
+ it.next();
+ if (it.key().startsWith(prefix)) {
+ it.remove();
+ }
+ }
+ }
+};
+
+KisBrushStrokePreviewCache::KisBrushStrokePreviewCache()
+ : QObject(nullptr)
+ , m_d(new Private)
+{
+ initDiskCache();
+ m_d->generator.reset(new KisBrushStrokePreviewGenerator(this));
+
+ KisAllResourcesModel *model = KisResourceModelProvider::resourceModel(ResourceType::PaintOpPresets);
+ if (model) {
+ connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)),
+ this, SLOT(slotScheduleGenerateAllPreviews()));
+ connect(model, SIGNAL(modelReset()),
+ this, SLOT(slotScheduleGenerateAllPreviews()));
+ }
+}
+
+KisBrushStrokePreviewCache::~KisBrushStrokePreviewCache()
+{
+}
+
+KisBrushStrokePreviewCache* KisBrushStrokePreviewCache::instance()
+{
+ static KisBrushStrokePreviewCache s_instance;
+ return &s_instance;
+}
+
+bool KisBrushStrokePreviewCache::needsStripedBackground(const QString &paintOpId)
+{
+ return paintOpId == QLatin1String("colorsmudge")
+ || paintOpId == QLatin1String("deformbrush")
+ || paintOpId == QLatin1String("filter");
+}
+
+bool KisBrushStrokePreviewCache::isNoPreviewEngine(const QString &paintOpId)
+{
+ return paintOpId == QLatin1String("roundmarker")
+ || paintOpId == QLatin1String("experimentbrush")
+ || paintOpId == QLatin1String("duplicate");
+}
+
+void KisBrushStrokePreviewCache::initDiskCache()
+{
+ const QString cacheDir = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
+ m_d->diskCachePath = cacheDir + QStringLiteral("/brush_stroke_previews");
+ QDir dir(m_d->diskCachePath);
+ if (!dir.exists()) {
+ dir.mkpath(QStringLiteral("."));
+ }
+}
+
+QString KisBrushStrokePreviewCache::getDiskCacheFilename(int presetId) const
+{
+ return QDir(m_d->diskCachePath).filePath(QString::number(presetId) + QStringLiteral(".png"));
+}
+
+bool KisBrushStrokePreviewCache::loadFromDiskCache(int presetId, QImage &image)
+{
+ const QString filename = getDiskCacheFilename(presetId);
+ return QFile::exists(filename) && image.load(filename);
+}
+
+void KisBrushStrokePreviewCache::saveToDiskCache(int presetId, const QImage &image)
+{
+ if (image.isNull()) {
+ return;
+ }
+
+ QSaveFile file(getDiskCacheFilename(presetId));
+ if (file.open(QIODevice::WriteOnly) && image.save(&file, "PNG", 50)) {
+ file.commit();
+ }
+}
+
+bool KisBrushStrokePreviewCache::hasDiskCache(int presetId) const
+{
+ return QFile::exists(getDiskCacheFilename(presetId));
+}
+
+void KisBrushStrokePreviewCache::removeDiskCache(int presetId)
+{
+ QFile::remove(getDiskCacheFilename(presetId));
+}
+
+QString KisBrushStrokePreviewCache::generateCacheKey(int presetId) const
+{
+ return QString::number(presetId);
+}
+
+QString KisBrushStrokePreviewCache::generateSizedCacheKey(int presetId, const QSize &size) const
+{
+ return QStringLiteral("%1_%2x%3").arg(presetId).arg(size.width()).arg(size.height());
+}
+
+void KisBrushStrokePreviewCache::evictIfNeeded()
+{
+ while (m_d->cache.size() >= m_d->maxCacheSize && !m_d->accessOrder.isEmpty()) {
+ const QString oldestKey = m_d->accessOrder.takeFirst();
+ m_d->cache.remove(oldestKey);
+ m_d->removeScaledVariants(oldestKey);
+ }
+}
+
+void KisBrushStrokePreviewCache::updateAccessOrder(const QString &key)
+{
+ m_d->accessOrder.removeAll(key);
+ m_d->accessOrder.append(key);
+}
+
+QImage KisBrushStrokePreviewCache::getPreview(KisPaintOpPresetSP preset, const QSize &size)
+{
+ const int presetId = validPresetId(preset);
+ if (presetId < 0 || size.isEmpty()) {
+ return size.isEmpty() ? QImage() : generatePlaceholder(size);
+ }
+
+ // Return "No Preview" placeholder for unsupported brush engines
+ if (preset && isNoPreviewEngine(preset->paintOp().id())) {
+ return generateNoPreviewPlaceholder(size);
+ }
+
+ QMutexLocker locker(&m_d->mutex);
+
+ const QString baseKey = generateCacheKey(presetId);
+ const QString sizedKey = generateSizedCacheKey(presetId, size);
+
+ // Check scaled cache first.
+ auto scaledIt = m_d->scaledCache.find(sizedKey);
+ if (scaledIt != m_d->scaledCache.end()) {
+ updateAccessOrder(baseKey);
+ return scaledIt.value();
+ }
+
+ // Check base cache.
+ auto it = m_d->cache.find(baseKey);
+ if (it != m_d->cache.end() && !it->image.isNull()) {
+ updateAccessOrder(baseKey);
+ QImage scaled = scalePreviewToSize(it->image, size);
+ m_d->scaledCache.insert(sizedKey, scaled);
+ return scaled;
+ }
+
+ // Try disk cache.
+ QImage diskImage;
+ if (loadFromDiskCache(presetId, diskImage) && !diskImage.isNull()) {
+ evictIfNeeded();
+ m_d->cache.insert(baseKey, {diskImage});
+ m_d->accessOrder.append(baseKey);
+ QImage scaled = scalePreviewToSize(diskImage, size);
+ m_d->scaledCache.insert(sizedKey, scaled);
+ return scaled;
+ }
+
+ return generatePlaceholder(size);
+}
+
+QImage KisBrushStrokePreviewCache::scalePreviewToSize(const QImage &source, const QSize &targetSize) const
+{
+ if (source.isNull() || targetSize.isEmpty()) {
+ return source;
+ }
+
+ // Center-crop to fill target.
+ const qreal sourceAspect = static_cast<qreal>(source.width()) / source.height();
+ const qreal targetAspect = static_cast<qreal>(targetSize.width()) / targetSize.height();
+
+ QImage scaled;
+ if (sourceAspect > targetAspect) {
+ int scaledHeight = targetSize.height();
+ int scaledWidth = static_cast<int>(scaledHeight * sourceAspect);
+ scaled = source.scaled(scaledWidth, scaledHeight, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
+ int xOffset = (scaled.width() - targetSize.width()) / 2;
+ scaled = scaled.copy(xOffset, 0, targetSize.width(), targetSize.height());
+ } else {
+ int scaledWidth = targetSize.width();
+ int scaledHeight = static_cast<int>(scaledWidth / sourceAspect);
+ scaled = source.scaled(scaledWidth, scaledHeight, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
+ int yOffset = (scaled.height() - targetSize.height()) / 2;
+ scaled = scaled.copy(0, yOffset, targetSize.width(), targetSize.height());
+ }
+
+ return scaled;
+}
+
+QImage KisBrushStrokePreviewCache::generatePlaceholder(const QSize &size) const
+{
+ QImage placeholder(size, QImage::Format_ARGB32_Premultiplied);
+ placeholder.fill(Qt::transparent);
+
+ QPainter painter(&placeholder);
+ painter.setPen(Qt::white);
+ QFont font;
+ font.setPixelSize(qMin(size.height() / 2, 10));
+ painter.setFont(font);
+ painter.drawText(placeholder.rect(), Qt::AlignCenter, i18n("Loading..."));
+
+ return placeholder;
+}
+
+QImage KisBrushStrokePreviewCache::generateNoPreviewPlaceholder(const QSize &size) const
+{
+ QImage placeholder(size, QImage::Format_ARGB32_Premultiplied);
+ placeholder.fill(Qt::transparent);
+
+ QPainter painter(&placeholder);
+ painter.setPen(Qt::white);
+ QFont font;
+ font.setPixelSize(qMin(size.height() / 2, 10));
+ painter.setFont(font);
+ painter.drawText(placeholder.rect(), Qt::AlignCenter, i18n("No Preview"));
+
+ return placeholder;
+}
+
+void KisBrushStrokePreviewCache::slotLivePreviewImageReady(int presetId, const QImage &previewImage)
+{
+ if (presetId < 0 || previewImage.isNull()) {
+ return;
+ }
+
+ saveToDiskCache(presetId, previewImage);
+
+ {
+ QMutexLocker locker(&m_d->mutex);
+
+ const QString baseKey = generateCacheKey(presetId);
+
+ auto it = m_d->cache.find(baseKey);
+ if (it != m_d->cache.end()) {
+ it->image = previewImage;
+ updateAccessOrder(baseKey);
+ } else {
+ evictIfNeeded();
+ m_d->cache.insert(baseKey, {previewImage});
+ m_d->accessOrder.append(baseKey);
+ }
+
+ m_d->removeScaledVariants(baseKey);
+ }
+
+ Q_EMIT sigPreviewReady(presetId);
+}
+
+void KisBrushStrokePreviewCache::invalidatePreset(int presetId)
+{
+ if (presetId < 0) {
+ return;
+ }
+
+ removeDiskCache(presetId);
+
+ QMutexLocker locker(&m_d->mutex);
+
+ const QString baseKey = generateCacheKey(presetId);
+
+ m_d->removeScaledVariants(baseKey);
+}
+
+void KisBrushStrokePreviewCache::generateAllPreviews()
+{
+ KisAllResourcesModel *model = KisResourceModelProvider::resourceModel(ResourceType::PaintOpPresets);
+ if (!model) {
+ return;
+ }
+
+ QList<KisPaintOpPresetSP> missing;
+ const int rowCount = model->rowCount();
+
+ for (int i = 0; i < rowCount; ++i) {
+ QModelIndex idx = model->index(i, 0);
+ KisPaintOpPresetSP preset = model->resourceForIndex(idx).dynamicCast<KisPaintOpPreset>();
+
+ const int presetId = validPresetId(preset);
+ if (presetId < 0) {
+ continue;
+ }
+
+ const QString baseKey = generateCacheKey(presetId);
+ bool cached;
+ {
+ QMutexLocker locker(&m_d->mutex);
+ cached = m_d->cache.contains(baseKey);
+ }
+
+ if (!cached && !hasDiskCache(presetId)) {
+ missing.append(preset);
+ }
+ }
+
+ if (!missing.isEmpty() && m_d->generator) {
+ m_d->generator->startBatch(missing);
+ }
+}
+
+void KisBrushStrokePreviewCache::slotScheduleGenerateAllPreviews()
+{
+ if (m_d->pendingGenerateAll) {
+ return;
+ }
+
+ m_d->pendingGenerateAll = true;
+ QTimer::singleShot(0, this, SLOT(slotRunGenerateAllPreviews()));
+}
+
+void KisBrushStrokePreviewCache::slotRunGenerateAllPreviews()
+{
+ m_d->pendingGenerateAll = false;
+ generateAllPreviews();
+}
+
+void KisBrushStrokePreviewCache::registerLivePreviewView(KisPresetLivePreviewView *view)
+{
+ if (m_d->generator) {
+ m_d->generator->setSourceView(view);
+ }
+}
+
+void KisBrushStrokePreviewCache::slotPresetSettingsChanged(KisPaintOpPresetSP preset)
+{
+ const int presetId = validPresetId(preset);
+ if (presetId < 0) {
+ return;
+ }
+
+ invalidatePreset(presetId);
+
+ if (m_d->generator) {
+ m_d->generator->requestPreview(preset);
+ }
+
+ Q_EMIT sigPreviewReady(presetId);
+}
+
+void KisBrushStrokePreviewCache::slotSetCurrentPreset(KisPaintOpPresetSP preset)
+{
+ m_d->presetConnections.clear();
+ m_d->currentPreset = preset;
+ m_d->currentSettingsFingerprint.clear();
+
+ if (!preset) {
+ return;
+ }
+
+ m_d->currentSettingsFingerprint = generateSettingsFingerprint(preset);
+
+ QPointer<KisPaintOpPresetUpdateProxy> proxy = preset->updateProxy();
+ if (proxy) {
+ m_d->presetConnections.addConnection(
+ proxy, SIGNAL(sigSettingsChanged()),
+ this, SLOT(slotCurrentPresetSettingsChanged()));
+ }
+}
+
+void KisBrushStrokePreviewCache::slotCurrentPresetSettingsChanged()
+{
+ if (!m_d->currentPreset) {
+ return;
+ }
+
+ const QString newFingerprint = generateSettingsFingerprint(m_d->currentPreset);
+ if (newFingerprint == m_d->currentSettingsFingerprint) {
+ return;
+ }
+
+ m_d->currentSettingsFingerprint = newFingerprint;
+ slotPresetSettingsChanged(m_d->currentPreset);
+}
+
+void KisBrushStrokePreviewCache::slotCanvasResourceChanged(int key, const QVariant &value)
+{
+ Q_UNUSED(value);
+
+ if (!m_d->currentPreset) {
+ return;
+ }
+
+ const bool affectsBrush = key == KoCanvasResource::Size
+ || key == KoCanvasResource::Opacity
+ || key == KoCanvasResource::Flow
+ || key == KoCanvasResource::BrushRotation;
+
+ if (!affectsBrush) {
+ return;
+ }
+
+ const int presetId = m_d->currentPreset->resourceId();
+ invalidatePreset(presetId);
+
+ if (m_d->generator) {
+ m_d->generator->requestPreview(m_d->currentPreset);
+ }
+
+ if (presetId >= 0) {
+ Q_EMIT sigPreviewReady(presetId);
+ }
+}
+
+QString KisBrushStrokePreviewCache::generateSettingsFingerprint(KisPaintOpPresetSP preset) const
+{
+ if (!preset || !preset->settings()) {
+ return QString();
+ }
+
+ QString xml = preset->settings()->toXML();
+
+ // Strip stroke-time params that vary per-stroke.
+ static const QStringList strokeTimeProperties = {
+ QStringLiteral("Texture/Pattern/OffsetX"),
+ QStringLiteral("Texture/Pattern/OffsetY")
+ };
+
+ Q_FOREACH (const QString &propName, strokeTimeProperties) {
+ QRegularExpression re(
+ QStringLiteral("<param name=\"%1\"[^>]*>[^<]*</param>\\s*")
+ .arg(QRegularExpression::escape(propName)));
+ xml.remove(re);
+ }
+
+ return xml;
+}
diff --git a/libs/ui/widgets/KisBrushStrokePreviewCache.h b/libs/ui/widgets/KisBrushStrokePreviewCache.h
new file mode 100644
index 0000000000..4e1ed051cc
--- /dev/null
+++ b/libs/ui/widgets/KisBrushStrokePreviewCache.h
@@ -0,0 +1,99 @@
+/*
+ * SPDX-FileCopyrightText: 2026 Tenzin Rangdol <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#ifndef KIS_BRUSH_STROKE_PREVIEW_CACHE_H
+#define KIS_BRUSH_STROKE_PREVIEW_CACHE_H
+
+#include <QImage>
+#include <QObject>
+#include <QScopedPointer>
+#include <QSize>
+#include <QString>
+#include <QVariant>
+
+#include <kis_paintop_preset.h>
+#include <kritaui_export.h>
+
+class KisPresetLivePreviewView;
+
+/**
+ * Thread-safe LRU cache for brush stroke preview images.
+ * Previews are generated via KisPresetLivePreviewView and persisted to disk.
+ */
+class KRITAUI_EXPORT KisBrushStrokePreviewCache : public QObject
+{
+ Q_OBJECT
+
+public:
+ static KisBrushStrokePreviewCache* instance();
+
+ /// True if paint engine needs striped background (colorsmudge, deform, filter).
+ static bool needsStripedBackground(const QString &paintOpId);
+
+ /// True if paint engine has no preview support.
+ static bool isNoPreviewEngine(const QString &paintOpId);
+
+ /// Get cached preview scaled to size, or placeholder if not cached.
+ QImage getPreview(KisPaintOpPresetSP preset, const QSize &size);
+
+ /// Invalidate cache for a preset when its settings change.
+ void invalidatePreset(int presetId);
+
+ /// Generate previews for all presets not already cached.
+ void generateAllPreviews();
+
+ /// Register live preview view for generating stroke previews.
+ void registerLivePreviewView(KisPresetLivePreviewView *view);
+
+Q_SIGNALS:
+ /// Emitted when a preview is ready; triggers UI repaint.
+ void sigPreviewReady(int presetId);
+
+public Q_SLOTS:
+ /// Receive preview image from live preview view.
+ void slotLivePreviewImageReady(int presetId, const QImage &previewImage);
+
+ /// Handle preset settings change.
+ void slotPresetSettingsChanged(KisPaintOpPresetSP preset);
+
+ /// Track current preset for settings change detection.
+ void slotSetCurrentPreset(KisPaintOpPresetSP preset);
+
+ /// Handle canvas resource changes (size, flow, opacity, rotation).
+ void slotCanvasResourceChanged(int key, const QVariant &value);
+
+private Q_SLOTS:
+ void slotCurrentPresetSettingsChanged();
+ void slotScheduleGenerateAllPreviews();
+ void slotRunGenerateAllPreviews();
+
+private:
+ KisBrushStrokePreviewCache();
+ ~KisBrushStrokePreviewCache() override;
+ Q_DISABLE_COPY(KisBrushStrokePreviewCache)
+
+ QString generateCacheKey(int presetId) const;
+ QString generateSizedCacheKey(int presetId, const QSize &size) const;
+ void evictIfNeeded();
+ void updateAccessOrder(const QString &key);
+ QImage generatePlaceholder(const QSize &size) const;
+ QImage generateNoPreviewPlaceholder(const QSize &size) const;
+ QString generateSettingsFingerprint(KisPaintOpPresetSP preset) const;
+ QImage scalePreviewToSize(const QImage &source, const QSize &targetSize) const;
+
+ // Disk cache
+ void initDiskCache();
+ QString getDiskCacheFilename(int presetId) const;
+ bool loadFromDiskCache(int presetId, QImage &image);
+ void saveToDiskCache(int presetId, const QImage &image);
+ bool hasDiskCache(int presetId) const;
+ void removeDiskCache(int presetId);
+
+ struct Private;
+ QScopedPointer<Private> m_d;
+};
+
+#endif // KIS_BRUSH_STROKE_PREVIEW_CACHE_H
diff --git a/libs/ui/widgets/KisBrushStrokePreviewGenerator.cpp b/libs/ui/widgets/KisBrushStrokePreviewGenerator.cpp
new file mode 100644
index 0000000000..140f81b50e
--- /dev/null
+++ b/libs/ui/widgets/KisBrushStrokePreviewGenerator.cpp
@@ -0,0 +1,332 @@
+/*
+ * SPDX-FileCopyrightText: 2026 Tenzin Rangdol <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#include "KisBrushStrokePreviewGenerator.h"
+
+#include "KisBrushStrokePreviewCache.h"
+#include "kis_preset_live_preview_view.h"
+
+#include <QTimer>
+#include <QThread>
+
+namespace {
+
+int previewPoolSize()
+{
+ const int minPoolSize = 1;
+ const int maxPoolSize = 3;
+ int ideal = QThread::idealThreadCount();
+ if (ideal < minPoolSize) {
+ ideal = minPoolSize;
+ }
+ return qBound(minPoolSize, ideal, maxPoolSize);
+}
+
+} // namespace
+
+KisBrushStrokePreviewGenerator::KisBrushStrokePreviewGenerator(KisBrushStrokePreviewCache *cache)
+ : QObject(cache)
+ , m_cache(cache)
+{
+}
+
+void KisBrushStrokePreviewGenerator::setSourceView(KisPresetLivePreviewView *view)
+{
+ if (!view) {
+ clearPreviewPool(nullptr);
+ m_livePreviewView = nullptr;
+ return;
+ }
+
+ KoCanvasResourceProvider *resourceManager = view->resourceManager();
+ if (!resourceManager) {
+ return;
+ }
+
+ KisPresetLivePreviewView *previousView = m_livePreviewView.data();
+ if (previousView && previousView->parent() != view) {
+ clearPreviewPool(nullptr);
+ previousView->deleteLater();
+ previousView = nullptr;
+ }
+
+ if (!previousView) {
+ clearPreviewPool(nullptr);
+ KisPresetLivePreviewView *generatorView = new KisPresetLivePreviewView(view);
+ generatorView->resize(view->size());
+ generatorView->setVisible(false);
+ generatorView->setup(resourceManager);
+ generatorView->setCachePreviewMode(true);
+ connect(generatorView, SIGNAL(sigPreviewImageReady(int,QImage)),
+ m_cache, SLOT(slotLivePreviewImageReady(int,QImage)),
+ Qt::UniqueConnection);
+ connect(generatorView, SIGNAL(sigPreviewImageReady(int,QImage)),
+ this, SLOT(slotPreviewGenerated(int,QImage)),
+ Qt::UniqueConnection);
+ m_livePreviewView = generatorView;
+ }
+
+ if (m_batchMode && m_livePreviewView) {
+ rebuildPreviewPool();
+ }
+}
+
+void KisBrushStrokePreviewGenerator::startBatch(const QList<KisPaintOpPresetSP> &presets)
+{
+ if (m_batchMode) {
+ finalizeBatchGeneration();
+ }
+
+ m_startupPresets = presets;
+ m_startupGenerationIndex = 0;
+ m_batchMode = true;
+ m_pendingPresetIds.clear();
+
+ if (m_livePreviewView) {
+ rebuildPreviewPool();
+ }
+
+ if (m_startupPresets.isEmpty()) {
+ finalizeBatchGeneration();
+ return;
+ }
+
+ QTimer::singleShot(0, this, SLOT(scheduleNextBatchGeneration()));
+}
+
+void KisBrushStrokePreviewGenerator::requestPreview(KisPaintOpPresetSP preset)
+{
+ if (!preset || !m_livePreviewView) {
+ return;
+ }
+
+ const int presetId = preset->resourceId();
+ if (presetId < 0) {
+ return;
+ }
+
+ // Ignore on-demand requests during batch generation to avoid interruption/blank previews
+ if (m_batchMode) {
+ return;
+ }
+
+ m_livePreviewView->setCurrentPreset(preset);
+ m_livePreviewView->requestUpdateStroke();
+}
+
+void KisBrushStrokePreviewGenerator::scheduleNextBatchGeneration()
+{
+ if (!m_batchMode) {
+ return;
+ }
+
+ // If no live preview view is available, finalize batch generation
+ // instead of retrying indefinitely
+ if (!m_livePreviewView) {
+ finalizeBatchGeneration();
+ return;
+ }
+
+ if (m_previewPool.isEmpty()) {
+ rebuildPreviewPool();
+ }
+
+ // If pool is still empty after rebuild, finalize instead of retrying
+ if (m_previewPool.isEmpty()) {
+ finalizeBatchGeneration();
+ return;
+ }
+
+ bool startedAny = false;
+ for (int i = 0; i < m_previewPool.size(); ++i) {
+ KisPresetLivePreviewView *view = m_previewPool.at(i).data();
+ if (!view || m_busyPreviewViews.contains(view)) {
+ continue;
+ }
+
+ if (startNextPresetGeneration(view)) {
+ startedAny = true;
+ }
+
+ if (m_startupGenerationIndex >= m_startupPresets.size()) {
+ break;
+ }
+ }
+
+ if (!startedAny && m_startupGenerationIndex >= m_startupPresets.size()
+ && m_busyPreviewViews.isEmpty()) {
+ finalizeBatchGeneration();
+ }
+}
+
+bool KisBrushStrokePreviewGenerator::startNextPresetGeneration(KisPresetLivePreviewView *view)
+{
+ if (!view) {
+ return false;
+ }
+
+ while (m_startupGenerationIndex < m_startupPresets.size()) {
+ KisPaintOpPresetSP preset = m_startupPresets.at(m_startupGenerationIndex);
+ ++m_startupGenerationIndex;
+
+ if (!preset) {
+ continue;
+ }
+
+ const int presetId = preset->resourceId();
+ if (presetId < 0) {
+ continue;
+ }
+
+ if (m_pendingPresetIds.contains(presetId)) {
+ continue;
+ }
+ m_pendingPresetIds.insert(presetId);
+
+ m_busyPreviewViews.insert(view);
+ view->setCurrentPreset(preset);
+ view->requestUpdateStrokeImmediate();
+ return true;
+ }
+
+ return false;
+}
+
+void KisBrushStrokePreviewGenerator::finalizeBatchGeneration()
+{
+ m_startupPresets.clear();
+ m_startupGenerationIndex = 0;
+ m_busyPreviewViews.clear();
+ m_pendingPresetIds.clear();
+
+ if (!m_batchMode) {
+ return;
+ }
+
+ m_batchMode = false;
+ if (!m_previewPool.isEmpty()) {
+ Q_FOREACH (const QPointer<KisPresetLivePreviewView> &viewPtr, m_previewPool) {
+ if (viewPtr) {
+ viewPtr->setBatchPreviewMode(false);
+ }
+ }
+ } else if (m_livePreviewView) {
+ m_livePreviewView->setBatchPreviewMode(false);
+ }
+}
+
+void KisBrushStrokePreviewGenerator::clearPreviewPool(KisPresetLivePreviewView *keepView)
+{
+ Q_FOREACH (const QPointer<KisPresetLivePreviewView> &viewPtr, m_previewPool) {
+ KisPresetLivePreviewView *view = viewPtr.data();
+ if (view && view != keepView) {
+ view->deleteLater();
+ }
+ }
+ m_previewPool.clear();
+ m_busyPreviewViews.clear();
+}
+
+void KisBrushStrokePreviewGenerator::rebuildPreviewPool()
+{
+ if (!m_livePreviewView) {
+ clearPreviewPool(nullptr);
+ return;
+ }
+
+ for (int i = m_previewPool.size() - 1; i >= 0; --i) {
+ if (!m_previewPool.at(i)) {
+ m_previewPool.removeAt(i);
+ }
+ }
+
+ bool hasLiveView = false;
+ Q_FOREACH (const QPointer<KisPresetLivePreviewView> &viewPtr, m_previewPool) {
+ if (viewPtr && viewPtr == m_livePreviewView) {
+ hasLiveView = true;
+ break;
+ }
+ }
+
+ if (!hasLiveView) {
+ clearPreviewPool(m_livePreviewView.data());
+ }
+
+ if (m_previewPool.isEmpty()) {
+ m_previewPool.append(m_livePreviewView.data());
+ }
+
+ Q_FOREACH (const QPointer<KisPresetLivePreviewView> &viewPtr, m_previewPool) {
+ if (!viewPtr) {
+ continue;
+ }
+
+ viewPtr->setBatchPreviewMode(m_batchMode);
+ viewPtr->setCachePreviewMode(true);
+ connect(viewPtr.data(), SIGNAL(sigPreviewImageReady(int,QImage)),
+ m_cache, SLOT(slotLivePreviewImageReady(int,QImage)),
+ Qt::UniqueConnection);
+ connect(viewPtr.data(), SIGNAL(sigPreviewImageReady(int,QImage)),
+ this, SLOT(slotPreviewGenerated(int,QImage)),
+ Qt::UniqueConnection);
+ }
+
+ const int desired = previewPoolSize();
+ if (m_previewPool.size() >= desired) {
+ return;
+ }
+
+ KoCanvasResourceProvider *resourceManager = m_livePreviewView->resourceManager();
+ if (!resourceManager) {
+ return;
+ }
+
+ m_previewPool.reserve(desired);
+ while (m_previewPool.size() < desired) {
+ KisPresetLivePreviewView *view = new KisPresetLivePreviewView(m_livePreviewView);
+ view->resize(m_livePreviewView->size());
+ view->setVisible(false);
+ view->setup(resourceManager);
+ view->setBatchPreviewMode(m_batchMode);
+ view->setCachePreviewMode(true);
+ connect(view, SIGNAL(sigPreviewImageReady(int,QImage)),
+ m_cache, SLOT(slotLivePreviewImageReady(int,QImage)),
+ Qt::UniqueConnection);
+ connect(view, SIGNAL(sigPreviewImageReady(int,QImage)),
+ this, SLOT(slotPreviewGenerated(int,QImage)),
+ Qt::UniqueConnection);
+ m_previewPool.append(view);
+ }
+}
+
+void KisBrushStrokePreviewGenerator::slotPreviewGenerated(int presetId, const QImage &previewImage)
+{
+ Q_UNUSED(previewImage);
+
+ if (presetId >= 0) {
+ m_pendingPresetIds.remove(presetId);
+ }
+
+ if (!m_batchMode) {
+ return;
+ }
+
+ KisPresetLivePreviewView *senderView =
+ qobject_cast<KisPresetLivePreviewView*>(sender());
+ if (!senderView || !m_busyPreviewViews.contains(senderView)) {
+ return;
+ }
+
+ m_busyPreviewViews.remove(senderView);
+ if (startNextPresetGeneration(senderView)) {
+ return;
+ }
+
+ if (m_startupGenerationIndex >= m_startupPresets.size()
+ && m_busyPreviewViews.isEmpty()) {
+ finalizeBatchGeneration();
+ }
+}
diff --git a/libs/ui/widgets/KisBrushStrokePreviewGenerator.h b/libs/ui/widgets/KisBrushStrokePreviewGenerator.h
new file mode 100644
index 0000000000..6abdb14ba6
--- /dev/null
+++ b/libs/ui/widgets/KisBrushStrokePreviewGenerator.h
@@ -0,0 +1,59 @@
+/*
+ * SPDX-FileCopyrightText: 2026 Tenzin Rangdol <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#ifndef KIS_BRUSH_STROKE_PREVIEW_GENERATOR_H
+#define KIS_BRUSH_STROKE_PREVIEW_GENERATOR_H
+
+#include <QList>
+#include <QObject>
+#include <QPointer>
+#include <QSet>
+#include <QVector>
+
+#include <kis_paintop_preset.h>
+
+class QImage;
+class KisBrushStrokePreviewCache;
+class KisPresetLivePreviewView;
+
+/**
+ * @brief Manages brush stroke preview generation and batch scheduling.
+ */
+class KisBrushStrokePreviewGenerator : public QObject
+{
+ Q_OBJECT
+
+public:
+ explicit KisBrushStrokePreviewGenerator(KisBrushStrokePreviewCache *cache);
+
+ void setSourceView(KisPresetLivePreviewView *view);
+ void startBatch(const QList<KisPaintOpPresetSP> &presets);
+ void requestPreview(KisPaintOpPresetSP preset);
+
+private Q_SLOTS:
+ void scheduleNextBatchGeneration();
+ /**
+ * @brief Handle completion for a presetId preview.
+ */
+ void slotPreviewGenerated(int presetId, const QImage &previewImage);
+
+private:
+ bool startNextPresetGeneration(KisPresetLivePreviewView *view);
+ void finalizeBatchGeneration();
+ void clearPreviewPool(KisPresetLivePreviewView *keepView);
+ void rebuildPreviewPool();
+
+ KisBrushStrokePreviewCache *m_cache = nullptr;
+ QPointer<KisPresetLivePreviewView> m_livePreviewView;
+ QVector<QPointer<KisPresetLivePreviewView>> m_previewPool;
+ QSet<KisPresetLivePreviewView*> m_busyPreviewViews;
+ QSet<int> m_pendingPresetIds;
+ QList<KisPaintOpPresetSP> m_startupPresets;
+ int m_startupGenerationIndex = 0;
+ bool m_batchMode = false;
+};
+
+#endif
diff --git a/libs/ui/widgets/kis_paintop_presets_chooser_popup.cpp b/libs/ui/widgets/kis_paintop_presets_chooser_popup.cpp
index 56d7c6dad1..07d019fe2a 100644
--- a/libs/ui/widgets/kis_paintop_presets_chooser_popup.cpp
+++ b/libs/ui/widgets/kis_paintop_presets_chooser_popup.cpp
@@ -57,6 +57,11 @@ KisPaintOpPresetsChooserPopup::KisPaintOpPresetsChooserPopup(QWidget * parent)
action->setChecked(mode == KisPresetChooser::DETAIL);
action->setActionGroup(actionGroup);
+ action = menu->addAction(KisIconUtils::loadIcon("krita_tool_freehand"), i18n("Strokes"), this, SLOT(slotStrokeMode()));
+ action->setCheckable(true);
+ action->setChecked(mode == KisPresetChooser::STROKE);
+ action->setActionGroup(actionGroup);
+
// add widget slider to control icon size
QSlider* iconSizeSlider = new QSlider(this);
iconSizeSlider->setOrientation(Qt::Horizontal);
@@ -115,6 +120,12 @@ void KisPaintOpPresetsChooserPopup::slotDetailMode()
m_d->uiWdgPaintOpPresets.wdgPresetChooser->setViewMode(KisPresetChooser::DETAIL);
}
+void KisPaintOpPresetsChooserPopup::slotStrokeMode()
+{
+ KisConfig(false).setPresetChooserViewMode(KisPresetChooser::STROKE);
+ m_d->uiWdgPaintOpPresets.wdgPresetChooser->setViewMode(KisPresetChooser::STROKE);
+}
+
void KisPaintOpPresetsChooserPopup::slotUpdateMenu()
{
QSignalBlocker b(m_d->iconSizeSlider);
diff --git a/libs/ui/widgets/kis_paintop_presets_chooser_popup.h b/libs/ui/widgets/kis_paintop_presets_chooser_popup.h
index 0b8afcefc7..e272c63f91 100644
--- a/libs/ui/widgets/kis_paintop_presets_chooser_popup.h
+++ b/libs/ui/widgets/kis_paintop_presets_chooser_popup.h
@@ -19,7 +19,7 @@ class KRITAUI_EXPORT KisPaintOpPresetsChooserPopup : public QWidget
{
Q_OBJECT
public:
- KisPaintOpPresetsChooserPopup(QWidget * parent = 0);
+ KisPaintOpPresetsChooserPopup(QWidget * parent = nullptr);
~KisPaintOpPresetsChooserPopup() override;
void updateViewSettings();
@@ -35,6 +35,7 @@ Q_SIGNALS:
private Q_SLOTS:
void slotThumbnailMode();
void slotDetailMode();
+ void slotStrokeMode();
void slotUpdateMenu();
void paintEvent(QPaintEvent *) override;
diff --git a/libs/ui/widgets/kis_paintop_presets_editor.cpp b/libs/ui/widgets/kis_paintop_presets_editor.cpp
index 2b028099b6..e4390a2889 100644
--- a/libs/ui/widgets/kis_paintop_presets_editor.cpp
+++ b/libs/ui/widgets/kis_paintop_presets_editor.cpp
@@ -50,6 +50,7 @@
// ones from brush engine selector
#include <brushengine/kis_paintop_factory.h>
#include <kis_preset_live_preview_view.h>
+#include "KisBrushStrokePreviewCache.h"
#include <lager/state.hpp>
@@ -169,6 +170,14 @@ KisPaintOpPresetsEditor::KisPaintOpPresetsEditor(KisCanvasResourceProvider * res
connect(action, &QAction::triggered,
m_d->uiWdgPaintOpPresetSettings.presetWidget, &KisPresetChooser::setViewModeToDetail);
+ action = viewModeMenu->addAction(KisIconUtils::loadIcon("krita_tool_freehand"),i18n("Strokes"));
+ action->setCheckable(true);
+ action->setChecked(mode == KisPresetChooser::STROKE);
+ action->setActionGroup(actionGroup);
+
+ connect(action, &QAction::triggered,
+ m_d->uiWdgPaintOpPresetSettings.presetWidget, &KisPresetChooser::setViewModeToStroke);
+
// Icon Size Slider
viewModeMenu->addSection(i18n("Icon Size"));
@@ -292,6 +301,10 @@ KisPaintOpPresetsEditor::KisPaintOpPresetsEditor(KisCanvasResourceProvider * res
// setup things like the scene construct images, layers, etc that is a one-time thing
m_d->uiWdgPaintOpPresetSettings.liveBrushPreviewView->setup(resourceProvider->resourceManager());
+ // Register the live preview view with the cache for preview generation.
+ KisBrushStrokePreviewCache::instance()->registerLivePreviewView(
+ m_d->uiWdgPaintOpPresetSettings.liveBrushPreviewView);
+
// Responsive Layout
m_d->horzSplitter = new QSplitter(this); // you can't add QSplitter to a UI file
m_d->horzSplitter->setChildrenCollapsible(false);
diff --git a/libs/ui/widgets/kis_preset_chooser.cpp b/libs/ui/widgets/kis_preset_chooser.cpp
index 07366c982c..ebc4912ca7 100644
--- a/libs/ui/widgets/kis_preset_chooser.cpp
+++ b/libs/ui/widgets/kis_preset_chooser.cpp
@@ -10,13 +10,15 @@
#include "kis_preset_chooser.h"
+#include <QEvent>
#include <QVBoxLayout>
#include <QPainter>
#include <QAbstractItemDelegate>
+#include <QAbstractItemView>
#include <QStyleOptionViewItem>
-#include <QSortFilterProxyModel>
+#include <QPalette>
+#include <QTimer>
#include <KisResourceModel.h>
-#include <QApplication>
#include <kis_config.h>
#include <klocalizedstring.h>
@@ -33,28 +35,38 @@
#include <brushengine/kis_paintop_preset.h>
#include "kis_config_notifier.h"
#include <kis_icon.h>
-#include <KisResourceModelProvider.h>
#include <KisTagFilterResourceProxyModel.h>
#include <KisResourceThumbnailCache.h>
-#include <KisResourceMetaDataModel.h>
+#include "KisBrushStrokePreviewCache.h"
-
-/// The resource item delegate for rendering the resource preview
+/// Resource item delegate for rendering brush stroke previews
class KisPresetDelegate : public QAbstractItemDelegate
{
public:
- KisPresetDelegate(QObject * parent = 0)
+ // Stroke preview ratio range: 1:3 to 1:4.
+ static constexpr int SLIDER_MIN = 30;
+ static constexpr int SLIDER_MAX = 80;
+ static constexpr double ASPECT_RATIO_MIN = 3.0;
+ static constexpr double ASPECT_RATIO_MAX = 4.0;
+
+ KisPresetDelegate(QObject * parent = nullptr)
: QAbstractItemDelegate(parent)
, m_showText(false)
- , m_useDirtyPresets(false) {}
+ , m_useDirtyPresets(false)
+ , m_viewMode(KisPresetChooser::THUMBNAIL)
+ , m_iconSize(50) {}
~KisPresetDelegate() override {}
/// reimplemented
void paint(QPainter *, const QStyleOptionViewItem &, const QModelIndex &) const override;
- /// reimplemented
QSize sizeHint(const QStyleOptionViewItem & option, const QModelIndex &) const override {
+ if (m_viewMode == KisPresetChooser::STROKE) {
+ int height = m_iconSize;
+ int width = static_cast<int>(height * calculateAspectRatio(m_iconSize));
+ return QSize(width, height);
+ }
return option.decorationSize;
}
@@ -62,13 +74,38 @@ public:
m_showText = showText;
}
+ void setViewMode(KisPresetChooser::ViewMode mode) {
+ m_viewMode = mode;
+ }
+
void setUseDirtyPresets(bool value) {
m_useDirtyPresets = value;
}
+ void setIconSize(int size) {
+ m_iconSize = qBound(SLIDER_MIN, size, SLIDER_MAX);
+ }
+
+ /// Interpolate aspect ratio from slider.
+ static double calculateAspectRatio(int iconSize) {
+ int clampedSize = qBound(SLIDER_MIN, iconSize, SLIDER_MAX);
+ double t = static_cast<double>(clampedSize - SLIDER_MIN) / (SLIDER_MAX - SLIDER_MIN);
+ return ASPECT_RATIO_MIN + t * (ASPECT_RATIO_MAX - ASPECT_RATIO_MIN);
+ }
+
+ static QSize calculateStrokeThumbnailSize(int iconSize) {
+ int clampedSize = qBound(SLIDER_MIN, iconSize, SLIDER_MAX);
+ double aspectRatio = calculateAspectRatio(clampedSize);
+ return QSize(static_cast<int>(clampedSize * aspectRatio), clampedSize);
+ }
+
private:
+ void paintThumbnail(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
+ void paintStrokePreview(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
bool m_showText;
+ KisPresetChooser::ViewMode m_viewMode;
bool m_useDirtyPresets;
+ int m_iconSize;
};
void KisPresetDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
@@ -84,6 +121,18 @@ void KisPresetDelegate::paint(QPainter * painter, const QStyleOptionViewItem & o
return;
}
+ if (m_viewMode == KisPresetChooser::STROKE) {
+ paintStrokePreview(painter, option, index);
+ } else {
+ paintThumbnail(painter, option, index);
+ }
+
+ painter->restore();
+}
+
+void KisPresetDelegate::paintThumbnail(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
+{
+
bool dirty = index.data(Qt::UserRole + KisAbstractResourceModel::Dirty).toBool();
QImage preview = KisResourceThumbnailCache::instance()->getImage(index);
@@ -161,9 +210,114 @@ void KisPresetDelegate::paint(QPainter * painter, const QStyleOptionViewItem & o
QRect selectedBorder = option.rect.adjusted(2 , 2, -2, -2); // constrict the rectangle so it doesn't bleed into other presets
painter->drawRect(selectedBorder);
}
+}
- painter->restore();
+void KisPresetDelegate::paintStrokePreview(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
+{
+ bool dirty = index.data(Qt::UserRole + KisAbstractResourceModel::Dirty).toBool();
+
+ KoResourceSP resource;
+ const KisAbstractResourceModel *resourceModel = dynamic_cast<const KisAbstractResourceModel*>(index.model());
+ if (resourceModel) {
+ resource = resourceModel->resourceForIndex(index);
+ }
+ KisPaintOpPresetSP preset = resource.dynamicCast<KisPaintOpPreset>();
+ qreal devicePixelRatioF = painter->device()->devicePixelRatioF();
+ const bool isSelected = option.state & QStyle::State_Selected;
+
+ const QColor backgroundColor = option.palette.color(QPalette::Window);
+ const QColor borderColor = option.palette.color(QPalette::Mid);
+ QColor textColor = option.palette.color(QPalette::Text);
+ if (isSelected) {
+ textColor = textColor.lightnessF() < 0.5 ? QColor(Qt::black) : QColor(Qt::white);
+ }
+
+ painter->fillRect(option.rect, borderColor);
+ QRect innerRect = option.rect.adjusted(2, 2, -2, -2);
+ painter->fillRect(innerRect, backgroundColor);
+ if (isSelected) {
+ const QColor accentColor = option.palette.highlight().color();
+ const qreal bgLightness = backgroundColor.lightnessF();
+ const qreal accentLightness = accentColor.lightnessF();
+ const bool sameSide =
+ (bgLightness >= 0.5 && accentLightness >= 0.5) ||
+ (bgLightness < 0.5 && accentLightness < 0.5);
+ if (sameSide) {
+ painter->setCompositionMode(QPainter::CompositionMode_HardLight);
+ painter->setOpacity(1.0);
+ painter->fillRect(innerRect, accentColor);
+ painter->setCompositionMode(QPainter::CompositionMode_SourceOver);
+ }
+ }
+
+ // Keep text height fixed; stroke area shrinks.
+ QFontMetrics fm(painter->font());
+ const int bottomPadding = 1;
+ const int textAreaHeight = fm.height() + 4 + bottomPadding;
+ const int textAreaTopTrim = 3;
+
+ QRect strokeRect = innerRect;
+ strokeRect.setHeight(qMax(10, innerRect.height() - (textAreaHeight - textAreaTopTrim)));
+
+ QSize previewSize = strokeRect.size() * devicePixelRatioF;
+
+ const QString paintOpId = preset ? preset->paintOp().id() : QString();
+ const bool useStripedBackground = KisBrushStrokePreviewCache::needsStripedBackground(paintOpId);
+
+ QImage strokePreview;
+ if (preset) {
+ strokePreview = KisBrushStrokePreviewCache::instance()->getPreview(preset, previewSize);
+ }
+ if (strokePreview.isNull()) {
+ strokePreview = QImage(previewSize, QImage::Format_ARGB32_Premultiplied);
+ strokePreview.fill(Qt::transparent);
+ }
+
+ if (useStripedBackground) {
+ strokePreview.setDevicePixelRatio(devicePixelRatioF);
+ painter->drawImage(strokeRect.topLeft(), strokePreview);
+ } else {
+ QImage tinted = strokePreview.convertToFormat(QImage::Format_ARGB32_Premultiplied);
+ QPainter maskPainter(&tinted);
+ maskPainter.setCompositionMode(QPainter::CompositionMode_SourceIn);
+ maskPainter.fillRect(tinted.rect(), textColor);
+ maskPainter.end();
+ tinted.setDevicePixelRatio(devicePixelRatioF);
+ painter->drawImage(strokeRect.topLeft(), tinted);
+ }
+
+ QString presetDisplayName = index.data(Qt::UserRole + KisAbstractResourceModel::Name)
+ .toString()
+ .replace(QLatin1Char('_'), QLatin1Char(' '));
+ if (dirty) {
+ presetDisplayName.append(QLatin1Char('*'));
+ }
+ QString elidedName = fm.elidedText(presetDisplayName, Qt::ElideRight, innerRect.width() - 14);
+
+ QRect textRect = innerRect;
+ textRect.setTop(innerRect.bottom() - textAreaHeight);
+ textRect.setLeft(innerRect.left() + 7);
+ textRect.setBottom(innerRect.bottom() - bottomPadding);
+ painter->setPen(textColor);
+ painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, elidedName);
+
+ if (dirty) {
+ const QIcon icon = KisIconUtils::loadIcon(QStringLiteral("dirty-preset"));
+ QPixmap pixmap = icon.pixmap(QSize(16, 16));
+ painter->drawPixmap(innerRect.x() + 3, innerRect.y() + 3, pixmap);
+ }
+
+ if (index.data(Qt::UserRole + KisAbstractResourceModel::BrokenStatus).toBool()) {
+ const QIcon icon = KisIconUtils::loadIcon(QStringLiteral("broken-preset"));
+ icon.paint(painter, QRect(innerRect.right() - 25, innerRect.y() + 3, 22, 22));
+ }
+
+ if (isSelected) {
+ painter->setPen(QPen(option.palette.highlight(), 4, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin));
+ QRect selectedBorder = option.rect.adjusted(2, 2, -2, -2);
+ painter->drawRect(selectedBorder);
+ }
}
KisPresetChooser::KisPresetChooser(QWidget *parent)
@@ -182,23 +336,26 @@ KisPresetChooser::KisPresetChooser(QWidget *parent)
m_chooser->showImportExportBtns(false);
layout->addWidget(m_chooser);
- connect(m_chooser, SIGNAL(resourceSelected(KoResourceSP )),
- this, SLOT(slotResourceWasSelected(KoResourceSP )));
-
connect(m_chooser, SIGNAL(resourceSelected(KoResourceSP )),
this, SIGNAL(resourceSelected(KoResourceSP )));
connect(m_chooser, SIGNAL(resourceClicked(KoResourceSP )),
this, SIGNAL(resourceClicked(KoResourceSP )));
- connect(m_chooser, &KisResourceItemChooser::listViewModeChanged, this, &KisPresetChooser::showHideBrushNames);
+ connect(m_chooser, SIGNAL(listViewModeChanged(ListViewMode)),
+ this, SLOT(showHideBrushNames(ListViewMode)));
+
+ connect(KisBrushStrokePreviewCache::instance(), SIGNAL(sigPreviewReady(int)),
+ this, SLOT(slotStrokePreviewReady(int)));
m_mode = ViewMode::THUMBNAIL;
connect(KisConfigNotifier::instance(), SIGNAL(configChanged()),
SLOT(notifyConfigChanged()));
-
notifyConfigChanged();
+
+ // Pre-generate stroke previews.
+ QTimer::singleShot(0, this, SLOT(slotGenerateStrokePreviews()));
}
KisPresetChooser::~KisPresetChooser()
@@ -209,6 +366,7 @@ void KisPresetChooser::setViewMode(KisPresetChooser::ViewMode mode)
{
m_mode = mode;
updateViewSettings();
+ KisBrushStrokePreviewCache::instance()->generateAllPreviews();
}
void KisPresetChooser::setViewModeToThumbnail()
@@ -221,35 +379,18 @@ void KisPresetChooser::setViewModeToDetail()
setViewMode(KisPresetChooser::ViewMode::DETAIL);
}
-void KisPresetChooser::notifyConfigChanged()
-{
- KisConfig cfg(true);
- m_delegate->setUseDirtyPresets(cfg.useDirtyPresets());
- setIconSize(cfg.presetIconSize());
-}
-
-void KisPresetChooser::slotResourceWasSelected(KoResourceSP resource)
+void KisPresetChooser::setViewModeToStroke()
{
- m_currentPresetConnections.clear();
- if (!resource) return;
-
- KisPaintOpPresetSP preset = resource.dynamicCast<KisPaintOpPreset>();
- KIS_SAFE_ASSERT_RECOVER_RETURN(preset);
-
- m_currentPresetConnections.addUniqueConnection(
- preset->updateProxy(), SIGNAL(sigSettingsChanged()),
- this, SLOT(slotCurrentPresetChanged()));
+ setViewMode(KisPresetChooser::ViewMode::STROKE);
}
-void KisPresetChooser::slotCurrentPresetChanged()
+void KisPresetChooser::notifyConfigChanged()
{
- KoResourceSP currentResource = m_chooser->currentResource();
- if (!currentResource) return;
-
- QModelIndex index = m_chooser->tagFilterModel()->indexForResource(currentResource);
- Q_EMIT m_chooser->tagFilterModel()->dataChanged(index,
- index,
- {Qt::UserRole + KisAbstractResourceModel::Thumbnail});
+ KisConfig cfg(true);
+ m_delegate->setUseDirtyPresets(cfg.useDirtyPresets());
+ int newIconSize = cfg.presetIconSize();
+ m_delegate->setIconSize(newIconSize);
+ setIconSize(newIconSize);
}
void KisPresetChooser::updateViewSettings()
@@ -258,11 +399,27 @@ void KisPresetChooser::updateViewSettings()
case ViewMode::THUMBNAIL: {
m_chooser->setListViewMode(ListViewMode::IconGrid);
m_delegate->setShowText(false);
+ m_delegate->setViewMode(ViewMode::THUMBNAIL);
break;
}
case ViewMode::DETAIL: {
m_chooser->setListViewMode(ListViewMode::Detail);
m_delegate->setShowText(true);
+ m_delegate->setViewMode(ViewMode::DETAIL);
+ break;
+ }
+ case ViewMode::STROKE: {
+ m_chooser->setListViewMode(ListViewMode::IconGrid);
+ m_delegate->setShowText(false);
+ m_delegate->setViewMode(ViewMode::STROKE);
+
+ int currentIconSize = iconSize();
+ m_delegate->setIconSize(currentIconSize);
+ QSize thumbnailSize = KisPresetDelegate::calculateStrokeThumbnailSize(currentIconSize);
+
+ m_chooser->itemView()->setGridSize(thumbnailSize);
+ m_chooser->itemView()->setIconSize(thumbnailSize);
+ m_chooser->itemView()->doItemsLayout();
break;
}
}
@@ -302,6 +459,17 @@ void KisPresetChooser::setIconSize(int newSize)
{
KisResourceItemChooserSync* chooserSync = KisResourceItemChooserSync::instance();
chooserSync->setBaseLength(newSize);
+
+ if (m_mode == ViewMode::STROKE) {
+ m_delegate->setIconSize(newSize);
+ QSize thumbnailSize = KisPresetDelegate::calculateStrokeThumbnailSize(newSize);
+
+ m_chooser->itemView()->setGridSize(thumbnailSize);
+ m_chooser->itemView()->setIconSize(thumbnailSize);
+ m_chooser->itemView()->doItemsLayout();
+ }
+
+ KisBrushStrokePreviewCache::instance()->generateAllPreviews();
}
int KisPresetChooser::iconSize()
@@ -312,14 +480,33 @@ int KisPresetChooser::iconSize()
void KisPresetChooser::saveIconSize()
{
- // save icon size
if (KisConfig(true).presetIconSize() != iconSize()) {
KisConfig(false).setPresetIconSize(iconSize());
}
}
+void KisPresetChooser::changeEvent(QEvent *event)
+{
+ QWidget::changeEvent(event);
+ if (event->type() == QEvent::PaletteChange) {
+ if (m_mode == ViewMode::STROKE) {
+ m_chooser->itemView()->viewport()->update();
+ }
+ }
+}
+
void KisPresetChooser::showHideBrushNames(ListViewMode newViewMode)
{
+ if (m_mode == ViewMode::STROKE) {
+ m_delegate->setShowText(false);
+ // Restore non-square grid size.
+ int currentIconSize = iconSize();
+ QSize thumbnailSize = KisPresetDelegate::calculateStrokeThumbnailSize(currentIconSize);
+ m_chooser->itemView()->setGridSize(thumbnailSize);
+ m_chooser->itemView()->setIconSize(thumbnailSize);
+ m_chooser->itemView()->doItemsLayout();
+ return;
+ }
switch (newViewMode) {
case ListViewMode::Detail: {
m_delegate->setShowText(true);
@@ -330,3 +517,33 @@ void KisPresetChooser::showHideBrushNames(ListViewMode newViewMode)
}
}
}
+
+void KisPresetChooser::slotStrokePreviewReady(int presetId)
+{
+ if (m_mode != ViewMode::STROKE) {
+ return;
+ }
+
+ KisTagFilterResourceProxyModel *model = m_chooser->tagFilterModel();
+ if (!model) {
+ m_chooser->itemView()->viewport()->update();
+ return;
+ }
+
+ QModelIndex index = model->indexForResourceId(presetId);
+ if (!index.isValid()) {
+ return;
+ }
+
+ const QRect rect = m_chooser->itemView()->visualRect(index);
+ if (!rect.isValid()) {
+ return;
+ }
+
+ m_chooser->itemView()->viewport()->update(rect);
+}
+
+void KisPresetChooser::slotGenerateStrokePreviews()
+{
+ KisBrushStrokePreviewCache::instance()->generateAllPreviews();
+}
diff --git a/libs/ui/widgets/kis_preset_chooser.h b/libs/ui/widgets/kis_preset_chooser.h
index 31eae8f5ce..1e977da3d4 100644
--- a/libs/ui/widgets/kis_preset_chooser.h
+++ b/libs/ui/widgets/kis_preset_chooser.h
@@ -13,7 +13,6 @@
#include <KoResource.h>
#include <KoID.h>
-#include "kis_signal_auto_connection.h"
#include "ResourceListViewModes.h"
class KoAbstractResourceServerAdapter;
@@ -39,13 +38,15 @@ public:
enum ViewMode {
THUMBNAIL, /// Shows thumbnails
- DETAIL /// Shows thumbnails with text next to it
+ DETAIL, /// Shows thumbnails with text next to it
+ STROKE /// Shows stroke previews with text
};
/// Sets a list of resources in the paintop list, when ever user press enter in the lineedit of paintop_presets_popup Class
void setViewMode(ViewMode mode);
void setViewModeToThumbnail();
void setViewModeToDetail();
+ void setViewModeToStroke();
void setCurrentResource(KoResourceSP resource);
@@ -80,20 +81,18 @@ public Q_SLOTS:
/// KisResourceItemChooser is in horizontal layout.
void showHideBrushNames(ListViewMode newViewMode);
+protected:
+ void changeEvent(QEvent *event) override;
+
private Q_SLOTS:
void notifyConfigChanged();
- void slotResourceWasSelected(KoResourceSP resource);
- void slotCurrentPresetChanged();
+ void slotStrokePreviewReady(int presetId);
+ void slotGenerateStrokePreviews();
private:
- KisResourceItemChooser *m_chooser {0};
- KisPresetDelegate* m_delegate {0};
+ KisResourceItemChooser *m_chooser {nullptr};
+ KisPresetDelegate* m_delegate {nullptr};
ViewMode m_mode;
-
- class PaintOpFilterModel;
- QPointer<PaintOpFilterModel> m_paintOpFilterModel;
-
- KisSignalAutoConnectionsStore m_currentPresetConnections;
};
#endif
diff --git a/libs/ui/widgets/kis_preset_live_preview_view.cpp b/libs/ui/widgets/kis_preset_live_preview_view.cpp
index 5fb452734f..2c4b54511b 100644
--- a/libs/ui/widgets/kis_preset_live_preview_view.cpp
+++ b/libs/ui/widgets/kis_preset_live_preview_view.cpp
@@ -6,10 +6,16 @@
*/
#include <QEvent>
+#include <QGraphicsPixmapItem>
+#include <QGraphicsScene>
+#include <QPalette>
+#include <QSet>
+
+#include <KoColorSpaceRegistry.h>
#include <kis_preset_live_preview_view.h>
-#include <QDebug>
-#include <QGraphicsPixmapItem>
+#include <kis_image.h>
+#include <kis_paint_layer.h>
#include "kis_paintop_settings.h"
#include <strokes/freehand_stroke.h>
#include <strokes/KisFreehandStrokeInfo.h>
@@ -18,10 +24,21 @@
#include <KisGlobalResourcesInterface.h>
#include "kis_transaction.h"
#include <KoCanvasResourceProvider.h>
+#include <KoCompositeOpRegistry.h>
+#include "KisBrushStrokePreviewCache.h"
+
+
+static bool needsBlendingModeOverride(const QString &compositeOp)
+{
+ //Brush presets with Erase blending mode have blank stroke previews without this
+ static const QSet<QString> invisibleModes = {COMPOSITE_ERASE};
+ return invisibleModes.contains(compositeOp);
+}
+
KisPresetLivePreviewView::KisPresetLivePreviewView(QWidget *parent)
: QGraphicsView(parent),
- m_updateCompressor(100, KisSignalCompressor::FIRST_ACTIVE)
+ m_updateCompressor(DefaultUpdateDelayMs, KisSignalCompressor::FIRST_ACTIVE)
{
connect(&m_updateCompressor, SIGNAL(timeout()), SLOT(updateStroke()));
}
@@ -36,9 +53,9 @@ void KisPresetLivePreviewView::setup(KoCanvasResourceProvider* resourceManager)
{
m_resourceManager = resourceManager;
- // initializing to 0 helps check later if they actually have something in them
- m_noPreviewText = 0;
- m_sceneImageItem = 0;
+ // initializing to nullptr helps check later if they actually have something in them
+ m_noPreviewText = nullptr;
+ m_sceneImageItem = nullptr;
setHorizontalScrollBarPolicy ( Qt::ScrollBarAlwaysOff );
setVerticalScrollBarPolicy ( Qt::ScrollBarAlwaysOff );
@@ -73,119 +90,163 @@ void KisPresetLivePreviewView::requestUpdateStroke()
m_updateCompressor.start();
}
-void KisPresetLivePreviewView::updateStroke()
+void KisPresetLivePreviewView::requestUpdateStrokeImmediate()
{
- // do not paint a stroke if we are any of these engines (they have some issue currently)
- if (m_currentPreset->paintOp().id() == "roundmarker" ||
- m_currentPreset->paintOp().id() == "experimentbrush" ||
- m_currentPreset->paintOp().id() == "duplicate") {
+ if (m_previewGenerationInProgress) {
+ m_updateCompressor.start();
+ return;
+ }
+ updateStroke();
+}
- paintBackground();
- slotPreviewGenerationCompleted();
+void KisPresetLivePreviewView::setBatchPreviewMode(bool enabled)
+{
+ if (m_batchPreviewMode == enabled) {
+ return;
+ }
+ m_batchPreviewMode = enabled;
+ m_updateCompressor.setDelay(enabled ? 0 : DefaultUpdateDelayMs);
+}
+
+void KisPresetLivePreviewView::setCachePreviewMode(bool enabled)
+{
+ m_cachePreviewMode = enabled;
+}
+
+KoCanvasResourceProvider* KisPresetLivePreviewView::resourceManager() const
+{
+ return m_resourceManager;
+}
+
+void KisPresetLivePreviewView::updateStroke()
+{
+ if (!m_currentPreset) {
return;
}
- if (!m_previewGenerationInProgress) {
- paintBackground();
- setupAndPaintStroke();
- } else {
+ if (m_previewGenerationInProgress) {
m_updateCompressor.start();
+ return;
}
+
+ m_previewPresetId = m_currentPreset->resourceId();
+
+ // do not paint a stroke if we are any of these engines (they have some issue currently)
+ if (KisBrushStrokePreviewCache::isNoPreviewEngine(m_currentPreset->paintOp().id())) {
+ paintBackground(m_cachePreviewMode);
+ slotPreviewGenerationCompleted();
+ return;
+ }
+
+ paintBackground(m_cachePreviewMode);
+ setupAndPaintStroke();
}
void KisPresetLivePreviewView::slotPreviewGenerationCompleted()
{
m_previewGenerationInProgress = false;
- QImage m_temp_image;
- m_temp_image = m_layer->paintDevice()->convertToQImage(0, m_image->bounds());
+ m_lastPreviewImage = m_layer->paintDevice()->convertToQImage(0, m_image->bounds());
- // only add the object once...then just update the pixmap so we can move the preview around
- if (!m_sceneImageItem) {
- m_sceneImageItem = m_brushPreviewScene->addPixmap(QPixmap::fromImage(m_temp_image));
- } else {
- m_sceneImageItem->setPixmap(QPixmap::fromImage(m_temp_image));
+ if (!m_batchPreviewMode && !m_cachePreviewMode) {
+ // only add the object once...then just update the pixmap so we can move the preview around
+ if (!m_sceneImageItem) {
+ m_sceneImageItem = m_brushPreviewScene->addPixmap(QPixmap::fromImage(m_lastPreviewImage));
+ } else {
+ m_sceneImageItem->setPixmap(QPixmap::fromImage(m_lastPreviewImage));
+ }
}
-}
-void KisPresetLivePreviewView::paintBackground()
-{
- // clean up "no preview" text object if it exists. we will add it later if we need it
- if (m_noPreviewText) {
- this->scene()->removeItem(m_noPreviewText);
- m_noPreviewText = 0;
+ // Emit preview for caching.
+ const int presetId = m_previewPresetId >= 0
+ ? m_previewPresetId
+ : (m_currentPreset ? m_currentPreset->resourceId() : -1);
+ if (presetId >= 0 && !m_lastPreviewImage.isNull()) {
+ Q_EMIT sigPreviewImageReady(presetId, m_lastPreviewImage);
}
+ m_previewPresetId = -1;
+}
- if (m_currentPreset->paintOp().id() == "colorsmudge" ||
- m_currentPreset->paintOp().id() == "deformbrush" ||
- m_currentPreset->paintOp().id() == "filter") {
-
- // easier to see deformations and smudging with alternating stripes in the background
- // paint the whole background with alternating stripes
- // filter engine may or may not show things depending on the filter...but it is better than nothing
+void KisPresetLivePreviewView::paintStripedBackground()
+{
+ const int grayStrips = 20;
+ const float sectionPercent = 1.0f / grayStrips;
+ const int imageWidth = m_layer->image()->width();
+ const int imageHeight = m_layer->image()->height();
- int grayStrips = 20;
- for (int i=0; i < grayStrips; i++ ) {
+ for (int i = 0; i < grayStrips; i++) {
+ KoColor fillColor(m_layer->paintDevice()->colorSpace());
+ fillColor.fromQColor((i % 2) ? QColor(80, 80, 80) : QColor(140, 140, 140));
- float sectionPercent = 1.0 / (float)grayStrips;
- bool isAlternating = i % 2;
- KoColor fillColor(m_layer->paintDevice()->colorSpace());
+ const QRect fillRect(imageWidth * sectionPercent * i,
+ 0,
+ imageWidth * (sectionPercent * i + sectionPercent),
+ imageHeight);
- if (isAlternating) {
- fillColor.fromQColor(QColor(80,80,80));
- } else {
- fillColor.fromQColor(QColor(140,140,140));
- }
+ KisTransaction t(m_layer->paintDevice());
+ m_layer->paintDevice()->fill(fillRect, fillColor);
+ t.end();
+ }
+}
+void KisPresetLivePreviewView::paintBackground(bool cacheMode)
+{
+ // clean up "no preview" text object if it exists. we will add it later if we need it
+ if (m_noPreviewText) {
+ this->scene()->removeItem(m_noPreviewText);
+ m_noPreviewText = nullptr;
+ }
- const QRect fillRect(m_layer->image()->width()*sectionPercent*i,
- 0,
- m_layer->image()->width()*(sectionPercent*i +sectionPercent),
- m_layer->image()->height());
+ const QString paintOpId = m_currentPreset->paintOp().id();
- KisTransaction t(m_layer->paintDevice());
- m_layer->paintDevice()->fill(fillRect, fillColor);
- t.end();
+ if (cacheMode) {
+ if (KisBrushStrokePreviewCache::isNoPreviewEngine(paintOpId)) {
+ m_layer->paintDevice()->clear();
+ m_paintColor = KoColor(QColor(Qt::white), m_colorSpace);
+ return;
}
- m_paintColor = KoColor(Qt::white, m_colorSpace);
+ if (KisBrushStrokePreviewCache::needsStripedBackground(paintOpId)) {
+ paintStripedBackground();
+ } else {
+ m_layer->paintDevice()->clear();
+ }
+ m_paintColor = KoColor(QColor(Qt::white), m_colorSpace);
+ return;
}
- else if (m_currentPreset->paintOp().id() == "roundmarker" ||
- m_currentPreset->paintOp().id() == "experimentbrush" ||
- m_currentPreset->paintOp().id() == "duplicate" ) {
- // cases where we will not show a preview for now
- // roundbrush (quick) -- this isn't showing anything, disable showing preview
- // experimentbrush -- this creates artifacts that carry over to other previews and messes up their display
- // duplicate (clone) brush doesn't have a preview as it doesn't show anything)
+ const QColor backgroundColor = palette().color(QPalette::Window);
+ const QColor textColor = palette().color(QPalette::Text);
- // fill with gray first to clear out what existed from previous preview
+ if (KisBrushStrokePreviewCache::needsStripedBackground(paintOpId)) {
+ paintStripedBackground();
+ m_paintColor = KoColor(textColor, m_colorSpace);
+ }
+ else if (KisBrushStrokePreviewCache::isNoPreviewEngine(paintOpId)) {
KisTransaction t(m_layer->paintDevice());
- m_layer->paintDevice()->fill(m_image->bounds(), KoColor(palette().color(QPalette::Window) , m_colorSpace));
+ m_layer->paintDevice()->fill(m_image->bounds(), KoColor(backgroundColor, m_colorSpace));
t.end();
- m_paintColor = KoColor(palette().color(QPalette::Text), m_colorSpace);
+ m_paintColor = KoColor(textColor, m_colorSpace);
QFont font;
font.setPixelSize(14);
font.setBold(false);
m_noPreviewText = this->scene()->addText(i18n("No Preview for this engine"),font);
+ m_noPreviewText->setDefaultTextColor(textColor);
m_noPreviewText->setPos(50, this->height()/4);
return;
-
}
else {
-
- // fill with gray first to clear out what existed from previous preview
KisTransaction t(m_layer->paintDevice());
- m_layer->paintDevice()->fill(m_image->bounds(), KoColor(palette().color(QPalette::Window) , m_colorSpace));
+ m_layer->paintDevice()->fill(m_image->bounds(), KoColor(backgroundColor, m_colorSpace));
t.end();
- m_paintColor = KoColor(palette().color(QPalette::Text), m_colorSpace);
+ m_paintColor = KoColor(textColor, m_colorSpace);
}
}
@@ -231,6 +292,11 @@ void KisPresetLivePreviewView::setupAndPaintStroke()
KisPaintOpSettingsSP settings = proxy_preset->settings();
settings->setPaintOpSize(previewSize);
+ const QString compositeOp = settings->paintOpCompositeOp();
+ if (needsBlendingModeOverride(compositeOp)) {
+ settings->setPaintOpCompositeOp(COMPOSITE_OVER);
+ }
+
int maxTextureSize = 200;
int textureOffsetX = settings->getInt("Texture/Pattern/MaximumOffsetX")*2;
int textureOffsetY = settings->getInt("Texture/Pattern/MaximumOffsetY")*2;
@@ -291,6 +357,10 @@ void KisPresetLivePreviewView::setupAndPaintStroke()
resources->setOpacity(settings->paintOpOpacity());
resources->setMirroring(false, false); // ignore mirroring in toolbar
+ if (needsBlendingModeOverride(compositeOp)) {
+ resources->setCompositeOpId(COMPOSITE_OVER);
+ }
+
resources->setFGColorOverride(m_paintColor);
KisFreehandStrokeInfo *strokeInfo = new KisFreehandStrokeInfo();
@@ -389,7 +459,7 @@ void KisPresetLivePreviewView::setupAndPaintStroke()
void KisPresetLivePreviewView::changeEvent(QEvent *event)
{
QWidget::changeEvent(event);
- if (event->type() == QEvent::PaletteChange) {
+ if (event->type() == QEvent::PaletteChange && !m_cachePreviewMode) {
if (m_currentPreset) {
requestUpdateStroke();
}
diff --git a/libs/ui/widgets/kis_preset_live_preview_view.h b/libs/ui/widgets/kis_preset_live_preview_view.h
index 1d92b8742a..3ce61e9510 100644
--- a/libs/ui/widgets/kis_preset_live_preview_view.h
+++ b/libs/ui/widgets/kis_preset_live_preview_view.h
@@ -7,23 +7,22 @@
#ifndef _KIS_PRESET_LIVE_PREVIEW_
#define _KIS_PRESET_LIVE_PREVIEW_
-#include <QGraphicsScene>
#include <QGraphicsView>
#include <QPainterPath>
-#include <QGraphicsPixmapItem>
-#include "kis_paintop_preset.h"
-#include "KoColorSpaceRegistry.h"
-#include "kis_paint_layer.h"
-#include "kis_painter.h"
+#include <KoColor.h>
+
#include "kis_distance_information.h"
+#include "kis_paintop_preset.h"
#include "kis_painting_information_builder.h"
-#include <kis_image.h>
-#include <kis_types.h>
-#include <KoColor.h>
#include "kis_signal_compressor.h"
+#include <kis_types.h>
class KoCanvasResourceProvider;
+class KoColorSpace;
+class QGraphicsPixmapItem;
+class QGraphicsScene;
+class QGraphicsTextItem;
/**
* Widget for displaying a live brush preview of your
@@ -56,12 +55,26 @@ public:
*/
void setCurrentPreset(KisPaintOpPresetSP preset);
void requestUpdateStroke();
+ void requestUpdateStrokeImmediate();
+ void setBatchPreviewMode(bool enabled);
+ void setCachePreviewMode(bool enabled);
+ KoCanvasResourceProvider* resourceManager() const;
+
+Q_SIGNALS:
+ /**
+ * @brief Emitted when a preview image is generated.
+ *
+ * @param presetId The presetId (resource id).
+ * @param previewImage Preview image.
+ */
+ void sigPreviewImageReady(int presetId, const QImage &previewImage);
private Q_SLOTS:
void updateStroke();
void slotPreviewGenerationCompleted();
private:
+ static constexpr int DefaultUpdateDelayMs = 100;
///internally sets the Resource Provider for brush preview (allowing gradients in preview)
KoCanvasResourceProvider* m_resourceManager {nullptr};
@@ -115,6 +128,8 @@ private:
bool m_previewGenerationInProgress {false};
KisSignalCompressor m_updateCompressor;
+ bool m_batchPreviewMode {false};
+ bool m_cachePreviewMode {false};
/// the range of brush sizes that will control zooming in/out
const float m_minBrushVal {10.0};
@@ -133,7 +148,12 @@ private:
* @brief works as both clearing the previous stroke, providing
* striped backgrounds for smudging brushes, and text if there is no preview
*/
- void paintBackground();
+ void paintBackground(bool cacheMode);
+
+ /**
+ * @brief Paint alternating gray stripes on the paint device
+ */
+ void paintStripedBackground();
/**
* @brief creates and performs the actual stroke that goes on top of the background
@@ -142,6 +162,12 @@ private:
void setupAndPaintStroke();
void changeEvent(QEvent*) override;
+
+ /// Last preview image.
+ QImage m_lastPreviewImage;
+
+ /// presetId (resource id) associated with the in-flight preview generation.
+ int m_previewPresetId {-1};
};
#endif
diff --git a/plugins/paintops/colorsmudge/KisColorSmudgeStrategyLightness.cpp b/plugins/paintops/colorsmudge/KisColorSmudgeStrategyLightness.cpp
index 52b24b66e4..5bbd27f931 100644
--- a/plugins/paintops/colorsmudge/KisColorSmudgeStrategyLightness.cpp
+++ b/plugins/paintops/colorsmudge/KisColorSmudgeStrategyLightness.cpp
@@ -14,6 +14,7 @@
#include "kis_selection.h"
#include "KisColorSmudgeInterstrokeData.h"
+#include "KisOverlayPaintDeviceWrapper.h"
#include "kis_algebra_2d.h"
#include <KoBgrColorSpaceTraits.h>
@@ -59,6 +60,10 @@ void KisColorSmudgeStrategyLightness::initializePainting()
m_heightmapDevice = new KisPaintDevice(KoColorSpaceRegistry::instance()->rgb8());
m_heightmapDevice->setDefaultBounds(m_colorOnlyDevice->defaultBounds());
m_heightmapDevice->setSupportsWraparoundMode(m_colorOnlyDevice->supportsWraproundMode());
+ // Create an owned overlay wrapper for fallback mode (e.g., stroke preview generation)
+ m_ownedOverlayDevice.reset(new KisOverlayPaintDeviceWrapper(
+ m_colorOnlyDevice, 1, KisOverlayPaintDeviceWrapper::LazyPreciseMode));
+ m_layerOverlayDevice = m_ownedOverlayDevice.data();
}
initializePaintingImpl(m_colorOnlyDevice->colorSpace(),
diff --git a/plugins/paintops/colorsmudge/KisColorSmudgeStrategyLightness.h b/plugins/paintops/colorsmudge/KisColorSmudgeStrategyLightness.h
index dbef5bc792..abe2d0eab9 100644
--- a/plugins/paintops/colorsmudge/KisColorSmudgeStrategyLightness.h
+++ b/plugins/paintops/colorsmudge/KisColorSmudgeStrategyLightness.h
@@ -7,10 +7,13 @@
#ifndef KRITA_KISCOLORSMUDGESTRATEGYLIGHTNESS_H
#define KRITA_KISCOLORSMUDGESTRATEGYLIGHTNESS_H
+#include <QScopedPointer>
#include "KisColorSmudgeStrategyBase.h"
#include "kis_painter.h"
#include "KisPaintThicknessOptionData.h"
+class KisOverlayPaintDeviceWrapper;
+
class KisColorSmudgeStrategyLightness : public KisColorSmudgeStrategyBase
{
public:
@@ -39,7 +42,8 @@ private:
KisPaintDeviceSP m_heightmapDevice;
KisPaintDeviceSP m_colorOnlyDevice;
KisPaintDeviceSP m_projectionDevice;
- KisOverlayPaintDeviceWrapper *m_layerOverlayDevice {nullptr};
+ QScopedPointer<KisOverlayPaintDeviceWrapper> m_ownedOverlayDevice;
+ KisOverlayPaintDeviceWrapper *m_layerOverlayDevice {nullptr}; // Not owned.
KisColorSmudgeSourceSP m_sourceWrapperDevice;
KisPainter m_finalPainter;
KisPainter m_heightmapPainter;