@@ -0,0 +1,94 @@
1+/*
2+ * Copyright (C) 2014 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+ */
18+
19+#include "screengrabber.h"
20+
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>
28+
29+#include <QDebug>
30+
31+void saveScreenshot(QImage screenshot, QString filename, QString format, int quality)
32+{
33+ if (!screenshot.save(filename, format.toLatin1().data(), quality))
34+ qWarning() << "ScreenShotter: failed to save snapshot!";
35+}
36+
37+ScreenGrabber::ScreenGrabber(QObject *parent)
38+ : QObject(parent),
39+ screenshotQuality(0)
40+{
41+ QDir screenshotsDir(QStandardPaths::displayName(QStandardPaths::PicturesLocation));
42+ screenshotsDir.mkdir("Screenshots");
43+ screenshotsDir.cd("Screenshots");
44+ if (screenshotsDir.exists())
45+ {
46+ fileNamePrefix = screenshotsDir.absolutePath();
47+ fileNamePrefix.append("/screenshot");
48+ }
49+ else
50+ {
51+ qWarning() << "ScreenShotter: failed to create directory at: " << screenshotsDir.absolutePath();
52+ }
53+}
54+
55+void ScreenGrabber::captureAndSave()
56+{
57+ if (fileNamePrefix.isEmpty())
58+ {
59+ qWarning() << "ScreenShotter: no directory to save screenshot";
60+ return;
61+ }
62+
63+ const QWindowList windows = QGuiApplication::topLevelWindows();
64+ if (windows.empty())
65+ {
66+ qWarning() << "ScreenShotter: no top level windows found!";
67+ return;
68+ }
69+
70+ QQuickWindow *main_window = qobject_cast<QQuickWindow *>(windows[0]);
71+ if (!main_window)
72+ {
73+ qWarning() << "ScreenShotter: can only take screenshots of QQuickWindows";
74+ return;
75+ }
76+
77+ QImage screenshot = main_window->grabWindow();
78+ QtConcurrent::run(saveScreenshot, screenshot, makeFileName(), getFormat(), screenshotQuality);
79+}
80+
81+QString ScreenGrabber::makeFileName()
82+{
83+ QString fileName(fileNamePrefix);
84+ fileName.append(QDateTime::currentDateTime().toString("yyyymmdd_hhmmsszzz"));
85+ fileName.append(".");
86+ fileName.append(getFormat());
87+ return fileName;
88+}
89+
90+QString ScreenGrabber::getFormat()
91+{
92+ //TODO: This should be configurable (perhaps through gsettings?)
93+ return "png";
94+}