-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
90 lines (79 loc) · 2.87 KB
/
main.cpp
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <QCommandLineParser>
#include <QGuiApplication>
#include <QQuickItem>
#include <QQuickItemGrabResult>
#include <QQuickView>
#include <QUrl>
#include <QWindow>
#include <QtDebug>
#include <set>
namespace {
void grabItemsRecursively(std::set<QSharedPointer<QQuickItemGrabResult>> &grabResults,
QQuickItem *item, bool quitOnLastItemGrabbed)
{
for (auto *child : item->childItems()) {
grabItemsRecursively(grabResults, child, quitOnLastItemGrabbed);
}
const auto fileName = item->property("fileName").toString();
if (fileName.isEmpty())
return;
auto grab = item->grabToImage();
if (!grab) {
qWarning() << "Failed to grab item" << item;
return;
}
grabResults.insert(grab);
QObject::connect(grab.get(), &QQuickItemGrabResult::ready,
[fileName, grab, &grabResults, quitOnLastItemGrabbed]() {
auto ok = grab->saveToFile(fileName);
if (ok) {
qInfo() << "Saved file" << fileName;
} else {
qWarning() << "Failed to save file" << fileName;
}
grabResults.erase(grab);
if (grabResults.empty() && quitOnLastItemGrabbed) {
QCoreApplication::quit();
}
});
}
} // namespace
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QCommandLineParser parser;
parser.addHelpOption();
parser.addOption({ "show-window", "Show QML file in window" });
parser.addPositionalArgument("filename", "Source QML file to process.");
parser.process(app);
const auto arguments = parser.positionalArguments();
if (arguments.empty()) {
qWarning() << "No filename specified";
return -1;
}
const auto fileName = arguments.front();
const bool showWindow = parser.isSet("show-window");
QWindow dummyWindow;
QQuickView offscreenView;
if (!showWindow) {
dummyWindow.create();
offscreenView.setParent(&dummyWindow);
}
offscreenView.setSource(QUrl::fromLocalFile(fileName));
auto *rootItem = offscreenView.rootObject();
if (!rootItem) {
qWarning() << "No root item created from" << fileName;
return -1;
}
// the parent window has to be visible to grabToImage()
offscreenView.show();
std::set<QSharedPointer<QQuickItemGrabResult>> grabResults;
grabItemsRecursively(grabResults, rootItem, /*quitOnLastItemGrabbed=*/!showWindow);
if (grabResults.empty()) {
qWarning() << "No item to grab found in " << fileName;
qWarning() << "(Set fileName property to items to be grabbed.)";
return -1;
}
qInfo() << "Found" << grabResults.size() << "items to grab";
return app.exec();
}