17 #include "screengrabber.h"
21 #include <QStandardPaths>
22 #include <QtGui/QImage>
23 #include <QtGui/QGuiApplication>
24 #include <QtQuick/QQuickWindow>
25 #include <QtConcurrent/QtConcurrentRun>
29 bool saveScreenshot(
const QImage &screenshot,
const QString &filename,
const QString &format,
int quality)
31 if (!screenshot.save(filename, format.toLatin1().data(), quality)) {
32 qWarning() <<
"ScreenGrabber: failed to save snapshot!";
39 ScreenGrabber::ScreenGrabber(QObject *parent)
43 if (qEnvironmentVariableIsSet(
"UNITY_TESTING")) {
44 qDebug() <<
"Using test environment";
45 QStandardPaths::setTestModeEnabled(
true);
46 screenshotsDir = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
48 qDebug() <<
"Using real environment";
49 screenshotsDir = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
51 screenshotsDir.mkpath(
"Screenshots");
52 screenshotsDir.cd(
"Screenshots");
53 if (screenshotsDir.exists()) {
54 fileNamePrefix = screenshotsDir.absolutePath();
55 fileNamePrefix.append(
"/screenshot");
57 qWarning() <<
"ScreenGrabber: failed to create directory at: " << screenshotsDir.absolutePath();
61 void ScreenGrabber::captureAndSave()
63 if (fileNamePrefix.isEmpty())
65 qWarning() <<
"ScreenShotter: no directory to save screenshot";
69 const QWindowList windows = QGuiApplication::topLevelWindows();
72 qWarning() <<
"ScreenShotter: no top level windows found!";
76 QQuickWindow *main_window = qobject_cast<QQuickWindow *>(windows[0]);
79 qWarning() <<
"ScreenShotter: can only take screenshots of QQuickWindows";
83 const QImage screenshot = main_window->grabWindow();
84 const QString filename = makeFileName();
85 qDebug() <<
"Saving screenshot to" << filename;
86 auto saveOp = QtConcurrent::run(saveScreenshot, screenshot, filename, getFormat(), screenshotQuality);
87 if (saveOp.result()) {
88 Q_EMIT screenshotSaved(filename);
92 QString ScreenGrabber::makeFileName()
const
94 QString fileName(fileNamePrefix);
95 fileName.append(QDateTime::currentDateTime().toString(
"yyyyMMdd_hhmmsszzz"));
97 fileName.append(getFormat());
101 QString ScreenGrabber::getFormat()
const