KisVisualColorSelectorShape.cpp 13.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * Copyright (C) Wolthera van Hovell tot Westerflier <griffinvalley@gmail.com>, (C) 2016
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
#include "KisVisualColorSelectorShape.h"

#include <QColor>
#include <QPixmap>
#include <QPainter>
#include <QPainterPath>
#include <QRect>
#include <QVector>
26
#include <QVector4D>
27 28 29 30 31 32 33 34 35 36 37 38 39
#include <QVBoxLayout>
#include <QList>
#include <QPolygon>
#include <QtMath>

#include <KSharedConfig>
#include <KConfigGroup>

#include "KoColorConversions.h"
#include "KoColorDisplayRendererInterface.h"
#include "KoChannelInfo.h"
#include <KoColorModelStandardIds.h>
#include <QPointer>
40

41 42 43 44 45 46
#include "kis_signal_compressor.h"
#include "kis_debug.h"

struct KisVisualColorSelectorShape::Private
{
    QImage gradient;
47
    QImage alphaMask;
48
    QImage fullSelector;
49 50
    bool imagesNeedUpdate { true };
    bool alphaNeedsUpdate { true };
51
    bool acceptTabletEvents { false };
52
    QPointF currentCoordinates; // somewhat redundant?
53
    QPointF dragStart;
54
    QVector4D currentChannelValues;
55
    Dimensions dimension;
56
    const KoColorSpace *colorSpace;
57 58 59 60 61 62 63 64 65 66 67 68 69
    int channel1;
    int channel2;
    const KoColorDisplayRendererInterface *displayRenderer = 0;
};

KisVisualColorSelectorShape::KisVisualColorSelectorShape(QWidget *parent,
                                                         KisVisualColorSelectorShape::Dimensions dimension,
                                                         const KoColorSpace *cs,
                                                         int channel1,
                                                         int channel2,
                                                         const KoColorDisplayRendererInterface *displayRenderer): QWidget(parent), m_d(new Private)
{
    m_d->dimension = dimension;
70 71
    m_d->colorSpace = cs;
    int maxchannel = m_d->colorSpace->colorChannelCount()-1;
72 73 74 75 76 77 78 79 80 81 82 83 84 85
    m_d->channel1 = qBound(0, channel1, maxchannel);
    m_d->channel2 = qBound(0, channel2, maxchannel);
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    setDisplayRenderer(displayRenderer);
}

KisVisualColorSelectorShape::~KisVisualColorSelectorShape()
{
}

QPointF KisVisualColorSelectorShape::getCursorPosition() {
    return m_d->currentCoordinates;
}

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
void KisVisualColorSelectorShape::setCursorPosition(QPointF position, bool signal)
{
    QPointF newPos(qBound(0.0, position.x(), 1.0), qBound(0.0, position.y(), 1.0));
    if (newPos != m_d->currentCoordinates)
    {
        m_d->currentCoordinates = newPos;
        // for internal consistency, because we have a bit of redundancy here
        m_d->currentChannelValues[m_d->channel1] = newPos.x();
        if (m_d->dimension == Dimensions::twodimensional){
            m_d->currentChannelValues[m_d->channel2] = newPos.y();
        }
        update();
        if (signal){
            emit sigCursorMoved(newPos);
        }
    }
}

void KisVisualColorSelectorShape::setChannelValues(QVector4D channelValues, bool setCursor)
{
    //qDebug() << this  << "setChannelValues";
    m_d->currentChannelValues = channelValues;
    if (setCursor) {
109 110
        m_d->currentCoordinates = QPointF(qBound(0.f, channelValues[m_d->channel1], 1.f),
                                          qBound(0.f, channelValues[m_d->channel2], 1.f));
111 112 113 114 115 116 117 118 119 120 121 122
    }
    else {
        // for internal consistency, because we have a bit of redundancy here
        m_d->currentChannelValues[m_d->channel1] = m_d->currentCoordinates.x();
        if (m_d->dimension == Dimensions::twodimensional){
            m_d->currentChannelValues[m_d->channel2] = m_d->currentCoordinates.y();
        }
    }
    m_d->imagesNeedUpdate = true;
    update();
}

123 124 125 126 127
void KisVisualColorSelectorShape::setAcceptTabletEvents(bool on)
{
    m_d->acceptTabletEvents = on;
}

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
void KisVisualColorSelectorShape::setDisplayRenderer (const KoColorDisplayRendererInterface *displayRenderer)
{
    if (displayRenderer) {
        if (m_d->displayRenderer) {
            m_d->displayRenderer->disconnect(this);
        }
        m_d->displayRenderer = displayRenderer;
    } else {
        m_d->displayRenderer = KoDumbColorDisplayRenderer::instance();
    }
}

void KisVisualColorSelectorShape::forceImageUpdate()
{
    //qDebug() << this  << "forceImageUpdate";
143
    m_d->alphaNeedsUpdate = true;
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
    m_d->imagesNeedUpdate = true;
}

