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")) {
50 tDir.setAutoRemove(
false);
51 screenshotsDir = tDir.path();
53 screenshotsDir = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
55 screenshotsDir.mkpath(QStringLiteral(
"Screenshots"));
56 screenshotsDir.cd(QStringLiteral(
"Screenshots"));
57 if (screenshotsDir.exists()) {
58 fileNamePrefix = screenshotsDir.absolutePath();
59 fileNamePrefix.append(
"/screenshot");
61 qWarning() <<
"ScreenGrabber: failed to create directory at: " << screenshotsDir.absolutePath();
65 void ScreenGrabber::captureAndSave(
int angle)
67 if (fileNamePrefix.isEmpty())
69 qWarning() <<
"ScreenShotter: no directory to save screenshot";
73 const QWindowList windows = QGuiApplication::topLevelWindows();
76 qWarning() <<
"ScreenShotter: no top level windows found!";
80 QQuickWindow *main_window = qobject_cast<QQuickWindow *>(windows[0]);
83 qWarning() <<
"ScreenShotter: can only take screenshots of QQuickWindows";
87 const QImage screenshot = main_window->grabWindow().transformed(QTransform().rotate(angle));
88 const QString filename = makeFileName();
89 qDebug() <<
"Saving screenshot to" << filename;
90 QFuture<QString> saveFuture(QtConcurrent::run(saveScreenshot, screenshot, filename, getFormat(), screenshotQuality));
91 m_watcher.setFuture(saveFuture);
94 void ScreenGrabber::onScreenshotSaved()
96 const QString filename = m_watcher.future().result();
97 if (!filename.isEmpty()) {
98 Q_EMIT screenshotSaved(filename);
102 QString ScreenGrabber::makeFileName()
const 104 QString fileName(fileNamePrefix);
105 fileName.append(QDateTime::currentDateTime().toString(QStringLiteral(
"yyyyMMdd_hhmmsszzz")));
106 fileName.append(
".");
107 fileName.append(getFormat());
111 QString ScreenGrabber::getFormat()
const 114 return QStringLiteral(
"png");