screenshot.cpp 13.3 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 22
 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"
#include <kwinglutils.h>
23
#include <kwinxrenderutils.h>
24 25
#include <QtCore/QTemporaryFile>
#include <QtCore/QDir>
26
#include <QtDBus/QDBusConnection>
27
#include <QVarLengthArray>
28
#include <QtGui/QPainter>
29
#include <QMatrix4x4>
Martin Flöser's avatar
Martin Flöser committed
30
#include <xcb/xcb_image.h>
Martin Flöser's avatar
Martin Flöser committed
31 32 33 34 35

namespace KWin
{

bool ScreenShotEffect::supported()
36
{
37
    return  effects->compositingType() == XRenderCompositing ||
38
            (effects->isOpenGLCompositing() && GLRenderTarget::supported());
39
}
Martin Flöser's avatar
Martin Flöser committed
40 41

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

ScreenShotEffect::~ScreenShotEffect()
50
{
51 52
    QDBusConnection::sessionBus().unregisterObject(QStringLiteral("/Screenshot"));
    QDBusConnection::sessionBus().unregisterService(QStringLiteral("org.kde.kwin.Screenshot"));
53
}
Martin Flöser's avatar
Martin Flöser committed
54 55 56 57

#ifdef KWIN_HAVE_XRENDER_COMPOSITING
static QImage xPictureToImage(xcb_render_picture_t srcPic, const QRect &geometry, xcb_image_t **xImage)
{
58 59 60
    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
61
    XRenderPicture pic(xpix, 32);
62
    xcb_render_composite(c, XCB_RENDER_PICT_OP_SRC, srcPic, XCB_RENDER_PICTURE_NONE, pic,
Martin Flöser's avatar
Martin Flöser committed
63
                         geometry.x(), geometry.y(), 0, 0, 0, 0, geometry.width(), geometry.height());
64 65
    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
66 67
    QImage img((*xImage)->data, (*xImage)->width, (*xImage)->height, (*xImage)->stride, QImage::Format_ARGB32_Premultiplied);
    // TODO: byte order might need swapping
68
    xcb_free_pixmap(c, xpix);
Martin Flöser's avatar
Martin Flöser committed
69 70 71 72
    return img;
}
#endif

Martin Flöser's avatar
Martin Flöser committed
73
void ScreenShotEffect::postPaintScreen()
74
{
Martin Flöser's avatar
Martin Flöser committed
75
    effects->postPaintScreen();
76
    if (m_scheduledScreenshot) {
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
        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;
109
        bool validTarget = true;
110 111
        QScopedPointer<GLTexture> offscreenTexture;
        QScopedPointer<GLRenderTarget> target;
112
        if (effects->isOpenGLCompositing()) {
113
            offscreenTexture.reset(new GLTexture(width, height));
114 115
            offscreenTexture->setFilter(GL_LINEAR);
            offscreenTexture->setWrapMode(GL_CLAMP_TO_EDGE);
116
            target.reset(new GLRenderTarget(*offscreenTexture));
117
            validTarget = target->valid();
118
        }
119
        if (validTarget) {
120 121
            d.setXTranslation(-m_scheduledScreenshot->x() - left);
            d.setYTranslation(-m_scheduledScreenshot->y() - top);
122

Martin Flöser's avatar
Martin Flöser committed
123 124
            // render window into offscreen texture
            int mask = PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_TRANSLUCENT;
125
            QImage img;
126
            if (effects->isOpenGLCompositing()) {
127
                GLRenderTarget::pushRenderTarget(target.data());
128 129 130
                glClearColor(0.0, 0.0, 0.0, 0.0);
                glClear(GL_COLOR_BUFFER_BIT);
                glClearColor(0.0, 0.0, 0.0, 1.0);
131 132 133
                setMatrix(offscreenTexture->width(), offscreenTexture->height());
                effects->drawWindow(m_scheduledScreenshot, mask, infiniteRegion(), d);
                restoreMatrix();
134 135
                // copy content from framebuffer into image
                img = QImage(QSize(width, height), QImage::Format_ARGB32);
136
                glReadnPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, img.byteCount(), (GLvoid*)img.bits());
137 138 139
                GLRenderTarget::popRenderTarget();
                ScreenShotEffect::convertFromGLImage(img, width, height);
            }
140
#ifdef KWIN_HAVE_XRENDER_COMPOSITING
Martin Flöser's avatar
Martin Flöser committed
141
            xcb_image_t *xImage = NULL;
142 143 144
            if (effects->compositingType() == XRenderCompositing) {
                setXRenderOffscreen(true);
                effects->drawWindow(m_scheduledScreenshot, mask, QRegion(0, 0, width, height), d);
145
                if (xRenderOffscreenTarget()) {
Martin Flöser's avatar
Martin Flöser committed
146
                    img = xPictureToImage(xRenderOffscreenTarget(), QRect(0, 0, width, height), &xImage);
147
                }
148 149
                setXRenderOffscreen(false);
            }
150
#endif
151

152 153
            if (m_type & INCLUDE_CURSOR) {
                grabPointerImage(img, m_scheduledScreenshot->x() + left, m_scheduledScreenshot->y() + top);
Martin Flöser's avatar
Martin Flöser committed
154
            }
155

Martin Flöser's avatar
Martin Flöser committed
156
            const int depth = img.depth();
157 158
            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
159

160 161 162
            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(),
Martin Flöser's avatar
Martin Flöser committed
163
                        0, 0, 0, depth, img.byteCount(), img.constBits());
164 165
            xcb_free_gc(xcbConnection(), cid);
            xcb_flush(xcbConnection());
Martin Flöser's avatar
Martin Flöser committed
166 167 168 169
            emit screenshotCreated(xpix);
#ifdef KWIN_HAVE_XRENDER_COMPOSITING
            if (xImage) {
                xcb_image_destroy(xImage);
170
            }
Martin Flöser's avatar
Martin Flöser committed
171
#endif
172
        }
Martin Flöser's avatar
Martin Flöser committed
173 174
        m_scheduledScreenshot = NULL;
    }
