Skip to content

Commit 13e8736

Browse files
committed
core/qmlglobal: add saveToFile
1 parent db77c71 commit 13e8736

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/core/qmlglobal.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,13 @@
1515
#include <qqmlcontext.h>
1616
#include <qqmlengine.h>
1717
#include <qqmllist.h>
18+
#include <qquickitemgrabresult.h>
1819
#include <qscreen.h>
1920
#include <qtenvironmentvariables.h>
21+
#include <qthreadpool.h>
2022
#include <qtmetamacros.h>
2123
#include <qtypes.h>
24+
#include <qurl.h>
2225
#include <qvariant.h>
2326
#include <qwindowdefs.h>
2427
#include <unistd.h>
@@ -313,6 +316,25 @@ QString QuickshellGlobal::iconPath(const QString& icon, const QString& fallback)
313316
return IconImageProvider::requestString(icon, "", fallback);
314317
}
315318

319+
void QuickshellGlobal::saveToFile(
320+
const QQuickItemGrabResult* grabResult,
321+
const QUrl& filePath
322+
) {
323+
if (!filePath.isLocalFile()) {
324+
qWarning() << "saveToFile can only save to a file on the local filesystem";
325+
return;
326+
}
327+
328+
const QString localFile = filePath.toLocalFile();
329+
QImage image = grabResult->image();
330+
331+
QThreadPool::globalInstance()->start([image, localFile] {
332+
if (!image.save(localFile)) {
333+
qWarning() << "Failed to save image to" << localFile;
334+
}
335+
});
336+
}
337+
316338
QuickshellGlobal* QuickshellGlobal::create(QQmlEngine* engine, QJSEngine* /*unused*/) {
317339
auto* qsg = new QuickshellGlobal();
318340
auto* generation = EngineGeneration::findEngineGeneration(engine);

src/core/qmlglobal.hpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#include <qqmlengine.h>
1010
#include <qqmlintegration.h>
1111
#include <qqmllist.h>
12+
#include <qquickitemgrabresult.h>
1213
#include <qscreen.h>
1314
#include <qtmetamacros.h>
1415
#include <qtypes.h>
@@ -184,6 +185,15 @@ class QuickshellGlobal: public QObject {
184185
/// This function is equivalent to @@Quickshell.Io.Process.startDetached().
185186
Q_INVOKABLE static void execDetached(const qs::io::process::ProcessContext& context);
186187

188+
/// Save the contents of an ItemGrabResult to a file asynchronously.
189+
///
190+
/// > [!INFO] This function is equivalent to an asynchronous version of
191+
/// > @@QtQuick.ItemGrabResult.saveToFile().
192+
/// >
193+
/// > You can use it in a similar way: `Item.grabToImage(res => Quickshell.saveToFile(res, path))`
194+
Q_INVOKABLE static void
195+
saveToFile(const QQuickItemGrabResult* grabResult, const QUrl& filePath);
196+
187197
/// Returns a string usable for a @@QtQuick.Image.source for a given system icon.
188198
///
189199
/// > [!INFO] By default, icons are loaded from the theme selected by the qt platform theme,

0 commit comments

Comments
 (0)