QColor KisVisualColorSelectorShape::getColorFromConverter(KoColor c){
    QColor col;
    KoColor color = c;
    if (m_d->displayRenderer) {
        color.convertTo(m_d->displayRenderer->getPaintingColorSpace());
        col = m_d->displayRenderer->toQColor(c);
    } else {
        col = c.toQColor();
    }
    return col;
}

159
// currently unused?
160 161 162
void KisVisualColorSelectorShape::slotSetActiveChannels(int channel1, int channel2)
{
    //qDebug() << this  << "slotSetActiveChannels";
163
    int maxchannel = m_d->colorSpace->colorChannelCount()-1;
164 165 166 167 168 169 170 171 172 173 174 175 176 177
    m_d->channel1 = qBound(0, channel1, maxchannel);
    m_d->channel2 = qBound(0, channel2, maxchannel);
    m_d->imagesNeedUpdate = true;
    update();
}

bool KisVisualColorSelectorShape::imagesNeedUpdate() const {
    return m_d->imagesNeedUpdate;
}

QImage KisVisualColorSelectorShape::getImageMap()
{
    //qDebug() << this  << ">>>>>>>>> getImageMap()" << m_d->imagesNeedUpdate;

178
    if (m_d->imagesNeedUpdate) {
179
        // Fill a buffer with the right kocolors
180
        m_d->gradient = renderBackground(m_d->currentChannelValues, m_d->colorSpace->pixelSize());
181 182 183 184 185
        m_d->imagesNeedUpdate = false;
    }
    return m_d->gradient;
}

186 187 188 189 190 191 192 193 194
const QImage KisVisualColorSelectorShape::getAlphaMask() const
{
    if (m_d->alphaNeedsUpdate) {
        m_d->alphaMask = renderAlphaMask();
        m_d->alphaNeedsUpdate = false;
    }
    return m_d->alphaMask;
}

195
QImage KisVisualColorSelectorShape::convertImageMap(const quint8 *rawColor, quint32 bufferSize, QSize imgSize) const
196
{
197
    Q_ASSERT(bufferSize == imgSize.width() * imgSize.height() * m_d->colorSpace->pixelSize());
198 199 200
    QImage image;
    // Convert the buffer to a qimage
    if (m_d->displayRenderer) {
201
        image = m_d->displayRenderer->convertToQImage(m_d->colorSpace, rawColor, imgSize.width(), imgSize.height());
202 203
    }
    else {
204 205 206
        image = m_d->colorSpace->convertToQImage(rawColor, imgSize.width(), imgSize.height(), 0,
                                                 KoColorConversionTransformation::internalRenderingIntent(),
                                                 KoColorConversionTransformation::internalConversionFlags());
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    }
    // safeguard:
    if (image.isNull())
    {
        image = QImage(width(), height(), QImage::Format_ARGB32);
        image.fill(Qt::black);
    }

    return image;
}

QImage KisVisualColorSelectorShape::renderBackground(const QVector4D &channelValues, quint32 pixelSize) const
{
    const KisVisualColorSelector *selector = qobject_cast<KisVisualColorSelector*>(parent());
    Q_ASSERT(selector);

223 224 225 226 227 228
    // Hi-DPI aware rendering requires that we determine the device pixel dimension;
    // actual widget size in device pixels is not accessible unfortunately, it might be 1px smaller...
    const qreal deviceDivider = 1.0 / devicePixelRatioF();
    const int deviceWidth = qCeil(width() * devicePixelRatioF());
    const int deviceHeight = qCeil(height() * devicePixelRatioF());
    quint32 imageSize = deviceWidth * deviceHeight * m_d->colorSpace->pixelSize();
229 230 231
    QScopedArrayPointer<quint8> raw(new quint8[imageSize] {});
    quint8 *dataPtr = raw.data();
    QVector4D coordinates = channelValues;
232 233 234 235 236 237 238 239

    QImage alpha = getAlphaMask();
    bool checkAlpha = !alpha.isNull() && alpha.valid(deviceWidth - 1, deviceHeight - 1);
    KIS_SAFE_ASSERT_RECOVER(!checkAlpha || alpha.format() == QImage::Format_Alpha8) {
        checkAlpha = false;
    }

    KoColor filler(Qt::white, m_d->colorSpace);
240
    for (int y = 0; y < deviceHeight; y++) {
241
        const uchar *alphaLine = checkAlpha ? alpha.scanLine(y) : 0;
242
        for (int x=0; x < deviceWidth; x++) {
243 244 245 246 247 248 249 250 251 252 253 254 255
            if (!checkAlpha || alphaLine[x]) {
                QPointF newcoordinate = convertWidgetCoordinateToShapeCoordinate(QPointF(x, y) * deviceDivider);
                coordinates[m_d->channel1] = newcoordinate.x();
                if (m_d->dimension == Dimensions::twodimensional) {
                    coordinates[m_d->channel2] = newcoordinate.y();
                }
                KoColor c = selector->convertShapeCoordsToKoColor(coordinates);
                memcpy(dataPtr, c.data(), pixelSize);
            }
            else {
                // need to write a color with non-zero alpha, otherwise the display converter
                // will for some arcane reason crop the final QImage and screw rendering
                memcpy(dataPtr, filler.data(), pixelSize);
256 257 258 259
            }
            dataPtr += pixelSize;
        }
    }
260 261
    QImage image = convertImageMap(raw.data(), imageSize, QSize(deviceWidth, deviceHeight));
    image.setDevicePixelRatio(devicePixelRatioF());
262 263 264 265 266 267 268 269

    if (!alpha.isNull()) {
        QPainter painter(&image);
        // transfer alphaMask to Alpha channel
        painter.setCompositionMode(QPainter::CompositionMode_DestinationIn);
        painter.drawImage(0, 0, alpha);
    }

270
    return image;
271 272
}

