fifteenimageprovider.cpp 2.44 KB
Newer Older
1
/*
2
 * SPDX-FileCopyrightText: 2014 Jeremy Whiting <jpwhiting@kde.org>
3
 *
4
 * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
5 6 7 8 9 10 11
 */

#include "fifteenimageprovider.h"

#include <QDebug>

FifteenImageProvider::FifteenImageProvider()
Alexander Lohnau's avatar
Alexander Lohnau committed
12 13 14 15
    : QQuickImageProvider(QQuickImageProvider::Pixmap)
    , m_boardSize(4)
    , m_pieceWidth(30)
    , m_pieceHeight(30)
16 17 18 19 20
{
}

QPixmap FifteenImageProvider::requestPixmap(const QString &id, QSize *size, const QSize &requestedSize)
{
21 22
    Q_UNUSED(requestedSize); // wanted sizes are actually encoded in the id

23 24
    // id format is boardSize-imagenumber-pieceWidth-pieceHeight-imagePath
    qDebug() << "pixmap requested with id " << id;
25
    QStringList idParts = id.split(QLatin1Char('-'));
26 27
    if (idParts.size() < 4) {
        *size = QSize();
28
        return QPixmap();
29
    }
30 31 32 33 34 35 36 37 38 39 40 41

    bool update = false;
    int boardSize = idParts.at(0).toInt();
    int pieceWidth = idParts.at(2).toInt();
    int pieceHeight = idParts.at(3).toInt();
    QString path = idParts.at(4);
    if (path != m_imagePath && !path.isEmpty()) {
        m_imagePath = path;
        qDebug() << "loading pixmap from file " << path << m_pixmap.load(path);
        update = true;
    }

42
    if (idParts.at(1) == QLatin1String("all")) {
43 44 45 46 47 48 49 50 51 52 53 54 55
        return m_pixmap;
    } else {
        if (pieceWidth != m_pieceWidth || pieceHeight != m_pieceHeight) {
            m_pieceWidth = pieceWidth;
            m_pieceHeight = pieceHeight;
            update = true;
        }

        if (m_boardSize != boardSize) {
            m_boardSize = boardSize;
            update = true;
        }

56
        if (update) {
57
            updatePixmaps();
58
        }
59 60 61 62

        int number = idParts.at(1).toInt();

        qDebug() << "pixmap for piece " << number << " requested";
63 64
        if (number > 0 && number < m_pixmaps.size()) {
            *size = QSize(m_pieceWidth, m_pieceHeight);
65
            return m_pixmaps.at(number);
66
        }
67
    }
68 69

    *size = QSize();
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
    return QPixmap();
}

void FifteenImageProvider::updatePixmaps()
{
    QSize size(m_pieceWidth * m_boardSize, m_pieceHeight * m_boardSize);
    QPixmap copyPixmap = m_pixmap.scaled(size);

    m_pixmaps.clear();
    m_pixmaps.resize(m_boardSize * m_boardSize);

    for (int i = 0; i < m_boardSize * m_boardSize; i++) {
        int posX = (i % m_boardSize) * m_pieceWidth;
        int posY = (i / m_boardSize) * m_pieceHeight;

        m_pixmaps[i] = copyPixmap.copy(posX, posY, m_pieceWidth, m_pieceHeight);
    }
}