on 86a756f help sign in
unity8/plugins/ScreenGrabber/screengrabber.cpp
93 lines 2.8 kB history raw
1/*
2 * Copyright (C) 2014-2015 Canonical, Ltd.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; version 3.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 * Authors: Alberto Aguirre <alberto.aguirre@canonical.com>
17 */
19#include "screengrabber.h"
21#include <QDir>
22#include <QDateTime>
23#include <QStandardPaths>
24#include <QtGui/QImage>
25#include <QtGui/QGuiApplication>
26#include <QtQuick/QQuickWindow>
27#include <QtConcurrent/QtConcurrentRun>
29#include <QDebug>
31void saveScreenshot(QImage screenshot, const QString &filename, const QString &format, int quality)
33 if (!screenshot.save(filename, format.toLatin1().data(), quality))
34 qWarning() << "ScreenShotter: failed to save snapshot!";
37ScreenGrabber::ScreenGrabber(QObject *parent)
38 : QObject(parent)
40 QDir screenshotsDir(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
41 screenshotsDir.mkpath("Screenshots");
42 screenshotsDir.cd("Screenshots");
43 if (screenshotsDir.exists())
44 {
45 fileNamePrefix = screenshotsDir.absolutePath();
46 fileNamePrefix.append("/screenshot");
47 }
48 else
49 {
50 qWarning() << "ScreenShotter: failed to create directory at: " << screenshotsDir.absolutePath();
51 }
54void ScreenGrabber::captureAndSave()
56 if (fileNamePrefix.isEmpty())
57 {
58 qWarning() << "ScreenShotter: no directory to save screenshot";
59 return;
60 }
62 const QWindowList windows = QGuiApplication::topLevelWindows();
63 if (windows.empty())
64 {
65 qWarning() << "ScreenShotter: no top level windows found!";
66 return;
67 }
69 QQuickWindow *main_window = qobject_cast<QQuickWindow *>(windows[0]);
70 if (!main_window)
71 {
72 qWarning() << "ScreenShotter: can only take screenshots of QQuickWindows";
73 return;
74 }
76 QImage screenshot = main_window->grabWindow();
77 QtConcurrent::run(saveScreenshot, screenshot, makeFileName(), getFormat(), screenshotQuality);
80QString ScreenGrabber::makeFileName() const
82 QString fileName(fileNamePrefix);
83 fileName.append(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmsszzz"));
84 fileName.append(".");
85 fileName.append(getFormat());
86 return fileName;
89QString ScreenGrabber::getFormat() const
91 //TODO: This should be configurable (perhaps through gsettings?)
92 return "png";