273 274 275 276 277
QImage KisVisualColorSelectorShape::renderAlphaMask() const
{
    return QImage();
}

278 279 280 281 282 283
QPointF KisVisualColorSelectorShape::mousePositionToShapeCoordinate(const QPointF &pos, const QPointF &dragStart) const
{
    Q_UNUSED(dragStart)
    return convertWidgetCoordinateToShapeCoordinate(pos);
}

284 285
void KisVisualColorSelectorShape::mousePressEvent(QMouseEvent *e)
{
286
    if (e->button() == Qt::LeftButton) {
287 288
        m_d->dragStart = e->localPos();
        QPointF coordinates = mousePositionToShapeCoordinate(e->localPos(), m_d->dragStart);
289
        setCursorPosition(coordinates, true);
290
    }
291 292 293
    else {
        e->ignore();
    }
294 295 296 297
}

void KisVisualColorSelectorShape::mouseMoveEvent(QMouseEvent *e)
{
298
    if (e->buttons() & Qt::LeftButton) {
299
        QPointF coordinates = mousePositionToShapeCoordinate(e->localPos(), m_d->dragStart);
300
        setCursorPosition(coordinates, true);
301 302 303 304 305
    } else {
        e->ignore();
    }
}

306
void KisVisualColorSelectorShape::mouseReleaseEvent(QMouseEvent *e)
307
{
308 309
    if (e->button() != Qt::LeftButton) {
        e->ignore();
310
    }
311
}
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348

void KisVisualColorSelectorShape::tabletEvent(QTabletEvent* event)
{
    // only accept tablet events that are associated to "left" button
    // NOTE: QTabletEvent does not have a windowPos() equivalent, but we don't need it
    if (m_d->acceptTabletEvents &&
        (event->button() == Qt::LeftButton || (event->buttons() & Qt::LeftButton)))
    {
        event->accept();
        switch (event->type()) {
        case  QEvent::TabletPress: {
            QMouseEvent mouseEvent(QEvent::MouseButtonPress, event->posF(), event->posF(),
                                   event->globalPosF(), event->button(), event->buttons(),
                                   event->modifiers(), Qt::MouseEventSynthesizedByApplication);
            mousePressEvent(&mouseEvent);
            break;
        }
        case QEvent::TabletMove: {
            QMouseEvent mouseEvent(QEvent::MouseMove, event->posF(), event->posF(),
                                   event->globalPosF(), event->button(), event->buttons(),
                                   event->modifiers(), Qt::MouseEventSynthesizedByApplication);
            mouseMoveEvent(&mouseEvent);
            break;
        }
        case QEvent::TabletRelease: {
            QMouseEvent mouseEvent(QEvent::MouseButtonRelease, event->posF(), event->posF(),
                                   event->globalPosF(), event->button(), event->buttons(),
                                   event->modifiers(), Qt::MouseEventSynthesizedByApplication);
            mouseReleaseEvent(&mouseEvent);
            break;
        }
        default:
            event->ignore();
        }
    }
}

349 350 351 352 353 354 355 356
void KisVisualColorSelectorShape::paintEvent(QPaintEvent*)
{
    QPainter painter(this);

    drawCursor();
    painter.drawImage(0,0,m_d->fullSelector);
}

357 358 359 360 361 362
void KisVisualColorSelectorShape::resizeEvent(QResizeEvent *)
{
    forceImageUpdate();
    setMask(getMaskMap());
}

363
KisVisualColorSelectorShape::Dimensions KisVisualColorSelectorShape::getDimensions() const
364 365 366 367 368 369 370 371 372 373
{
    return m_d->dimension;
}

void KisVisualColorSelectorShape::setFullImage(QImage full)
{
    m_d->fullSelector = full;
}
KoColor KisVisualColorSelectorShape::getCurrentColor()
{
374 375 376 377 378 379
    const KisVisualColorSelector *selector = qobject_cast<KisVisualColorSelector*>(parent());
    if (selector)
    {
        return selector->convertShapeCoordsToKoColor(m_d->currentChannelValues);
    }
    return KoColor(m_d->colorSpace);
380 381
}

382
QVector <int> KisVisualColorSelectorShape::getChannels() const
383 384 385 386 387 388
{
    QVector <int> channels(2);
    channels[0] = m_d->channel1;
    channels[1] = m_d->channel2;
    return channels;
}