17 #include "screengrabber.h"
21 #include <QStandardPaths>
22 #include <QTemporaryDir>
23 #include <QtGui/QImage>
24 #include <QtGui/QGuiApplication>
25 #include <QtQuick/QQuickWindow>
26 #include <QtConcurrent/QtConcurrentRun>
30 bool saveScreenshot(
const QImage &screenshot,
const QString &filename,
const QString &format,
int quality)
32 if (!screenshot.save(filename, format.toLatin1().data(), quality)) {
33 qWarning() <<
"ScreenGrabber: failed to save snapshot!";
40 ScreenGrabber::ScreenGrabber(QObject *parent)
44 if (qEnvironmentVariableIsSet(
"UNITY_TESTING")) {
45 qDebug() <<
"Using test environment";
47 tDir.setAutoRemove(
false);
48 screenshotsDir = tDir.path();
50 qDebug() <<
"Using real environment";
51 screenshotsDir = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
53 screenshotsDir.mkpath(QStringLiteral(
"Screenshots"));
54 screenshotsDir.cd(QStringLiteral(
"Screenshots"));
55 if (screenshotsDir.exists()) {
56 fileNamePrefix = screenshotsDir.absolutePath();
57 fileNamePrefix.append(
"/screenshot");
59 qWarning() <<
"ScreenGrabber: failed to create directory at: " << screenshotsDir.absolutePath();
63 void ScreenGrabber::captureAndSave(
int angle)
65 if (fileNamePrefix.isEmpty())
67 qWarning() <<
"ScreenShotter: no directory to save screenshot";
71 const QWindowList windows = QGuiApplication::topLevelWindows();
74 qWarning() <<
"ScreenShotter: no top level windows found!";
78 QQuickWindow *main_window = qobject_cast<QQuickWindow *>(windows[0]);
81 qWarning() <<
"ScreenShotter: can only take screenshots of QQuickWindows";
85 const QImage screenshot = main_window->grabWindow().transformed(QTransform().rotate(angle));
86 const QString filename = makeFileName();
87 qDebug() <<
"Saving screenshot to" << filename;
88 auto saveOp = QtConcurrent::run(saveScreenshot, screenshot, filename, getFormat(), screenshotQuality);
89 if (saveOp.result()) {
90 Q_EMIT screenshotSaved(filename);
94 QString ScreenGrabber::makeFileName()
const
96 QString fileName(fileNamePrefix);
97 fileName.append(QDateTime::currentDateTime().toString(QStringLiteral(
"yyyyMMdd_hhmmsszzz")));
99 fileName.append(getFormat());
103 QString ScreenGrabber::getFormat()
const
106 return QStringLiteral(
"png");