17 #include "screengrabber.h"
21 #include <QStandardPaths>
22 #include <QTemporaryDir>
23 #include <QtGui/QImage>
24 #include <QtGui/QGuiApplication>
25 #include <QtQuick/QQuickWindow>
29 QString saveScreenshot(
const QImage &screenshot,
const QString &filename,
const QString &format,
int quality)
31 if (screenshot.save(filename, format.toLatin1().data(), quality)) {
34 qWarning() <<
"ScreenGrabber: failed to save snapshot!";
39 ScreenGrabber::ScreenGrabber(QObject *parent)
42 QObject::connect(&m_watcher,
43 &QFutureWatcher<QString>::finished,
45 &ScreenGrabber::onScreenshotSaved);
48 if (qEnvironmentVariableIsSet(
"UNITY_TESTING")) {
49 qDebug() <<
"Using test environment";
51 tDir.setAutoRemove(
false);
52 screenshotsDir = tDir.path();
54 qDebug() <<
"Using real environment";
55 screenshotsDir = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
57 screenshotsDir.mkpath(QStringLiteral(
"Screenshots"));
58 screenshotsDir.cd(QStringLiteral(
"Screenshots"));
59 if (screenshotsDir.exists()) {
60 fileNamePrefix = screenshotsDir.absolutePath();
61 fileNamePrefix.append(
"/screenshot");
63 qWarning() <<
"ScreenGrabber: failed to create directory at: " << screenshotsDir.absolutePath();
67 void ScreenGrabber::captureAndSave(
int angle)
69 if (fileNamePrefix.isEmpty())
71 qWarning() <<
"ScreenShotter: no directory to save screenshot";
75 const QWindowList windows = QGuiApplication::topLevelWindows();
78 qWarning() <<
"ScreenShotter: no top level windows found!";
82 QQuickWindow *main_window = qobject_cast<QQuickWindow *>(windows[0]);
85 qWarning() <<
"ScreenShotter: can only take screenshots of QQuickWindows";
89 const QImage screenshot = main_window->grabWindow().transformed(QTransform().rotate(angle));
90 const QString filename = makeFileName();
91 qDebug() <<
"Saving screenshot to" << filename;
92 QFuture<QString> saveFuture(QtConcurrent::run(saveScreenshot, screenshot, filename, getFormat(), screenshotQuality));
93 m_watcher.setFuture(saveFuture);
96 void ScreenGrabber::onScreenshotSaved()
98 const QString filename = m_watcher.future().result();
99 if (!filename.isEmpty()) {
100 Q_EMIT screenshotSaved(filename);
104 QString ScreenGrabber::makeFileName()
const
106 QString fileName(fileNamePrefix);
107 fileName.append(QDateTime::currentDateTime().toString(QStringLiteral(
"yyyyMMdd_hhmmsszzz")));
108 fileName.append(
".");
109 fileName.append(getFormat());
113 QString ScreenGrabber::getFormat()
const
116 return QStringLiteral(
"png");