screenshot.cpp 17.5 KB
Newer Older
Martin Flöser's avatar
Martin Flöser committed
1 2 3 4
/********************************************************************
 KWin - the KDE window manager
 This file is part of the KDE project.

5
 Copyright (C) 2010 Martin Gräßlin <mgraesslin@kde.org>
Martin Flöser's avatar
Martin Flöser committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*********************************************************************/
#include "screenshot.h"
22
#include <kwinglplatform.h>
Martin Flöser's avatar
Martin Flöser committed
23
#include <kwinglutils.h>
24
#include <kwinxrenderutils.h>
25 26
#include <QtCore/QTemporaryFile>
#include <QtCore/QDir>
27
#include <QtDBus/QDBusConnection>
28
#include <QVarLengthArray>
29
#include <QtGui/QPainter>
30
#include <QMatrix4x4>
Martin Flöser's avatar
Martin Flöser committed
31
#include <xcb/xcb_image.h>
Martin Flöser's avatar
Martin Flöser committed
32

33 34 35
#include <KLocalizedString>
#include <KNotification>

Martin Flöser's avatar
Martin Flöser committed
36 37 38 39
namespace KWin
{

bool ScreenShotEffect::supported()
40
{
41
    return  effects->compositingType() == XRenderCompositing ||
42
            (effects->isOpenGLCompositing() && GLRenderTarget::supported());
43
}
Martin Flöser's avatar
Martin Flöser committed
44 45

ScreenShotEffect::ScreenShotEffect()
46
    : m_scheduledScreenshot(0)
47
    , m_replyConnection(QDBusConnection::sessionBus())
48
{
49
    connect ( effects, SIGNAL(windowClosed(KWin::EffectWindow*)), SLOT(windowClosed(KWin::EffectWindow*)) );
50 51
    QDBusConnection::sessionBus().registerObject(QStringLiteral("/Screenshot"), this, QDBusConnection::ExportScriptableContents);
    QDBusConnection::sessionBus().registerService(QStringLiteral("org.kde.kwin.Screenshot"));
52
}
Martin Flöser's avatar
Martin Flöser committed
53 54

ScreenShotEffect::~ScreenShotEffect()
55
{
56 57
    QDBusConnection::sessionBus().unregisterObject(QStringLiteral("/Screenshot"));
    QDBusConnection::sessionBus().unregisterService(QStringLiteral("org.kde.kwin.Screenshot"));
58
}
Martin Flöser's avatar
Martin Flöser committed
59 60 61 62

#ifdef KWIN_HAVE_XRENDER_COMPOSITING
static QImage xPictureToImage(xcb_render_picture_t srcPic, const QRect &geometry, xcb_image_t **xImage)
{
63 64 65
    xcb_connection_t *c = effects->xcbConnection();
    xcb_pixmap_t xpix = xcb_generate_id(c);
    xcb_create_pixmap(c, 32, xpix, effects->x11RootWindow(), geometry.width(), geometry.height());
Martin Flöser's avatar
Martin Flöser committed
66
    XRenderPicture pic(xpix, 32);
67
    xcb_render_composite(c, XCB_RENDER_PICT_OP_SRC, srcPic, XCB_RENDER_PICTURE_NONE, pic,
Martin Flöser's avatar
Martin Flöser committed
68
                         geometry.x(), geometry.y(), 0, 0, 0, 0, geometry.width(), geometry.height());
69 70
    xcb_flush(c);
    *xImage = xcb_image_get(c, xpix, 0, 0, geometry.width(), geometry.height(), ~0, XCB_IMAGE_FORMAT_Z_PIXMAP);
Martin Flöser's avatar
Martin Flöser committed
71 72
    QImage img((*xImage)->data, (*xImage)->width, (*xImage)->height, (*xImage)->stride, QImage::Format_ARGB32_Premultiplied);
    // TODO: byte order might need swapping
73
    xcb_free_pixmap(c, xpix);
74
    return img.copy();
Martin Flöser's avatar
Martin Flöser committed
75 76 77
}
#endif

78 79 80 81 82 83
void ScreenShotEffect::paintScreen(int mask, QRegion region, ScreenPaintData &data)
{
    m_cachedOutputGeometry = data.outputGeometry();
    effects->paintScreen(mask, region, data);
}

Martin Flöser's avatar
Martin Flöser committed
84
void ScreenShotEffect::postPaintScreen()
85
{
Martin Flöser's avatar
Martin Flöser committed
86
    effects->postPaintScreen();
87
    if (m_scheduledScreenshot) {
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
        WindowPaintData d(m_scheduledScreenshot);
        double left = 0;
        double top = 0;
        double right = m_scheduledScreenshot->width();
        double bottom = m_scheduledScreenshot->height();
        if (m_scheduledScreenshot->hasDecoration() && m_type & INCLUDE_DECORATION) {
            foreach (const WindowQuad & quad, d.quads) {
                // we need this loop to include the decoration padding
                left   = qMin(left, quad.left());
                top    = qMin(top, quad.top());
                right  = qMax(right, quad.right());
                bottom = qMax(bottom, quad.bottom());
            }
        } else if (m_scheduledScreenshot->hasDecoration()) {
            WindowQuadList newQuads;
            left = m_scheduledScreenshot->width();
            top = m_scheduledScreenshot->height();
            right = 0;
            bottom = 0;
            foreach (const WindowQuad & quad, d.quads) {
                if (quad.type() == WindowQuadContents) {
                    newQuads << quad;
                    left   = qMin(left, quad.left());
                    top    = qMin(top, quad.top());
                    right  = qMax(right, quad.right());
                    bottom = qMax(bottom, quad.bottom());
                }
            }
            d.quads = newQuads;
        }
        const int width = right - left;
        const int height = bottom - top;
120
        bool validTarget = true;
121 122
        QScopedPointer<GLTexture> offscreenTexture;
        QScopedPointer<GLRenderTarget> target;
123
        if (effects->isOpenGLCompositing()) {
124
            offscreenTexture.reset(new GLTexture(GL_RGBA8, width, height));
125 126
            offscreenTexture->setFilter(GL_LINEAR);
            offscreenTexture->setWrapMode(GL_CLAMP_TO_EDGE);
127
            target.reset(new GLRenderTarget(*offscreenTexture));
128
            validTarget = target->valid();
129
        }
130
        if (validTarget) {
131 132
            d.setXTranslation(-m_scheduledScreenshot->x() - left);
            d.setYTranslation(-m_scheduledScreenshot->y() - top);
133

Martin Flöser's avatar
Martin Flöser committed
134 135
            // render window into offscreen texture
            int mask = PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_TRANSLUCENT;
136
            QImage img;
137
            if (effects->isOpenGLCompositing()) {
138
                GLRenderTarget::pushRenderTarget(target.data());
139 140 141
                glClearColor(0.0, 0.0, 0.0, 0.0);
                glClear(GL_COLOR_BUFFER_BIT);
                glClearColor(0.0, 0.0, 0.0, 1.0);
142 143 144 145 146

                QMatrix4x4 projection;
                projection.ortho(QRect(0, 0, offscreenTexture->width(), offscreenTexture->height()));
                d.setProjectionMatrix(projection);

147
                effects->drawWindow(m_scheduledScreenshot, mask, infiniteRegion(), d);
148

149 150
                // copy content from framebuffer into image
                img = QImage(QSize(width, height), QImage::Format_ARGB32);
151
                glReadnPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, img.byteCount(), (GLvoid*)img.bits());
152 153 154
                GLRenderTarget::popRenderTarget();
                ScreenShotEffect::convertFromGLImage(img, width, height);
            }
155
#ifdef KWIN_HAVE_XRENDER_COMPOSITING
Martin Flöser's avatar
Martin Flöser committed
156
            xcb_image_t *xImage = NULL;
157 158 159
            if (effects->compositingType() == XRenderCompositing) {
                setXRenderOffscreen(true);
                effects->drawWindow(m_scheduledScreenshot, mask, QRegion(0, 0, width, height), d);
160
                if (xRenderOffscreenTarget()) {
Martin Flöser's avatar
Martin Flöser committed
161
                    img = xPictureToImage(xRenderOffscreenTarget(), QRect(0, 0, width, height), &xImage);
162
                }
163 164
                setXRenderOffscreen(false);
            }
165
#endif
166

167 168
            if (m_type & INCLUDE_CURSOR) {
                grabPointerImage(img, m_scheduledScreenshot->x() + left, m_scheduledScreenshot->y() + top);
Martin Flöser's avatar
Martin Flöser committed
169
            }
170

171 172 173 174
            if (m_windowMode == WindowMode::Xpixmap) {
                const int depth = img.depth();
                xcb_pixmap_t xpix = xcb_generate_id(xcbConnection());
                xcb_create_pixmap(xcbConnection(), depth, xpix, x11RootWindow(), img.width(), img.height());
Martin Flöser's avatar
Martin Flöser committed
175

176 177 178 179 180 181 182 183 184 185 186
                xcb_gcontext_t cid = xcb_generate_id(xcbConnection());
                xcb_create_gc(xcbConnection(), cid, xpix, 0, NULL);
                xcb_put_image(xcbConnection(), XCB_IMAGE_FORMAT_Z_PIXMAP, xpix, cid, img.width(), img.height(),
                            0, 0, 0, depth, img.byteCount(), img.constBits());
                xcb_free_gc(xcbConnection(), cid);
                xcb_flush(xcbConnection());
                emit screenshotCreated(xpix);
                m_windowMode = WindowMode::NoCapture;
            } else if (m_windowMode == WindowMode::File) {
                sendReplyImage(img);
            }
Martin Flöser's avatar
Martin Flöser committed
187 188 189
#ifdef KWIN_HAVE_XRENDER_COMPOSITING
            if (xImage) {
                xcb_image_destroy(xImage);
190
            }
Martin Flöser's avatar
Martin Flöser committed
191
#endif
192
        }
Martin Flöser's avatar
Martin Flöser committed
193 194
        m_scheduledScreenshot = NULL;
    }
195 196