175
}
Martin Flöser's avatar
Martin Flöser committed
176

177 178 179 180 181 182 183 184
static QMatrix4x4 s_origProjection;
static QMatrix4x4 s_origModelview;

void ScreenShotEffect::setMatrix(int width, int height)
{
    QMatrix4x4 projection;
    QMatrix4x4 identity;
    projection.ortho(QRect(0, 0, width, height));
185 186 187 188 189 190
    ShaderBinder binder(ShaderManager::GenericShader);
    GLShader *shader = binder.shader();
    s_origProjection = shader->getUniformMatrix4x4("projection");
    s_origModelview = shader->getUniformMatrix4x4("modelview");
    shader->setUniform(GLShader::ProjectionMatrix, projection);
    shader->setUniform(GLShader::ModelViewMatrix, identity);
191 192 193 194
}

void ScreenShotEffect::restoreMatrix()
{
195 196 197 198
    ShaderBinder binder(ShaderManager::GenericShader);
    GLShader *shader = binder.shader();
    shader->setUniform(GLShader::ProjectionMatrix, s_origProjection);
    shader->setUniform(GLShader::ModelViewMatrix, s_origModelview);
199 200
}

201
void ScreenShotEffect::screenshotWindowUnderCursor(int mask)
202
{
203 204
    m_type = (ScreenShotType)mask;
    const QPoint cursor = effects->cursorPos();
205 206 207 208 209 210 211 212 213
    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;
214 215
    }
    if (m_scheduledScreenshot) {
216
        m_scheduledScreenshot->addRepaintFull();
Martin Flöser's avatar
Martin Flöser committed
217
    }
218
}
219

220 221 222 223 224 225 226 227 228 229
void ScreenShotEffect::screenshotForWindow(qulonglong winid, int mask)
{
    m_type = (ScreenShotType) mask;
    EffectWindow* w = effects->findWindow(winid);
    if(w && !w->isMinimized() && !w->isDeleted()) {
        m_scheduledScreenshot = w;
        m_scheduledScreenshot->addRepaintFull();
    }
}

230 231
QString ScreenShotEffect::screenshotFullscreen()
{
232
    return blitScreenshot(effects->virtualScreenGeometry());
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
}

QString ScreenShotEffect::screenshotScreen(int screen)
{
    return blitScreenshot(effects->clientArea(FullScreenArea, screen, 0));
}

QString ScreenShotEffect::screenshotArea(int x, int y, int width, int height)
{
    return blitScreenshot(QRect(x, y, width, height));
}

