screenshot.cpp 14.1 KB
Newer Older
Martin Flöser's avatar
Martin Flöser committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/********************************************************************
 KWin - the KDE window manager
 This file is part of the KDE project.

 Copyright (C) 2010 Martin Gräßlin <kde@martin-graesslin.com>
 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
#include <KDE/KDebug>
25
#include <KDE/KTemporaryFile>
26 27 28 29 30 31
#include <QtDBus/QDBusConnection>
#include <QtCore/QVarLengthArray>
#include <QtGui/QPainter>

#include <X11/extensions/Xfixes.h>
#include <QX11Info>
Martin Flöser's avatar
Martin Flöser committed
32 33 34 35

namespace KWin
{

36 37
KWIN_EFFECT(screenshot, ScreenShotEffect)
KWIN_EFFECT_SUPPORTED(screenshot, ScreenShotEffect::supported())
Martin Flöser's avatar
Martin Flöser committed
38 39

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 47
    : m_scheduledScreenshot(0)
{
48
    connect ( effects, SIGNAL(windowClosed(KWin::EffectWindow*)), SLOT(windowClosed(KWin::EffectWindow*)) );
49 50 51
    QDBusConnection::sessionBus().registerObject("/Screenshot", this, QDBusConnection::ExportScriptableContents);
    QDBusConnection::sessionBus().registerService("org.kde.kwin.Screenshot");
}
Martin Flöser's avatar
Martin Flöser committed
52 53

ScreenShotEffect::~ScreenShotEffect()
54 55 56 57
{
    QDBusConnection::sessionBus().unregisterObject("/Screenshot");
    QDBusConnection::sessionBus().unregisterService("org.kde.kwin.Screenshot");
}
Martin Flöser's avatar
Martin Flöser committed
58
void ScreenShotEffect::postPaintScreen()
59
{
Martin Flöser's avatar
Martin Flöser committed
60
    effects->postPaintScreen();
61
    if (m_scheduledScreenshot) {
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
        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;
94
        bool validTarget = true;
95 96
        QScopedPointer<GLTexture> offscreenTexture;
        QScopedPointer<GLRenderTarget> target;
97
        if (effects->isOpenGLCompositing()) {
98 99
            int w = width;
            int h = height;
100 101 102 103
            if (!GLTexture::NPOTTextureSupported()) {
                w = nearestPowerOfTwo(w);
                h = nearestPowerOfTwo(h);
            }
104
            offscreenTexture.reset(new GLTexture(w, h));
105 106
            offscreenTexture->setFilter(GL_LINEAR);
            offscreenTexture->setWrapMode(GL_CLAMP_TO_EDGE);
107
            target.reset(new GLRenderTarget(*offscreenTexture));
108
            validTarget = target->valid();
109
        }
110
        if (validTarget) {
111 112
            d.setXTranslation(-m_scheduledScreenshot->x() - left);
            d.setYTranslation(-m_scheduledScreenshot->y() - top);
113

Martin Flöser's avatar
Martin Flöser committed
114 115
            // render window into offscreen texture
            int mask = PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_TRANSLUCENT;
116
            QImage img;
117
            if (effects->isOpenGLCompositing()) {
118
                GLRenderTarget::pushRenderTarget(target.data());
119 120 121
                glClearColor(0.0, 0.0, 0.0, 0.0);
                glClear(GL_COLOR_BUFFER_BIT);
                glClearColor(0.0, 0.0, 0.0, 1.0);
122 123 124
                setMatrix(offscreenTexture->width(), offscreenTexture->height());
                effects->drawWindow(m_scheduledScreenshot, mask, infiniteRegion(), d);
                restoreMatrix();
125 126
                // copy content from framebuffer into image
                img = QImage(QSize(width, height), QImage::Format_ARGB32);
127
                glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid*)img.bits());
128 129 130
                GLRenderTarget::popRenderTarget();
                ScreenShotEffect::convertFromGLImage(img, width, height);
            }
131
#ifdef KWIN_HAVE_XRENDER_COMPOSITING
132 133 134
            if (effects->compositingType() == XRenderCompositing) {
                setXRenderOffscreen(true);
                effects->drawWindow(m_scheduledScreenshot, mask, QRegion(0, 0, width, height), d);
135 136 137 138 139 140 141 142 143 144
                if (xRenderOffscreenTarget()) {
                    xcb_pixmap_t xpix = xcb_generate_id(connection());
                    xcb_create_pixmap(connection(), 32, xpix, rootWindow(), width, height);
                    // TODO: Qt5 - convert from xpixmap to QImage without a QPixmap
                    QPixmap pixmap = QPixmap::fromX11Pixmap(xpix);
                    xcb_render_composite(connection(), XCB_RENDER_PICT_OP_SRC, xRenderOffscreenTarget(),
                                         XCB_RENDER_PICTURE_NONE, pixmap.x11PictureHandle(), 0, 0, 0, 0, 0, 0, width, height);
                    img = pixmap.toImage().copy(0, 0, width, height);
                    xcb_free_pixmap(connection(), xpix);
                }
145 146
                setXRenderOffscreen(false);
            }
147
#endif
148

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

153
            m_lastScreenshot = QPixmap::fromImage(img);
154 155
            if (m_lastScreenshot.handle() == 0) {
                Pixmap xpix = XCreatePixmap(display(), rootWindow(), m_lastScreenshot.width(),
156
                                            m_lastScreenshot.height(), 32);
157 158
                m_lastScreenshot = QPixmap::fromX11Pixmap(xpix, QPixmap::ExplicitlyShared);
                QPainter p(&m_lastScreenshot);
159
                p.setCompositionMode(QPainter::CompositionMode_Source);
160
                p.drawImage(QPoint(0, 0), img);
161 162
                p.end();
                XSync(display(), False);
163
            }
164 165
            emit screenshotCreated(m_lastScreenshot.handle());
        }
Martin Flöser's avatar
Martin Flöser committed
166 167
        m_scheduledScreenshot = NULL;
    }
168
}
Martin Flöser's avatar
Martin Flöser committed
169

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
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));
    if (effects->compositingType() == OpenGL2Compositing) {
        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);
    } else if (effects->compositingType() == OpenGL1Compositing) {
#ifdef KWIN_HAVE_OPENGL_1
        glMatrixMode(GL_PROJECTION);
        glPushMatrix();
        loadMatrix(projection);
        glMatrixMode(GL_MODELVIEW);
        glPushMatrix();
        glLoadIdentity();
#endif
    }
}

void ScreenShotEffect::restoreMatrix()
{
    if (effects->compositingType() == OpenGL2Compositing) {
        ShaderBinder binder(ShaderManager::GenericShader);
        GLShader *shader = binder.shader();
        shader->setUniform(GLShader::ProjectionMatrix, s_origProjection);
        shader->setUniform(GLShader::ModelViewMatrix, s_origModelview);
    } else if (effects->compositingType() == OpenGL1Compositing) {
#ifdef KWIN_HAVE_OPENGL_1
        glMatrixMode(GL_PROJECTION);
        glPopMatrix();
        glMatrixMode(GL_MODELVIEW);
        glPopMatrix();
#endif
    }
}

214
void ScreenShotEffect::screenshotWindowUnderCursor(int mask)
215
{
216 217
    m_type = (ScreenShotType)mask;
    const QPoint cursor = effects->cursorPos();
218 219 220 221 222 223 224 225 226
    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;
227 228
    }
    if (m_scheduledScreenshot) {
229
        m_scheduledScreenshot->addRepaintFull();
Martin Flöser's avatar
Martin Flöser committed
230
    }
231
}
232

233 234 235 236 237 238 239 240 241 242
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();
    }
}

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
QString ScreenShotEffect::screenshotFullscreen()
{
    return blitScreenshot(QRect(0, 0, displayWidth(), displayHeight()));
}

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)
262
    kDebug(1212) << "Framebuffer Blit not supported";
263 264
    return QString();
#else
265
    QImage img;
266
    if (effects->isOpenGLCompositing())
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
    {
        if (!GLRenderTarget::blitSupported()) {
            kDebug(1212) << "Framebuffer Blit not supported";
            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());
    }

    if (effects->compositingType() == XRenderCompositing) {
284
#ifdef KWIN_HAVE_XRENDER_COMPOSITING
285 286 287 288 289 290 291 292
        QPixmap buffer(geometry.size());
        if (buffer.handle() == 0) {
            Pixmap xpix = XCreatePixmap(display(), rootWindow(), geometry.width(), geometry.height(), 32);
            buffer = QPixmap::fromX11Pixmap(xpix, QPixmap::ExplicitlyShared);
        }
        XRenderComposite(display(), PictOpSrc, effects->xrenderBufferPicture(), None, buffer.x11PictureHandle(),
                                    0, 0, 0, 0, geometry.x(), geometry.y(), geometry.width(), geometry.height());
        img = buffer.toImage();
293
#endif
294 295
    }

296 297 298 299 300 301 302 303 304 305 306
    KTemporaryFile temp;
    temp.setSuffix(".png");
    temp.setAutoRemove(false);
    if (!temp.open()) {
        return QString();
    }
    img.save(&temp);
    temp.close();
    return temp.fileName();
#endif
}
Martin Flöser's avatar
Martin Flöser committed
307

308
void ScreenShotEffect::grabPointerImage(QImage& snapshot, int offsetx, int offsety)
309 310
// Uses the X11_EXTENSIONS_XFIXES_H extension to grab the pointer image, and overlays it onto the snapshot.
{
311 312 313
    XFixesCursorImage *xcursorimg = XFixesGetCursorImage(QX11Info::display());
    if (!xcursorimg)
        return;
314 315 316 317

    //Annoyingly, xfixes specifies the data to be 32bit, but places it in an unsigned long *
    //which can be 64 bit.  So we need to iterate over a 64bit structure to put it in a 32bit
    //structure.
318
    QVarLengthArray< quint32 > pixels(xcursorimg->width * xcursorimg->height);
319 320 321 322
    for (int i = 0; i < xcursorimg->width * xcursorimg->height; ++i)
        pixels[i] = xcursorimg->pixels[i] & 0xffffffff;

    QImage qcursorimg((uchar *) pixels.data(), xcursorimg->width, xcursorimg->height,
323
                      QImage::Format_ARGB32_Premultiplied);
324 325 326 327 328 329 330

    QPainter painter(&snapshot);
    painter.drawImage(QPointF(xcursorimg->x - xcursorimg->xhot - offsetx, xcursorimg->y - xcursorimg ->yhot - offsety), qcursorimg);

    XFree(xcursorimg);
}

Martin Flöser's avatar
Martin Flöser committed
331 332 333 334 335 336 337 338
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();
339
        uint *end = p + w * h;
Martin Flöser's avatar
Martin Flöser committed
340 341 342 343 344 345 346 347 348
        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);
349
            for (int x = 0; x < w; ++x) {
Martin Flöser's avatar
Martin Flöser committed
350 351
                const uint pixel = *q;
                *q = ((pixel << 16) & 0xff0000) | ((pixel >> 16) & 0xff)
352
                     | (pixel & 0xff00ff00);
Martin Flöser's avatar
Martin Flöser committed
353 354 355 356 357 358 359 360 361

                q++;
            }
        }

    }
    img = img.mirrored();
}

362 363
bool ScreenShotEffect::isActive() const
{
364
    return m_scheduledScreenshot != NULL && !effects->isScreenLocked();
365 366
}

367 368 369 370 371 372 373 374
void ScreenShotEffect::windowClosed( EffectWindow* w )
{
    if (w == m_scheduledScreenshot) {
        m_scheduledScreenshot = NULL;
        screenshotWindowUnderCursor(m_type);
    }
}

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