    if (!m_scheduledGeometry.isNull()) {
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
        if (!m_cachedOutputGeometry.isNull()) {
            // special handling for per-output geometry rendering
            const QRect intersection = m_scheduledGeometry.intersected(m_cachedOutputGeometry);
            if (intersection.isEmpty()) {
                // doesn't intersect, not going onto this screenshot
                return;
            }
            const QImage img = blitScreenshot(intersection);
            if (img.size() == m_scheduledGeometry.size()) {
                // we are done
                sendReplyImage(img);
                return;
            }
            if (m_multipleOutputsImage.isNull()) {
                m_multipleOutputsImage = QImage(m_scheduledGeometry.size(), QImage::Format_ARGB32);
                m_multipleOutputsImage.fill(Qt::transparent);
            }
            QPainter p;
            p.begin(&m_multipleOutputsImage);
            p.drawImage(intersection.topLeft() - m_scheduledGeometry.topLeft(), img);
            p.end();
            m_multipleOutputsRendered = m_multipleOutputsRendered.united(intersection);
            if (m_multipleOutputsRendered.boundingRect() == m_scheduledGeometry) {
                sendReplyImage(m_multipleOutputsImage);
            }

        } else {
            const QImage img = blitScreenshot(m_scheduledGeometry);
            sendReplyImage(img);
        }
227
    }
228
}
Martin Flöser's avatar
Martin Flöser committed
229

