From 28bffb26a7b20c585d266e01713f0da8298fbba5 Mon Sep 17 00:00:00 2001 From: Kirill Kostin <15322854+k-kostin@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:12:46 +0300 Subject: [PATCH 1/2] Render STL thumbnails in a bounded CPU companion --- CMakeLists.txt | 8 + README.md | 2 + bin/test | 4 +- src/thumbnails.cpp | 71 ++++++-- src/thumbnails.h | 20 ++- tests/folio_tests.cpp | 121 ++++++++++++++ tests/stl_thumbnail_tests.cpp | 158 ++++++++++++++++++ tools/stl-thumbnailer/CMakeLists.txt | 8 + tools/stl-thumbnailer/LICENSE | 21 +++ tools/stl-thumbnailer/README.md | 11 ++ tools/stl-thumbnailer/main.cpp | 39 +++++ tools/stl-thumbnailer/render.cpp | 240 +++++++++++++++++++++++++++ tools/stl-thumbnailer/render.h | 14 ++ 13 files changed, 695 insertions(+), 22 deletions(-) create mode 100644 tests/stl_thumbnail_tests.cpp create mode 100644 tools/stl-thumbnailer/CMakeLists.txt create mode 100644 tools/stl-thumbnailer/LICENSE create mode 100644 tools/stl-thumbnailer/README.md create mode 100644 tools/stl-thumbnailer/main.cpp create mode 100644 tools/stl-thumbnailer/render.cpp create mode 100644 tools/stl-thumbnailer/render.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 7e2cf8f2..b347c278 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -13,6 +13,7 @@ find_package(Qt6 REQUIRED COMPONENTS Core Gui Qml Quick QuickControls2 DBus Conc find_package(PkgConfig REQUIRED) pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0 gio-unix-2.0) find_package(ZLIB REQUIRED) +add_subdirectory(tools/stl-thumbnailer) # Everything but main.cpp, shared by the app and the tests, so a new source # file in src/ needs no line here. @@ -26,13 +27,20 @@ target_link_libraries(folio_core PUBLIC add_executable(folio src/main.cpp src/resources.qrc) target_link_libraries(folio PRIVATE folio_core) +add_dependencies(folio folio-stl-thumbnailer) # The tests compile the same sources, run offscreen, and read the QML they # check straight from src/. add_executable(folio_tests tests/folio_tests.cpp) target_link_libraries(folio_tests PRIVATE folio_core Qt6::Test) +add_dependencies(folio_tests folio-stl-thumbnailer) # The bundled plugins, which the tests run against stubs. target_compile_definitions(folio_tests PRIVATE FOLIO_PLUGINS="${CMAKE_SOURCE_DIR}/plugins") enable_testing() add_test(NAME folio_tests COMMAND folio_tests) set_tests_properties(folio_tests PROPERTIES ENVIRONMENT QT_QPA_PLATFORM=offscreen) + +add_executable(stl_thumbnail_tests tests/stl_thumbnail_tests.cpp) +target_link_libraries(stl_thumbnail_tests PRIVATE folio_stl Qt6::Test) +add_dependencies(stl_thumbnail_tests folio-stl-thumbnailer) +add_test(NAME stl_thumbnail_tests COMMAND stl_thumbnail_tests) diff --git a/README.md b/README.md index ef59b417..bef42fa0 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,8 @@ Files (`folio`) is Omarchy's file manager. It's one quiet window that follows your Omarchy theme and language, works from the keyboard, and never crawls your home folder in the background: folders are read when you open them, and thumbnails are made when a tile needs one, shared with every other app through `~/.cache/thumbnails`. +STL models get transparent thumbnails from a small bundled CPU renderer, without a graphics driver or a separate 3D application. An explicit user thumbnailer takes precedence; an installed system thumbnailer handles files the bundled renderer declines. + - **Three views**: a grid with real previews, a list, and Finder-style columns. Ctrl+1/2/3 switches. - **Space previews** pictures, video, audio, PDFs, text and Markdown at full size, in their own window. - **The sidebar** holds everything in your home folder, pinned folders (shared with GTK file dialogs), Recents, Trash with restore, your drives, and the machines on your tailnet, which open over SFTP. diff --git a/bin/test b/bin/test index b05cd6f4..62acdbbb 100755 --- a/bin/test +++ b/bin/test @@ -3,6 +3,6 @@ set -eu ROOT="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)" cmake -S "$ROOT" -B "$ROOT/build" -DCMAKE_BUILD_TYPE=Release >/dev/null -cmake --build "$ROOT/build" --target folio_tests -j"$(nproc)" +cmake --build "$ROOT/build" --target folio_tests stl_thumbnail_tests -j"$(nproc)" cd "$ROOT/build" -QT_QPA_PLATFORM=offscreen ./folio_tests +QT_QPA_PLATFORM=offscreen ctest --output-on-failure --no-tests=error "$@" diff --git a/src/thumbnails.cpp b/src/thumbnails.cpp index 3613a6d9..b5dc7b92 100644 --- a/src/thumbnails.cpp +++ b/src/thumbnails.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -152,12 +153,11 @@ void stop(QProcess &process, qint64 session) { process.waitForFinished(stoppedPatience); } -Ran run(QProcess &process, const QString &program, const QStringList &args, int patience, const std::atomic_bool &quitting) { +Ran run(QProcess &process, const QString &program, const QStringList &args, QDeadlineTimer deadline, const std::atomic_bool &quitting) { // A thumbnail asked for as Folio quits is never started. - if (quitting) + if (quitting || deadline.hasExpired()) return Ran::Unjudged; - // One deadline for the start and the finish together. - const QDeadlineTimer deadline(patience); + // The caller's absolute deadline also covers an STL's system fallback. process.setChildProcessModifier([folio = ::getpid()] { keepInASession(folio); }); process.start(program, args); // In slices, so quitting doesn't wait on a program slow to start (one on a stalled network mount, say). @@ -250,11 +250,12 @@ const QHash &packageFor() { } // namespace -Thumbnails::Thumbnails(const QString &cacheDirectory, const QStringList &thumbnailerDirectories, int patience) +Thumbnails::Thumbnails(const QString &cacheDirectory, const QStringList &thumbnailerDirectories, int patience, const QString &stlHelper) : m_cache(cacheDirectory.isEmpty() ? QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + "/thumbnails" : cacheDirectory), - m_patience(patience) { + m_patience(patience), + m_stlHelper(stlHelper.isNull() ? QCoreApplication::applicationDirPath() + "/folio-stl-thumbnailer" : stlHelper) { QStringList directories = thumbnailerDirectories; if (directories.isEmpty()) { // Later directories win, so the user's own thumbnailers override the @@ -265,6 +266,7 @@ Thumbnails::Thumbnails(const QString &cacheDirectory, const QStringList &thumbna directories << base + "/thumbnailers"; } QMimeDatabase mimes; + const QString userDirectory = QDir(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation)).filePath("thumbnailers"); for (const QString &directory : directories) { // A .thumbnailer file may name a type by an alias, as glycin names DDS pictures image/x-dds. QHash named, aliased; @@ -301,6 +303,10 @@ Thumbnails::Thumbnails(const QString &cacheDirectory, const QStringList &thumbna // Within one directory the file that names a type itself wins over one that names an alias of it. m_thumbnailers.insert(aliased); m_thumbnailers.insert(named); + if (QDir(directory).absolutePath() == QDir(userDirectory).absolutePath()) { + for (auto it = aliased.cbegin(); it != aliased.cend(); ++it) m_userThumbnailers.insert(it.key()); + for (auto it = named.cbegin(); it != named.cend(); ++it) m_userThumbnailers.insert(it.key()); + } } // An older Folio's failure markers (fail/folio, or a fail/folio- with a lower number) are never read again, so // they are cleared away, on a worker since there may be thousands. A newer Folio's are left for it, so an installed @@ -323,12 +329,28 @@ Thumbnails::Thumbnails(const QString &cacheDirectory, const QStringList &thumbna QString Thumbnails::missingPackage(const QString &mime) const { // Qt draws its own pictures in-process, an installed thumbnailer needs nothing more, and pdftoppm draws a PDF without one. if ((mime.startsWith("image/") && QImageReader::supportedMimeTypes().contains(mime.toLatin1())) - || m_thumbnailers.contains(mime) + || m_thumbnailers.contains(mime) || nativeStl(mime) || (mime == "application/pdf" && !QStandardPaths::findExecutable("pdftoppm").isEmpty())) return {}; return packageFor().value(mime); } +bool Thumbnails::nativeStl(const QString &mime) const { + if (mime != "model/stl" && mime != "model/x.stl-ascii" && mime != "model/x.stl-binary") return false; + if (m_userThumbnailers.contains(mime) || m_userThumbnailers.contains("model/stl")) return false; + const QFileInfo helper(m_stlHelper); + return !m_stlHelper.isEmpty() && helper.isFile() && helper.isExecutable(); +} + +QString Thumbnails::providerKey(const QString &mime) const { + const QString fallback = m_thumbnailers.value(mime); + if (!nativeStl(mime)) return fallback; + const QFileInfo helper(m_stlHelper); + // A newly installed/updated helper or fallback gets its turn after an earlier failure. + return QStringLiteral("stl-cpu-1:%1:%2:%3\n%4").arg(m_stlHelper) + .arg(helper.size()).arg(helper.lastModified().toMSecsSinceEpoch()).arg(fallback); +} + QString Thumbnails::cacheKey(const QString &path) { return QCryptographicHash::hash(fileUri(path).toUtf8(), QCryptographicHash::Md5).toHex() + ".png"; } @@ -380,7 +402,7 @@ QImage Thumbnails::load(const QString &path, const QString &mime, int size) cons const QString type = mime.endsWith("/*") ? QMimeDatabase().mimeTypeForFile(path, QMimeDatabase::MatchExtension).name() : mime; - const QString thumbnailer = m_thumbnailers.value(type); + const QString thumbnailer = providerKey(type); if (failedBefore(path, modified, thumbnailer)) return {}; // A file that cannot be read is not a broken one: nothing is tried, so nothing is remembered. @@ -403,6 +425,17 @@ QImage Thumbnails::load(const QString &path, const QString &mime, int size) cons } QImage Thumbnails::generate(const QString &path, const QString &mime, int pixels, bool &attempted) const { + const QDeadlineTimer deadline(m_patience); + if (nativeStl(mime)) { + QImage image; + attempted = stlPicture(path, pixels, image, deadline); + if (!image.isNull()) return image; + if (m_quitting || deadline.hasExpired()) { + // A fallback not given a turn has not judged the file. + if (m_quitting || !m_thumbnailers.value(mime).isEmpty()) attempted = false; + return {}; + } + } // A camera RAW with no installed thumbnailer, the desktop's own answer, shows the JPEG the camera embedded. if (RawEmbed::handles(mime) && !m_thumbnailers.contains(mime)) { attempted = true; @@ -428,7 +461,7 @@ QImage Thumbnails::generate(const QString &path, const QString &mime, int pixels if (!command.isEmpty()) { // A thumbnailer that could not start has not judged the file, whatever a reader made of it first; a PDF is then left to pdftoppm. QImage image; - attempted = runThumbnailer(command, path, pixels, image); + attempted = runThumbnailer(command, path, pixels, image, deadline); if (attempted) return image; } @@ -436,7 +469,7 @@ QImage Thumbnails::generate(const QString &path, const QString &mime, int pixels // CUPS) draws the first page. if (mime == "application/pdf" && !QStandardPaths::findExecutable("pdftoppm").isEmpty()) { QImage image; - attempted = pdfPage(path, pixels, image); + attempted = pdfPage(path, pixels, image, deadline); return image; } return {}; @@ -489,19 +522,29 @@ QImage Thumbnails::textPage(const QString &path, int pixels, const QColor &paper return page; } -bool Thumbnails::pdfPage(const QString &path, int pixels, QImage &image) const { +bool Thumbnails::pdfPage(const QString &path, int pixels, QImage &image, QDeadlineTimer deadline) const { QTemporaryDir scratch; if (!scratch.isValid()) return false; QProcess process; const Ran ran = run(process, "pdftoppm", {"-f", "1", "-l", "1", "-singlefile", "-png", "-scale-to", QString::number(pixels), - path, scratch.filePath("page")}, m_patience, m_quitting); + path, scratch.filePath("page")}, deadline, m_quitting); if (ran == Ran::Finished) image = QImage(scratch.filePath("page.png")); return ran != Ran::Unjudged; } -bool Thumbnails::runThumbnailer(const QString &command, const QString &path, int pixels, QImage &image) const { +bool Thumbnails::stlPicture(const QString &path, int pixels, QImage &image, QDeadlineTimer deadline) const { + QTemporaryDir scratch; + if (!scratch.isValid()) return false; + const QString output = scratch.filePath("thumbnail.png"); + QProcess process; + const Ran ran = run(process, m_stlHelper, {path, output, QString::number(pixels)}, deadline, m_quitting); + if (ran == Ran::Finished) image = QImage(output); + return ran != Ran::Unjudged; +} + +bool Thumbnails::runThumbnailer(const QString &command, const QString &path, int pixels, QImage &image, QDeadlineTimer deadline) const { QTemporaryDir scratch; if (!scratch.isValid()) return false; @@ -517,7 +560,7 @@ bool Thumbnails::runThumbnailer(const QString &command, const QString &path, int QProcess process; process.setProcessChannelMode(QProcess::ForwardedErrorChannel); - const Ran ran = run(process, program, args, m_patience, m_quitting); + const Ran ran = run(process, program, args, deadline, m_quitting); if (ran == Ran::Finished) image = QImage(output); return ran != Ran::Unjudged; diff --git a/src/thumbnails.h b/src/thumbnails.h index 07435888..cf32b22c 100644 --- a/src/thumbnails.h +++ b/src/thumbnails.h @@ -2,10 +2,12 @@ #include #include +#include #include #include #include #include +#include #include #include @@ -21,9 +23,10 @@ class Thumbnails : public QObject { Q_OBJECT public: - // `patience` is how long a thumbnailer may take, in milliseconds; tests shorten it. + // `patience` covers a thumbnail and any fallback, in milliseconds. A null + // stlHelper finds the bundled companion; an explicit empty string disables it. explicit Thumbnails(const QString &cacheDirectory = {}, const QStringList &thumbnailerDirectories = {}, - int patience = 15000); + int patience = 15000, const QString &stlHelper = {}); // Returns a thumbnail no larger than `size` on its longest side, from the // cache when it is fresh, or a null image when none can be made. @@ -34,8 +37,8 @@ class Thumbnails : public QObject { static QString cacheKey(const QString &path); // The spec's fail/-: the number is raised when Folio learns to draw more, so old failures are tried - // again. 3: names with a thumbnailer's codes in them, and PDFs whose thumbnailer couldn't start, are drawn now. - static inline const QString failures = QStringLiteral("fail/folio-3"); + // again. 4: a bundled CPU helper can draw STL files a system thumbnailer could not. + static inline const QString failures = QStringLiteral("fail/folio-4"); static QString bucketFor(int size); // A text file's first lines set on a page in the given colors. Made // fresh each time rather than cached, since the colors follow the theme. @@ -47,11 +50,14 @@ class Thumbnails : public QObject { private: QString cachePath(const QString &path, int size) const; QString failPath(const QString &path) const; + bool nativeStl(const QString &mime) const; + QString providerKey(const QString &mime) const; // Sets `attempted` when Qt's reader or a thumbnailer could take the file. QImage generate(const QString &path, const QString &mime, int pixels, bool &attempted) const; // Both answer whether the program judged the file: one that could not start, or was stopped as Folio quit, has not. - bool runThumbnailer(const QString &command, const QString &path, int pixels, QImage &image) const; - bool pdfPage(const QString &path, int pixels, QImage &image) const; + bool runThumbnailer(const QString &command, const QString &path, int pixels, QImage &image, QDeadlineTimer deadline) const; + bool pdfPage(const QString &path, int pixels, QImage &image, QDeadlineTimer deadline) const; + bool stlPicture(const QString &path, int pixels, QImage &image, QDeadlineTimer deadline) const; void remember(QImage image, const QString &path, int size, const QDateTime &modified) const; // A failure goes with the type's thumbnailer as it was then, none included: one installed since gets its turn. void rememberFailure(const QString &path, const QDateTime &modified, const QString &thumbnailer) const; @@ -63,6 +69,8 @@ class Thumbnails : public QObject { int m_patience; std::atomic_bool m_quitting{false}; QHash m_thumbnailers; + QSet m_userThumbnailers; + QString m_stlHelper; }; // Serves image://thumb//// to QML on a thread pool. diff --git a/tests/folio_tests.cpp b/tests/folio_tests.cpp index 51803520..ac108dc3 100644 --- a/tests/folio_tests.cpp +++ b/tests/folio_tests.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -5908,6 +5909,126 @@ private slots: QCOMPARE(thumbnails.load(dir.filePath("photo.heic"), "image/*", 128).size(), QSize(64, 32)); } + void thumbnailsDrawStlWithoutAnExternalRenderer() + { + QTemporaryDir dir; + QByteArray stl(80, ' '); + QDataStream stream(&stl, QIODevice::Append); + stream.setByteOrder(QDataStream::LittleEndian); + stream.setFloatingPointPrecision(QDataStream::SinglePrecision); + stream << quint32(4); + const float faces[][9] = {{0,0,0, 0,1,0, 1,0,0}, {0,0,0, 1,0,0, 0,0,1}, + {0,0,0, 0,0,1, 0,1,0}, {1,0,0, 0,1,0, 0,0,1}}; + for (const auto &face : faces) { + stream << 0.f << 0.f << 0.f; + for (float coordinate : face) stream << coordinate; + stream << quint16(0); + } + const QString path = dir.filePath("part.stl"); + write(path, stl); + Thumbnails thumbnails(dir.filePath("cache"), {dir.filePath("no-thumbnailers")}); + const QImage image = thumbnails.load(path, "model/stl", 256); + QVERIFY(!image.isNull()); + QCOMPARE(image.size(), QSize(256, 256)); + QVERIFY(QFile::exists(dir.filePath("cache/large/" + Thumbnails::cacheKey(path)))); + } + + void thumbnailsPreferUserStlThenCpuThenSystem() + { + QTemporaryDir dir; + const auto restore = dataHomeAt(dir.filePath("user")); + const QString user = dir.filePath("user/thumbnailers"), system = dir.filePath("system"); + QVERIFY(QDir().mkpath(user)); QVERIFY(QDir().mkpath(system)); + const QString part = dir.filePath("雪 50%off.stl"), helper = dir.filePath("cpu"), runs = dir.filePath("runs"); + write(part, "fixture passed to each selected renderer"); + QVERIFY(QImage(32,16,QImage::Format_RGB32).save(dir.filePath("cpu.png"))); + QVERIFY(QImage(16,32,QImage::Format_RGB32).save(dir.filePath("system.png"))); + write(helper, "#!/bin/sh\necho cpu >> \"" + runs.toUtf8() + "\"\ncp \"" + + dir.filePath("cpu.png").toUtf8() + "\" \"$2\"\n"); + QVERIFY(QFile::setPermissions(helper, QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner)); + write(system + "/system.thumbnailer", "[Thumbnailer Entry]\nExec=/bin/cp \"" + + dir.filePath("system.png").toUtf8() + "\" %o\nMimeType=model/stl;\n"); + const auto load = [&](const QString &cache) { + return Thumbnails(dir.filePath(cache), {system,user}, 3000, helper).load(part,"model/stl",128); + }; + QCOMPARE(load("native").size(), QSize(32,16)); + QVERIFY(QFile::exists(runs)); QVERIFY(QFile::remove(runs)); + // A canonical type declared through an alias is still an explicit user override. + write(user + "/custom.thumbnailer", "[Thumbnailer Entry]\nExec=/bin/cp \"" + + dir.filePath("system.png").toUtf8() + "\" %o\nMimeType=model/x.stl-binary;\n"); + QCOMPARE(load("user").size(), QSize(16,32)); + QVERIFY(!QFile::exists(runs)); + QVERIFY(QFile::remove(user + "/custom.thumbnailer")); + // Refusal, a missing PNG, and a damaged PNG all let the system renderer answer. + int declined = 0; + for (const QByteArray &body : {QByteArray("exit 1\n"), QByteArray("exit 0\n"), QByteArray("printf partial > \"$2\"\n")}) { + write(helper, "#!/bin/sh\n" + body); + QVERIFY(QFile::setPermissions(helper, QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner)); + QCOMPARE(Thumbnails(dir.filePath("fallback-"+QString::number(++declined)), {system,user}, 3000, helper) + .load(part,"model/stl",128).size(), QSize(16,32)); + } + QVERIFY(QFile::remove(helper)); + QCOMPARE(load("absent").size(), QSize(16,32)); + } + + void thumbnailsRetryStlWhenItsEffectiveProvidersChange() + { + QTemporaryDir dir; + const QString part = dir.filePath("part.stl"), helper = dir.filePath("cpu"), system = dir.filePath("system"); + QVERIFY(QDir().mkpath(system)); write(part,"part"); + const QString cache = dir.filePath("cache"); + write(system + "/fallback.thumbnailer", "[Thumbnailer Entry]\nExec=/bin/false\nMimeType=model/stl;\n"); + Thumbnails beforeInstall(cache,{system},3000,helper); + QVERIFY(beforeInstall.load(part,"model/stl",128).isNull()); + QVERIFY(QFile::exists(dir.filePath("cache/" + Thumbnails::failures + "/" + Thumbnails::cacheKey(part)))); + QVERIFY(QImage(40,20,QImage::Format_RGB32).save(dir.filePath("frame.png"))); + const auto install = [&](const QByteArray &body) { + write(helper,"#!/bin/sh\n" + body); + return QFile::setPermissions(helper,QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner); + }; + QVERIFY(install("cp \""+dir.filePath("frame.png").toUtf8()+"\" \"$2\"\n")); + QCOMPARE(beforeInstall.load(part,"model/stl",128).size(),QSize(40,20)); + // A CPU-only failure must not suppress a system provider installed later. + const QString second = dir.filePath("second-cache"); + QVERIFY(QFile::remove(system + "/fallback.thumbnailer")); + QVERIFY(install("exit 1\n")); + QVERIFY(Thumbnails(second,{system},3000,helper).load(part,"model/stl",128).isNull()); + write(system + "/fallback.thumbnailer", "[Thumbnailer Entry]\nExec=/bin/cp \"" + + dir.filePath("frame.png").toUtf8() + "\" %o\nMimeType=model/stl;\n"); + QCOMPARE(Thumbnails(second,{system},3000,helper).load(part,"model/stl",128).size(),QSize(40,20)); + // Updating the executable also changes the effective route, with input and fallback unchanged. + const QString third = dir.filePath("third-cache"); + QVERIFY(QFile::remove(system + "/fallback.thumbnailer")); + QVERIFY(Thumbnails(third,{system},3000,helper).load(part,"model/stl",128).isNull()); + QVERIFY(install("cp \""+dir.filePath("frame.png").toUtf8()+"\" \"$2\"\n")); + QCOMPARE(Thumbnails(third,{system},3000,helper).load(part,"model/stl",128).size(),QSize(40,20)); + } + + void thumbnailsStlFallbackSharesTheJobDeadline() + { + QTemporaryDir dir; + const QString part=dir.filePath("part.stl"), helper=dir.filePath("cpu"), system=dir.filePath("system"); + QVERIFY(QDir().mkpath(system)); write(part,"part"); + const QString started=dir.filePath("fallback-started"); + write(helper,"#!/bin/sh\nsleep 0.2\nexit 1\n"); + QVERIFY(QFile::setPermissions(helper,QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner)); + write(system+"/fallback.thumbnailer", "[Thumbnailer Entry]\nExec=/bin/sh -c \"echo run > '" + + started.toUtf8()+"'; sleep 1\"\nMimeType=model/stl;\n"); + Thumbnails thumbnails(dir.filePath("cache"),{system},350,helper); + QElapsedTimer clock; clock.start(); + QVERIFY(thumbnails.load(part,"model/stl",128).isNull()); + QVERIFY(QFile::exists(started)); + QVERIFY2(clock.elapsed()<480,"The fallback restarted the job's time allowance"); + QVERIFY(QFile::remove(started)); + // A CPU process using up the whole allowance never starts the fallback, + // and an untried system renderer cannot cause a failure marker. + write(helper,"#!/bin/sh\nsleep 1\nexit 1\n"); + Thumbnails expired(dir.filePath("expired"),{system},150,helper); + QVERIFY(expired.load(part,"model/stl",128).isNull()); + QVERIFY(!QFile::exists(started)); + QVERIFY(!QFile::exists(dir.filePath("expired/"+Thumbnails::failures+"/"+Thumbnails::cacheKey(part)))); + } + void thumbnailsSetTextOnAPage() { QTemporaryDir dir; diff --git a/tests/stl_thumbnail_tests.cpp b/tests/stl_thumbnail_tests.cpp new file mode 100644 index 00000000..ba6d7eb8 --- /dev/null +++ b/tests/stl_thumbnail_tests.cpp @@ -0,0 +1,158 @@ +#include "render.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using Point = std::array; +using Triangle = std::array; + +static QByteArray binary(const QList &faces) { + QByteArray bytes(80, ' '); + QDataStream out(&bytes, QIODevice::Append); + out.setByteOrder(QDataStream::LittleEndian); + out.setFloatingPointPrecision(QDataStream::SinglePrecision); + out << quint32(faces.size()); + for (const auto &face : faces) { + out << 0.f << 0.f << 0.f; + for (const auto &point : face) for (float coordinate : point) out << coordinate; + out << quint16(0); + } + return bytes; +} +static QByteArray ascii(const QList &faces) { + QByteArray bytes = "solid public test\r\n"; + for (const auto &face : faces) { + bytes += "facet\tnormal 0 0 1\r\nouter loop\r\n"; + for (const auto &point : face) { + bytes += "vertex"; + for (float coordinate : point) bytes += (coordinate < 0 ? " " : " +") + QByteArray::number(coordinate, 'e', 8); + bytes += "\r\n"; + } + bytes += "endloop\r\nendfacet\r\n"; + } + return bytes + "endsolid public test\r\n"; +} +static bool write(const QString &name, const QByteArray &bytes) { + QFile file(name); + return file.open(QIODevice::WriteOnly) && file.write(bytes) == bytes.size(); +} +static qsizetype covered(const QImage &image) { + qsizetype count = 0; + for (int y = 0; y < image.height(); ++y) + for (int x = 0; x < image.width(); ++x) count += qAlpha(image.pixel(x, y)) != 0; + return count; +} + +class StlThumbnailTests : public QObject { + Q_OBJECT + const Triangle face{{{0,0,0}, {10,0,0}, {0,10,0}}}; + const QString worker = QCoreApplication::applicationDirPath() + "/folio-stl-thumbnailer"; +private slots: + void binaryAsciiAndBothWindingsAgree() { + const QImage expected = StlThumbnail::render(binary({face}), 128); + QVERIFY(!expected.isNull()); + QCOMPARE(expected.size(), QSize(128, 128)); + QVERIFY(covered(expected) > 1000); + QVERIFY(covered(expected) < 128*128); + QCOMPARE(StlThumbnail::render(ascii({face}), 128), expected); + auto backwards = face; + std::swap(backwards[1], backwards[2]); + QCOMPARE(StlThumbnail::render(binary({backwards}), 128), expected); + QByteArray solid = binary({face}); + solid.replace(0, 5, "solid"); + QCOMPARE(StlThumbnail::render(solid, 128), expected); + for (int y = 0; y < expected.height(); ++y) { + for (int x = 0; x < expected.width(); ++x) { + const QRgb p = expected.pixel(x,y); + QVERIFY(qRed(p) <= qAlpha(p) && qGreen(p) <= qAlpha(p) && qBlue(p) <= qAlpha(p)); + } + } + } + void depthDoesNotDependOnFaceOrder() { + const double r = std::sqrt(.5), d = 1/std::sqrt(3.), u = 1/std::sqrt(6.); + const auto point = [&](double x, double y, double z) { + return Point{float(x*r-y*u+z*d), float(x*r+y*u-z*d), float(2*y*u+z*d)}; + }; + const Triangle near{{point(-1,-1,2), point(1,-1,6), point(0,1,4)}}; + const Triangle far{{point(-1,-1,0), point(1,-1,0), point(0,1,0)}}; + const auto a = StlThumbnail::render(binary({near,far}), 128); + const auto b = StlThumbnail::render(binary({far,near}), 128); + QVERIFY(!a.isNull()); + QCOMPARE(a, b); + } + void rejectsInvalidAndUnboundedInputs() { + QVERIFY(StlThumbnail::render({}, 128).isNull()); + QVERIFY(StlThumbnail::render(binary({face}).chopped(1), 128).isNull()); + QVERIFY(StlThumbnail::render(ascii({face}).replace("endfacet", "incomplete"), 128).isNull()); + QVERIFY(StlThumbnail::render(ascii({face}).replace("endsolid", "unclosed"), 128).isNull()); + QVERIFY(StlThumbnail::render(binary({face}), 0).isNull()); + QVERIFY(StlThumbnail::render(binary({face}), StlThumbnail::maxPixels+1).isNull()); + auto coloured = binary({face}); coloured[coloured.size()-1] = char(0x80); + QVERIFY(StlThumbnail::render(coloured,128).isNull()); + coloured = binary({face}); coloured.replace(0,6,"COLOR="); + QVERIFY(StlThumbnail::render(coloured,128).isNull()); + for (float value : {std::numeric_limits::infinity(), std::numeric_limits::quiet_NaN(), 1e20f}) { + auto bad = face; bad[0][0] = value; + QVERIFY(StlThumbnail::render(binary({bad}), 128).isNull()); + } + auto degenerate = face; degenerate[1] = degenerate[2] = degenerate[0]; + QVERIFY(StlThumbnail::render(binary({degenerate}), 128).isNull()); + QVERIFY(StlThumbnail::render("solid " + QByteArray(1025, 'a') + "\nendsolid\n", 128).isNull()); + QVERIFY(StlThumbnail::render(ascii({face}).replace("vertex", QByteArray(129, 'x')), 128).isNull()); + } + void finiteExtremeAndTinyCoordinatesStayBounded() { + for (float scale : {1e-25f, 1e7f}) { + auto scaled = face; + for (auto &p : scaled) for (auto &c : p) c *= scale; + const auto image = StlThumbnail::render(binary({scaled}), 128); + QVERIFY(!image.isNull()); + QVERIFY(covered(image) > 1000); + } + auto translated = face; + for (auto &p : translated) for (auto &c : p) c = c*10000+1e8f; + QVERIFY(!StlThumbnail::render(binary({translated}), 128).isNull()); + } + void boundsOverdrawRatherThanReturningAPartialPicture() { + QList repeated; + for (int i = 0; i < 100; ++i) repeated << face; + QString error; + QVERIFY(StlThumbnail::render(binary(repeated), 1024, &error).isNull()); + QVERIFY(error.contains("work bound")); + } + void commandReadsRegularFilesAndPreservesExistingOutput() { + QTemporaryDir dir; + const QString input = dir.filePath("part 雪 50%off '$().stl"), output = dir.filePath("out.png"); + QVERIFY(write(input, binary({face}))); + auto run = [&](const QString &path, const QString &target) { + QProcess process; + process.start(worker, {path,target,"128"}); + if (!process.waitForFinished(3000)) { process.kill(); process.waitForFinished(); return -1; } + return process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1; + }; + QCOMPARE(run(input, output), 0); + QCOMPARE(QImage(output).size(), QSize(128,128)); + QVERIFY(write(output, "caller data")); + QVERIFY(run(input, output) != 0); + QFile kept(output); QVERIFY(kept.open(QIODevice::ReadOnly)); QCOMPARE(kept.readAll(), QByteArray("caller data")); + const QString link = dir.filePath("link.stl"); + QVERIFY(QFile::link(input, link)); + QCOMPARE(run(link, dir.filePath("linked.png")), 0); + const QString fifo = dir.filePath("fifo.stl"); + QVERIFY(::mkfifo(QFile::encodeName(fifo).constData(), 0600) == 0); + QVERIFY(run(fifo, dir.filePath("fifo.png")) > 0); + const QString huge = dir.filePath("huge.stl"); + QFile sparse(huge); QVERIFY(sparse.open(QIODevice::WriteOnly)); + QVERIFY(sparse.resize(StlThumbnail::maxBytes+1)); sparse.close(); + QVERIFY(run(huge, dir.filePath("huge.png")) > 0); + QVERIFY(!QFile::exists(dir.filePath("huge.png"))); + } +}; +QTEST_GUILESS_MAIN(StlThumbnailTests) +#include "stl_thumbnail_tests.moc" diff --git a/tools/stl-thumbnailer/CMakeLists.txt b/tools/stl-thumbnailer/CMakeLists.txt new file mode 100644 index 00000000..6d90092f --- /dev/null +++ b/tools/stl-thumbnailer/CMakeLists.txt @@ -0,0 +1,8 @@ +add_library(folio_stl STATIC render.cpp render.h) +target_include_directories(folio_stl PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) +target_link_libraries(folio_stl PUBLIC Qt6::Core Qt6::Gui) +target_compile_options(folio_stl PRIVATE -Wall -Wextra) + +add_executable(folio-stl-thumbnailer main.cpp) +target_link_libraries(folio-stl-thumbnailer PRIVATE folio_stl) +set_target_properties(folio-stl-thumbnailer PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) diff --git a/tools/stl-thumbnailer/LICENSE b/tools/stl-thumbnailer/LICENSE new file mode 100644 index 00000000..ba6c6d18 --- /dev/null +++ b/tools/stl-thumbnailer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 GM + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tools/stl-thumbnailer/README.md b/tools/stl-thumbnailer/README.md new file mode 100644 index 00000000..64c3feeb --- /dev/null +++ b/tools/stl-thumbnailer/README.md @@ -0,0 +1,11 @@ +# STL thumbnail companion + +`folio-stl-thumbnailer INPUT OUTPUT SIZE` makes a transparent PNG without starting a window or initializing a graphics backend. Input and output paths are absolute; SIZE is 1–1024 pixels. The output must not already exist. The tool is built with Folio's existing C++/Qt dependencies and runs in the thumbnail helper session, outside the UI process. + +The renderer scans a bounded input snapshot twice, fitting an orthographic camera before rasterizing both sides with a depth buffer and two-by-two coverage samples. It allocates no vertex graph. The camera, raster equations and stepped OKLab palette are adapted from [Flea](https://github.com/thisisgm/flea/tree/cde415617459de2cb452bee14b7699e82a4bdd9b/src/ui_logic_pv4), Copyright (c) 2026 GM, under the [MIT license](LICENSE). + +Input is limited to 128 MiB, two million triangles and finite coordinates within 1e9 units. ASCII accepts ordinary whitespace, CRLF and scientific notation. Binary headers starting with `solid` are identified by their count and size. Degenerate geometry, malformed input, unsupported color extensions and excessive raster work are declined. The work bound counts at most 128 million covered bounding-box samples; it never publishes a partially rendered image. + +Folio keeps an explicit user thumbnailer first. Otherwise it tries its companion executable, then the selected system thumbnailer if the companion declines or is absent. Both attempts share the same job deadline and session cleanup. Successful images use the existing shared thumbnail cache. Failure markers include the effective CPU/fallback route so installation or replacement of a provider permits another attempt. + +Packagers should ship `build/folio-stl-thumbnailer` beside `build/folio`, and this directory's `LICENSE` as an additional license notice. No system `.thumbnailer` file is registered: Folio chooses its bundled companion deliberately, without depending on enumeration order between competing system thumbnailers. diff --git a/tools/stl-thumbnailer/main.cpp b/tools/stl-thumbnailer/main.cpp new file mode 100644 index 00000000..74f399cf --- /dev/null +++ b/tools/stl-thumbnailer/main.cpp @@ -0,0 +1,39 @@ +#include "render.h" +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char **argv) { + QCoreApplication app(argc, argv); + const QStringList args = app.arguments(); + bool sizeOk = false; + const int pixels = args.value(3).toInt(&sizeOk); + if (args.size() != 4 || !QDir::isAbsolutePath(args[1]) || !QDir::isAbsolutePath(args[2]) + || !sizeOk || pixels < 1 || pixels > StlThumbnail::maxPixels) return 2; + // Nonblocking open and fstat refer to the same descriptor, including symlinks: + // a FIFO swapped in during lookup cannot hold the helper waiting for a writer. + const int fd = ::open(QFile::encodeName(args[1]).constData(), O_RDONLY | O_NONBLOCK | O_CLOEXEC); + if (fd < 0) return 1; + struct stat status{}; + if (::fstat(fd, &status) != 0 || !S_ISREG(status.st_mode) + || status.st_size <= 0 || status.st_size > StlThumbnail::maxBytes) { ::close(fd); return 1; } + QFile input; + if (!input.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) { ::close(fd); return 1; } + const QByteArray bytes = input.read(status.st_size+1); + if (input.error() != QFileDevice::NoError || bytes.size() != status.st_size) return 1; + QString error; + const QImage image = StlThumbnail::render(bytes, pixels, &error); + if (image.isNull()) { QTextStream(stderr) << error << '\n'; return 1; } + QFile output(args[2]); + if (!output.open(QIODevice::WriteOnly | QIODevice::NewOnly)) return 1; + output.setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner); + QImageWriter writer(&output, "png"); + writer.setCompression(1); + if (!writer.write(image) || !output.flush()) { output.close(); output.remove(); return 1; } + return 0; +} diff --git a/tools/stl-thumbnailer/render.cpp b/tools/stl-thumbnailer/render.cpp new file mode 100644 index 00000000..0edbc4db --- /dev/null +++ b/tools/stl-thumbnailer/render.cpp @@ -0,0 +1,240 @@ +// Camera fitting, depth-buffer rasterization and stepped OKLab shading adapted +// from Flea (MIT), cde415617459de2cb452bee14b7699e82a4bdd9b. +// Copyright (c) 2026 GM. See LICENSE in this directory. +#include "render.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using Point = std::array; +using Triangle = std::array; +using Visit = std::function; +constexpr double maxCoordinate = 1e9; +// Bounds work even for a file made of millions of full-frame overlapping faces. +constexpr quint64 maxSamples = 128'000'000; + +double dot(const Point &a, const Point &b) { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]; } +Point subtract(const Point &a, const Point &b) { return {a[0]-b[0], a[1]-b[1], a[2]-b[2]}; } +Point cross(const Point &a, const Point &b) { + return {a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]}; +} +Point unit(Point p) { + const double length = std::hypot(p[0], p[1], p[2]); + if (length == 0) return {}; + for (auto &coordinate : p) coordinate /= length; + return p; +} +bool coordinate(double value) { return std::isfinite(value) && std::abs(value) <= maxCoordinate; } +bool space(char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\v' || c == '\f'; } + +class Tokens { +public: + explicit Tokens(QByteArrayView bytes) : m_bytes(bytes) {} + QByteArrayView next() { + while (m_at < m_bytes.size() && space(m_bytes[m_at])) ++m_at; + const qsizetype start = m_at; + while (m_at < m_bytes.size() && !space(m_bytes[m_at])) { + if (++m_at - start > 128) { good = false; return {}; } + } + return m_bytes.sliced(start, m_at-start); + } + bool expect(QByteArrayView word) { return next() == word && good; } + // Names after solid/endsolid may contain spaces; they are not geometry. + bool name() { + const qsizetype start = m_at; + while (m_at < m_bytes.size() && m_bytes[m_at] != '\n') + if (++m_at - start > 1024) return good = false; + return true; + } + bool number(double &value) { + auto word = next(); + if (!word.empty() && word.front() == '+') word = word.sliced(1); + if (word.empty()) return false; + const auto read = std::from_chars(word.data(), word.data()+word.size(), value); + return good && read.ec == std::errc() && read.ptr == word.data()+word.size() && coordinate(value); + } + bool good = true; +private: + QByteArrayView m_bytes; + qsizetype m_at = 0; +}; + +// Scan twice instead of allocating a vertex/face graph: first fit the camera, +// then render. Both scans see the same bounded in-memory snapshot of the file. +bool scan(const QByteArray &bytes, const Visit &visit) { + if (bytes.size() >= 84) { + const quint32 count = qFromLittleEndian(bytes.constData()+80); + if (84 + quint64(count)*50 == quint64(bytes.size())) { + if (count == 0 || count > StlThumbnail::maxTriangles) return false; + // Color extensions have incompatible conventions; leave them to an installed renderer. + if (bytes.first(80).contains("COLOR=")) return false; + for (quint32 i = 0; i < count; ++i) { + Triangle triangle; + const char *face = bytes.constData()+84+quint64(i)*50; + if (qFromLittleEndian(face+48) != 0) return false; + for (int corner = 0; corner < 3; ++corner) { + for (int axis = 0; axis < 3; ++axis) { + const quint32 bits = qFromLittleEndian(face+12+corner*12+axis*4); + float value; + std::memcpy(&value, &bits, sizeof value); + if (!coordinate(value)) return false; + triangle[corner][axis] = value; + } + } + if (!visit(triangle)) return false; + } + return true; + } + } + Tokens words(bytes); + quint32 count = 0; + auto token = words.next(); + while (!token.empty()) { + if (token != "solid" || !words.name()) return false; + bool closed = false; + while (!(token = words.next()).empty()) { + if (token == "endsolid") { closed = words.name(); break; } + if (token != "facet" || !words.expect("normal")) return false; + double ignored; + for (int axis = 0; axis < 3; ++axis) if (!words.number(ignored)) return false; + if (!words.expect("outer") || !words.expect("loop")) return false; + Triangle triangle; + for (auto &point : triangle) { + if (!words.expect("vertex")) return false; + for (auto &value : point) { + if (!words.number(value)) return false; + // STL's binary coordinates are float32; keep ASCII equivalent. + value = float(value); + } + } + if (!words.expect("endloop") || !words.expect("endfacet") + || ++count > StlThumbnail::maxTriangles || !visit(triangle)) return false; + } + if (!closed) return false; + token = words.next(); + } + return words.good && count > 0; +} + +std::array tones() { + const Point lit{.65, .68, .73}; + Point linear = lit; + for (auto &c : linear) c = c <= .04045 ? c/12.92 : std::pow((c+.055)/1.055, 2.4); + const double l = std::cbrt(dot(linear, {.41222146, .53633255, .051445995})); + const double m = std::cbrt(dot(linear, {.2119035, .6806995, .10739696})); + const double s = std::cbrt(dot(linear, {.08830246, .28171885, .6299787})); + const double light = std::max(0., .21045426*l + .7936178*m - .004072047*s - .30); + const double a = 1.9779985*l - 2.4285922*m + .4505937*s; + const double b = .025904037*l + .78277177*m - .80867577*s; + const auto cube = [](double x) { return x*x*x; }; + const Point lab{cube(light+.39633778*a+.21580376*b), + cube(light-.105561346*a-.06385417*b), cube(light-.08948418*a-1.2914855*b)}; + Point shade{dot(lab, {4.0767417, -3.3077116, .23096994}), + dot(lab, {-1.268438, 2.6097574, -.34131938}), + dot(lab, {-.0041960863, -.7034186, 1.7076147})}; + for (auto &c : shade) { + c = std::clamp(c, 0., 1.); + c = c <= .0031308 ? c*12.92 : 1.055*std::pow(c, 1./2.4)-.055; + } + std::array result; + for (int k = 0; k <= 10; ++k) { + Point value; + for (int i = 0; i < 3; ++i) value[i] = shade[i]+(lit[i]-shade[i])*k/10.; + result[k] = qRgb(qRound(value[0]*255), qRound(value[1]*255), qRound(value[2]*255)); + } + return result; +} +} + +QImage StlThumbnail::render(const QByteArray &bytes, int pixels, QString *error) try { + const auto fail = [&](const char *message) { if (error) *error = QString::fromLatin1(message); return QImage(); }; + if (bytes.isEmpty() || bytes.size() > maxBytes || pixels < 1 || pixels > maxPixels) + return fail("STL input or image size exceeds its bound"); + const Point right = unit({1, 1, 0}), toward = unit({1, -1, 1}), up = cross(toward, right); + const Point light = unit({-.55*right[0]+.65*up[0]+.5*toward[0], + -.55*right[1]+.65*up[1]+.5*toward[1], + -.55*right[2]+.65*up[2]+.5*toward[2]}); + Point lo{INFINITY, INFINITY, INFINITY}, hi{-INFINITY, -INFINITY, -INFINITY}; + const auto project = [&](const Point &p) { return Point{dot(p, right), -dot(p, up), dot(p, toward)}; }; + if (!scan(bytes, [&](const Triangle &triangle) { + for (const auto &p : triangle) { + const auto q = project(p); + for (int i = 0; i < 3; ++i) { lo[i] = std::min(lo[i], q[i]); hi[i] = std::max(hi[i], q[i]); } + } + return true; + })) return fail("Invalid or oversized STL geometry"); + const double span = std::max(hi[0]-lo[0], hi[1]-lo[1]); + if (!(span > 0) || !std::isfinite(span)) return fail("STL has no visible extent"); + const int width = pixels*2; + const double scale = .92*width/span; + const Point centre{(lo[0]+hi[0])/2, (lo[1]+hi[1])/2, (lo[2]+hi[2])/2}; + const double depthSpan = std::max(span, hi[2]-lo[2]); + const auto screen = [&](const Point &p) { + const auto q = project(p); + return std::array{float((q[0]-centre[0])*scale+width/2.), + float((q[1]-centre[1])*scale+width/2.), float((q[2]-centre[2])/depthSpan)}; + }; + std::vector depth(size_t(width)*width, -std::numeric_limits::infinity()); + std::vector colour(depth.size(), 0); + const auto ink = tones(); + quint64 work = 0; + bool visible = false; + if (!scan(bytes, [&](const Triangle &triangle) { + const auto a = screen(triangle[0]), b = screen(triangle[1]), c = screen(triangle[2]); + const float area = (b[0]-a[0])*(c[1]-a[1])-(b[1]-a[1])*(c[0]-a[0]); + if (!std::isfinite(area) || std::abs(area) < 1e-8f) return true; + const auto bound = [width](float x) { return int(std::clamp(x, 0.f, float(width))); }; + const int x0 = bound(std::floor(std::min({a[0], b[0], c[0]}))); + const int x1 = bound(std::ceil(std::max({a[0], b[0], c[0]}))); + const int y0 = bound(std::floor(std::min({a[1], b[1], c[1]}))); + const int y1 = bound(std::ceil(std::max({a[1], b[1], c[1]}))); + work += quint64(x1-x0)*quint64(y1-y0); + if (work > maxSamples) return false; + auto normal = unit(cross(subtract(triangle[1], triangle[0]), subtract(triangle[2], triangle[0]))); + if (dot(normal, normal) == 0) return true; + if (dot(normal, toward) < 0) for (auto &v : normal) v = -v; + const int shade = qRound(std::clamp((dot(normal, light)+.3)/1.25, 0., 1.)*10); + const float inverse = 1/area; + for (int y = y0; y < y1; ++y) { + for (int x = x0; x < x1; ++x) { + const float px = x+.5f, py = y+.5f; + const float w0 = ((c[0]-b[0])*(py-b[1])-(c[1]-b[1])*(px-b[0]))*inverse; + const float w1 = ((a[0]-c[0])*(py-c[1])-(a[1]-c[1])*(px-c[0]))*inverse; + const float w2 = 1-w0-w1; + if (w0 < 0 || w1 < 0 || w2 < 0) continue; + const float z = w0*a[2]+w1*b[2]+w2*c[2]; + const size_t at = size_t(y)*width+x; + if (z > depth[at]) { depth[at] = z; colour[at] = ink[shade]; visible = true; } + } + } + return true; + })) return fail("STL exceeds the raster work bound"); + if (!visible) return fail("STL produced no visible pixels"); + QImage image(pixels, pixels, QImage::Format_ARGB32_Premultiplied); + if (image.isNull()) return fail("Cannot allocate STL image"); + // Average premultiplied samples, preserving transparent silhouette edges. + for (int y = 0; y < pixels; ++y) { + auto *row = reinterpret_cast(image.scanLine(y)); + for (int x = 0; x < pixels; ++x) { + const size_t at = size_t(y*2)*width+x*2; + int r=0, g=0, b=0, a=0; + for (size_t i : {at, at+1, at+width, at+width+1}) { + r += qRed(colour[i]); g += qGreen(colour[i]); b += qBlue(colour[i]); a += qAlpha(colour[i]); + } + row[x] = qRgba((r+2)/4, (g+2)/4, (b+2)/4, (a+2)/4); + } + } + return image; +} catch (const std::bad_alloc &) { + if (error) *error = QStringLiteral("Cannot allocate STL buffers"); + return {}; +} diff --git a/tools/stl-thumbnailer/render.h b/tools/stl-thumbnailer/render.h new file mode 100644 index 00000000..1ca52c80 --- /dev/null +++ b/tools/stl-thumbnailer/render.h @@ -0,0 +1,14 @@ +#pragma once + +#include +#include +#include + +namespace StlThumbnail { +inline constexpr qint64 maxBytes = 128 * 1024 * 1024; +inline constexpr quint32 maxTriangles = 2'000'000; +inline constexpr int maxPixels = 1024; + +// A bounded, two-sided orthographic picture. No file is opened by the renderer. +QImage render(const QByteArray &bytes, int pixels, QString *error = nullptr); +} From d87b9dd74862c62b2e412689cf539e649c1635b4 Mon Sep 17 00:00:00 2001 From: Kirill Kostin <15322854+k-kostin@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:16:29 +0300 Subject: [PATCH 2/2] Scope CPU work refusals to the requested thumbnail size --- src/thumbnails.cpp | 10 +++++----- src/thumbnails.h | 2 +- tests/folio_tests.cpp | 17 +++++++++++++++++ 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/src/thumbnails.cpp b/src/thumbnails.cpp index b5dc7b92..f9dd6194 100644 --- a/src/thumbnails.cpp +++ b/src/thumbnails.cpp @@ -342,13 +342,13 @@ bool Thumbnails::nativeStl(const QString &mime) const { return !m_stlHelper.isEmpty() && helper.isFile() && helper.isExecutable(); } -QString Thumbnails::providerKey(const QString &mime) const { +QString Thumbnails::providerKey(const QString &mime, int pixels) const { const QString fallback = m_thumbnailers.value(mime); if (!nativeStl(mime)) return fallback; const QFileInfo helper(m_stlHelper); - // A newly installed/updated helper or fallback gets its turn after an earlier failure. - return QStringLiteral("stl-cpu-1:%1:%2:%3\n%4").arg(m_stlHelper) - .arg(helper.size()).arg(helper.lastModified().toMSecsSinceEpoch()).arg(fallback); + // A new helper, fallback or smaller size gets its turn after an earlier failure. + return QStringLiteral("stl-cpu-1:%1:%2:%3:%4\n%5").arg(m_stlHelper) + .arg(helper.size()).arg(helper.lastModified().toMSecsSinceEpoch()).arg(pixels).arg(fallback); } QString Thumbnails::cacheKey(const QString &path) { @@ -402,7 +402,7 @@ QImage Thumbnails::load(const QString &path, const QString &mime, int size) cons const QString type = mime.endsWith("/*") ? QMimeDatabase().mimeTypeForFile(path, QMimeDatabase::MatchExtension).name() : mime; - const QString thumbnailer = providerKey(type); + const QString thumbnailer = providerKey(type, pixels); if (failedBefore(path, modified, thumbnailer)) return {}; // A file that cannot be read is not a broken one: nothing is tried, so nothing is remembered. diff --git a/src/thumbnails.h b/src/thumbnails.h index cf32b22c..4520e654 100644 --- a/src/thumbnails.h +++ b/src/thumbnails.h @@ -51,7 +51,7 @@ class Thumbnails : public QObject { QString cachePath(const QString &path, int size) const; QString failPath(const QString &path) const; bool nativeStl(const QString &mime) const; - QString providerKey(const QString &mime) const; + QString providerKey(const QString &mime, int pixels) const; // Sets `attempted` when Qt's reader or a thumbnailer could take the file. QImage generate(const QString &path, const QString &mime, int pixels, bool &attempted) const; // Both answer whether the program judged the file: one that could not start, or was stopped as Folio quit, has not. diff --git a/tests/folio_tests.cpp b/tests/folio_tests.cpp index ac108dc3..3647a6be 100644 --- a/tests/folio_tests.cpp +++ b/tests/folio_tests.cpp @@ -5933,6 +5933,23 @@ private slots: QVERIFY(QFile::exists(dir.filePath("cache/large/" + Thumbnails::cacheKey(path)))); } + void thumbnailsDoNotReuseStlWorkRefusalAtASmallerSize() + { + QTemporaryDir dir; + QByteArray stl(80, ' '); + QDataStream stream(&stl, QIODevice::Append); + stream.setByteOrder(QDataStream::LittleEndian); + stream.setFloatingPointPrecision(QDataStream::SinglePrecision); + stream << quint32(100); + for (int i = 0; i < 100; ++i) + stream << 0.f << 0.f << 1.f << 0.f << 0.f << 0.f << 10.f << 0.f << 0.f << 0.f << 10.f << 0.f << quint16(0); + const QString part = dir.filePath("part.stl"); + write(part, stl); + Thumbnails thumbnails(dir.filePath("cache"), {dir.filePath("no-thumbnailers")}); + QVERIFY(thumbnails.load(part, "model/stl", 1024).isNull()); + QCOMPARE(thumbnails.load(part, "model/stl", 128).size(), QSize(128,128)); + } + void thumbnailsPreferUserStlThenCpuThenSystem() { QTemporaryDir dir;