QString ScreenShotEffect::blitScreenshot(const QRect &geometry)
{
#ifdef KWIN_HAVE_OPENGLES
    Q_UNUSED(geometry)
249
    qCDebug(KWINEFFECTS) << "Framebuffer Blit not supported";
250 251
    return QString();
#else
252
    QImage img;
253
    if (effects->isOpenGLCompositing())
254 255
    {
        if (!GLRenderTarget::blitSupported()) {
256
            qCDebug(KWINEFFECTS) << "Framebuffer Blit not supported";
257 258 259 260 261 262 263 264 265 266 267 268 269
            return QString();
        }
        GLTexture tex(geometry.width(), geometry.height());
        GLRenderTarget target(tex);
        target.blitFromFramebuffer(geometry);
        // copy content from framebuffer into image
        tex.bind();
        img = QImage(geometry.size(), QImage::Format_ARGB32);
        glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid*)img.bits());
        tex.unbind();
        ScreenShotEffect::convertFromGLImage(img, geometry.width(), geometry.height());
    }

Martin Flöser's avatar
Martin Flöser committed
270 271 272
#ifdef KWIN_HAVE_XRENDER_COMPOSITING
    xcb_image_t *xImage = NULL;
#endif
273
    if (effects->compositingType() == XRenderCompositing) {
274
#ifdef KWIN_HAVE_XRENDER_COMPOSITING
Martin Flöser's avatar
Martin Flöser committed
275
        img = xPictureToImage(effects->xrenderBufferPicture(), geometry, &xImage);
276
#endif
277 278
    }

279
    QTemporaryFile temp(QDir::tempPath() + QDir::separator() + QLatin1String("kwin_screenshot_XXXXXX.png"));
280 281 282 283 284
    temp.setAutoRemove(false);
    if (!temp.open()) {
        return QString();
    }
    img.save(&temp);
Martin Flöser's avatar
Martin Flöser committed
285 286 287 288 289
#ifdef KWIN_HAVE_XRENDER_COMPOSITING
    if (xImage) {
        xcb_image_destroy(xImage);
    }
#endif
290 291 292 293
    temp.close();
    return temp.fileName();
#endif
}
Martin Flöser's avatar
Martin Flöser committed
294

295
void ScreenShotEffect::grabPointerImage(QImage& snapshot, int offsetx, int offsety)
296 297
// Uses the X11_EXTENSIONS_XFIXES_H extension to grab the pointer image, and overlays it onto the snapshot.
{
Martin Flöser's avatar
Martin Flöser committed
298
    QScopedPointer<xcb_xfixes_get_cursor_image_reply_t, QScopedPointerPodDeleter> cursor(
299 300
        xcb_xfixes_get_cursor_image_reply(xcbConnection(),
                                          xcb_xfixes_get_cursor_image_unchecked(xcbConnection()),
Martin Flöser's avatar
Martin Flöser committed
301 302
                                          NULL));
    if (cursor.isNull())
303
        return;
304

Martin Flöser's avatar
Martin Flöser committed
305
    QImage qcursorimg((uchar *) xcb_xfixes_get_cursor_image_cursor_image(cursor.data()), cursor->width, cursor->height,
306
                      QImage::Format_ARGB32_Premultiplied);
307 308

    QPainter painter(&snapshot);
Martin Flöser's avatar
Martin Flöser committed
309
    painter.drawImage(QPointF(cursor->x - cursor->xhot - offsetx, cursor->y - cursor ->yhot - offsety), qcursorimg);
310 311
}

Martin Flöser's avatar
Martin Flöser committed
312 313 314 315 316 317 318 319
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();
320
        uint *end = p + w * h;
Martin Flöser's avatar
Martin Flöser committed
321 322 323 324 325 326 327 328 329
        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);
330
            for (int x = 0; x < w; ++x) {
Martin Flöser's avatar
Martin Flöser committed
331 332
                const uint pixel = *q;
                *q = ((pixel << 16) & 0xff0000) | ((pixel >> 16) & 0xff)
333
                     | (pixel & 0xff00ff00);
Martin Flöser's avatar
Martin Flöser committed
334 335 336 337 338 339 340 341 342

                q++;
            }
        }

    }
    img = img.mirrored();
}

343 344
bool ScreenShotEffect::isActive() const
{
345
    return m_scheduledScreenshot != NULL && !effects->isScreenLocked();
346 347
}

348 349 350 351 352 353 354 355
void ScreenShotEffect::windowClosed( EffectWindow* w )
{
    if (w == m_scheduledScreenshot) {
        m_scheduledScreenshot = NULL;
        screenshotWindowUnderCursor(m_type);
    }
}

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