230 231 232 233 234 235
void ScreenShotEffect::sendReplyImage(const QImage &img)
{
    m_replyConnection.send(m_replyMessage.createReply(saveTempImage(img)));
    m_scheduledGeometry = QRect();
    m_multipleOutputsImage = QImage();
    m_multipleOutputsRendered = QRegion();
236
    m_captureCursor = false;
237
    m_windowMode = WindowMode::NoCapture;
238 239 240 241 242 243 244 245 246 247 248 249 250 251
}

QString ScreenShotEffect::saveTempImage(const QImage &img)
{
    if (img.isNull()) {
        return QString();
    }
    QTemporaryFile temp(QDir::tempPath() + QDir::separator() + QLatin1String("kwin_screenshot_XXXXXX.png"));
    temp.setAutoRemove(false);
    if (!temp.open()) {
        return QString();
    }
    img.save(&temp);
    temp.close();
252 253 254 255
    KNotification::event(KNotification::Notification,
                        i18nc("Notification caption that a screenshot got saved to file", "Screenshot"),
                        i18nc("Notification with path to screenshot file", "Screenshot saved to %1", temp.fileName()),
                        QStringLiteral("spectacle"));
256 257 258
    return temp.fileName();
}

259
void ScreenShotEffect::screenshotWindowUnderCursor(int mask)
260
{
261 262
    m_type = (ScreenShotType)mask;
    const QPoint cursor = effects->cursorPos();
263 264 265 266 267 268 269 270 271
    EffectWindowList order = effects->stackingOrder();
    EffectWindowList::const_iterator it = order.constEnd(), first = order.constBegin();
    while( it != first ) {
        m_scheduledScreenshot = *(--it);
        if (m_scheduledScreenshot->isOnCurrentDesktop() &&
            !m_scheduledScreenshot->isMinimized() && !m_scheduledScreenshot->isDeleted() &&
            m_scheduledScreenshot->geometry().contains(cursor))
            break;
        m_scheduledScreenshot = 0;
272 273
    }
    if (m_scheduledScreenshot) {
274
        m_scheduledScreenshot->addRepaintFull();
Martin Flöser's avatar
Martin Flöser committed
275
    }
276
}
277

