// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: BSD-2-Clause // // The shape of the themes tab: how many tiles fit a row and whether they fill // it, that the tile in use carries the set wallpaper, and that a click reports // the picture rather than writing a setting behind the page's back. // // The tile is the file the application loads, in a module of its own so the // scene can import it as the gallery does. The grid is the part with arithmetic // in it. Themes are handed in rather than read off a folder: that is // ThemeLibrary's half. Kirigami is imported for real, since the figures are in // its units. #include "PictureFixture.h" #include #include #include #include #include #include #include #include #include namespace { const char *sceneQml = R"QML( import QtQuick import QtQuick.Layouts import org.kde.kirigami as Kirigami import koutnet.app Kirigami.ApplicationWindow { id: page width: 900 height: 700 visible: true // Stands in for the ThemeLibrary singleton, which the gallery reads its // folder from - spelled in lower case here because a QML id may not start // with a capital, which a registered singleton's name may. It is a child of // the window rather than a second root object because a QML file has one // root, and a second one is a syntax error. The folder is all of it that the // grid asks for: the list of themes is handed in, and the line that shows the // folder and the button that reloads it are left out with the rest of the // card. QtObject { id: themeLibrary property string directory: "/nonexistent" } // Handed in by the test: what a theme is is ThemeLibrary's half of the work, // and the urls it hands over are file ones. property var themes: [] property string selectedPath: "" // What the page was told, which is what a wallpaper setting would be given. // A var and not a string, so that nothing chosen is told apart from an empty // picture picked on purpose. property var chosenPath: null property int chosenCount: 0 // ---- ThemeGallery.qml, the grid of it ---- Item { id: root objectName: "gallery" anchors.fill: parent // Handed in by the page, which is the binding SettingsPage puts on the // gallery. The file's own default is the library's list, and the page's // overrides it, so a scene that binds it to the page reads the same. property var themes: page.themes property string directory: themeLibrary.directory property string selectedPath: page.selectedPath signal chosen(string path) readonly property real kSpacing: Kirigami.Units.largeSpacing readonly property real kMinTileWidth: Kirigami.Units.gridUnit * 10 // Stands in for what the page does with the gallery's signal: the // wallpaper setting written, and the opacity put back if it was at zero. function choose(path) { page.chosenPath = path page.chosenCount = page.chosenCount + 1 page.selectedPath = path } ColumnLayout { width: root.width spacing: 0 // Not a layout, for the reason given in the file: a layout measured // off tiles that are measured off the layout settles at the width of // one tile, and the row then stops short of the card. Item { id: grid objectName: "grid" Layout.fillWidth: true readonly property int tileCount: Math.max(1, Math.floor((width + root.kSpacing) / (root.kMinTileWidth + root.kSpacing))) readonly property real tileWidth: Math.max(root.kMinTileWidth, (width - (tileCount - 1) * root.kSpacing) / tileCount) readonly property real tileHeight: noneTile.height readonly property real rowSpacing: root.kSpacing * 2 readonly property int rowCount: Math.max(1, Math.ceil((themeRow.count + 1) / tileCount)) implicitHeight: rowCount * (tileHeight + rowSpacing) - rowSpacing // The way back to a window with no picture behind it, first in // the grid: it is the choice that is not a theme, and a row of // pictures with nothing at the start of it is a row of pictures // that all point one way. ThemeTile { id: noneTile objectName: "tile-none" x: 0 y: 0 width: grid.tileWidth label: "No picture" selected: root.selectedPath.length === 0 onClicked: root.choose("") } Repeater { id: themeRow model: root.themes delegate: ThemeTile { required property var modelData required property int index readonly property int slot: index + 1 objectName: "tile-" + slot width: grid.tileWidth x: (slot % grid.tileCount) * (grid.tileWidth + root.kSpacing) y: Math.floor(slot / grid.tileCount) * (grid.tileHeight + grid.rowSpacing) sourceUrl: modelData.url label: modelData.label selected: root.selectedPath === modelData.path onClicked: root.choose(modelData.path) } } } } } } )QML"; // The module the application loads the tile out of, by the name the application // knows it by: the tile imports its palette from koutnet.app, and a scene that // wanted the tile under any other name would have to rewrite that import to get // at it, which is the one edit to a file that is about not editing it. const char *qmldir = R"QML( module koutnet.app ThemeTile 1.0 ThemeTile.qml singleton ThemePalette 1.0 ThemePalette.qml )QML"; // The palette as the application has it with no theme picked: every colour is // the scheme colour it replaces, which is what the real palette answers with when // there is no picture to take any colour from. The real one is a picture's average // read out of C++ and the settings' wallpaper path, and neither of those is what // this gallery is about. // // What this does keep is the names. A tile asking for a colour the real palette // does not have is a question the real one answers with nothing at all, and an // item asked for a colour it was never given paints with nothing, so the tile's // colours are checked here as much as its shapes are. const char *paletteQml = R"QML( pragma Singleton import QtQuick import org.kde.kirigami as Kirigami QtObject { readonly property color surface: Kirigami.Theme.backgroundColor readonly property color surfaceAlt: Kirigami.Theme.alternateBackgroundColor readonly property color text: Kirigami.Theme.textColor readonly property color accent: Kirigami.Theme.highlightColor readonly property color accentText: Kirigami.Theme.highlightedTextColor } )QML"; } // namespace class ThemeGalleryTest : public QObject { Q_OBJECT // The four themes this gallery is shown, in the shape ThemeLibrary hands them // over: a name, the name to draw, the path a wallpaper setting takes and the // url an Image takes. static const QList> &themeNames() { static const QList> names{ {QStringLiteral("cloud-gin"), QStringLiteral("Cloud Gin")}, {QStringLiteral("village"), QStringLiteral("Village")}, {QStringLiteral("sepia"), QStringLiteral("Sepia")}, {QStringLiteral("rain-soon"), QStringLiteral("Rain Soon")}, }; return names; } // Where the picture of a theme of that name is: the folder the test wrote it // into, under the name of the theme, which is the same arrangement the themes // folder itself is in. QString themePath(const QString &name) const { return m_dir->filePath(name + QStringLiteral(".bmp")); } QVariantList themeList() const { QVariantList out; for (const auto &theme : themeNames()) { const QString path = themePath(theme.first); out << QVariantMap{ {QStringLiteral("name"), theme.first}, {QStringLiteral("label"), theme.second}, {QStringLiteral("path"), path}, {QStringLiteral("url"), QUrl::fromLocalFile(path).toString()}, }; } return out; } static void settle(int rounds = 4) { for (int i = 0; i < rounds; ++i) { QCoreApplication::processEvents(QEventLoop::AllEvents, 20); } } // A layout is not finished when the events that asked for it are done: a width // set on the window is passed on to the page, and from the page to the grid, in // a polish pass that belongs to a frame. So a test that reads a size the moment // after changing it reads the size from before, and did so often enough to be a // test that failed now and then for no reason a reader could name. Asking the // window for a frame is what runs the pass. static void settleLayout(QQuickWindow *window) { settle(); if (window) window->update(); settle(); } static void resizeWindow(QObject *scene, int width) { for (int attempt = 0; attempt < 3; ++attempt) { scene->setProperty("width", width); settle(); if (scene->property("width").toInt() == width) break; } } static bool writeFile(const QString &path, const char *contents) { QFile file(path); return file.open(QIODevice::WriteOnly) && file.write(contents) == qint64(qstrlen(contents)); } QTemporaryDir *m_dir = nullptr; QQmlApplicationEngine *m_view = nullptr; QObject *m_scene = nullptr; QQuickItem *gallery() const { return m_scene->findChild(QStringLiteral("gallery")); } QQuickItem *grid() const { return m_scene->findChild(QStringLiteral("grid")); } // Every item under the gallery, by the tree it is drawn in: a Repeater's // tiles are put in the grid to be drawn and are not children of it as // objects, so looking for them by name through the objects finds one tile and // not the four beside it. static void collectItems(QQuickItem *item, QList &out) { out << item; const auto children = item->childItems(); for (QQuickItem *child : children) { collectItems(child, out); } } // The tiles in reading order, which is the order the grid lays them out in: // the tile with no picture first, then one for each theme. Sorted by where // they are rather than by the order they were made in, which is the order of // the themes and says nothing about the second row. QList tiles() const { QList all; collectItems(gallery(), all); QList found; for (QQuickItem *item : all) { if (item->objectName().startsWith(QLatin1String("tile-"))) found << item; } std::sort(found.begin(), found.end(), [](QQuickItem *a, QQuickItem *b) { if (!qFuzzyCompare(a->y() + 1, b->y() + 1)) return a->y() < b->y(); return a->x() < b->x(); }); return found; } // The image a tile draws its picture in, found by what it is rather than by // a name: the frame, the plate and the caption are items with no source, the // picture is an item with one, and a name put in the tile for the sake of a // test is a name that goes stale with the tile it was put in for. static QQuickItem *pictureOf(QQuickItem *tile) { QList all; collectItems(tile, all); for (QQuickItem *item : all) { if (item->metaObject()->indexOfProperty("source") >= 0) return item; } return nullptr; } // One tile by the slot it sits in, which is how the grid names them. QQuickItem *tile(const QString &name) const { for (QQuickItem *item : tiles()) { if (item->objectName() == QLatin1String("tile-") + name) return item; } return nullptr; } // A tile clicked, the way a person clicks it: a press and a release on the // tile itself, which is what the button state the tile is - checked, hovered // - hangs off. Calling the signal the handler is on instead would be testing // the handler with the button left out. static void click(QQuickItem *tile) { QTest::mouseClick(tile->window(), Qt::LeftButton, Qt::NoModifier, tile->mapToScene(QPointF(tile->width() / 2, tile->height() / 2)).toPoint()); } private Q_SLOTS: void initTestCase() { m_dir = new QTemporaryDir; QVERIFY(m_dir->isValid()); // The tile is the file the application loads, put in place as the module // it is one in, so that the scene below imports it the way the real // gallery does and the tile under test is the tile in the application. A // copy of it written out here would be a second version of the thing // whose shape this is about. // koutnet/app and not koutnet.app: a module whose name has a dot in it // lives in a directory of its first part and one of the rest, which is the // arrangement qmldir's own names are read back with - a directory called // koutnet.app is a module the engine walks straight past. const QString moduleDir = m_dir->filePath(QStringLiteral("koutnet/app")); QVERIFY(QDir().mkpath(moduleDir)); QFile tile(QStringLiteral(KOUTNET_QML_DIR "/ThemeTile.qml")); QVERIFY2(tile.open(QIODevice::ReadOnly), qPrintable(tile.fileName())); QVERIFY(writeFile(moduleDir + QStringLiteral("/ThemeTile.qml"), tile.readAll().constData())); tile.close(); // The palette the tile paints itself with, stood in for by the application // with no theme picked - see paletteQml for why it is a stand-in and what // about it is the real thing. QVERIFY(writeFile(moduleDir + QStringLiteral("/ThemePalette.qml"), paletteQml)); QVERIFY(writeFile(moduleDir + QStringLiteral("/qmldir"), qmldir)); QVERIFY(writeFile(m_dir->filePath(QStringLiteral("scene.qml")), sceneQml)); // one picture a theme, in the colours of a chart, so that a tile with a // picture on it and a tile without are told apart by more than a name int colour = 0x3050a0; for (const auto &theme : themeNames()) { QVERIFY(writeTestPicture(themePath(theme.first), QColor::fromRgb(colour))); colour += 0x201010; } } void cleanupTestCase() { delete m_dir; } void init() { delete m_view; m_view = new QQmlApplicationEngine; m_view->addImportPath(m_dir->path()); QQmlComponent c(m_view, QUrl::fromLocalFile(m_dir->filePath(QStringLiteral("scene.qml")))); if (c.isError()) { for (const auto &e : c.errors()) { qWarning("%s", qPrintable(e.toString())); } QFAIL("the scene does not load"); } m_scene = c.create(); QVERIFY(m_scene); // handed in rather than written into the scene, which is where the themes // come from in the application m_scene->setProperty("themes", themeList()); m_scene->setParent(m_view); auto *window = qobject_cast(m_scene); QVERIFY(window); // A window this narrow, and with no floor under it: a window is told the // smallest size its content will take, and the gallery's own minimum width // is the width of one of its tiles, so a window asked for less than that is // told it cannot be that small and the question the tests are asking - // what the grid does with a width too narrow for two tiles to a row - is a // question the window answers before the grid is asked anything at all. window->setMinimumSize(QSize(0, 0)); window->show(); settle(); QVERIFY(window->isVisible()); // And exposed, which is a further thing than visible and the one that // matters here: a window that is visible but not exposed has no scene // graph and so no frames, and every layout change after this is a change // nobody lays out. Offscreen exposure is asynchronous, so this is a wait // and not a look. QTRY_VERIFY(window->isExposed()); QVERIFY(gallery()); QVERIFY(grid()); } void cleanup() { delete m_view; m_view = nullptr; m_scene = nullptr; } // There is a tile for every theme and one more for having no picture, and the // one for no picture is first. This is the difference between a grid that // shows what is in the folder and one that shows what was thought of when it // was written: a theme put in the folder gets a tile without anything being // edited. void aTileForEveryThemeAndOneForNoPictureAtTheStart() { const QList found = tiles(); QCOMPARE(found.size(), 5); QCOMPARE(found.first()->property("label").toString(), QStringLiteral("No picture")); QCOMPARE(found.at(1)->property("label").toString(), QStringLiteral("Cloud Gin")); QCOMPARE(found.at(2)->property("label").toString(), QStringLiteral("Village")); QCOMPARE(found.last()->property("label").toString(), QStringLiteral("Rain Soon")); } // A tile draws the picture it was handed, and the tile with no picture draws // none: an image with nothing in it rather than an image left over from the // last theme that was there. What is drawn in its place is a plate the shape // of a picture, which is a matter of looks and not of the grid. void aTileDrawsItsOwnPicture() { QCOMPARE(tiles().size(), 5); const QString cloudGin = themePath(QStringLiteral("cloud-gin")); QQuickItem *gin = tile(QStringLiteral("1")); QVERIFY(gin); QCOMPARE(gin->property("label").toString(), QStringLiteral("Cloud Gin")); QCOMPARE(gin->property("sourceUrl").toString(), QUrl::fromLocalFile(cloudGin).toString()); QQuickItem *picture = pictureOf(gin); QVERIFY(picture); QCOMPARE(picture->property("source").toUrl(), QUrl::fromLocalFile(cloudGin)); QVERIFY(picture->isVisible()); QQuickItem *none = tile(QStringLiteral("none")); QVERIFY(none); QCOMPARE(none->property("sourceUrl").toString(), QString()); QQuickItem *noPicture = pictureOf(none); QVERIFY(noPicture); QCOMPARE(noPicture->property("source").toUrl(), QUrl()); QVERIFY(!noPicture->isVisible()); } // As many tiles to a row as fit at their narrowest, and each one then taking // up what is left over, so that a row ends at the edge of the card. A grid // that stops short of the edge looks like the pictures ran out, and one that // hangs a tile over it looks like the window is too narrow for it. void theRowOfTilesFillsTheWidthItIsGiven() { QCOMPARE(grid()->property("tileCount").toInt(), 4); QCOMPARE(tiles().size(), 5); const QList row{ tile(QStringLiteral("none")), tile(QStringLiteral("1")), tile(QStringLiteral("2")), tile(QStringLiteral("3")), }; const qreal spacing = gallery()->property("kSpacing").toReal(); for (QQuickItem *tileItem : row) { QCOMPARE(tileItem->width(), grid()->property("tileWidth").toReal()); QCOMPARE(tileItem->y(), row.first()->y()); } for (int i = 1; i < row.size(); ++i) { QCOMPARE(row.at(i)->x() - row.at(i - 1)->x(), row.first()->width() + spacing); } // the last tile's trailing edge, where the grid's is: the row is full QVERIFY(qAbs(row.last()->x() + row.last()->width() - grid()->width()) < 0.5); } // A narrower window gets fewer tiles to a row and not smaller ones below the // width a name stays legible at: a tile narrowed to fit is a name under it // with a third of the name elided off the end. void aNarrowerWindowGetsFewerTilesToARowNotNarrowerOnes() { QCOMPARE(tiles().size(), 5); resizeWindow(m_scene, 400); settleLayout(qobject_cast(m_scene)); QCOMPARE(grid()->property("tileCount").toInt(), 2); QVERIFY(grid()->property("tileWidth").toReal() >= gallery()->property("kMinTileWidth").toReal()); // and a window too narrow for even two keeps one to a row rather than // dropping the tiles off the edge resizeWindow(m_scene, 200); settleLayout(qobject_cast(m_scene)); QCOMPARE(grid()->property("tileCount").toInt(), 1); QCOMPARE(tiles().at(1)->x(), 0.0); } // The tiles in a row are one height, and a tile is as tall as its picture and // its name under it: a tile whose height does not follow its width is a row // of tiles with the next row drawn through them. void theTilesInARowAreOneHeight() { const QList found = tiles(); QCOMPARE(found.size(), 5); for (QQuickItem *tileItem : found) { QCOMPARE(tileItem->height(), found.first()->height()); } // five eighths of the tile is the picture, which is a wallpaper's own // shape: the window crops its wallpaper to fill and so does the tile QCOMPARE(found.first()->property("kPictureHeight").toInt(), qRound(found.first()->width() * 0.625)); QVERIFY(found.first()->height() > found.first()->property("kPictureHeight").toReal()); } // The pictures are decoded at one fixed size whatever the window is doing. A // sourceSize read off the tile is a re-decode at every step of a window drag, // and a folder of these is fifteen-megabyte photographs: the grid goes blank // and comes back while the settings window is being resized. The tile is a // different width at each of these, and the size the pictures are decoded at // is the same one all the way down, so this is not a case of the tile never // having moved. void theSizeThePicturesAreDecodedAtDoesNotFollowTheWindow() { QQuickItem *gin = tile(QStringLiteral("1")); QVERIFY(gin); QQuickItem *picture = pictureOf(gin); QVERIFY(picture); const QVariant decodedAt = picture->property("sourceSize"); QVERIFY(decodedAt.toSize().isValid()); QSet widths; for (const int window : {300, 500, 700, 1100, 1800}) { resizeWindow(m_scene, window); settleLayout(qobject_cast(m_scene)); widths.insert(gin->width()); QCOMPARE(picture->property("sourceSize"), decodedAt); } QVERIFY(widths.size() > 1); } // The tile in use is the one carrying the picture that is set, and no other: // one setting, one answer to which theme this is, and the answer is on the // picture rather than in a row saying "selected". void theTileInUseIsTheOneTheWallpaperSettingNames() { QCOMPARE(tiles().size(), 5); m_scene->setProperty("selectedPath", themePath(QStringLiteral("village"))); settle(); const QList found = tiles(); QCOMPARE(found.at(2)->property("label").toString(), QStringLiteral("Village")); QVERIFY(found.at(2)->property("selected").toBool()); for (int i = 0; i < found.size(); ++i) { if (i != 2) { QCOMPARE(found.at(i)->property("selected").toBool(), false); } } } // No wallpaper set is the tile with no picture being in use, which is a state // of its own rather than a gallery where nothing has been picked yet. void noWallpaperIsTheTileWithNoPicture() { QCOMPARE(tiles().size(), 5); QCOMPARE(tile(QStringLiteral("none"))->property("selected").toBool(), true); m_scene->setProperty("selectedPath", themePath(QStringLiteral("sepia"))); settle(); QCOMPARE(tile(QStringLiteral("none"))->property("selected").toBool(), false); QVERIFY(tile(QStringLiteral("3"))->property("selected").toBool()); } // A tile clicked says which picture was picked, and the page is the one that // writes it: a gallery writing the setting itself is a second place the // wallpaper is chosen from. void clickingATileSaysWhichPictureWasPicked() { QVERIFY(tile(QStringLiteral("1"))); click(tile(QStringLiteral("1"))); settle(); QCOMPARE(m_scene->property("chosenPath").toString(), themePath(QStringLiteral("cloud-gin"))); QCOMPARE(m_scene->property("chosenCount").toInt(), 1); // and it is the tile picked that is in use afterwards, not the one that was // in use before: the setting and the check cannot be told apart QCOMPARE(tile(QStringLiteral("1"))->property("selected").toBool(), true); QCOMPARE(tile(QStringLiteral("none"))->property("selected").toBool(), false); } // The way back to a plain window is a tile like any other: it is in the grid // and it clicks, and what it says is an empty path rather than a theme. void theTileWithNoPictureIsClickedToo() { m_scene->setProperty("selectedPath", themePath(QStringLiteral("village"))); settle(); QVERIFY(tile(QStringLiteral("none"))); click(tile(QStringLiteral("none"))); settle(); QCOMPARE(m_scene->property("chosenPath").toString(), QString()); QCOMPARE(m_scene->property("selectedPath").toString(), QString()); // and it was said rather than nothing having been chosen at all: an empty // picture and no choice read the same otherwise QCOMPARE(m_scene->property("chosenCount").toInt(), 1); } }; QTEST_MAIN(ThemeGalleryTest) #include "ThemeGalleryTest.moc"