278 279 280 281 282
void ScreenShotEffect::screenshotForWindow(qulonglong winid, int mask)
{
    m_type = (ScreenShotType) mask;
    EffectWindow* w = effects->findWindow(winid);
    if(w && !w->isMinimized() && !w->isDeleted()) {
283
        m_windowMode = WindowMode::Xpixmap;
284 285 286 287 288
        m_scheduledScreenshot = w;
        m_scheduledScreenshot->addRepaintFull();
    }
}

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
QString ScreenShotEffect::interactive(int mask)
{
    if (!calledFromDBus()) {
        return QString();
    }
    if (!m_scheduledGeometry.isNull() || m_windowMode != WindowMode::NoCapture) {
        sendErrorReply(QDBusError::Failed, "A screenshot is already been taken");
        return QString();
    }
    m_type = (ScreenShotType) mask;
    m_windowMode = WindowMode::File;
    m_replyConnection = connection();
    m_replyMessage = message();
    setDelayedReply(true);
    effects->startInteractiveWindowSelection(
        [this] (EffectWindow *w) {
            if (!w) {
                m_replyConnection.send(m_replyMessage.createErrorReply(QDBusError::Failed, "Screenshot got cancelled"));
                m_windowMode = WindowMode::NoCapture;
                return;
            } else {
                m_scheduledScreenshot = w;
                m_scheduledScreenshot->addRepaintFull();
            }
    });
    return QString();
}

317
QString ScreenShotEffect::screenshotFullscreen(bool captureCursor)
318
{
319 320 321 322 323 324 325 326 327 328 329
    if (!calledFromDBus()) {
        return QString();
    }
    if (!m_scheduledGeometry.isNull()) {
        sendErrorReply(QDBusError::Failed, "A screenshot is already been taken");
        return QString();
    }
    m_replyConnection = connection();
    m_replyMessage = message();
    setDelayedReply(true);
    m_scheduledGeometry = effects->virtualScreenGeometry();
330
    m_captureCursor = captureCursor;
331 332
    effects->addRepaintFull();
    return QString();
333 334
}

335
QString ScreenShotEffect::screenshotScreen(int screen, bool captureCursor)
336
{
337 338 339 340 341 342 343 344 345 346 347 348
    if (!calledFromDBus()) {
        return QString();
    }
    if (!m_scheduledGeometry.isNull()) {
        sendErrorReply(QDBusError::Failed, "A screenshot is already been taken");
        return QString();
    }
    m_scheduledGeometry = effects->clientArea(FullScreenArea, screen, 0);
    if (m_scheduledGeometry.isNull()) {
        sendErrorReply(QDBusError::Failed, "Invalid screen requested");
        return QString();
    }
349
    m_captureCursor = captureCursor;
350 351 352 353 354
    m_replyConnection = connection();
    m_replyMessage = message();
    setDelayedReply(true);
    effects->addRepaint(m_scheduledGeometry);
    return QString();
355 356
}

357
QString ScreenShotEffect::screenshotArea(int x, int y, int width, int height, bool captureCursor)
358
{
359 360 361 362 363 364 365 366 367 368 369 370 371
    if (!calledFromDBus()) {
        return QString();
    }
    if (!m_scheduledGeometry.isNull()) {
        sendErrorReply(QDBusError::Failed, "A screenshot is already been taken");
        return QString();
    }
    m_scheduledGeometry = QRect(x, y, width, height);
    if (m_scheduledGeometry.isNull() || m_scheduledGeometry.isEmpty()) {
        m_scheduledGeometry = QRect();
        sendErrorReply(QDBusError::Failed, "Invalid area requested");
        return QString();
    }
372
    m_captureCursor = captureCursor;
373 374 375 376 377
    m_replyConnection = connection();
    m_replyMessage = message();
    setDelayedReply(true);
    effects->addRepaint(m_scheduledGeometry);
    return QString();
378 379
}

380
QImage ScreenShotEffect::blitScreenshot(const QRect &geometry)
381
{
382
    QImage img;
383
    if (effects->isOpenGLCompositing())
384 385
    {
        if (!GLRenderTarget::blitSupported()) {
386
            qCDebug(KWINEFFECTS) << "Framebuffer Blit not supported";
387
            return img;
388
        }
389
        GLTexture tex(GL_RGBA8, geometry.width(), geometry.height());
390 391 392 393 394
        GLRenderTarget target(tex);
        target.blitFromFramebuffer(geometry);
        // copy content from framebuffer into image
        tex.bind();
        img = QImage(geometry.size(), QImage::Format_ARGB32);
395 396 397 398 399
        if (GLPlatform::instance()->isGLES()) {
            glReadPixels(0, 0, img.width(), img.height(), GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid*)img.bits());
        } else {
            glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid*)img.bits());
        }
400 401 402 403
        tex.unbind();
        ScreenShotEffect::convertFromGLImage(img, geometry.width(), geometry.height());
    }

Martin Flöser's avatar
Martin Flöser committed
404
#ifdef KWIN_HAVE_XRENDER_COMPOSITING
405
    if (effects->compositingType() == XRenderCompositing) {
406
    xcb_image_t *xImage = NULL;
Martin Flöser's avatar
Martin Flöser committed
407
        img = xPictureToImage(effects->xrenderBufferPicture(), geometry, &xImage);
408 409 410
        if (xImage) {
            xcb_image_destroy(xImage);
        }
Martin Flöser's avatar
Martin Flöser committed
411 412
    }
#endif
413

414 415 416 417
    if (m_captureCursor) {
        grabPointerImage(img, geometry.x(), geometry.y());
    }

418
    return img;
419
}
Martin Flöser's avatar
Martin Flöser committed
420

421
void ScreenShotEffect::grabPointerImage(QImage& snapshot, int offsetx, int offsety)
422
{
423 424
    const auto cursor = effects->cursorImage();
    if (cursor.image().isNull())
425
        return;
426 427

    QPainter painter(&snapshot);
428
    painter.drawImage(effects->cursorPos() - cursor.hotSpot() - QPoint(offsetx, offsety), cursor.image());
429 430
}

Martin Flöser's avatar
Martin Flöser committed
431 432 433 434 435 436 437 438
void ScreenShotEffect::convertFromGLImage(QImage &img, int w, int h)
{
    // from QtOpenGL/qgl.cpp
    // Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
    // see http://qt.gitorious.org/qt/qt/blobs/master/src/opengl/qgl.cpp
    if (QSysInfo::ByteOrder == QSysInfo::BigEndian) {
        // OpenGL gives RGBA; Qt wants ARGB
        uint *p = (uint*)img.bits();
439
        uint *end = p + w * h;
Martin Flöser's avatar
Martin Flöser committed
440 441 442 443 444 445 446 447 448
        while (p < end) {
            uint a = *p << 24;
            *p = (*p >> 8) | a;
            p++;
        }
    } else {
        // OpenGL gives ABGR (i.e. RGBA backwards); Qt wants ARGB
        for (int y = 0; y < h; y++) {
            uint *q = (uint*)img.scanLine(y);
449
            for (int x = 0; x < w; ++x) {
Martin Flöser's avatar
Martin Flöser committed
450 451
                const uint pixel = *q;
                *q = ((pixel << 16) & 0xff0000) | ((pixel >> 16) & 0xff)
452
                     | (pixel & 0xff00ff00);
Martin Flöser's avatar
Martin Flöser committed
453 454 455 456 457 458 459 460 461

                q++;
            }
        }

    }
    img = img.mirrored();
}

462 463
bool ScreenShotEffect::isActive() const
{
464
    return (m_scheduledScreenshot != NULL || !m_scheduledGeometry.isNull()) && !effects->isScreenLocked();
465 466
}

467 468 469 470 471 472 473 474
void ScreenShotEffect::windowClosed( EffectWindow* w )
{
    if (w == m_scheduledScreenshot) {
        m_scheduledScreenshot = NULL;
        screenshotWindowUnderCursor(m_type);
    }
}

Martin Flöser's avatar
Martin Flöser committed
475
} // namespace