diff --git a/effects/backgroundcontrast/contrast.cpp b/effects/backgroundcontrast/contrast.cpp index f920fcd88..5247d83b8 100644 --- a/effects/backgroundcontrast/contrast.cpp +++ b/effects/backgroundcontrast/contrast.cpp @@ -1,486 +1,485 @@ /* * Copyright © 2010 Fredrik Höglund * Copyright © 2011 Philipp Knechtges * Copyright 2014 Marco Martin * * 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; see the file COPYING. if not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "contrast.h" #include "contrastshader.h" // KConfigSkeleton #include #include #include #include #include namespace KWin { static const QByteArray s_contrastAtomName = QByteArrayLiteral("_KDE_NET_WM_BACKGROUND_CONTRAST_REGION"); ContrastEffect::ContrastEffect() { shader = ContrastShader::create(); reconfigure(ReconfigureAll); // ### Hackish way to announce support. // Should be included in _NET_SUPPORTED instead. if (shader && shader->isValid()) { net_wm_contrast_region = effects->announceSupportProperty(s_contrastAtomName, this); KWayland::Server::Display *display = effects->waylandDisplay(); if (display) { m_contrastManager = display->createContrastManager(this); m_contrastManager->create(); } } else { net_wm_contrast_region = 0; } connect(effects, SIGNAL(windowAdded(KWin::EffectWindow*)), this, SLOT(slotWindowAdded(KWin::EffectWindow*))); connect(effects, SIGNAL(windowDeleted(KWin::EffectWindow*)), this, SLOT(slotWindowDeleted(KWin::EffectWindow*))); connect(effects, SIGNAL(propertyNotify(KWin::EffectWindow*,long)), this, SLOT(slotPropertyNotify(KWin::EffectWindow*,long))); connect(effects, SIGNAL(screenGeometryChanged(QSize)), this, SLOT(slotScreenGeometryChanged())); connect(effects, &EffectsHandler::xcbConnectionChanged, this, [this] { if (shader && shader->isValid()) { net_wm_contrast_region = effects->announceSupportProperty(s_contrastAtomName, this); } } ); // Fetch the contrast regions for all windows for (EffectWindow *window: effects->stackingOrder()) { updateContrastRegion(window); } } ContrastEffect::~ContrastEffect() { delete shader; } void ContrastEffect::slotScreenGeometryChanged() { effects->makeOpenGLContextCurrent(); if (!supported()) { effects->reloadEffect(this); return; } for (EffectWindow *window: effects->stackingOrder()) { updateContrastRegion(window); } } void ContrastEffect::reconfigure(ReconfigureFlags flags) { Q_UNUSED(flags) if (shader) shader->init(); if (!shader || !shader->isValid()) { effects->removeSupportProperty(s_contrastAtomName, this); delete m_contrastManager; m_contrastManager = nullptr; } } void ContrastEffect::updateContrastRegion(EffectWindow *w) { QRegion region; float colorTransform[16]; QByteArray value; if (net_wm_contrast_region != XCB_ATOM_NONE) { value = w->readProperty(net_wm_contrast_region, net_wm_contrast_region, 32); if (value.size() > 0 && !((value.size() - (16 * sizeof(uint32_t))) % ((4 * sizeof(uint32_t))))) { const uint32_t *cardinals = reinterpret_cast(value.constData()); const float *floatCardinals = reinterpret_cast(value.constData()); unsigned int i = 0; for (; i < ((value.size() - (16 * sizeof(uint32_t)))) / sizeof(uint32_t);) { int x = cardinals[i++]; int y = cardinals[i++]; int w = cardinals[i++]; int h = cardinals[i++]; region += QRect(x, y, w, h); } for (unsigned int j = 0; j < 16; ++j) { colorTransform[j] = floatCardinals[i + j]; } QMatrix4x4 colorMatrix(colorTransform); m_colorMatrices[w] = colorMatrix; } } KWayland::Server::SurfaceInterface *surf = w->surface(); if (surf && surf->contrast()) { region = surf->contrast()->region(); m_colorMatrices[w] = colorMatrix(surf->contrast()->contrast(), surf->contrast()->intensity(), surf->contrast()->saturation()); } //!value.isNull() full window in X11 case, surf->contrast() //valid, full window in wayland case if (region.isEmpty() && (!value.isNull() || (surf && surf->contrast()))) { // Set the data to a dummy value. // This is needed to be able to distinguish between the value not // being set, and being set to an empty region. w->setData(WindowBackgroundContrastRole, 1); } else w->setData(WindowBackgroundContrastRole, region); } void ContrastEffect::slotWindowAdded(EffectWindow *w) { KWayland::Server::SurfaceInterface *surf = w->surface(); if (surf) { m_contrastChangedConnections[w] = connect(surf, &KWayland::Server::SurfaceInterface::contrastChanged, this, [this, w] () { if (w) { updateContrastRegion(w); } }); } updateContrastRegion(w); } void ContrastEffect::slotWindowDeleted(EffectWindow *w) { if (m_contrastChangedConnections.contains(w)) { disconnect(m_contrastChangedConnections[w]); m_contrastChangedConnections.remove(w); m_colorMatrices.remove(w); } } void ContrastEffect::slotPropertyNotify(EffectWindow *w, long atom) { if (w && atom == net_wm_contrast_region && net_wm_contrast_region != XCB_ATOM_NONE) { updateContrastRegion(w); } } QMatrix4x4 ContrastEffect::colorMatrix(qreal contrast, qreal intensity, qreal saturation) { QMatrix4x4 satMatrix; //saturation QMatrix4x4 intMatrix; //intensity QMatrix4x4 contMatrix; //contrast //Saturation matrix if (!qFuzzyCompare(saturation, 1.0)) { const qreal rval = (1.0 - saturation) * .2126; const qreal gval = (1.0 - saturation) * .7152; const qreal bval = (1.0 - saturation) * .0722; satMatrix = QMatrix4x4(rval + saturation, rval, rval, 0.0, gval, gval + saturation, gval, 0.0, bval, bval, bval + saturation, 0.0, 0, 0, 0, 1.0); } //IntensityMatrix if (!qFuzzyCompare(intensity, 1.0)) { intMatrix.scale(intensity, intensity, intensity); } //Contrast Matrix if (!qFuzzyCompare(contrast, 1.0)) { const float transl = (1.0 - contrast) / 2.0; contMatrix = QMatrix4x4(contrast, 0, 0, 0.0, 0, contrast, 0, 0.0, 0, 0, contrast, 0.0, transl, transl, transl, 1.0); } QMatrix4x4 colorMatrix = contMatrix * satMatrix * intMatrix; //colorMatrix = colorMatrix.transposed(); return colorMatrix; } bool ContrastEffect::enabledByDefault() { GLPlatform *gl = GLPlatform::instance(); if (gl->isIntel() && gl->chipClass() < SandyBridge) return false; if (gl->isSoftwareEmulation()) { return false; } return true; } bool ContrastEffect::supported() { bool supported = effects->isOpenGLCompositing() && GLRenderTarget::supported(); if (supported) { int maxTexSize; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTexSize); const QSize screenSize = effects->virtualScreenSize(); if (screenSize.width() > maxTexSize || screenSize.height() > maxTexSize) supported = false; } return supported; } QRegion ContrastEffect::contrastRegion(const EffectWindow *w) const { QRegion region; const QVariant value = w->data(WindowBackgroundContrastRole); if (value.isValid()) { const QRegion appRegion = qvariant_cast(value); if (!appRegion.isEmpty()) { region |= appRegion.translated(w->contentsRect().topLeft()) & w->decorationInnerRect(); } else { // An empty region means that the blur effect should be enabled // for the whole window. region = w->decorationInnerRect(); } } return region; } void ContrastEffect::uploadRegion(QVector2D *&map, const QRegion ®ion) { for (const QRect &r : region) { const QVector2D topLeft(r.x(), r.y()); const QVector2D topRight(r.x() + r.width(), r.y()); const QVector2D bottomLeft(r.x(), r.y() + r.height()); const QVector2D bottomRight(r.x() + r.width(), r.y() + r.height()); // First triangle *(map++) = topRight; *(map++) = topLeft; *(map++) = bottomLeft; // Second triangle *(map++) = bottomLeft; *(map++) = bottomRight; *(map++) = topRight; } } void ContrastEffect::uploadGeometry(GLVertexBuffer *vbo, const QRegion ®ion) { const int vertexCount = region.rectCount() * 6; if (!vertexCount) return; QVector2D *map = (QVector2D *) vbo->map(vertexCount * sizeof(QVector2D)); uploadRegion(map, region); vbo->unmap(); const GLVertexAttrib layout[] = { { VA_Position, 2, GL_FLOAT, 0 }, { VA_TexCoord, 2, GL_FLOAT, 0 } }; vbo->setAttribLayout(layout, 2, sizeof(QVector2D)); } void ContrastEffect::prePaintScreen(ScreenPrePaintData &data, int time) { m_paintedArea = QRegion(); m_currentContrast = QRegion(); effects->prePaintScreen(data, time); } void ContrastEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) { // this effect relies on prePaintWindow being called in the bottom to top order effects->prePaintWindow(w, data, time); if (!w->isPaintingEnabled()) { return; } if (!shader || !shader->isValid()) { return; } const QRegion oldPaint = data.paint; // we don't have to blur a region we don't see m_currentContrast -= data.clip; // if we have to paint a non-opaque part of this window that intersects with the // currently blurred region (which is not cached) we have to redraw the whole region if ((data.paint-data.clip).intersects(m_currentContrast)) { data.paint |= m_currentContrast; } // in case this window has regions to be blurred const QRect screen = effects->virtualScreenGeometry(); const QRegion contrastArea = contrastRegion(w).translated(w->pos()) & screen; // we are not caching the window // if this window or an window underneath the modified area is painted again we have to // do everything if (m_paintedArea.intersects(contrastArea) || data.paint.intersects(contrastArea)) { data.paint |= contrastArea; // we have to check again whether we do not damage a blurred area // of a window we do not cache if (contrastArea.intersects(m_currentContrast)) { data.paint |= m_currentContrast; } } m_currentContrast |= contrastArea; // m_paintedArea keep track of all repainted areas m_paintedArea -= data.clip; m_paintedArea |= data.paint; } bool ContrastEffect::shouldContrast(const EffectWindow *w, int mask, const WindowPaintData &data) const { if (!shader || !shader->isValid()) return false; if (effects->activeFullScreenEffect() && !w->data(WindowForceBackgroundContrastRole).toBool()) return false; if (w->isDesktop()) return false; bool scaled = !qFuzzyCompare(data.xScale(), 1.0) && !qFuzzyCompare(data.yScale(), 1.0); bool translated = data.xTranslation() || data.yTranslation(); if ((scaled || (translated || (mask & PAINT_WINDOW_TRANSFORMED))) && !w->data(WindowForceBackgroundContrastRole).toBool()) return false; if (!w->hasAlpha()) return false; return true; } void ContrastEffect::drawWindow(EffectWindow *w, int mask, QRegion region, WindowPaintData &data) { const QRect screen = GLRenderTarget::virtualScreenGeometry(); if (shouldContrast(w, mask, data)) { QRegion shape = region & contrastRegion(w).translated(w->pos()) & screen; // let's do the evil parts - someone wants to blur behind a transformed window const bool translated = data.xTranslation() || data.yTranslation(); const bool scaled = data.xScale() != 1 || data.yScale() != 1; if (scaled) { QPoint pt = shape.boundingRect().topLeft(); QVector shapeRects = shape.rects(); shape = QRegion(); // clear foreach (QRect r, shapeRects) { r.moveTo(pt.x() + (r.x() - pt.x()) * data.xScale() + data.xTranslation(), pt.y() + (r.y() - pt.y()) * data.yScale() + data.yTranslation()); r.setWidth(r.width() * data.xScale()); r.setHeight(r.height() * data.yScale()); shape |= r; } shape = shape & region; //Only translated, not scaled } else if (translated) { shape = shape.translated(data.xTranslation(), data.yTranslation()); shape = shape & region; } if (!shape.isEmpty()) { doContrast(w, shape, screen, data.opacity(), data.screenProjectionMatrix()); } } // Draw the window over the contrast area effects->drawWindow(w, mask, region, data); } void ContrastEffect::paintEffectFrame(EffectFrame *frame, QRegion region, double opacity, double frameOpacity) { //FIXME: this is a no-op for now, it should figure out the right contrast, intensity, saturation effects->paintEffectFrame(frame, region, opacity, frameOpacity); } void ContrastEffect::doContrast(EffectWindow *w, const QRegion& shape, const QRect& screen, const float opacity, const QMatrix4x4 &screenProjection) { const QRegion actualShape = shape & screen; const QRect r = actualShape.boundingRect(); qreal scale = GLRenderTarget::virtualScreenScale(); // Upload geometry for the horizontal and vertical passes GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); uploadGeometry(vbo, actualShape); vbo->bindArrays(); // Create a scratch texture and copy the area in the back buffer that we're // going to blur into it GLTexture scratch(GL_RGBA8, r.width() * scale, r.height() * scale); scratch.setFilter(GL_LINEAR); scratch.setWrapMode(GL_CLAMP_TO_EDGE); - scratch.bind(); - const QRect sg = GLRenderTarget::virtualScreenGeometry(); - glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, (r.x() - sg.x()) * scale, (sg.height() - sg.y() - r.y() - r.height()) * scale, - scratch.width(), scratch.height()); + GLRenderTarget scratchTarget(scratch); + scratchTarget.blitFromFramebuffer(r); + scratch.bind(); // Draw the texture on the offscreen framebuffer object, while blurring it horizontally shader->setColorMatrix(m_colorMatrices.value(w)); shader->bind(); shader->setOpacity(opacity); // Set up the texture matrix to transform from screen coordinates // to texture coordinates. QMatrix4x4 textureMatrix; textureMatrix.scale(1.0 / r.width(), -1.0 / r.height(), 1); textureMatrix.translate(-r.x(), -r.height() - r.y(), 0); shader->setTextureMatrix(textureMatrix); shader->setModelViewProjectionMatrix(screenProjection); vbo->draw(GL_TRIANGLES, 0, actualShape.rectCount() * 6); scratch.unbind(); scratch.discard(); vbo->unbindArrays(); if (opacity < 1.0) { glDisable(GL_BLEND); } shader->unbind(); } } // namespace KWin diff --git a/effects/blur/blur.cpp b/effects/blur/blur.cpp index cc4734e60..297a98bd0 100644 --- a/effects/blur/blur.cpp +++ b/effects/blur/blur.cpp @@ -1,773 +1,766 @@ /* * Copyright © 2010 Fredrik Höglund * Copyright © 2011 Philipp Knechtges * Copyright © 2018 Alex Nemeth * * 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; see the file COPYING. if not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "blur.h" #include "effects.h" #include "blurshader.h" // KConfigSkeleton #include "blurconfig.h" #include #include #include // for QGuiApplication #include #include // for ceil() #include #include #include #include #include #include namespace KWin { static const QByteArray s_blurAtomName = QByteArrayLiteral("_KDE_NET_WM_BLUR_BEHIND_REGION"); BlurEffect::BlurEffect() { initConfig(); m_shader = BlurShader::create(); initBlurStrengthValues(); reconfigure(ReconfigureAll); // ### Hackish way to announce support. // Should be included in _NET_SUPPORTED instead. if (m_shader && m_shader->isValid() && m_renderTargetsValid) { net_wm_blur_region = effects->announceSupportProperty(s_blurAtomName, this); KWayland::Server::Display *display = effects->waylandDisplay(); if (display) { m_blurManager = display->createBlurManager(this); m_blurManager->create(); } } else { net_wm_blur_region = 0; } connect(effects, SIGNAL(windowAdded(KWin::EffectWindow*)), this, SLOT(slotWindowAdded(KWin::EffectWindow*))); connect(effects, SIGNAL(windowDeleted(KWin::EffectWindow*)), this, SLOT(slotWindowDeleted(KWin::EffectWindow*))); connect(effects, SIGNAL(propertyNotify(KWin::EffectWindow*,long)), this, SLOT(slotPropertyNotify(KWin::EffectWindow*,long))); connect(effects, SIGNAL(screenGeometryChanged(QSize)), this, SLOT(slotScreenGeometryChanged())); connect(effects, &EffectsHandler::xcbConnectionChanged, this, [this] { if (m_shader && m_shader->isValid() && m_renderTargetsValid) { net_wm_blur_region = effects->announceSupportProperty(s_blurAtomName, this); } } ); // Fetch the blur regions for all windows foreach (EffectWindow *window, effects->stackingOrder()) updateBlurRegion(window); } BlurEffect::~BlurEffect() { deleteFBOs(); delete m_shader; m_shader = nullptr; } void BlurEffect::slotScreenGeometryChanged() { effects->makeOpenGLContextCurrent(); updateTexture(); // Fetch the blur regions for all windows foreach (EffectWindow *window, effects->stackingOrder()) updateBlurRegion(window); effects->doneOpenGLContextCurrent(); } bool BlurEffect::renderTargetsValid() const { return !m_renderTargets.isEmpty() && std::find_if(m_renderTargets.cbegin(), m_renderTargets.cend(), [](const GLRenderTarget *target) { return !target->valid(); }) == m_renderTargets.cend(); } void BlurEffect::deleteFBOs() { qDeleteAll(m_renderTargets); m_renderTargets.clear(); m_renderTextures.clear(); } void BlurEffect::updateTexture() { deleteFBOs(); /* Reserve memory for: * - The original sized texture (1) * - The downsized textures (m_downSampleIterations) * - The helper texture (1) */ m_renderTargets.reserve(m_downSampleIterations + 2); m_renderTextures.reserve(m_downSampleIterations + 2); for (int i = 0; i <= m_downSampleIterations; i++) { m_renderTextures.append(GLTexture(GL_RGBA8, effects->virtualScreenSize() / (1 << i))); m_renderTextures.last().setFilter(GL_LINEAR); m_renderTextures.last().setWrapMode(GL_CLAMP_TO_EDGE); m_renderTargets.append(new GLRenderTarget(m_renderTextures.last())); } // This last set is used as a temporary helper texture m_renderTextures.append(GLTexture(GL_RGBA8, effects->virtualScreenSize())); m_renderTextures.last().setFilter(GL_LINEAR); m_renderTextures.last().setWrapMode(GL_CLAMP_TO_EDGE); m_renderTargets.append(new GLRenderTarget(m_renderTextures.last())); m_renderTargetsValid = renderTargetsValid(); // Prepare the stack for the rendering m_renderTargetStack.clear(); m_renderTargetStack.reserve(m_downSampleIterations * 2); // Upsample for (int i = 1; i < m_downSampleIterations; i++) { m_renderTargetStack.push(m_renderTargets[i]); } // Downsample for (int i = m_downSampleIterations; i > 0; i--) { m_renderTargetStack.push(m_renderTargets[i]); } // Copysample m_renderTargetStack.push(m_renderTargets[0]); // Generate the noise helper texture generateNoiseTexture(); } void BlurEffect::initBlurStrengthValues() { // This function creates an array of blur strength values that are evenly distributed // The range of the slider on the blur settings UI int numOfBlurSteps = 15; int remainingSteps = numOfBlurSteps; /* * Explanation for these numbers: * * The texture blur amount depends on the downsampling iterations and the offset value. * By changing the offset we can alter the blur amount without relying on further downsampling. * But there is a minimum and maximum value of offset per downsample iteration before we * get artifacts. * * The minOffset variable is the minimum offset value for an iteration before we * get blocky artifacts because of the downsampling. * * The maxOffset value is the maximum offset value for an iteration before we * get diagonal line artifacts because of the nature of the dual kawase blur algorithm. * * The expandSize value is the minimum value for an iteration before we reach the end * of a texture in the shader and sample outside of the area that was copied into the * texture from the screen. */ // {minOffset, maxOffset, expandSize} blurOffsets.append({1.0, 2.0, 10}); // Down sample size / 2 blurOffsets.append({2.0, 3.0, 20}); // Down sample size / 4 blurOffsets.append({2.0, 5.0, 50}); // Down sample size / 8 blurOffsets.append({3.0, 8.0, 150}); // Down sample size / 16 //blurOffsets.append({5.0, 10.0, 400}); // Down sample size / 32 //blurOffsets.append({7.0, ?.0}); // Down sample size / 64 float offsetSum = 0; for (int i = 0; i < blurOffsets.size(); i++) { offsetSum += blurOffsets[i].maxOffset - blurOffsets[i].minOffset; } for (int i = 0; i < blurOffsets.size(); i++) { int iterationNumber = std::ceil((blurOffsets[i].maxOffset - blurOffsets[i].minOffset) / offsetSum * numOfBlurSteps); remainingSteps -= iterationNumber; if (remainingSteps < 0) { iterationNumber += remainingSteps; } float offsetDifference = blurOffsets[i].maxOffset - blurOffsets[i].minOffset; for (int j = 1; j <= iterationNumber; j++) { // {iteration, offset} blurStrengthValues.append({i + 1, blurOffsets[i].minOffset + (offsetDifference / iterationNumber) * j}); } } } void BlurEffect::reconfigure(ReconfigureFlags flags) { Q_UNUSED(flags) BlurConfig::self()->read(); int blurStrength = BlurConfig::blurStrength() - 1; m_downSampleIterations = blurStrengthValues[blurStrength].iteration; m_offset = blurStrengthValues[blurStrength].offset; m_expandSize = blurOffsets[m_downSampleIterations - 1].expandSize; m_noiseStrength = BlurConfig::noiseStrength(); m_scalingFactor = QGuiApplication::primaryScreen()->logicalDotsPerInch() / 96.0; updateTexture(); if (!m_shader || !m_shader->isValid()) { effects->removeSupportProperty(s_blurAtomName, this); delete m_blurManager; m_blurManager = nullptr; } // Update all windows for the blur to take effect effects->addRepaintFull(); } void BlurEffect::updateBlurRegion(EffectWindow *w) const { QRegion region; QByteArray value; if (net_wm_blur_region != XCB_ATOM_NONE) { value = w->readProperty(net_wm_blur_region, XCB_ATOM_CARDINAL, 32); if (value.size() > 0 && !(value.size() % (4 * sizeof(uint32_t)))) { const uint32_t *cardinals = reinterpret_cast(value.constData()); for (unsigned int i = 0; i < value.size() / sizeof(uint32_t);) { int x = cardinals[i++]; int y = cardinals[i++]; int w = cardinals[i++]; int h = cardinals[i++]; region += QRect(x, y, w, h); } } } KWayland::Server::SurfaceInterface *surf = w->surface(); if (surf && surf->blur()) { region = surf->blur()->region(); } //!value.isNull() full window in X11 case, surf->blur() //valid, full window in wayland case if (region.isEmpty() && (!value.isNull() || (surf && surf->blur()))) { // Set the data to a dummy value. // This is needed to be able to distinguish between the value not // being set, and being set to an empty region. w->setData(WindowBlurBehindRole, 1); } else w->setData(WindowBlurBehindRole, region); } void BlurEffect::slotWindowAdded(EffectWindow *w) { KWayland::Server::SurfaceInterface *surf = w->surface(); if (surf) { windowBlurChangedConnections[w] = connect(surf, &KWayland::Server::SurfaceInterface::blurChanged, this, [this, w] () { if (w) { updateBlurRegion(w); } }); } updateBlurRegion(w); } void BlurEffect::slotWindowDeleted(EffectWindow *w) { if (windowBlurChangedConnections.contains(w)) { disconnect(windowBlurChangedConnections[w]); windowBlurChangedConnections.remove(w); } } void BlurEffect::slotPropertyNotify(EffectWindow *w, long atom) { if (w && atom == net_wm_blur_region && net_wm_blur_region != XCB_ATOM_NONE) { updateBlurRegion(w); } } bool BlurEffect::enabledByDefault() { GLPlatform *gl = GLPlatform::instance(); if (gl->isIntel() && gl->chipClass() < SandyBridge) return false; if (gl->isSoftwareEmulation()) { return false; } return true; } bool BlurEffect::supported() { bool supported = effects->isOpenGLCompositing() && GLRenderTarget::supported(); if (supported) { int maxTexSize; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTexSize); const QSize screenSize = effects->virtualScreenSize(); if (screenSize.width() > maxTexSize || screenSize.height() > maxTexSize) supported = false; } return supported; } QRect BlurEffect::expand(const QRect &rect) const { return rect.adjusted(-m_expandSize, -m_expandSize, m_expandSize, m_expandSize); } QRegion BlurEffect::expand(const QRegion ®ion) const { QRegion expanded; for (const QRect &rect : region) { expanded += expand(rect); } return expanded; } QRegion BlurEffect::blurRegion(const EffectWindow *w) const { QRegion region; const QVariant value = w->data(WindowBlurBehindRole); if (value.isValid()) { const QRegion appRegion = qvariant_cast(value); if (!appRegion.isEmpty()) { if (w->decorationHasAlpha() && effects->decorationSupportsBlurBehind()) { region = w->shape(); region -= w->decorationInnerRect(); } region |= appRegion.translated(w->contentsRect().topLeft()) & w->decorationInnerRect(); } else { // An empty region means that the blur effect should be enabled // for the whole window. region = w->shape(); } } else if (w->decorationHasAlpha() && effects->decorationSupportsBlurBehind()) { // If the client hasn't specified a blur region, we'll only enable // the effect behind the decoration. region = w->shape(); region -= w->decorationInnerRect(); } return region; } void BlurEffect::uploadRegion(QVector2D *&map, const QRegion ®ion, const int downSampleIterations) { for (int i = 0; i <= downSampleIterations; i++) { const int divisionRatio = (1 << i); for (const QRect &r : region) { const QVector2D topLeft( r.x() / divisionRatio, r.y() / divisionRatio); const QVector2D topRight( (r.x() + r.width()) / divisionRatio, r.y() / divisionRatio); const QVector2D bottomLeft( r.x() / divisionRatio, (r.y() + r.height()) / divisionRatio); const QVector2D bottomRight((r.x() + r.width()) / divisionRatio, (r.y() + r.height()) / divisionRatio); // First triangle *(map++) = topRight; *(map++) = topLeft; *(map++) = bottomLeft; // Second triangle *(map++) = bottomLeft; *(map++) = bottomRight; *(map++) = topRight; } } } void BlurEffect::uploadGeometry(GLVertexBuffer *vbo, const QRegion &blurRegion, const QRegion &windowRegion) { const int vertexCount = ((blurRegion.rectCount() * (m_downSampleIterations + 1)) + windowRegion.rectCount()) * 6; if (!vertexCount) return; QVector2D *map = (QVector2D *) vbo->map(vertexCount * sizeof(QVector2D)); uploadRegion(map, blurRegion, m_downSampleIterations); uploadRegion(map, windowRegion, 0); vbo->unmap(); const GLVertexAttrib layout[] = { { VA_Position, 2, GL_FLOAT, 0 }, { VA_TexCoord, 2, GL_FLOAT, 0 } }; vbo->setAttribLayout(layout, 2, sizeof(QVector2D)); } void BlurEffect::prePaintScreen(ScreenPrePaintData &data, int time) { m_damagedArea = QRegion(); m_paintedArea = QRegion(); m_currentBlur = QRegion(); effects->prePaintScreen(data, time); } void BlurEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) { // this effect relies on prePaintWindow being called in the bottom to top order effects->prePaintWindow(w, data, time); if (!w->isPaintingEnabled()) { return; } if (!m_shader || !m_shader->isValid()) { return; } // to blur an area partially we have to shrink the opaque area of a window QRegion newClip; const QRegion oldClip = data.clip; for (const QRect &rect : data.clip) { newClip |= rect.adjusted(m_expandSize, m_expandSize, -m_expandSize, -m_expandSize); } data.clip = newClip; const QRegion oldPaint = data.paint; // we don't have to blur a region we don't see m_currentBlur -= newClip; // if we have to paint a non-opaque part of this window that intersects with the // currently blurred region we have to redraw the whole region if ((data.paint - oldClip).intersects(m_currentBlur)) { data.paint |= m_currentBlur; } // in case this window has regions to be blurred const QRect screen = effects->virtualScreenGeometry(); const QRegion blurArea = blurRegion(w).translated(w->pos()) & screen; const QRegion expandedBlur = (w->isDock() ? blurArea : expand(blurArea)) & screen; // if this window or a window underneath the blurred area is painted again we have to // blur everything if (m_paintedArea.intersects(expandedBlur) || data.paint.intersects(blurArea)) { data.paint |= expandedBlur; // we keep track of the "damage propagation" m_damagedArea |= (w->isDock() ? (expandedBlur & m_damagedArea) : expand(expandedBlur & m_damagedArea)) & blurArea; // we have to check again whether we do not damage a blurred area // of a window if (expandedBlur.intersects(m_currentBlur)) { data.paint |= m_currentBlur; } } m_currentBlur |= expandedBlur; // we don't consider damaged areas which are occluded and are not // explicitly damaged by this window m_damagedArea -= data.clip; m_damagedArea |= oldPaint; // in contrast to m_damagedArea does m_paintedArea keep track of all repainted areas m_paintedArea -= data.clip; m_paintedArea |= data.paint; } bool BlurEffect::shouldBlur(const EffectWindow *w, int mask, const WindowPaintData &data) const { if (!m_renderTargetsValid || !m_shader || !m_shader->isValid()) return false; if (effects->activeFullScreenEffect() && !w->data(WindowForceBlurRole).toBool()) return false; if (w->isDesktop()) return false; bool scaled = !qFuzzyCompare(data.xScale(), 1.0) && !qFuzzyCompare(data.yScale(), 1.0); bool translated = data.xTranslation() || data.yTranslation(); if ((scaled || (translated || (mask & PAINT_WINDOW_TRANSFORMED))) && !w->data(WindowForceBlurRole).toBool()) return false; bool blurBehindDecos = effects->decorationsHaveAlpha() && effects->decorationSupportsBlurBehind(); if (!w->hasAlpha() && w->opacity() >= 1.0 && !(blurBehindDecos && w->hasDecoration())) return false; return true; } void BlurEffect::drawWindow(EffectWindow *w, int mask, QRegion region, WindowPaintData &data) { const QRect screen = GLRenderTarget::virtualScreenGeometry(); if (shouldBlur(w, mask, data)) { QRegion shape = region & blurRegion(w).translated(w->pos()) & screen; // let's do the evil parts - someone wants to blur behind a transformed window const bool translated = data.xTranslation() || data.yTranslation(); const bool scaled = data.xScale() != 1 || data.yScale() != 1; if (scaled) { QPoint pt = shape.boundingRect().topLeft(); QVector shapeRects = shape.rects(); shape = QRegion(); // clear foreach (QRect r, shapeRects) { r.moveTo(pt.x() + (r.x() - pt.x()) * data.xScale() + data.xTranslation(), pt.y() + (r.y() - pt.y()) * data.yScale() + data.yTranslation()); r.setWidth(r.width() * data.xScale()); r.setHeight(r.height() * data.yScale()); shape |= r; } shape = shape & region; //Only translated, not scaled } else if (translated) { shape = shape.translated(data.xTranslation(), data.yTranslation()); shape = shape & region; } if (!shape.isEmpty()) { doBlur(shape, screen, data.opacity(), data.screenProjectionMatrix(), w->isDock(), w->geometry()); } } // Draw the window over the blurred area effects->drawWindow(w, mask, region, data); } void BlurEffect::paintEffectFrame(EffectFrame *frame, QRegion region, double opacity, double frameOpacity) { const QRect screen = effects->virtualScreenGeometry(); bool valid = m_renderTargetsValid && m_shader && m_shader->isValid(); QRegion shape = frame->geometry().adjusted(-borderSize, -borderSize, borderSize, borderSize) & screen; if (valid && !shape.isEmpty() && region.intersects(shape.boundingRect()) && frame->style() != EffectFrameNone) { doBlur(shape, screen, opacity * frameOpacity, frame->screenProjectionMatrix(), false, frame->geometry()); } effects->paintEffectFrame(frame, region, opacity, frameOpacity); } void BlurEffect::generateNoiseTexture() { if (m_noiseStrength == 0) { return; } // Init randomness based on time qsrand((uint)QTime::currentTime().msec()); QImage noiseImage(QSize(256, 256), QImage::Format_Grayscale8); for (int y = 0; y < noiseImage.height(); y++) { uint8_t *noiseImageLine = (uint8_t *) noiseImage.scanLine(y); for (int x = 0; x < noiseImage.width(); x++) { noiseImageLine[x] = qrand() % m_noiseStrength + (128 - m_noiseStrength / 2); } } // The noise texture looks distorted when not scaled with integer noiseImage = noiseImage.scaled(noiseImage.size() * m_scalingFactor); m_noiseTexture = GLTexture(noiseImage); m_noiseTexture.setFilter(GL_NEAREST); m_noiseTexture.setWrapMode(GL_REPEAT); } void BlurEffect::doBlur(const QRegion& shape, const QRect& screen, const float opacity, const QMatrix4x4 &screenProjection, bool isDock, QRect windowRect) { QRegion expandedBlurRegion = expand(shape) & expand(screen); // Upload geometry for the down and upsample iterations GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); uploadGeometry(vbo, expandedBlurRegion, shape); vbo->bindArrays(); /* * If the window is a dock or panel we avoid the "extended blur" effect. * Extended blur is when windows that are not under the blurred area affect * the final blur result. * We want to avoid this on panels, because it looks really weird and ugly * when maximized windows or windows near the panel affect the dock blur. */ - isDock ? m_renderTextures.last().bind() : m_renderTextures[0].bind(); + GLTexture& copyTexture = isDock ? m_renderTextures.last() : m_renderTextures.first(); QRect copyRect = expandedBlurRegion.boundingRect() & screen; - glCopyTexSubImage2D( - GL_TEXTURE_2D, - 0, - copyRect.x(), - effects->virtualScreenSize().height() - copyRect.y() - copyRect.height(), - copyRect.x(), - effects->virtualScreenSize().height() - copyRect.y() - copyRect.height(), - copyRect.width(), - copyRect.height() - ); + GLRenderTarget copyTarget(copyTexture); + copyTarget.blitFromFramebuffer(copyRect); + copyTexture.bind(); GLRenderTarget::pushRenderTargets(m_renderTargetStack); int blurRectCount = expandedBlurRegion.rectCount() * 6; if (isDock) { copyScreenSampleTexture(vbo, blurRectCount, shape, screen.size(), screenProjection); } else { // Remove the m_renderTargets[0] from the top of the stack that we will not use GLRenderTarget::popRenderTarget(); } downSampleTexture(vbo, blurRectCount); upSampleTexture(vbo, blurRectCount); // Modulate the blurred texture with the window opacity if the window isn't opaque if (opacity < 1.0) { glEnable(GL_BLEND); #if 1 // bow shape, always above y = x float o = 1.0f-opacity; o = 1.0f - o*o; #else // sigmoid shape, above y = x for x > 0.5, below y = x for x < 0.5 float o = 2.0f*opacity - 1.0f; o = 0.5f + o / (1.0f + qAbs(o)); #endif glBlendColor(0, 0, 0, o); glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); } upscaleRenderToScreen(vbo, blurRectCount * (m_downSampleIterations + 1), shape.rectCount() * 6, screenProjection, shape.boundingRect(), windowRect.topLeft()); if (opacity < 1.0) { glDisable(GL_BLEND); } vbo->unbindArrays(); } void BlurEffect::upscaleRenderToScreen(GLVertexBuffer *vbo, int vboStart, int blurRectCount, QMatrix4x4 screenProjection, QRect windowShape, QPoint windowPosition) { glActiveTexture(GL_TEXTURE0); m_renderTextures[1].bind(); if (m_noiseStrength > 0) { m_shader->bind(BlurShader::NoiseSampleType); m_shader->setTargetTextureSize(m_renderTextures[0].size()); m_shader->setNoiseTextureSize(m_noiseTexture.size()); m_shader->setTexturePosition(windowPosition); glActiveTexture(GL_TEXTURE1); m_noiseTexture.bind(); } else { m_shader->bind(BlurShader::UpSampleType); m_shader->setTargetTextureSize(m_renderTextures[0].size()); } m_shader->setOffset(m_offset); m_shader->setModelViewProjectionMatrix(screenProjection); //Render to the screen vbo->draw(GL_TRIANGLES, vboStart, blurRectCount); glActiveTexture(GL_TEXTURE0); m_shader->unbind(); } void BlurEffect::downSampleTexture(GLVertexBuffer *vbo, int blurRectCount) { QMatrix4x4 modelViewProjectionMatrix; m_shader->bind(BlurShader::DownSampleType); m_shader->setOffset(m_offset); for (int i = 1; i <= m_downSampleIterations; i++) { modelViewProjectionMatrix.setToIdentity(); modelViewProjectionMatrix.ortho(0, m_renderTextures[i].width(), m_renderTextures[i].height(), 0 , 0, 65535); m_shader->setModelViewProjectionMatrix(modelViewProjectionMatrix); m_shader->setTargetTextureSize(m_renderTextures[i].size()); //Copy the image from this texture m_renderTextures[i - 1].bind(); vbo->draw(GL_TRIANGLES, blurRectCount * i, blurRectCount); GLRenderTarget::popRenderTarget(); } m_shader->unbind(); } void BlurEffect::upSampleTexture(GLVertexBuffer *vbo, int blurRectCount) { QMatrix4x4 modelViewProjectionMatrix; m_shader->bind(BlurShader::UpSampleType); m_shader->setOffset(m_offset); for (int i = m_downSampleIterations - 1; i >= 1; i--) { modelViewProjectionMatrix.setToIdentity(); modelViewProjectionMatrix.ortho(0, m_renderTextures[i].width(), m_renderTextures[i].height(), 0 , 0, 65535); m_shader->setModelViewProjectionMatrix(modelViewProjectionMatrix); m_shader->setTargetTextureSize(m_renderTextures[i].size()); //Copy the image from this texture m_renderTextures[i + 1].bind(); vbo->draw(GL_TRIANGLES, blurRectCount * i, blurRectCount); GLRenderTarget::popRenderTarget(); } m_shader->unbind(); } void BlurEffect::copyScreenSampleTexture(GLVertexBuffer *vbo, int blurRectCount, QRegion blurShape, QSize screenSize, QMatrix4x4 screenProjection) { m_shader->bind(BlurShader::CopySampleType); m_shader->setModelViewProjectionMatrix(screenProjection); m_shader->setTargetTextureSize(screenSize); /* * This '1' sized adjustment is necessary do avoid windows affecting the blur that are * right next to this window. */ m_shader->setBlurRect(blurShape.boundingRect().adjusted(1, 1, -1, -1), screenSize); vbo->draw(GL_TRIANGLES, 0, blurRectCount); GLRenderTarget::popRenderTarget(); m_shader->unbind(); } } // namespace KWin diff --git a/effects/coverswitch/coverswitch.cpp b/effects/coverswitch/coverswitch.cpp index 463e13ec4..83bf0edcc 100644 --- a/effects/coverswitch/coverswitch.cpp +++ b/effects/coverswitch/coverswitch.cpp @@ -1,1000 +1,1004 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2008 Martin Gräßlin 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 . *********************************************************************/ #include "coverswitch.h" // KConfigSkeleton #include "coverswitchconfig.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace KWin { CoverSwitchEffect::CoverSwitchEffect() : mActivated(0) , angle(60.0) , animation(false) , start(false) , stop(false) , stopRequested(false) , startRequested(false) , zPosition(900.0) , scaleFactor(0.0) , direction(Left) , selected_window(0) , captionFrame(NULL) , primaryTabBox(false) , secondaryTabBox(false) { initConfig(); reconfigure(ReconfigureAll); // Caption frame captionFont.setBold(true); captionFont.setPointSize(captionFont.pointSize() * 2); if (effects->compositingType() == OpenGL2Compositing) { m_reflectionShader = ShaderManager::instance()->generateShaderFromResources(ShaderTrait::MapTexture, QString(), QStringLiteral("coverswitch-reflection.glsl")); } else { m_reflectionShader = NULL; } connect(effects, SIGNAL(windowClosed(KWin::EffectWindow*)), this, SLOT(slotWindowClosed(KWin::EffectWindow*))); connect(effects, SIGNAL(tabBoxAdded(int)), this, SLOT(slotTabBoxAdded(int))); connect(effects, SIGNAL(tabBoxClosed()), this, SLOT(slotTabBoxClosed())); connect(effects, SIGNAL(tabBoxUpdated()), this, SLOT(slotTabBoxUpdated())); connect(effects, SIGNAL(tabBoxKeyEvent(QKeyEvent*)), this, SLOT(slotTabBoxKeyEvent(QKeyEvent*))); } CoverSwitchEffect::~CoverSwitchEffect() { delete captionFrame; delete m_reflectionShader; } bool CoverSwitchEffect::supported() { return effects->isOpenGLCompositing() && effects->animationsSupported(); } void CoverSwitchEffect::reconfigure(ReconfigureFlags) { CoverSwitchConfig::self()->read(); animationDuration = animationTime(200); animateSwitch = CoverSwitchConfig::animateSwitch(); animateStart = CoverSwitchConfig::animateStart(); animateStop = CoverSwitchConfig::animateStop(); reflection = CoverSwitchConfig::reflection(); + multisampling = CoverSwitchConfig::multisampling(); windowTitle = CoverSwitchConfig::windowTitle(); zPosition = CoverSwitchConfig::zPosition(); timeLine.setCurveShape(QTimeLine::EaseInOutCurve); timeLine.setDuration(animationDuration); // Defined outside the ui primaryTabBox = CoverSwitchConfig::tabBox(); secondaryTabBox = CoverSwitchConfig::tabBoxAlternative(); QColor tmp = CoverSwitchConfig::mirrorFrontColor(); mirrorColor[0][0] = tmp.redF(); mirrorColor[0][1] = tmp.greenF(); mirrorColor[0][2] = tmp.blueF(); mirrorColor[0][3] = 1.0; tmp = CoverSwitchConfig::mirrorRearColor(); mirrorColor[1][0] = tmp.redF(); mirrorColor[1][1] = tmp.greenF(); mirrorColor[1][2] = tmp.blueF(); mirrorColor[1][3] = -1.0; } void CoverSwitchEffect::prePaintScreen(ScreenPrePaintData& data, int time) { if (mActivated || stop || stopRequested) { data.mask |= Effect::PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; + if (multisampling) { + data.mask |= Effect::PAINT_SCREEN_MULTISAMPLE; + } if (animation || start || stop) { timeLine.setCurrentTime(timeLine.currentTime() + time); } if (selected_window == NULL) abort(); } effects->prePaintScreen(data, time); } void CoverSwitchEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) { effects->paintScreen(mask, region, data); if (mActivated || stop || stopRequested) { QList< EffectWindow* > tempList = currentWindowList; int index = tempList.indexOf(selected_window); if (animation || start || stop) { if (!start && !stop) { if (direction == Right) index++; else index--; if (index < 0) index = tempList.count() + index; if (index >= tempList.count()) index = index % tempList.count(); } foreach (Direction direction, scheduled_directions) { if (direction == Right) index++; else index--; if (index < 0) index = tempList.count() + index; if (index >= tempList.count()) index = index % tempList.count(); } } int leftIndex = index - 1; if (leftIndex < 0) leftIndex = tempList.count() - 1; int rightIndex = index + 1; if (rightIndex == tempList.count()) rightIndex = 0; EffectWindow* frontWindow = tempList[ index ]; leftWindows.clear(); rightWindows.clear(); bool evenWindows = (tempList.count() % 2 == 0) ? true : false; int leftWindowCount = 0; if (evenWindows) leftWindowCount = tempList.count() / 2 - 1; else leftWindowCount = (tempList.count() - 1) / 2; for (int i = 0; i < leftWindowCount; i++) { int tempIndex = (leftIndex - i); if (tempIndex < 0) tempIndex = tempList.count() + tempIndex; leftWindows.prepend(tempList[ tempIndex ]); } int rightWindowCount = 0; if (evenWindows) rightWindowCount = tempList.count() / 2; else rightWindowCount = (tempList.count() - 1) / 2; for (int i = 0; i < rightWindowCount; i++) { int tempIndex = (rightIndex + i) % tempList.count(); rightWindows.prepend(tempList[ tempIndex ]); } if (reflection) { // no reflections during start and stop animation // except when using a shader if ((!start && !stop) || effects->compositingType() == OpenGL2Compositing) paintScene(frontWindow, leftWindows, rightWindows, true); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // we can use a huge scale factor (needed to calculate the rearground vertices) // as we restrict with a PaintClipper painting on the current screen float reflectionScaleFactor = 100000 * tan(60.0 * M_PI / 360.0f) / area.width(); const float width = area.width(); const float height = area.height(); float vertices[] = { -width * 0.5f, height, 0.0, width * 0.5f, height, 0.0, width*reflectionScaleFactor, height, -5000, -width*reflectionScaleFactor, height, -5000 }; // foreground if (start) { mirrorColor[0][3] = timeLine.currentValue(); } else if (stop) { mirrorColor[0][3] = 1.0 - timeLine.currentValue(); } else { mirrorColor[0][3] = 1.0; } int y = 0; // have to adjust the y values to fit OpenGL // in OpenGL y==0 is at bottom, in Qt at top if (effects->numScreens() > 1) { QRect fullArea = effects->clientArea(FullArea, 0, 1); if (fullArea.height() != area.height()) { if (area.y() == 0) y = fullArea.height() - area.height(); else y = fullArea.height() - area.y() - area.height(); } } // use scissor to restrict painting of the reflection plane to current screen glScissor(area.x(), y, area.width(), area.height()); glEnable(GL_SCISSOR_TEST); if (m_reflectionShader && m_reflectionShader->isValid()) { ShaderManager::instance()->pushShader(m_reflectionShader); QMatrix4x4 windowTransformation = data.projectionMatrix(); windowTransformation.translate(area.x() + area.width() * 0.5f, 0.0, 0.0); m_reflectionShader->setUniform(GLShader::ModelViewProjectionMatrix, windowTransformation); m_reflectionShader->setUniform("u_frontColor", QVector4D(mirrorColor[0][0], mirrorColor[0][1], mirrorColor[0][2], mirrorColor[0][3])); m_reflectionShader->setUniform("u_backColor", QVector4D(mirrorColor[1][0], mirrorColor[1][1], mirrorColor[1][2], mirrorColor[1][3])); // TODO: make this one properly QVector verts; QVector texcoords; verts.reserve(18); texcoords.reserve(12); texcoords << 1.0 << 0.0; verts << vertices[6] << vertices[7] << vertices[8]; texcoords << 1.0 << 0.0; verts << vertices[9] << vertices[10] << vertices[11]; texcoords << 0.0 << 0.0; verts << vertices[0] << vertices[1] << vertices[2]; texcoords << 0.0 << 0.0; verts << vertices[0] << vertices[1] << vertices[2]; texcoords << 0.0 << 0.0; verts << vertices[3] << vertices[4] << vertices[5]; texcoords << 1.0 << 0.0; verts << vertices[6] << vertices[7] << vertices[8]; GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); vbo->setData(6, 3, verts.data(), texcoords.data()); vbo->render(GL_TRIANGLES); ShaderManager::instance()->popShader(); } glDisable(GL_SCISSOR_TEST); glDisable(GL_BLEND); } paintScene(frontWindow, leftWindows, rightWindows); // Render the caption frame if (windowTitle) { double opacity = 1.0; if (start) opacity = timeLine.currentValue(); else if (stop) opacity = 1.0 - timeLine.currentValue(); if (animation) captionFrame->setCrossFadeProgress(timeLine.currentValue()); captionFrame->render(region, opacity); } } } void CoverSwitchEffect::postPaintScreen() { if ((mActivated && (animation || start)) || stop || stopRequested) { if (timeLine.currentValue() == 1.0) { timeLine.setCurrentTime(0); if (stop) { stop = false; effects->setActiveFullScreenEffect(0); foreach (EffectWindow * window, referrencedWindows) { window->unrefWindow(); } referrencedWindows.clear(); currentWindowList.clear(); if (startRequested) { startRequested = false; mActivated = true; effects->refTabBox(); currentWindowList = effects->currentTabBoxWindowList(); if (animateStart) { start = true; } } } else if (!scheduled_directions.isEmpty()) { direction = scheduled_directions.dequeue(); if (start) { animation = true; start = false; } } else { animation = false; start = false; if (stopRequested) { stopRequested = false; stop = true; } } } effects->addRepaintFull(); } effects->postPaintScreen(); } void CoverSwitchEffect::paintScene(EffectWindow* frontWindow, const EffectWindowList& leftWindows, const EffectWindowList& rightWindows, bool reflectedWindows) { // LAYOUT // one window in the front. Other windows left and right rotated // for odd number of windows: left: (n-1)/2; front: 1; right: (n-1)/2 // for even number of windows: left: n/2; front: 1; right: n/2 -1 // // ANIMATION // forward (alt+tab) // all left windows are moved to next position // top most left window is rotated and moved to front window position // front window is rotated and moved to next right window position // right windows are moved to next position // last right window becomes totally transparent in half the time // appears transparent on left side and becomes totally opaque again // backward (alt+shift+tab) same as forward but opposite direction int width = area.width(); int leftWindowCount = leftWindows.count(); int rightWindowCount = rightWindows.count(); // Problem during animation: a window which is painted after another window // appears in front of the other // so during animation the painting order has to be rearreanged // paint sequence no animation: left, right, front // paint sequence forward animation: right, front, left if (!animation) { paintWindows(leftWindows, true, reflectedWindows); paintWindows(rightWindows, false, reflectedWindows); paintFrontWindow(frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows); } else { if (direction == Right) { if (timeLine.currentValue() < 0.5) { // paint in normal way paintWindows(leftWindows, true, reflectedWindows); paintWindows(rightWindows, false, reflectedWindows); paintFrontWindow(frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows); } else { paintWindows(rightWindows, false, reflectedWindows); paintFrontWindow(frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows); paintWindows(leftWindows, true, reflectedWindows, rightWindows.at(0)); } } else { paintWindows(leftWindows, true, reflectedWindows); if (timeLine.currentValue() < 0.5) { paintWindows(rightWindows, false, reflectedWindows); paintFrontWindow(frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows); } else { EffectWindow* leftWindow; if (leftWindowCount > 0) { leftWindow = leftWindows.at(0); paintFrontWindow(frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows); } else leftWindow = frontWindow; paintWindows(rightWindows, false, reflectedWindows, leftWindow); } } } } void CoverSwitchEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) { if (mActivated || stop || stopRequested) { if (!(mask & PAINT_WINDOW_TRANSFORMED) && !w->isDesktop()) { if ((start || stop) && w->isDock()) { data.setOpacity(1.0 - timeLine.currentValue()); if (stop) data.setOpacity(timeLine.currentValue()); } else return; } } if ((start || stop) && (!w->isOnCurrentDesktop() || w->isMinimized())) { if (stop) // Fade out windows not on the current desktop data.setOpacity((1.0 - timeLine.currentValue())); else // Fade in Windows from other desktops when animation is started data.setOpacity(timeLine.currentValue()); } effects->paintWindow(w, mask, region, data); } void CoverSwitchEffect::slotTabBoxAdded(int mode) { if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return; if (!mActivated) { effects->setShowingDesktop(false); // only for windows mode if (((mode == TabBoxWindowsMode && primaryTabBox) || (mode == TabBoxWindowsAlternativeMode && secondaryTabBox) || (mode == TabBoxCurrentAppWindowsMode && primaryTabBox) || (mode == TabBoxCurrentAppWindowsAlternativeMode && secondaryTabBox)) && effects->currentTabBoxWindowList().count() > 0) { effects->startMouseInterception(this, Qt::ArrowCursor); activeScreen = effects->activeScreen(); if (!stop && !stopRequested) { effects->refTabBox(); effects->setActiveFullScreenEffect(this); scheduled_directions.clear(); selected_window = effects->currentTabBoxWindow(); currentWindowList = effects->currentTabBoxWindowList(); direction = Left; mActivated = true; if (animateStart) { start = true; } // Calculation of correct area area = effects->clientArea(FullScreenArea, activeScreen, effects->currentDesktop()); const QSize screenSize = effects->virtualScreenSize(); scaleFactor = (zPosition + 1100) * 2.0 * tan(60.0 * M_PI / 360.0f) / screenSize.width(); if (screenSize.width() - area.width() != 0) { // one of the screens is smaller than the other (horizontal) if (area.width() < screenSize.width() - area.width()) scaleFactor *= (float)area.width() / (float)(screenSize.width() - area.width()); else if (area.width() != screenSize.width() - area.width()) { // vertical layout with different width // but we don't want to catch screens with same width and different height if (screenSize.height() != area.height()) scaleFactor *= (float)area.width() / (float)(screenSize.width()); } } if (effects->numScreens() > 1) { // unfortunatelly we have to change the projection matrix in dual screen mode // code is adapted from SceneOpenGL2::createProjectionMatrix() QRect fullRect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); float fovy = 60.0f; float aspect = 1.0f; float zNear = 0.1f; float zFar = 100.0f; float ymax = zNear * std::tan(fovy * M_PI / 360.0f); float ymin = -ymax; float xmin = ymin * aspect; float xmax = ymax * aspect; if (area.width() != fullRect.width()) { if (area.x() == 0) { // horizontal layout: left screen xmin *= (float)area.width() / (float)fullRect.width(); xmax *= (fullRect.width() - 0.5f * area.width()) / (0.5f * fullRect.width()); } else { // horizontal layout: right screen xmin *= (fullRect.width() - 0.5f * area.width()) / (0.5f * fullRect.width()); xmax *= (float)area.width() / (float)fullRect.width(); } } if (area.height() != fullRect.height()) { if (area.y() == 0) { // vertical layout: top screen ymin *= (fullRect.height() - 0.5f * area.height()) / (0.5f * fullRect.height()); ymax *= (float)area.height() / (float)fullRect.height(); } else { // vertical layout: bottom screen ymin *= (float)area.height() / (float)fullRect.height(); ymax *= (fullRect.height() - 0.5f * area.height()) / (0.5f * fullRect.height()); } } m_projectionMatrix = QMatrix4x4(); m_projectionMatrix.frustum(xmin, xmax, ymin, ymax, zNear, zFar); const float scaleFactor = 1.1f / zNear; // Create a second matrix that transforms screen coordinates // to world coordinates. QMatrix4x4 matrix; matrix.translate(xmin * scaleFactor, ymax * scaleFactor, -1.1); matrix.scale( (xmax - xmin) * scaleFactor / fullRect.width(), -(ymax - ymin) * scaleFactor / fullRect.height(), 0.001); // Combine the matrices m_projectionMatrix *= matrix; m_modelviewMatrix = QMatrix4x4(); m_modelviewMatrix.translate(area.x(), area.y(), 0.0); } // Setup caption frame geometry if (windowTitle) { QRect frameRect = QRect(area.width() * 0.25f + area.x(), area.height() * 0.9f + area.y(), area.width() * 0.5f, QFontMetrics(captionFont).height()); if (!captionFrame) { captionFrame = effects->effectFrame(EffectFrameStyled); captionFrame->setFont(captionFont); captionFrame->enableCrossFade(true); } captionFrame->setGeometry(frameRect); captionFrame->setIconSize(QSize(frameRect.height(), frameRect.height())); // And initial contents updateCaption(); } effects->addRepaintFull(); } else { startRequested = true; } } } } void CoverSwitchEffect::slotTabBoxClosed() { if (mActivated) { if (animateStop) { if (!animation && !start) { stop = true; } else if (start && scheduled_directions.isEmpty()) { start = false; stop = true; timeLine.setCurrentTime(timeLine.duration() - timeLine.currentValue()); } else { stopRequested = true; } } else effects->setActiveFullScreenEffect(0); mActivated = false; effects->unrefTabBox(); effects->stopMouseInterception(this); effects->addRepaintFull(); } } void CoverSwitchEffect::slotTabBoxUpdated() { if (mActivated) { if (animateSwitch && currentWindowList.count() > 1) { // determine the switch direction if (selected_window != effects->currentTabBoxWindow()) { if (selected_window != NULL) { int old_index = currentWindowList.indexOf(selected_window); int new_index = effects->currentTabBoxWindowList().indexOf(effects->currentTabBoxWindow()); Direction new_direction; int distance = new_index - old_index; if (distance > 0) new_direction = Left; if (distance < 0) new_direction = Right; if (effects->currentTabBoxWindowList().count() == 2) { new_direction = Left; distance = 1; } if (distance != 0) { distance = abs(distance); int tempDistance = effects->currentTabBoxWindowList().count() - distance; if (tempDistance < abs(distance)) { distance = tempDistance; if (new_direction == Left) new_direction = Right; else new_direction = Left; } if (!animation && !start) { animation = true; direction = new_direction; distance--; } for (int i = 0; i < distance; i++) { if (!scheduled_directions.isEmpty() && scheduled_directions.last() != new_direction) scheduled_directions.pop_back(); else scheduled_directions.enqueue(new_direction); if (scheduled_directions.count() == effects->currentTabBoxWindowList().count()) scheduled_directions.clear(); } } } selected_window = effects->currentTabBoxWindow(); currentWindowList = effects->currentTabBoxWindowList(); updateCaption(); } } effects->addRepaintFull(); } } void CoverSwitchEffect::paintWindowCover(EffectWindow* w, bool reflectedWindow, WindowPaintData& data) { QRect windowRect = w->geometry(); data.setYTranslation(area.height() - windowRect.y() - windowRect.height()); data.setZTranslation(-zPosition); if (start) { if (w->isMinimized()) { data.multiplyOpacity(timeLine.currentValue()); } else { const QVector3D translation = data.translation() * timeLine.currentValue(); data.setXTranslation(translation.x()); data.setYTranslation(translation.y()); data.setZTranslation(translation.z()); if (effects->numScreens() > 1) { QRect clientRect = effects->clientArea(FullScreenArea, w->screen(), effects->currentDesktop()); QRect fullRect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); if (w->screen() == activeScreen) { if (clientRect.width() != fullRect.width() && clientRect.x() != fullRect.x()) { data.translate(- clientRect.x() * (1.0f - timeLine.currentValue())); } if (clientRect.height() != fullRect.height() && clientRect.y() != fullRect.y()) { data.translate(0.0, - clientRect.y() * (1.0f - timeLine.currentValue())); } } else { if (clientRect.width() != fullRect.width() && clientRect.x() < area.x()) { data.translate(- clientRect.width() * (1.0f - timeLine.currentValue())); } if (clientRect.height() != fullRect.height() && clientRect.y() < area.y()) { data.translate(0.0, - clientRect.height() * (1.0f - timeLine.currentValue())); } } } data.setRotationAngle(data.rotationAngle() * timeLine.currentValue()); } } if (stop) { if (w->isMinimized() && w != effects->activeWindow()) { data.multiplyOpacity((1.0 - timeLine.currentValue())); } else { const QVector3D translation = data.translation() * (1.0 - timeLine.currentValue()); data.setXTranslation(translation.x()); data.setYTranslation(translation.y()); data.setZTranslation(translation.z()); if (effects->numScreens() > 1) { QRect clientRect = effects->clientArea(FullScreenArea, w->screen(), effects->currentDesktop()); QRect rect = effects->clientArea(FullScreenArea, activeScreen, effects->currentDesktop()); QRect fullRect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); if (w->screen() == activeScreen) { if (clientRect.width() != fullRect.width() && clientRect.x() != fullRect.x()) { data.translate(- clientRect.x() * timeLine.currentValue()); } if (clientRect.height() != fullRect.height() && clientRect.y() != fullRect.y()) { data.translate(0.0, - clientRect.y() * timeLine.currentValue()); } } else { if (clientRect.width() != fullRect.width() && clientRect.x() < rect.x()) { data.translate(- clientRect.width() * timeLine.currentValue()); } if (clientRect.height() != fullRect.height() && clientRect.y() < area.y()) { data.translate(0.0, - clientRect.height() * timeLine.currentValue()); } } } data.setRotationAngle(data.rotationAngle() * (1.0 - timeLine.currentValue())); } } if (reflectedWindow) { QMatrix4x4 reflectionMatrix; reflectionMatrix.scale(1.0, -1.0, 1.0); data.setModelViewMatrix(reflectionMatrix*data.modelViewMatrix()); data.setYTranslation(- area.height() - windowRect.y() - windowRect.height()); if (start) { data.multiplyOpacity(timeLine.currentValue()); } else if (stop) { data.multiplyOpacity(1.0 - timeLine.currentValue()); } effects->drawWindow(w, PAINT_WINDOW_TRANSFORMED, infiniteRegion(), data); } else { effects->paintWindow(w, PAINT_WINDOW_TRANSFORMED, infiniteRegion(), data); } } void CoverSwitchEffect::paintFrontWindow(EffectWindow* frontWindow, int width, int leftWindows, int rightWindows, bool reflectedWindow) { if (frontWindow == NULL) return; bool specialHandlingForward = false; WindowPaintData data(frontWindow); if (effects->numScreens() > 1) { data.setProjectionMatrix(m_projectionMatrix); data.setModelViewMatrix(m_modelviewMatrix); } data.setXTranslation(area.width() * 0.5 - frontWindow->geometry().x() - frontWindow->geometry().width() * 0.5); if (leftWindows == 0) { leftWindows = 1; if (!start && !stop) specialHandlingForward = true; } if (rightWindows == 0) { rightWindows = 1; } if (animation) { float distance = 0.0; const QSize screenSize = effects->virtualScreenSize(); if (direction == Right) { // move to right distance = -frontWindow->geometry().width() * 0.5f + area.width() * 0.5f + (((float)screenSize.width() * 0.5 * scaleFactor) - (float)area.width() * 0.5f) / rightWindows; data.translate(distance * timeLine.currentValue()); data.setRotationAxis(Qt::YAxis); data.setRotationAngle(-angle * timeLine.currentValue()); data.setRotationOrigin(QVector3D(frontWindow->geometry().width(), 0.0, 0.0)); } else { // move to left distance = frontWindow->geometry().width() * 0.5f - area.width() * 0.5f + ((float)width * 0.5f - ((float)screenSize.width() * 0.5 * scaleFactor)) / leftWindows; float factor = 1.0; if (specialHandlingForward) factor = 2.0; data.translate(distance * timeLine.currentValue() * factor); data.setRotationAxis(Qt::YAxis); data.setRotationAngle(angle * timeLine.currentValue()); } } if (specialHandlingForward) { data.multiplyOpacity((1.0 - timeLine.currentValue() * 2.0)); paintWindowCover(frontWindow, reflectedWindow, data); } else paintWindowCover(frontWindow, reflectedWindow, data); } void CoverSwitchEffect::paintWindows(const EffectWindowList& windows, bool left, bool reflectedWindows, EffectWindow* additionalWindow) { int width = area.width(); int windowCount = windows.count(); EffectWindow* window; int rotateFactor = 1; if (!left) { rotateFactor = -1; } const QSize screenSize = effects->virtualScreenSize(); float xTranslate = -((float)(width) * 0.5f - ((float)screenSize.width() * 0.5 * scaleFactor)); if (!left) xTranslate = ((float)screenSize.width() * 0.5 * scaleFactor) - (float)width * 0.5f; // handling for additional window from other side // has to appear on this side after half of the time if (animation && timeLine.currentValue() >= 0.5 && additionalWindow != NULL) { WindowPaintData data(additionalWindow); if (effects->numScreens() > 1) { data.setProjectionMatrix(m_projectionMatrix); data.setModelViewMatrix(m_modelviewMatrix); } data.setRotationAxis(Qt::YAxis); data.setRotationAngle(angle * rotateFactor); if (left) { data.translate(-xTranslate - additionalWindow->geometry().x()); } else { data.translate(xTranslate + area.width() - additionalWindow->geometry().x() - additionalWindow->geometry().width()); data.setRotationOrigin(QVector3D(additionalWindow->geometry().width(), 0.0, 0.0)); } data.multiplyOpacity((timeLine.currentValue() - 0.5) * 2.0); paintWindowCover(additionalWindow, reflectedWindows, data); } // normal behaviour for (int i = 0; i < windows.count(); i++) { window = windows.at(i); if (window == NULL || window->isDeleted()) { continue; } WindowPaintData data(window); if (effects->numScreens() > 1) { data.setProjectionMatrix(m_projectionMatrix); data.setModelViewMatrix(m_modelviewMatrix); } data.setRotationAxis(Qt::YAxis); data.setRotationAngle(angle); if (left) data.translate(-xTranslate + xTranslate * i / windowCount - window->geometry().x()); else data.translate(xTranslate + width - xTranslate * i / windowCount - window->geometry().x() - window->geometry().width()); if (animation) { if (direction == Right) { if ((i == windowCount - 1) && left) { // right most window on left side -> move to front // have to move one window distance plus half the difference between the window and the desktop size data.translate((xTranslate / windowCount + (width - window->geometry().width()) * 0.5f) * timeLine.currentValue()); data.setRotationAngle(angle - angle * timeLine.currentValue()); } // right most window does not have to be moved else if (!left && (i == 0)); // do nothing else { // all other windows - move to next position data.translate(xTranslate / windowCount * timeLine.currentValue()); } } else { if ((i == windowCount - 1) && !left) { // left most window on right side -> move to front data.translate(- (xTranslate / windowCount + (width - window->geometry().width()) * 0.5f) * timeLine.currentValue()); data.setRotationAngle(angle - angle * timeLine.currentValue()); } // left most window does not have to be moved else if (i == 0 && left); // do nothing else { // all other windows - move to next position data.translate(- xTranslate / windowCount * timeLine.currentValue()); } } } if (!left) data.setRotationOrigin(QVector3D(window->geometry().width(), 0.0, 0.0)); data.setRotationAngle(data.rotationAngle() * rotateFactor); // make window most to edge transparent if animation if (animation && i == 0 && ((direction == Left && left) || (direction == Right && !left))) { // only for the first half of the animation if (timeLine.currentValue() < 0.5) { data.multiplyOpacity((1.0 - timeLine.currentValue() * 2.0)); paintWindowCover(window, reflectedWindows, data); } } else { paintWindowCover(window, reflectedWindows, data); } } } void CoverSwitchEffect::windowInputMouseEvent(QEvent* e) { if (e->type() != QEvent::MouseButtonPress) return; // we don't want click events during animations if (animation) return; QMouseEvent* event = static_cast< QMouseEvent* >(e); switch (event->button()) { case Qt::XButton1: // wheel up selectPreviousWindow(); break; case Qt::XButton2: // wheel down selectNextWindow(); break; case Qt::LeftButton: case Qt::RightButton: case Qt::MidButton: default: QPoint pos = event->pos(); // determine if a window has been clicked // not interested in events above a fullscreen window (ignoring panel size) if (pos.y() < (area.height()*scaleFactor - area.height()) * 0.5f *(1.0f / scaleFactor)) return; // if there is no selected window (that is no window at all) we cannot click it if (!selected_window) return; if (pos.x() < (area.width()*scaleFactor - selected_window->width()) * 0.5f *(1.0f / scaleFactor)) { float availableSize = (area.width() * scaleFactor - area.width()) * 0.5f * (1.0f / scaleFactor); for (int i = 0; i < leftWindows.count(); i++) { int windowPos = availableSize / leftWindows.count() * i; if (pos.x() < windowPos) continue; if (i + 1 < leftWindows.count()) { if (pos.x() > availableSize / leftWindows.count()*(i + 1)) continue; } effects->setTabBoxWindow(leftWindows[i]); return; } } if (pos.x() > area.width() - (area.width()*scaleFactor - selected_window->width()) * 0.5f *(1.0f / scaleFactor)) { float availableSize = (area.width() * scaleFactor - area.width()) * 0.5f * (1.0f / scaleFactor); for (int i = 0; i < rightWindows.count(); i++) { int windowPos = area.width() - availableSize / rightWindows.count() * i; if (pos.x() > windowPos) continue; if (i + 1 < rightWindows.count()) { if (pos.x() < area.width() - availableSize / rightWindows.count()*(i + 1)) continue; } effects->setTabBoxWindow(rightWindows[i]); return; } } break; } } void CoverSwitchEffect::abort() { // it's possible that abort is called after tabbox has been closed // in this case the cleanup is already done (see bug 207554) if (mActivated) { effects->unrefTabBox(); effects->stopMouseInterception(this); } effects->setActiveFullScreenEffect(0); mActivated = false; stop = false; stopRequested = false; effects->addRepaintFull(); captionFrame->free(); } void CoverSwitchEffect::slotWindowClosed(EffectWindow* c) { if (c == selected_window) selected_window = 0; // if the list is not empty, the effect is active if (!currentWindowList.isEmpty()) { c->refWindow(); referrencedWindows.append(c); currentWindowList.removeAll(c); leftWindows.removeAll(c); rightWindows.removeAll(c); } } bool CoverSwitchEffect::isActive() const { return (mActivated || stop || stopRequested) && !effects->isScreenLocked(); } void CoverSwitchEffect::updateCaption() { if (!selected_window || !windowTitle) { return; } if (selected_window->isDesktop()) { captionFrame->setText(i18nc("Special entry in alt+tab list for minimizing all windows", "Show Desktop")); static QPixmap pix = QIcon::fromTheme(QStringLiteral("user-desktop")).pixmap(captionFrame->iconSize()); captionFrame->setIcon(pix); } else { captionFrame->setText(selected_window->caption()); captionFrame->setIcon(selected_window->icon()); } } void CoverSwitchEffect::slotTabBoxKeyEvent(QKeyEvent *event) { if (event->type() == QEvent::KeyPress) { switch (event->key()) { case Qt::Key_Left: selectPreviousWindow(); break; case Qt::Key_Right: selectNextWindow(); break; default: // nothing break; } } } void CoverSwitchEffect::selectNextOrPreviousWindow(bool forward) { if (!mActivated || !selected_window) { return; } const int index = effects->currentTabBoxWindowList().indexOf(selected_window); int newIndex = index; if (forward) { ++newIndex; } else { --newIndex; } if (newIndex == effects->currentTabBoxWindowList().size()) { newIndex = 0; } else if (newIndex < 0) { newIndex = effects->currentTabBoxWindowList().size() -1; } if (index == newIndex) { return; } effects->setTabBoxWindow(effects->currentTabBoxWindowList().at(newIndex)); } } // namespace diff --git a/effects/coverswitch/coverswitch.h b/effects/coverswitch/coverswitch.h index 320c0521d..9b1e3482a 100644 --- a/effects/coverswitch/coverswitch.h +++ b/effects/coverswitch/coverswitch.h @@ -1,167 +1,168 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2008 Martin Gräßlin 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 . *********************************************************************/ #ifndef KWIN_COVERSWITCH_H #define KWIN_COVERSWITCH_H #include #include #include #include #include #include #include #include #include namespace KWin { class CoverSwitchEffect : public Effect { Q_OBJECT Q_PROPERTY(int animationDuration READ configuredAnimationDuration) Q_PROPERTY(bool animateSwitch READ isAnimateSwitch) Q_PROPERTY(bool animateStart READ isAnimateStart) Q_PROPERTY(bool animateStop READ isAnimateStop) Q_PROPERTY(bool reflection READ isReflection) Q_PROPERTY(bool windowTitle READ isWindowTitle) Q_PROPERTY(qreal zPosition READ windowZPosition) Q_PROPERTY(bool primaryTabBox READ isPrimaryTabBox) Q_PROPERTY(bool secondaryTabBox READ isSecondaryTabBox) // TODO: mirror colors public: CoverSwitchEffect(); ~CoverSwitchEffect(); virtual void reconfigure(ReconfigureFlags); virtual void prePaintScreen(ScreenPrePaintData& data, int time); virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); virtual void postPaintScreen(); virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); virtual void windowInputMouseEvent(QEvent* e); virtual bool isActive() const; static bool supported(); // for properties int configuredAnimationDuration() const { return animationDuration; } bool isAnimateSwitch() const { return animateSwitch; } bool isAnimateStart() const { return animateStart; } bool isAnimateStop() const { return animateStop; } bool isReflection() const { return reflection; } bool isWindowTitle() const { return windowTitle; } qreal windowZPosition() const { return zPosition; } bool isPrimaryTabBox() const { return primaryTabBox; } bool isSecondaryTabBox() const { return secondaryTabBox; } int requestedEffectChainPosition() const override { return 50; } public Q_SLOTS: void slotWindowClosed(KWin::EffectWindow *c); void slotTabBoxAdded(int mode); void slotTabBoxClosed(); void slotTabBoxUpdated(); void slotTabBoxKeyEvent(QKeyEvent* event); private: void paintScene(EffectWindow* frontWindow, const EffectWindowList& leftWindows, const EffectWindowList& rightWindows, bool reflectedWindows = false); void paintWindowCover(EffectWindow* w, bool reflectedWindow, WindowPaintData& data); void paintFrontWindow(EffectWindow* frontWindow, int width, int leftWindows, int rightWindows, bool reflectedWindow); void paintWindows(const EffectWindowList& windows, bool left, bool reflectedWindows, EffectWindow* additionalWindow = NULL); void selectNextOrPreviousWindow(bool forward); inline void selectNextWindow() { selectNextOrPreviousWindow(true); } inline void selectPreviousWindow() { selectNextOrPreviousWindow(false); } void abort(); /** * Updates the caption of the caption frame. * Taking care of rewording the desktop client. * As well sets the icon for the caption frame. **/ void updateCaption(); bool mActivated; float angle; bool animateSwitch; bool animateStart; bool animateStop; bool animation; bool start; bool stop; bool reflection; + bool multisampling; float mirrorColor[2][4]; bool windowTitle; int animationDuration; bool stopRequested; bool startRequested; QTimeLine timeLine; QRect area; float zPosition; float scaleFactor; enum Direction { Left, Right }; Direction direction; QQueue scheduled_directions; EffectWindow* selected_window; int activeScreen; QList< EffectWindow* > leftWindows; QList< EffectWindow* > rightWindows; EffectWindowList currentWindowList; EffectWindowList referrencedWindows; EffectFrame* captionFrame; QFont captionFont; bool primaryTabBox; bool secondaryTabBox; GLShader *m_reflectionShader; QMatrix4x4 m_projectionMatrix; QMatrix4x4 m_modelviewMatrix; }; } // namespace #endif diff --git a/effects/coverswitch/coverswitch.kcfg b/effects/coverswitch/coverswitch.kcfg index 77db6d29b..bd3e0ab3a 100644 --- a/effects/coverswitch/coverswitch.kcfg +++ b/effects/coverswitch/coverswitch.kcfg @@ -1,42 +1,45 @@ 0 true true true true QColor(0, 0, 0) QColor(0, 0, 0) true 900 false false + + true + diff --git a/effects/coverswitch/coverswitch_config.ui b/effects/coverswitch/coverswitch_config.ui index 982caf6d1..0fb6340f4 100644 --- a/effects/coverswitch/coverswitch_config.ui +++ b/effects/coverswitch/coverswitch_config.ui @@ -1,307 +1,314 @@ KWin::CoverSwitchEffectConfigForm 0 0 453 - 270 + 289 Display window &titles + + + + Use multisampling + + + Zoom Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter Define how far away the windows should appear 3000 100 500 Qt::Horizontal QSlider::TicksBelow 200 Near Qt::Horizontal 40 20 Far Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 0 0 0 Animation Animate switch Animation on tab box open Animation on tab box close - Animation duration: + A&nimation duration: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter kcfg_Duration 0 0 Default milliseconds 9999 10 Reflections Reflections QFormLayout::FieldsStayAtSizeHint Rear color Front color Qt::Vertical 20 0 KColorButton QPushButton
kcolorbutton.h
kcfg_Reflection toggled(bool) kcfg_MirrorFrontColor setEnabled(bool) 60 49 282 110 kcfg_Reflection toggled(bool) kcfg_MirrorRearColor setEnabled(bool) 102 51 284 72 kcfg_Reflection toggled(bool) label_2 setEnabled(bool) 136 47 202 78 kcfg_Reflection toggled(bool) label setEnabled(bool) 175 49 209 102
diff --git a/effects/cube/cube.cpp b/effects/cube/cube.cpp index 3e924511d..af29597bf 100644 --- a/effects/cube/cube.cpp +++ b/effects/cube/cube.cpp @@ -1,1921 +1,1924 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2008 Martin Gräßlin 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 . *********************************************************************/ #include "cube.h" // KConfigSkeleton #include "cubeconfig.h" #include "cube_inside.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace KWin { CubeEffect::CubeEffect() : activated(false) , cube_painting(false) , keyboard_grab(false) , schedule_close(false) , painting_desktop(1) , frontDesktop(0) , cubeOpacity(1.0) , opacityDesktopOnly(true) , displayDesktopName(false) , desktopNameFrame(NULL) , reflection(true) , rotating(false) , desktopChangedWhileRotating(false) , paintCaps(true) , rotationDirection(Left) , verticalRotationDirection(Upwards) , verticalPosition(Normal) , wallpaper(NULL) , texturedCaps(true) , capTexture(NULL) , manualAngle(0.0) , manualVerticalAngle(0.0) , currentShape(QTimeLine::EaseInOutCurve) , start(false) , stop(false) , reflectionPainting(false) , activeScreen(0) , bottomCap(false) , closeOnMouseRelease(false) , zoom(0.0) , zPosition(0.0) , useForTabBox(false) , tabBoxMode(false) , shortcutsRegistered(false) , mode(Cube) , useShaders(false) , cylinderShader(0) , sphereShader(0) , zOrderingFactor(0.0f) , mAddedHeightCoeff1(0.0f) , mAddedHeightCoeff2(0.0f) , m_cubeCapBuffer(NULL) , m_proxy(this) , m_cubeAction(new QAction(this)) , m_cylinderAction(new QAction(this)) , m_sphereAction(new QAction(this)) { initConfig(); desktopNameFont.setBold(true); desktopNameFont.setPointSize(14); if (effects->compositingType() == OpenGL2Compositing) { m_reflectionShader = ShaderManager::instance()->generateShaderFromResources(ShaderTrait::MapTexture, QString(), QStringLiteral("cube-reflection.glsl")); m_capShader = ShaderManager::instance()->generateShaderFromResources(ShaderTrait::MapTexture, QString(), QStringLiteral("cube-cap.glsl")); } else { m_reflectionShader = NULL; m_capShader = NULL; } m_textureMirrorMatrix.scale(1.0, -1.0, 1.0); m_textureMirrorMatrix.translate(0.0, -1.0, 0.0); connect(effects, SIGNAL(tabBoxAdded(int)), this, SLOT(slotTabBoxAdded(int))); connect(effects, SIGNAL(tabBoxClosed()), this, SLOT(slotTabBoxClosed())); connect(effects, SIGNAL(tabBoxUpdated()), this, SLOT(slotTabBoxUpdated())); reconfigure(ReconfigureAll); } bool CubeEffect::supported() { return effects->isOpenGLCompositing(); } void CubeEffect::reconfigure(ReconfigureFlags) { CubeConfig::self()->read(); foreach (ElectricBorder border, borderActivate) { effects->unreserveElectricBorder(border, this); } foreach (ElectricBorder border, borderActivateCylinder) { effects->unreserveElectricBorder(border, this); } foreach (ElectricBorder border, borderActivateSphere) { effects->unreserveElectricBorder(border, this); } borderActivate.clear(); borderActivateCylinder.clear(); borderActivateSphere.clear(); QList borderList = QList(); borderList.append(int(ElectricNone)); borderList = CubeConfig::borderActivate(); foreach (int i, borderList) { borderActivate.append(ElectricBorder(i)); effects->reserveElectricBorder(ElectricBorder(i), this); } borderList.clear(); borderList.append(int(ElectricNone)); borderList = CubeConfig::borderActivateCylinder(); foreach (int i, borderList) { borderActivateCylinder.append(ElectricBorder(i)); effects->reserveElectricBorder(ElectricBorder(i), this); } borderList.clear(); borderList.append(int(ElectricNone)); borderList = CubeConfig::borderActivateSphere(); foreach (int i, borderList) { borderActivateSphere.append(ElectricBorder(i)); effects->reserveElectricBorder(ElectricBorder(i), this); } cubeOpacity = (float)CubeConfig::opacity() / 100.0f; opacityDesktopOnly = CubeConfig::opacityDesktopOnly(); displayDesktopName = CubeConfig::displayDesktopName(); reflection = CubeConfig::reflection(); // TODO: rename rotationDuration to duration rotationDuration = animationTime(CubeConfig::rotationDuration() != 0 ? CubeConfig::rotationDuration() : 500); backgroundColor = CubeConfig::backgroundColor(); capColor = CubeConfig::capColor(); paintCaps = CubeConfig::caps(); + multisampling = CubeConfig::multisampling(); closeOnMouseRelease = CubeConfig::closeOnMouseRelease(); zPosition = CubeConfig::zPosition(); useForTabBox = CubeConfig::tabBox(); invertKeys = CubeConfig::invertKeys(); invertMouse = CubeConfig::invertMouse(); capDeformationFactor = (float)CubeConfig::capDeformation() / 100.0f; useZOrdering = CubeConfig::zOrdering(); delete wallpaper; wallpaper = NULL; delete capTexture; capTexture = NULL; texturedCaps = CubeConfig::texturedCaps(); timeLine.setCurveShape(QTimeLine::EaseInOutCurve); timeLine.setDuration(rotationDuration); verticalTimeLine.setCurveShape(QTimeLine::EaseInOutCurve); verticalTimeLine.setDuration(rotationDuration); // do not connect the shortcut if we use cylinder or sphere if (!shortcutsRegistered) { QAction* cubeAction = m_cubeAction; cubeAction->setObjectName(QStringLiteral("Cube")); cubeAction->setText(i18n("Desktop Cube")); KGlobalAccel::self()->setDefaultShortcut(cubeAction, QList() << Qt::CTRL + Qt::Key_F11); KGlobalAccel::self()->setShortcut(cubeAction, QList() << Qt::CTRL + Qt::Key_F11); effects->registerGlobalShortcut(Qt::CTRL + Qt::Key_F11, cubeAction); effects->registerPointerShortcut(Qt::ControlModifier | Qt::AltModifier, Qt::LeftButton, cubeAction); cubeShortcut = KGlobalAccel::self()->shortcut(cubeAction); QAction* cylinderAction = m_cylinderAction; cylinderAction->setObjectName(QStringLiteral("Cylinder")); cylinderAction->setText(i18n("Desktop Cylinder")); KGlobalAccel::self()->setShortcut(cylinderAction, QList()); effects->registerGlobalShortcut(QKeySequence(), cylinderAction); cylinderShortcut = KGlobalAccel::self()->shortcut(cylinderAction); QAction* sphereAction = m_sphereAction; sphereAction->setObjectName(QStringLiteral("Sphere")); sphereAction->setText(i18n("Desktop Sphere")); KGlobalAccel::self()->setShortcut(sphereAction, QList()); sphereShortcut = KGlobalAccel::self()->shortcut(sphereAction); effects->registerGlobalShortcut(QKeySequence(), sphereAction); connect(cubeAction, SIGNAL(triggered(bool)), this, SLOT(toggleCube())); connect(cylinderAction, SIGNAL(triggered(bool)), this, SLOT(toggleCylinder())); connect(sphereAction, SIGNAL(triggered(bool)), this, SLOT(toggleSphere())); connect(KGlobalAccel::self(), &KGlobalAccel::globalShortcutChanged, this, &CubeEffect::globalShortcutChanged); shortcutsRegistered = true; } // set the cap color on the shader if (m_capShader && m_capShader->isValid()) { ShaderBinder binder(m_capShader); m_capShader->setUniform(GLShader::Color, capColor); } // touch borders const QVector relevantBorders{ElectricLeft, ElectricTop, ElectricRight, ElectricBottom}; for (auto e : relevantBorders) { effects->unregisterTouchBorder(e, m_cubeAction); effects->unregisterTouchBorder(e, m_sphereAction); effects->unregisterTouchBorder(e, m_cylinderAction); } auto touchEdge = [&relevantBorders] (const QList touchBorders, QAction *action) { for (int i : touchBorders) { if (!relevantBorders.contains(ElectricBorder(i))) { continue; } effects->registerTouchBorder(ElectricBorder(i), action); } }; touchEdge(CubeConfig::touchBorderActivate(), m_cubeAction); touchEdge(CubeConfig::touchBorderActivateCylinder(), m_cylinderAction); touchEdge(CubeConfig::touchBorderActivateSphere(), m_sphereAction); } CubeEffect::~CubeEffect() { delete wallpaper; delete capTexture; delete cylinderShader; delete sphereShader; delete desktopNameFrame; delete m_reflectionShader; delete m_capShader; delete m_cubeCapBuffer; } QImage CubeEffect::loadCubeCap(const QString &capPath) { if (!texturedCaps) { return QImage(); } return QImage(capPath); } void CubeEffect::slotCubeCapLoaded() { QFutureWatcher *watcher = dynamic_cast*>(sender()); if (!watcher) { // not invoked from future watcher return; } QImage img = watcher->result(); if (!img.isNull()) { effects->makeOpenGLContextCurrent(); capTexture = new GLTexture(img); capTexture->setFilter(GL_LINEAR); if (!GLPlatform::instance()->isGLES()) { capTexture->setWrapMode(GL_CLAMP_TO_BORDER); } // need to recreate the VBO for the cube cap delete m_cubeCapBuffer; m_cubeCapBuffer = NULL; effects->addRepaintFull(); } watcher->deleteLater(); } QImage CubeEffect::loadWallPaper(const QString &file) { return QImage(file); } void CubeEffect::slotWallPaperLoaded() { QFutureWatcher *watcher = dynamic_cast*>(sender()); if (!watcher) { // not invoked from future watcher return; } QImage img = watcher->result(); if (!img.isNull()) { effects->makeOpenGLContextCurrent(); wallpaper = new GLTexture(img); effects->addRepaintFull(); } watcher->deleteLater(); } bool CubeEffect::loadShader() { effects->makeOpenGLContextCurrent(); if (!(GLPlatform::instance()->supports(GLSL) && (effects->compositingType() == OpenGL2Compositing))) return false; cylinderShader = ShaderManager::instance()->generateShaderFromResources(ShaderTrait::MapTexture | ShaderTrait::AdjustSaturation | ShaderTrait::Modulate, QStringLiteral("cylinder.vert"), QString()); if (!cylinderShader->isValid()) { qCCritical(KWINEFFECTS) << "The cylinder shader failed to load!"; return false; } else { ShaderBinder binder(cylinderShader); cylinderShader->setUniform("sampler", 0); QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); cylinderShader->setUniform("width", (float)rect.width() * 0.5f); } sphereShader = ShaderManager::instance()->generateShaderFromResources(ShaderTrait::MapTexture | ShaderTrait::AdjustSaturation | ShaderTrait::Modulate, QStringLiteral("sphere.vert"), QString()); if (!sphereShader->isValid()) { qCCritical(KWINEFFECTS) << "The sphere shader failed to load!"; return false; } else { ShaderBinder binder(sphereShader); sphereShader->setUniform("sampler", 0); QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); sphereShader->setUniform("width", (float)rect.width() * 0.5f); sphereShader->setUniform("height", (float)rect.height() * 0.5f); sphereShader->setUniform("u_offset", QVector2D(0, 0)); } return true; } void CubeEffect::prePaintScreen(ScreenPrePaintData& data, int time) { if (activated) { data.mask |= PAINT_SCREEN_TRANSFORMED | Effect::PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS | PAINT_SCREEN_BACKGROUND_FIRST; - + if (multisampling) { + data.mask |= PAINT_SCREEN_MULTISAMPLE; + } if (rotating || start || stop) { timeLine.setCurrentTime(timeLine.currentTime() + time); rotateCube(); } if (verticalRotating) { verticalTimeLine.setCurrentTime(verticalTimeLine.currentTime() + time); rotateCube(); } } effects->prePaintScreen(data, time); } void CubeEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) { if (activated) { QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); // background float clearColor[4]; glGetFloatv(GL_COLOR_CLEAR_VALUE, clearColor); glClearColor(backgroundColor.redF(), backgroundColor.greenF(), backgroundColor.blueF(), 1.0); glClear(GL_COLOR_BUFFER_BIT); glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); // wallpaper if (wallpaper) { ShaderBinder binder(ShaderTrait::MapTexture); binder.shader()->setUniform(GLShader::ModelViewProjectionMatrix, data.projectionMatrix()); wallpaper->bind(); wallpaper->render(region, rect); wallpaper->unbind(); } glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // some veriables needed for painting the caps float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2) / (float)effects->numberOfDesktops() * 180.0f); float point = rect.width() / 2 * tan(cubeAngle * 0.5f * M_PI / 180.0f); float zTranslate = zPosition + zoom; if (start) zTranslate *= timeLine.currentValue(); if (stop) zTranslate *= (1.0 - timeLine.currentValue()); // reflection if (reflection && mode != Sphere) { // we can use a huge scale factor (needed to calculate the rearground vertices) float scaleFactor = 1000000 * tan(60.0 * M_PI / 360.0f) / rect.height(); m_reflectionMatrix.setToIdentity(); m_reflectionMatrix.scale(1.0, -1.0, 1.0); // TODO reflection is not correct when mixing manual (mouse) rotating with rotation by cursor keys // there's also a small bug when zooming float addedHeight1 = -sin(asin(float(rect.height()) / mAddedHeightCoeff1) + fabs(manualVerticalAngle) * M_PI / 180.0f) * mAddedHeightCoeff1; float addedHeight2 = -sin(asin(float(rect.height()) / mAddedHeightCoeff2) + fabs(manualVerticalAngle) * M_PI / 180.0f) * mAddedHeightCoeff2 - addedHeight1; if (manualVerticalAngle > 0.0f && effects->numberOfDesktops() & 1) { m_reflectionMatrix.translate(0.0, cos(fabs(manualAngle) * M_PI / 360.0f * float(effects->numberOfDesktops())) * addedHeight2 + addedHeight1 - float(rect.height()), 0.0); } else { m_reflectionMatrix.translate(0.0, sin(fabs(manualAngle) * M_PI / 360.0f * float(effects->numberOfDesktops())) * addedHeight2 + addedHeight1 - float(rect.height()), 0.0); } reflectionPainting = true; glEnable(GL_CULL_FACE); paintCap(true, -point - zTranslate, data.projectionMatrix()); // cube glCullFace(GL_BACK); paintCube(mask, region, data); glCullFace(GL_FRONT); paintCube(mask, region, data); paintCap(false, -point - zTranslate, data.projectionMatrix()); glDisable(GL_CULL_FACE); reflectionPainting = false; const float width = rect.width(); const float height = rect.height(); float vertices[] = { -width * 0.5f, height, 0.0, width * 0.5f, height, 0.0, width * scaleFactor, height, -5000, -width * scaleFactor, height, -5000 }; // foreground float alpha = 0.7; if (start) alpha = 0.3 + 0.4 * timeLine.currentValue(); if (stop) alpha = 0.3 + 0.4 * (1.0 - timeLine.currentValue()); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if (m_reflectionShader && m_reflectionShader->isValid()) { // ensure blending is enabled - no attribute stack ShaderBinder binder(m_reflectionShader); QMatrix4x4 windowTransformation = data.projectionMatrix(); windowTransformation.translate(rect.x() + rect.width() * 0.5f, 0.0, 0.0); m_reflectionShader->setUniform(GLShader::ModelViewProjectionMatrix, windowTransformation); m_reflectionShader->setUniform("u_alpha", alpha); QVector verts; QVector texcoords; verts.reserve(18); texcoords.reserve(12); texcoords << 0.0 << 0.0; verts << vertices[6] << vertices[7] << vertices[8]; texcoords << 0.0 << 0.0; verts << vertices[9] << vertices[10] << vertices[11]; texcoords << 1.0 << 0.0; verts << vertices[0] << vertices[1] << vertices[2]; texcoords << 1.0 << 0.0; verts << vertices[0] << vertices[1] << vertices[2]; texcoords << 1.0 << 0.0; verts << vertices[3] << vertices[4] << vertices[5]; texcoords << 0.0 << 0.0; verts << vertices[6] << vertices[7] << vertices[8]; GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); vbo->setData(6, 3, verts.data(), texcoords.data()); vbo->render(GL_TRIANGLES); } glDisable(GL_BLEND); } glEnable(GL_CULL_FACE); // caps paintCap(false, -point - zTranslate, data.projectionMatrix()); // cube glCullFace(GL_FRONT); paintCube(mask, region, data); glCullFace(GL_BACK); paintCube(mask, region, data); // cap paintCap(true, -point - zTranslate, data.projectionMatrix()); glDisable(GL_CULL_FACE); glDisable(GL_BLEND); // desktop name box - inspired from coverswitch if (displayDesktopName) { double opacity = 1.0; if (start) opacity = timeLine.currentValue(); if (stop) opacity = 1.0 - timeLine.currentValue(); QRect screenRect = effects->clientArea(ScreenArea, activeScreen, frontDesktop); QRect frameRect = QRect(screenRect.width() * 0.33f + screenRect.x(), screenRect.height() * 0.95f + screenRect.y(), screenRect.width() * 0.34f, QFontMetrics(desktopNameFont).height()); if (!desktopNameFrame) { desktopNameFrame = effects->effectFrame(EffectFrameStyled); desktopNameFrame->setFont(desktopNameFont); } desktopNameFrame->setGeometry(frameRect); desktopNameFrame->setText(effects->desktopName(frontDesktop)); desktopNameFrame->render(region, opacity); } } else { effects->paintScreen(mask, region, data); } } void CubeEffect::rotateCube() { QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); m_rotationMatrix.setToIdentity(); float internalCubeAngle = 360.0f / effects->numberOfDesktops(); float zTranslate = zPosition + zoom; if (start) zTranslate *= timeLine.currentValue(); if (stop) zTranslate *= (1.0 - timeLine.currentValue()); // Rotation of the cube float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2) / (float)effects->numberOfDesktops() * 180.0f); float point = rect.width() / 2 * tan(cubeAngle * 0.5f * M_PI / 180.0f); if (verticalRotating || verticalPosition != Normal || manualVerticalAngle != 0.0) { // change the verticalPosition if manualVerticalAngle > 90 or < -90 degrees if (manualVerticalAngle <= -90.0) { manualVerticalAngle += 90.0; if (verticalPosition == Normal) verticalPosition = Down; if (verticalPosition == Up) verticalPosition = Normal; } if (manualVerticalAngle >= 90.0) { manualVerticalAngle -= 90.0; if (verticalPosition == Normal) verticalPosition = Up; if (verticalPosition == Down) verticalPosition = Normal; } float angle = 0.0; if (verticalPosition == Up) { angle = 90.0; if (!verticalRotating) { if (manualVerticalAngle < 0.0) angle += manualVerticalAngle; else manualVerticalAngle = 0.0; } } else if (verticalPosition == Down) { angle = -90.0; if (!verticalRotating) { if (manualVerticalAngle > 0.0) angle += manualVerticalAngle; else manualVerticalAngle = 0.0; } } else { angle = manualVerticalAngle; } if (verticalRotating) { angle *= verticalTimeLine.currentValue(); if (verticalPosition == Normal && verticalRotationDirection == Upwards) angle = -90.0 + 90 * verticalTimeLine.currentValue(); if (verticalPosition == Normal && verticalRotationDirection == Downwards) angle = 90.0 - 90 * verticalTimeLine.currentValue(); angle += manualVerticalAngle * (1.0 - verticalTimeLine.currentValue()); } if (stop) angle *= (1.0 - timeLine.currentValue()); m_rotationMatrix.translate(rect.width() / 2, rect.height() / 2, -point - zTranslate); m_rotationMatrix.rotate(angle, 1.0, 0.0, 0.0); m_rotationMatrix.translate(-rect.width() / 2, -rect.height() / 2, point + zTranslate); } if (rotating || (manualAngle != 0.0)) { int tempFrontDesktop = frontDesktop; if (manualAngle > internalCubeAngle * 0.5f) { manualAngle -= internalCubeAngle; tempFrontDesktop--; if (tempFrontDesktop == 0) tempFrontDesktop = effects->numberOfDesktops(); } if (manualAngle < -internalCubeAngle * 0.5f) { manualAngle += internalCubeAngle; tempFrontDesktop++; if (tempFrontDesktop > effects->numberOfDesktops()) tempFrontDesktop = 1; } float rotationAngle = internalCubeAngle * timeLine.currentValue(); if (rotationAngle > internalCubeAngle * 0.5f) { rotationAngle -= internalCubeAngle; if (!desktopChangedWhileRotating) { desktopChangedWhileRotating = true; if (rotationDirection == Left) { tempFrontDesktop++; } else if (rotationDirection == Right) { tempFrontDesktop--; } if (tempFrontDesktop > effects->numberOfDesktops()) tempFrontDesktop = 1; else if (tempFrontDesktop == 0) tempFrontDesktop = effects->numberOfDesktops(); } } // don't change front desktop during stop animation as this would break some logic if (!stop) frontDesktop = tempFrontDesktop; if (rotationDirection == Left) { rotationAngle *= -1; } if (stop) rotationAngle = manualAngle * (1.0 - timeLine.currentValue()); else rotationAngle += manualAngle * (1.0 - timeLine.currentValue()); m_rotationMatrix.translate(rect.width() / 2, rect.height() / 2, -point - zTranslate); m_rotationMatrix.rotate(rotationAngle, 0.0, 1.0, 0.0); m_rotationMatrix.translate(-rect.width() / 2, -rect.height() / 2, point + zTranslate); } } void CubeEffect::paintCube(int mask, QRegion region, ScreenPaintData& data) { QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); float internalCubeAngle = 360.0f / effects->numberOfDesktops(); cube_painting = true; float zTranslate = zPosition + zoom; if (start) zTranslate *= timeLine.currentValue(); if (stop) zTranslate *= (1.0 - timeLine.currentValue()); // Rotation of the cube float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2) / (float)effects->numberOfDesktops() * 180.0f); float point = rect.width() / 2 * tan(cubeAngle * 0.5f * M_PI / 180.0f); for (int i = 0; i < effects->numberOfDesktops(); i++) { // start painting the cube painting_desktop = (i + frontDesktop) % effects->numberOfDesktops(); if (painting_desktop == 0) { painting_desktop = effects->numberOfDesktops(); } QMatrix4x4 matrix; matrix.translate(0, 0, -zTranslate); const QVector3D origin(rect.width() / 2, 0.0, -point); matrix.translate(origin); matrix.rotate(internalCubeAngle * i, 0, 1, 0); matrix.translate(-origin); m_currentFaceMatrix = matrix; effects->paintScreen(mask, region, data); } cube_painting = false; painting_desktop = effects->currentDesktop(); } void CubeEffect::paintCap(bool frontFirst, float zOffset, const QMatrix4x4 &projection) { if ((!paintCaps) || effects->numberOfDesktops() <= 2) return; GLenum firstCull = frontFirst ? GL_FRONT : GL_BACK; GLenum secondCull = frontFirst ? GL_BACK : GL_FRONT; const QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); // create the VBO if not yet created if (!m_cubeCapBuffer) { switch(mode) { case Cube: paintCubeCap(); break; case Cylinder: paintCylinderCap(); break; case Sphere: paintSphereCap(); break; default: // impossible break; } } QMatrix4x4 capMvp; QMatrix4x4 capMatrix; capMatrix.translate(rect.width() / 2, 0.0, zOffset); capMatrix.rotate((1 - frontDesktop) * 360.0f / effects->numberOfDesktops(), 0.0, 1.0, 0.0); capMatrix.translate(0.0, rect.height(), 0.0); if (mode == Sphere) { capMatrix.scale(1.0, -1.0, 1.0); } bool capShader = false; if (effects->compositingType() == OpenGL2Compositing && m_capShader && m_capShader->isValid()) { capShader = true; ShaderManager::instance()->pushShader(m_capShader); float opacity = cubeOpacity; if (start) { opacity *= timeLine.currentValue(); } else if (stop) { opacity *= (1.0 - timeLine.currentValue()); } m_capShader->setUniform("u_opacity", opacity); m_capShader->setUniform("u_mirror", 1); if (reflectionPainting) { capMvp = projection * m_reflectionMatrix * m_rotationMatrix; } else { capMvp = projection * m_rotationMatrix; } m_capShader->setUniform(GLShader::ModelViewProjectionMatrix, capMvp * capMatrix); m_capShader->setUniform("u_untextured", texturedCaps ? 0 : 1); if (texturedCaps && effects->numberOfDesktops() > 3 && capTexture) { capTexture->bind(); } } glEnable(GL_BLEND); glCullFace(firstCull); m_cubeCapBuffer->render(GL_TRIANGLES); if (mode == Sphere) { capMatrix.scale(1.0, -1.0, 1.0); } capMatrix.translate(0.0, -rect.height(), 0.0); if (capShader) { m_capShader->setUniform(GLShader::ModelViewProjectionMatrix, capMvp * capMatrix); m_capShader->setUniform("u_mirror", 0); } glCullFace(secondCull); m_cubeCapBuffer->render(GL_TRIANGLES); glDisable(GL_BLEND); if (capShader) { ShaderManager::instance()->popShader(); if (texturedCaps && effects->numberOfDesktops() > 3 && capTexture) { capTexture->unbind(); } } } void CubeEffect::paintCubeCap() { QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2) / (float)effects->numberOfDesktops() * 180.0f); float z = rect.width() / 2 * tan(cubeAngle * 0.5f * M_PI / 180.0f); float zTexture = rect.width() / 2 * tan(45.0f * M_PI / 180.0f); float angle = 360.0f / effects->numberOfDesktops(); bool texture = texturedCaps && effects->numberOfDesktops() > 3 && capTexture; QVector verts; QVector texCoords; for (int i = 0; i < effects->numberOfDesktops(); i++) { int triangleRows = effects->numberOfDesktops() * 5; float zTriangleDistance = z / (float)triangleRows; float widthTriangle = tan(angle * 0.5 * M_PI / 180.0) * zTriangleDistance; float currentWidth = 0.0; float cosValue = cos(i * angle * M_PI / 180.0); float sinValue = sin(i * angle * M_PI / 180.0); for (int j = 0; j < triangleRows; j++) { float previousWidth = currentWidth; currentWidth = tan(angle * 0.5 * M_PI / 180.0) * zTriangleDistance * (j + 1); int evenTriangles = 0; int oddTriangles = 0; for (int k = 0; k < floor(currentWidth / widthTriangle * 2 - 1 + 0.5f); k++) { float x1 = -previousWidth; float x2 = -currentWidth; float x3 = 0.0; float z1 = 0.0; float z2 = 0.0; float z3 = 0.0; if (k % 2 == 0) { x1 += evenTriangles * widthTriangle * 2; x2 += evenTriangles * widthTriangle * 2; x3 = x2 + widthTriangle * 2; z1 = j * zTriangleDistance; z2 = (j + 1) * zTriangleDistance; z3 = (j + 1) * zTriangleDistance; float xRot = cosValue * x1 - sinValue * z1; float zRot = sinValue * x1 + cosValue * z1; x1 = xRot; z1 = zRot; xRot = cosValue * x2 - sinValue * z2; zRot = sinValue * x2 + cosValue * z2; x2 = xRot; z2 = zRot; xRot = cosValue * x3 - sinValue * z3; zRot = sinValue * x3 + cosValue * z3; x3 = xRot; z3 = zRot; evenTriangles++; } else { x1 += oddTriangles * widthTriangle * 2; x2 += (oddTriangles + 1) * widthTriangle * 2; x3 = x1 + widthTriangle * 2; z1 = j * zTriangleDistance; z2 = (j + 1) * zTriangleDistance; z3 = j * zTriangleDistance; float xRot = cosValue * x1 - sinValue * z1; float zRot = sinValue * x1 + cosValue * z1; x1 = xRot; z1 = zRot; xRot = cosValue * x2 - sinValue * z2; zRot = sinValue * x2 + cosValue * z2; x2 = xRot; z2 = zRot; xRot = cosValue * x3 - sinValue * z3; zRot = sinValue * x3 + cosValue * z3; x3 = xRot; z3 = zRot; oddTriangles++; } float texX1 = 0.0; float texX2 = 0.0; float texX3 = 0.0; float texY1 = 0.0; float texY2 = 0.0; float texY3 = 0.0; if (texture) { if (capTexture->isYInverted()) { texX1 = x1 / (rect.width()) + 0.5; texY1 = 0.5 + z1 / zTexture * 0.5; texX2 = x2 / (rect.width()) + 0.5; texY2 = 0.5 + z2 / zTexture * 0.5; texX3 = x3 / (rect.width()) + 0.5; texY3 = 0.5 + z3 / zTexture * 0.5; texCoords << texX1 << texY1; } else { texX1 = x1 / (rect.width()) + 0.5; texY1 = 0.5 - z1 / zTexture * 0.5; texX2 = x2 / (rect.width()) + 0.5; texY2 = 0.5 - z2 / zTexture * 0.5; texX3 = x3 / (rect.width()) + 0.5; texY3 = 0.5 - z3 / zTexture * 0.5; texCoords << texX1 << texY1; } } verts << x1 << 0.0 << z1; if (texture) { texCoords << texX2 << texY2; } verts << x2 << 0.0 << z2; if (texture) { texCoords << texX3 << texY3; } verts << x3 << 0.0 << z3; } } } delete m_cubeCapBuffer; m_cubeCapBuffer = new GLVertexBuffer(GLVertexBuffer::Static); m_cubeCapBuffer->setData(verts.count() / 3, 3, verts.constData(), texture ? texCoords.constData() : NULL); } void CubeEffect::paintCylinderCap() { QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2) / (float)effects->numberOfDesktops() * 180.0f); float radian = (cubeAngle * 0.5) * M_PI / 180; float radius = (rect.width() * 0.5) * tan(radian); float segment = radius / 30.0f; bool texture = texturedCaps && effects->numberOfDesktops() > 3 && capTexture; QVector verts; QVector texCoords; for (int i = 1; i <= 30; i++) { int steps = 72; for (int j = 0; j <= steps; j++) { const float azimuthAngle = (j * (360.0f / steps)) * M_PI / 180.0f; const float azimuthAngle2 = ((j + 1) * (360.0f / steps)) * M_PI / 180.0f; const float x1 = segment * (i - 1) * sin(azimuthAngle); const float x2 = segment * i * sin(azimuthAngle); const float x3 = segment * (i - 1) * sin(azimuthAngle2); const float x4 = segment * i * sin(azimuthAngle2); const float z1 = segment * (i - 1) * cos(azimuthAngle); const float z2 = segment * i * cos(azimuthAngle); const float z3 = segment * (i - 1) * cos(azimuthAngle2); const float z4 = segment * i * cos(azimuthAngle2); if (texture) { if (capTexture->isYInverted()) { texCoords << (radius + x1) / (radius * 2.0f) << (z1 + radius) / (radius * 2.0f); texCoords << (radius + x2) / (radius * 2.0f) << (z2 + radius) / (radius * 2.0f); texCoords << (radius + x3) / (radius * 2.0f) << (z3 + radius) / (radius * 2.0f); texCoords << (radius + x4) / (radius * 2.0f) << (z4 + radius) / (radius * 2.0f); texCoords << (radius + x3) / (radius * 2.0f) << (z3 + radius) / (radius * 2.0f); texCoords << (radius + x2) / (radius * 2.0f) << (z2 + radius) / (radius * 2.0f); } else { texCoords << (radius + x1) / (radius * 2.0f) << 1.0f - (z1 + radius) / (radius * 2.0f); texCoords << (radius + x2) / (radius * 2.0f) << 1.0f - (z2 + radius) / (radius * 2.0f); texCoords << (radius + x3) / (radius * 2.0f) << 1.0f - (z3 + radius) / (radius * 2.0f); texCoords << (radius + x4) / (radius * 2.0f) << 1.0f - (z4 + radius) / (radius * 2.0f); texCoords << (radius + x3) / (radius * 2.0f) << 1.0f - (z3 + radius) / (radius * 2.0f); texCoords << (radius + x2) / (radius * 2.0f) << 1.0f - (z2 + radius) / (radius * 2.0f); } } verts << x1 << 0.0 << z1; verts << x2 << 0.0 << z2; verts << x3 << 0.0 << z3; verts << x4 << 0.0 << z4; verts << x3 << 0.0 << z3; verts << x2 << 0.0 << z2; } } delete m_cubeCapBuffer; m_cubeCapBuffer = new GLVertexBuffer(GLVertexBuffer::Static); m_cubeCapBuffer->setData(verts.count() / 3, 3, verts.constData(), texture ? texCoords.constData() : NULL); } void CubeEffect::paintSphereCap() { QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2) / (float)effects->numberOfDesktops() * 180.0f); float zTexture = rect.width() / 2 * tan(45.0f * M_PI / 180.0f); float radius = (rect.width() * 0.5) / cos(cubeAngle * 0.5 * M_PI / 180.0); float angle = acos((rect.height() * 0.5) / radius) * 180.0 / M_PI; angle /= 30; bool texture = texturedCaps && effects->numberOfDesktops() > 3 && capTexture; QVector verts; QVector texCoords; for (int i = 0; i < 30; i++) { float topAngle = angle * i * M_PI / 180.0; float bottomAngle = angle * (i + 1) * M_PI / 180.0; float yTop = rect.height() * 0.5 - radius * cos(topAngle); yTop -= (yTop - rect.height() * 0.5) * capDeformationFactor; float yBottom = rect.height() * 0.5 - radius * cos(bottomAngle); yBottom -= (yBottom - rect.height() * 0.5) * capDeformationFactor; for (int j = 0; j < 36; j++) { const float x1 = radius * sin(topAngle) * sin((90.0 + j * 10.0) * M_PI / 180.0); const float z1 = radius * sin(topAngle) * cos((90.0 + j * 10.0) * M_PI / 180.0); const float x2 = radius * sin(bottomAngle) * sin((90.0 + j * 10.0) * M_PI / 180.00); const float z2 = radius * sin(bottomAngle) * cos((90.0 + j * 10.0) * M_PI / 180.0); const float x3 = radius * sin(bottomAngle) * sin((90.0 + (j + 1) * 10.0) * M_PI / 180.0); const float z3 = radius * sin(bottomAngle) * cos((90.0 + (j + 1) * 10.0) * M_PI / 180.0); const float x4 = radius * sin(topAngle) * sin((90.0 + (j + 1) * 10.0) * M_PI / 180.0); const float z4 = radius * sin(topAngle) * cos((90.0 + (j + 1) * 10.0) * M_PI / 180.0); if (texture) { if (capTexture->isYInverted()) { texCoords << x4 / (rect.width()) + 0.5 << 0.5 + z4 / zTexture * 0.5; texCoords << x1 / (rect.width()) + 0.5 << 0.5 + z1 / zTexture * 0.5; texCoords << x2 / (rect.width()) + 0.5 << 0.5 + z2 / zTexture * 0.5; texCoords << x2 / (rect.width()) + 0.5 << 0.5 + z2 / zTexture * 0.5; texCoords << x3 / (rect.width()) + 0.5 << 0.5 + z3 / zTexture * 0.5; texCoords << x4 / (rect.width()) + 0.5 << 0.5 + z4 / zTexture * 0.5; } else { texCoords << x4 / (rect.width()) + 0.5 << 0.5 - z4 / zTexture * 0.5; texCoords << x1 / (rect.width()) + 0.5 << 0.5 - z1 / zTexture * 0.5; texCoords << x2 / (rect.width()) + 0.5 << 0.5 - z2 / zTexture * 0.5; texCoords << x2 / (rect.width()) + 0.5 << 0.5 - z2 / zTexture * 0.5; texCoords << x3 / (rect.width()) + 0.5 << 0.5 - z3 / zTexture * 0.5; texCoords << x4 / (rect.width()) + 0.5 << 0.5 - z4 / zTexture * 0.5; } } verts << x4 << yTop << z4; verts << x1 << yTop << z1; verts << x2 << yBottom << z2; verts << x2 << yBottom << z2; verts << x3 << yBottom << z3; verts << x4 << yTop << z4; } } delete m_cubeCapBuffer; m_cubeCapBuffer = new GLVertexBuffer(GLVertexBuffer::Static); m_cubeCapBuffer->setData(verts.count() / 3, 3, verts.constData(), texture ? texCoords.constData() : NULL); } void CubeEffect::postPaintScreen() { effects->postPaintScreen(); if (activated) { if (start) { if (timeLine.currentValue() == 1.0) { start = false; timeLine.setCurrentTime(0); // more rotations? if (!rotations.empty()) { rotationDirection = rotations.dequeue(); rotating = true; // change the curve shape if current shape is not easeInOut if (currentShape != QTimeLine::EaseInOutCurve) { // more rotations follow -> linear curve if (!rotations.empty()) { currentShape = QTimeLine::LinearCurve; } // last rotation step -> easeOut curve else { currentShape = QTimeLine::EaseOutCurve; } timeLine.setCurveShape(currentShape); } else { // if there is at least one more rotation, we can change to easeIn if (!rotations.empty()) { currentShape = QTimeLine::EaseInCurve; timeLine.setCurveShape(currentShape); } } } } effects->addRepaintFull(); return; // schedule_close could have been called, start has to finish first } if (stop) { if (timeLine.currentValue() == 1.0) { effects->setCurrentDesktop(frontDesktop); stop = false; timeLine.setCurrentTime(0); activated = false; // set the new desktop if (keyboard_grab) effects->ungrabKeyboard(); keyboard_grab = false; effects->stopMouseInterception(this); effects->setActiveFullScreenEffect(0); delete m_cubeCapBuffer; m_cubeCapBuffer = NULL; if (desktopNameFrame) desktopNameFrame->free(); } effects->addRepaintFull(); } if (rotating || verticalRotating) { if (rotating && timeLine.currentValue() == 1.0) { timeLine.setCurrentTime(0.0); rotating = false; desktopChangedWhileRotating = false; manualAngle = 0.0; // more rotations? if (!rotations.empty()) { rotationDirection = rotations.dequeue(); rotating = true; // change the curve shape if current shape is not easeInOut if (currentShape != QTimeLine::EaseInOutCurve) { // more rotations follow -> linear curve if (!rotations.empty()) { currentShape = QTimeLine::LinearCurve; } // last rotation step -> easeOut curve else { currentShape = QTimeLine::EaseOutCurve; } timeLine.setCurveShape(currentShape); } else { // if there is at least one more rotation, we can change to easeIn if (!rotations.empty()) { currentShape = QTimeLine::EaseInCurve; timeLine.setCurveShape(currentShape); } } } else { // reset curve shape if there are no more rotations if (currentShape != QTimeLine::EaseInOutCurve) { currentShape = QTimeLine::EaseInOutCurve; timeLine.setCurveShape(currentShape); } } } if (verticalRotating && verticalTimeLine.currentValue() == 1.0) { verticalTimeLine.setCurrentTime(0); verticalRotating = false; manualVerticalAngle = 0.0; // more rotations? if (!verticalRotations.empty()) { verticalRotationDirection = verticalRotations.dequeue(); verticalRotating = true; if (verticalRotationDirection == Upwards) { if (verticalPosition == Normal) verticalPosition = Up; if (verticalPosition == Down) verticalPosition = Normal; } if (verticalRotationDirection == Downwards) { if (verticalPosition == Normal) verticalPosition = Down; if (verticalPosition == Up) verticalPosition = Normal; } } } effects->addRepaintFull(); return; // rotation has to end before cube is closed } if (schedule_close) { schedule_close = false; stop = true; effects->addRepaintFull(); } } } void CubeEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) { if (activated) { if (cube_painting) { if (mode == Cylinder || mode == Sphere) { int leftDesktop = frontDesktop - 1; int rightDesktop = frontDesktop + 1; if (leftDesktop == 0) leftDesktop = effects->numberOfDesktops(); if (rightDesktop > effects->numberOfDesktops()) rightDesktop = 1; if (painting_desktop == frontDesktop) data.quads = data.quads.makeGrid(40); else if (painting_desktop == leftDesktop || painting_desktop == rightDesktop) data.quads = data.quads.makeGrid(100); else data.quads = data.quads.makeGrid(250); } if (w->isOnDesktop(painting_desktop)) { QRect rect = effects->clientArea(FullArea, activeScreen, painting_desktop); if (w->x() < rect.x()) { data.quads = data.quads.splitAtX(-w->x()); } if (w->x() + w->width() > rect.x() + rect.width()) { data.quads = data.quads.splitAtX(rect.width() - w->x()); } if (w->y() < rect.y()) { data.quads = data.quads.splitAtY(-w->y()); } if (w->y() + w->height() > rect.y() + rect.height()) { data.quads = data.quads.splitAtY(rect.height() - w->y()); } if (useZOrdering && !w->isDesktop() && !w->isDock() && !w->isOnAllDesktops()) data.setTransformed(); w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } else { // check for windows belonging to the previous desktop int prev_desktop = painting_desktop - 1; if (prev_desktop == 0) prev_desktop = effects->numberOfDesktops(); if (w->isOnDesktop(prev_desktop) && mode == Cube && !useZOrdering) { QRect rect = effects->clientArea(FullArea, activeScreen, prev_desktop); if (w->x() + w->width() > rect.x() + rect.width()) { w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); data.quads = data.quads.splitAtX(rect.width() - w->x()); if (w->y() < rect.y()) { data.quads = data.quads.splitAtY(-w->y()); } if (w->y() + w->height() > rect.y() + rect.height()) { data.quads = data.quads.splitAtY(rect.height() - w->y()); } data.setTransformed(); effects->prePaintWindow(w, data, time); return; } } // check for windows belonging to the next desktop int next_desktop = painting_desktop + 1; if (next_desktop > effects->numberOfDesktops()) next_desktop = 1; if (w->isOnDesktop(next_desktop) && mode == Cube && !useZOrdering) { QRect rect = effects->clientArea(FullArea, activeScreen, next_desktop); if (w->x() < rect.x()) { w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); data.quads = data.quads.splitAtX(-w->x()); if (w->y() < rect.y()) { data.quads = data.quads.splitAtY(-w->y()); } if (w->y() + w->height() > rect.y() + rect.height()) { data.quads = data.quads.splitAtY(rect.height() - w->y()); } data.setTransformed(); effects->prePaintWindow(w, data, time); return; } } w->disablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } } } effects->prePaintWindow(w, data, time); } void CubeEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) { ShaderManager *shaderManager = ShaderManager::instance(); if (activated && cube_painting) { region= infiniteRegion(); // we need to explicitly prevent any clipping, bug #325432 //qCDebug(KWINEFFECTS) << w->caption(); float opacity = cubeOpacity; if (start) { opacity = 1.0 - (1.0 - opacity) * timeLine.currentValue(); if (reflectionPainting) opacity = 0.5 + (cubeOpacity - 0.5) * timeLine.currentValue(); // fade in windows belonging to different desktops if (painting_desktop == effects->currentDesktop() && (!w->isOnDesktop(painting_desktop))) opacity = timeLine.currentValue() * cubeOpacity; } if (stop) { opacity = 1.0 - (1.0 - opacity) * (1.0 - timeLine.currentValue()); if (reflectionPainting) opacity = 0.5 + (cubeOpacity - 0.5) * (1.0 - timeLine.currentValue()); // fade out windows belonging to different desktops if (painting_desktop == effects->currentDesktop() && (!w->isOnDesktop(painting_desktop))) opacity = cubeOpacity * (1.0 - timeLine.currentValue()); } // z-Ordering if (!w->isDesktop() && !w->isDock() && useZOrdering && !w->isOnAllDesktops()) { float zOrdering = (effects->stackingOrder().indexOf(w) + 1) * zOrderingFactor; if (start) zOrdering *= timeLine.currentValue(); if (stop) zOrdering *= (1.0 - timeLine.currentValue()); data.translate(0.0, 0.0, zOrdering); } // check for windows belonging to the previous desktop int prev_desktop = painting_desktop - 1; if (prev_desktop == 0) prev_desktop = effects->numberOfDesktops(); int next_desktop = painting_desktop + 1; if (next_desktop > effects->numberOfDesktops()) next_desktop = 1; if (w->isOnDesktop(prev_desktop) && (mask & PAINT_WINDOW_TRANSFORMED)) { QRect rect = effects->clientArea(FullArea, activeScreen, prev_desktop); WindowQuadList new_quads; foreach (const WindowQuad & quad, data.quads) { if (quad.right() > rect.width() - w->x()) { new_quads.append(quad); } } data.quads = new_quads; data.setXTranslation(-rect.width()); } if (w->isOnDesktop(next_desktop) && (mask & PAINT_WINDOW_TRANSFORMED)) { QRect rect = effects->clientArea(FullArea, activeScreen, next_desktop); WindowQuadList new_quads; foreach (const WindowQuad & quad, data.quads) { if (w->x() + quad.right() <= rect.x()) { new_quads.append(quad); } } data.quads = new_quads; data.setXTranslation(rect.width()); } QRect rect = effects->clientArea(FullArea, activeScreen, painting_desktop); if (start || stop) { // we have to change opacity values for fade in/out of windows which are shown on front-desktop if (prev_desktop == effects->currentDesktop() && w->x() < rect.x()) { if (start) opacity = timeLine.currentValue() * cubeOpacity; if (stop) opacity = cubeOpacity * (1.0 - timeLine.currentValue()); } if (next_desktop == effects->currentDesktop() && w->x() + w->width() > rect.x() + rect.width()) { if (start) opacity = timeLine.currentValue() * cubeOpacity; if (stop) opacity = cubeOpacity * (1.0 - timeLine.currentValue()); } } // HACK set opacity to 0.99 in case of fully opaque to ensure that windows are painted in correct sequence // bug #173214 if (opacity > 0.99f) opacity = 0.99f; if (opacityDesktopOnly && !w->isDesktop()) opacity = 0.99f; data.multiplyOpacity(opacity); if (w->isOnDesktop(painting_desktop) && w->x() < rect.x()) { WindowQuadList new_quads; foreach (const WindowQuad & quad, data.quads) { if (quad.right() > -w->x()) { new_quads.append(quad); } } data.quads = new_quads; } if (w->isOnDesktop(painting_desktop) && w->x() + w->width() > rect.x() + rect.width()) { WindowQuadList new_quads; foreach (const WindowQuad & quad, data.quads) { if (quad.right() <= rect.width() - w->x()) { new_quads.append(quad); } } data.quads = new_quads; } if (w->y() < rect.y()) { WindowQuadList new_quads; foreach (const WindowQuad & quad, data.quads) { if (quad.bottom() > -w->y()) { new_quads.append(quad); } } data.quads = new_quads; } if (w->y() + w->height() > rect.y() + rect.height()) { WindowQuadList new_quads; foreach (const WindowQuad & quad, data.quads) { if (quad.bottom() <= rect.height() - w->y()) { new_quads.append(quad); } } data.quads = new_quads; } GLShader *currentShader = nullptr; if (mode == Cylinder) { shaderManager->pushShader(cylinderShader); cylinderShader->setUniform("xCoord", (float)w->x()); cylinderShader->setUniform("cubeAngle", (effects->numberOfDesktops() - 2) / (float)effects->numberOfDesktops() * 90.0f); float factor = 0.0f; if (start) factor = 1.0f - timeLine.currentValue(); if (stop) factor = timeLine.currentValue(); cylinderShader->setUniform("timeLine", factor); currentShader = cylinderShader; } if (mode == Sphere) { shaderManager->pushShader(sphereShader); sphereShader->setUniform("u_offset", QVector2D(w->x(), w->y())); sphereShader->setUniform("cubeAngle", (effects->numberOfDesktops() - 2) / (float)effects->numberOfDesktops() * 90.0f); float factor = 0.0f; if (start) factor = 1.0f - timeLine.currentValue(); if (stop) factor = timeLine.currentValue(); sphereShader->setUniform("timeLine", factor); currentShader = sphereShader; } if (currentShader) { data.shader = currentShader; } data.setProjectionMatrix(data.screenProjectionMatrix()); if (reflectionPainting) { data.setModelViewMatrix(m_reflectionMatrix * m_rotationMatrix * m_currentFaceMatrix); } else { data.setModelViewMatrix(m_rotationMatrix * m_currentFaceMatrix); } } effects->paintWindow(w, mask, region, data); if (activated && cube_painting) { if (mode == Cylinder || mode == Sphere) { shaderManager->popShader(); } if (w->isDesktop() && effects->numScreens() > 1 && paintCaps) { QRect rect = effects->clientArea(FullArea, activeScreen, painting_desktop); QRegion paint = QRegion(rect); for (int i = 0; i < effects->numScreens(); i++) { if (i == w->screen()) continue; paint = paint.subtracted(QRegion(effects->clientArea(ScreenArea, i, painting_desktop))); } paint = paint.subtracted(QRegion(w->geometry())); // in case of free area in multiscreen setup fill it with cap color if (!paint.isEmpty()) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); QVector verts; float quadSize = 0.0f; int leftDesktop = frontDesktop - 1; int rightDesktop = frontDesktop + 1; if (leftDesktop == 0) leftDesktop = effects->numberOfDesktops(); if (rightDesktop > effects->numberOfDesktops()) rightDesktop = 1; if (painting_desktop == frontDesktop) quadSize = 100.0f; else if (painting_desktop == leftDesktop || painting_desktop == rightDesktop) quadSize = 150.0f; else quadSize = 250.0f; foreach (const QRect & paintRect, paint.rects()) { for (int i = 0; i <= (paintRect.height() / quadSize); i++) { for (int j = 0; j <= (paintRect.width() / quadSize); j++) { verts << qMin(paintRect.x() + (j + 1)*quadSize, (float)paintRect.x() + paintRect.width()) << paintRect.y() + i*quadSize; verts << paintRect.x() + j*quadSize << paintRect.y() + i*quadSize; verts << paintRect.x() + j*quadSize << qMin(paintRect.y() + (i + 1)*quadSize, (float)paintRect.y() + paintRect.height()); verts << paintRect.x() + j*quadSize << qMin(paintRect.y() + (i + 1)*quadSize, (float)paintRect.y() + paintRect.height()); verts << qMin(paintRect.x() + (j + 1)*quadSize, (float)paintRect.x() + paintRect.width()) << qMin(paintRect.y() + (i + 1)*quadSize, (float)paintRect.y() + paintRect.height()); verts << qMin(paintRect.x() + (j + 1)*quadSize, (float)paintRect.x() + paintRect.width()) << paintRect.y() + i*quadSize; } } } bool capShader = false; if (effects->compositingType() == OpenGL2Compositing && m_capShader && m_capShader->isValid()) { capShader = true; ShaderManager::instance()->pushShader(m_capShader); m_capShader->setUniform("u_mirror", 0); m_capShader->setUniform("u_untextured", 1); QMatrix4x4 mvp = data.screenProjectionMatrix(); if (reflectionPainting) { mvp = mvp * m_reflectionMatrix * m_rotationMatrix * m_currentFaceMatrix; } else { mvp = mvp * m_rotationMatrix * m_currentFaceMatrix; } m_capShader->setUniform(GLShader::ModelViewProjectionMatrix, mvp); } GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); QColor color = capColor; capColor.setAlphaF(cubeOpacity); vbo->setColor(color); vbo->setData(verts.size() / 2, 2, verts.constData(), NULL); if (!capShader || mode == Cube) { // TODO: use sphere and cylinder shaders vbo->render(GL_TRIANGLES); } if (capShader) { ShaderManager::instance()->popShader(); } glDisable(GL_BLEND); } } } } bool CubeEffect::borderActivated(ElectricBorder border) { if (!borderActivate.contains(border) && !borderActivateCylinder.contains(border) && !borderActivateSphere.contains(border)) return false; if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return false; if (borderActivate.contains(border)) { if (!activated || (activated && mode == Cube)) toggleCube(); else return false; } if (borderActivateCylinder.contains(border)) { if (!activated || (activated && mode == Cylinder)) toggleCylinder(); else return false; } if (borderActivateSphere.contains(border)) { if (!activated || (activated && mode == Sphere)) toggleSphere(); else return false; } return true; } void CubeEffect::toggleCube() { qCDebug(KWINEFFECTS) << "toggle cube"; toggle(Cube); } void CubeEffect::toggleCylinder() { qCDebug(KWINEFFECTS) << "toggle cylinder"; if (!useShaders) useShaders = loadShader(); if (useShaders) toggle(Cylinder); } void CubeEffect::toggleSphere() { qCDebug(KWINEFFECTS) << "toggle sphere"; if (!useShaders) useShaders = loadShader(); if (useShaders) toggle(Sphere); } void CubeEffect::toggle(CubeMode newMode) { if ((effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) || effects->numberOfDesktops() < 2) return; if (!activated) { mode = newMode; setActive(true); } else { setActive(false); } } void CubeEffect::grabbedKeyboardEvent(QKeyEvent* e) { if (stop) return; // taken from desktopgrid.cpp if (e->type() == QEvent::KeyPress) { // check for global shortcuts // HACK: keyboard grab disables the global shortcuts so we have to check for global shortcut (bug 156155) if (mode == Cube && cubeShortcut.contains(e->key() + e->modifiers())) { toggleCube(); return; } if (mode == Cylinder && cylinderShortcut.contains(e->key() + e->modifiers())) { toggleCylinder(); return; } if (mode == Sphere && sphereShortcut.contains(e->key() + e->modifiers())) { toggleSphere(); return; } int desktop = -1; // switch by F or just if (e->key() >= Qt::Key_F1 && e->key() <= Qt::Key_F35) desktop = e->key() - Qt::Key_F1 + 1; else if (e->key() >= Qt::Key_0 && e->key() <= Qt::Key_9) desktop = e->key() == Qt::Key_0 ? 10 : e->key() - Qt::Key_0; if (desktop != -1) { if (desktop <= effects->numberOfDesktops()) { // we have to rotate to chosen desktop // and end effect when rotation finished rotateToDesktop(desktop); setActive(false); } return; } switch(e->key()) { // wrap only on autorepeat case Qt::Key_Left: // rotate to previous desktop qCDebug(KWINEFFECTS) << "left"; if (!rotating && !start) { rotating = true; if (invertKeys) rotationDirection = Right; else rotationDirection = Left; } else { if (rotations.count() < effects->numberOfDesktops()) { if (invertKeys) rotations.enqueue(Right); else rotations.enqueue(Left); } } break; case Qt::Key_Right: // rotate to next desktop qCDebug(KWINEFFECTS) << "right"; if (!rotating && !start) { rotating = true; if (invertKeys) rotationDirection = Left; else rotationDirection = Right; } else { if (rotations.count() < effects->numberOfDesktops()) { if (invertKeys) rotations.enqueue(Left); else rotations.enqueue(Right); } } break; case Qt::Key_Up: qCDebug(KWINEFFECTS) << "up"; if (invertKeys) { if (verticalPosition != Down) { if (!verticalRotating) { verticalRotating = true; verticalRotationDirection = Downwards; if (verticalPosition == Normal) verticalPosition = Down; if (verticalPosition == Up) verticalPosition = Normal; } else { verticalRotations.enqueue(Downwards); } } else if (manualVerticalAngle > 0.0 && !verticalRotating) { // rotate to down position from the manual position verticalRotating = true; verticalRotationDirection = Downwards; verticalPosition = Down; manualVerticalAngle -= 90.0; } } else { if (verticalPosition != Up) { if (!verticalRotating) { verticalRotating = true; verticalRotationDirection = Upwards; if (verticalPosition == Normal) verticalPosition = Up; if (verticalPosition == Down) verticalPosition = Normal; } else { verticalRotations.enqueue(Upwards); } } else if (manualVerticalAngle < 0.0 && !verticalRotating) { // rotate to up position from the manual position verticalRotating = true; verticalRotationDirection = Upwards; verticalPosition = Up; manualVerticalAngle += 90.0; } } break; case Qt::Key_Down: qCDebug(KWINEFFECTS) << "down"; if (invertKeys) { if (verticalPosition != Up) { if (!verticalRotating) { verticalRotating = true; verticalRotationDirection = Upwards; if (verticalPosition == Normal) verticalPosition = Up; if (verticalPosition == Down) verticalPosition = Normal; } else { verticalRotations.enqueue(Upwards); } } else if (manualVerticalAngle < 0.0 && !verticalRotating) { // rotate to up position from the manual position verticalRotating = true; verticalRotationDirection = Upwards; verticalPosition = Up; manualVerticalAngle += 90.0; } } else { if (verticalPosition != Down) { if (!verticalRotating) { verticalRotating = true; verticalRotationDirection = Downwards; if (verticalPosition == Normal) verticalPosition = Down; if (verticalPosition == Up) verticalPosition = Normal; } else { verticalRotations.enqueue(Downwards); } } else if (manualVerticalAngle > 0.0 && !verticalRotating) { // rotate to down position from the manual position verticalRotating = true; verticalRotationDirection = Downwards; verticalPosition = Down; manualVerticalAngle -= 90.0; } } break; case Qt::Key_Escape: rotateToDesktop(effects->currentDesktop()); setActive(false); return; case Qt::Key_Enter: case Qt::Key_Return: case Qt::Key_Space: setActive(false); return; case Qt::Key_Plus: zoom -= 10.0; zoom = qMax(-zPosition, zoom); rotateCube(); break; case Qt::Key_Minus: zoom += 10.0f; rotateCube(); break; default: break; } effects->addRepaintFull(); } } void CubeEffect::rotateToDesktop(int desktop) { int tempFrontDesktop = frontDesktop; if (!rotations.empty()) { // all scheduled rotations will be removed as a speed up rotations.clear(); } if (rotating && !desktopChangedWhileRotating) { // front desktop will change during the actual rotation - this has to be considered if (rotationDirection == Left) { tempFrontDesktop++; } else if (rotationDirection == Right) { tempFrontDesktop--; } if (tempFrontDesktop > effects->numberOfDesktops()) tempFrontDesktop = 1; else if (tempFrontDesktop == 0) tempFrontDesktop = effects->numberOfDesktops(); } // find the fastest rotation path from tempFrontDesktop to desktop int rightRotations = tempFrontDesktop - desktop; if (rightRotations < 0) rightRotations += effects->numberOfDesktops(); int leftRotations = desktop - tempFrontDesktop; if (leftRotations < 0) leftRotations += effects->numberOfDesktops(); if (leftRotations <= rightRotations) { for (int i = 0; i < leftRotations; i++) { rotations.enqueue(Left); } } else { for (int i = 0; i < rightRotations; i++) { rotations.enqueue(Right); } } if (!start && !rotating && !rotations.empty()) { rotating = true; rotationDirection = rotations.dequeue(); } // change timeline curve if more rotations are following if (!rotations.empty()) { currentShape = QTimeLine::EaseInCurve; timeLine.setCurveShape(currentShape); } } void CubeEffect::setActive(bool active) { foreach (CubeInsideEffect * inside, m_cubeInsideEffects) { inside->setActive(true); } if (active) { QString capPath = CubeConfig::capPath(); if (texturedCaps && !capTexture && !capPath.isEmpty()) { QFutureWatcher *watcher = new QFutureWatcher(this); connect(watcher, SIGNAL(finished()), SLOT(slotCubeCapLoaded())); watcher->setFuture(QtConcurrent::run(this, &CubeEffect::loadCubeCap, capPath)); } QString wallpaperPath = CubeConfig::wallpaper().toLocalFile(); if (!wallpaper && !wallpaperPath.isEmpty()) { QFutureWatcher *watcher = new QFutureWatcher(this); connect(watcher, SIGNAL(finished()), SLOT(slotWallPaperLoaded())); watcher->setFuture(QtConcurrent::run(this, &CubeEffect::loadWallPaper, wallpaperPath)); } activated = true; activeScreen = effects->activeScreen(); keyboard_grab = effects->grabKeyboard(this); effects->startMouseInterception(this, Qt::OpenHandCursor); frontDesktop = effects->currentDesktop(); zoom = 0.0; zOrderingFactor = zPosition / (effects->stackingOrder().count() - 1); start = true; effects->setActiveFullScreenEffect(this); qCDebug(KWINEFFECTS) << "Cube is activated"; verticalPosition = Normal; verticalRotating = false; manualAngle = 0.0; manualVerticalAngle = 0.0; desktopChangedWhileRotating = false; if (reflection) { QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); float temporaryCoeff = float(rect.width()) / tan(M_PI / float(effects->numberOfDesktops())); mAddedHeightCoeff1 = sqrt(float(rect.height()) * float(rect.height()) + temporaryCoeff * temporaryCoeff); mAddedHeightCoeff2 = sqrt(float(rect.height()) * float(rect.height()) + float(rect.width()) * float(rect.width()) + temporaryCoeff * temporaryCoeff); } m_rotationMatrix.setToIdentity(); effects->addRepaintFull(); } else { schedule_close = true; // we have to add a repaint, to start the deactivating effects->addRepaintFull(); } } void CubeEffect::windowInputMouseEvent(QEvent* e) { if (!activated) return; if (tabBoxMode) return; if (stop) return; QMouseEvent *mouse = dynamic_cast< QMouseEvent* >(e); if (!mouse) return; static QPoint oldpos; static QElapsedTimer dblClckTime; static int dblClckCounter(0); if (mouse->type() == QEvent::MouseMove && mouse->buttons().testFlag(Qt::LeftButton)) { const QPoint pos = mouse->pos(); QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); bool repaint = false; // vertical movement only if there is not a rotation if (!verticalRotating) { // display height corresponds to 180* int deltaY = pos.y() - oldpos.y(); float deltaVerticalDegrees = (float)deltaY / rect.height() * 180.0f; if (invertMouse) manualVerticalAngle += deltaVerticalDegrees; else manualVerticalAngle -= deltaVerticalDegrees; if (deltaVerticalDegrees != 0.0) repaint = true; } // horizontal movement only if there is not a rotation if (!rotating) { // display width corresponds to sum of angles of the polyhedron int deltaX = oldpos.x() - pos.x(); float deltaDegrees = (float)deltaX / rect.width() * 360.0f; if (deltaX == 0) { if (pos.x() == 0) deltaDegrees = 5.0f; if (pos.x() == rect.width() - 1) deltaDegrees = -5.0f; } if (invertMouse) manualAngle += deltaDegrees; else manualAngle -= deltaDegrees; if (deltaDegrees != 0.0) repaint = true; } if (repaint) { rotateCube(); effects->addRepaintFull(); } oldpos = pos; } else if (mouse->type() == QEvent::MouseButtonPress && mouse->button() == Qt::LeftButton) { oldpos = mouse->pos(); if (dblClckTime.elapsed() > QApplication::doubleClickInterval()) dblClckCounter = 0; if (!dblClckCounter) dblClckTime.start(); } else if (mouse->type() == QEvent::MouseButtonRelease) { effects->defineCursor(Qt::OpenHandCursor); if (mouse->button() == Qt::LeftButton && ++dblClckCounter == 2) { dblClckCounter = 0; if (dblClckTime.elapsed() < QApplication::doubleClickInterval()) { setActive(false); return; } } else if (mouse->button() == Qt::XButton1) { if (!rotating && !start) { rotating = true; if (invertMouse) rotationDirection = Right; else rotationDirection = Left; } else { if (rotations.count() < effects->numberOfDesktops()) { if (invertMouse) rotations.enqueue(Right); else rotations.enqueue(Left); } } effects->addRepaintFull(); } else if (mouse->button() == Qt::XButton2) { if (!rotating && !start) { rotating = true; if (invertMouse) rotationDirection = Left; else rotationDirection = Right; } else { if (rotations.count() < effects->numberOfDesktops()) { if (invertMouse) rotations.enqueue(Left); else rotations.enqueue(Right); } } effects->addRepaintFull(); } else if (mouse->button() == Qt::RightButton || (mouse->button() == Qt::LeftButton && closeOnMouseRelease)) { setActive(false); } } } void CubeEffect::slotTabBoxAdded(int mode) { if (activated) return; if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return; if (useForTabBox && mode == TabBoxDesktopListMode) { effects->refTabBox(); tabBoxMode = true; setActive(true); rotateToDesktop(effects->currentTabBoxDesktop()); } } void CubeEffect::slotTabBoxUpdated() { if (activated) { rotateToDesktop(effects->currentTabBoxDesktop()); effects->addRepaintFull(); } } void CubeEffect::slotTabBoxClosed() { if (activated) { effects->unrefTabBox(); tabBoxMode = false; setActive(false); } } void CubeEffect::globalShortcutChanged(QAction *action, const QKeySequence &seq) { if (action->objectName() == QStringLiteral("Cube")) { cubeShortcut.clear(); cubeShortcut.append(seq); } else if (action->objectName() == QStringLiteral("Cylinder")) { cylinderShortcut.clear(); cylinderShortcut.append(seq); } else if (action->objectName() == QStringLiteral("Sphere")) { sphereShortcut.clear(); sphereShortcut.append(seq); } } void* CubeEffect::proxy() { return &m_proxy; } void CubeEffect::registerCubeInsideEffect(CubeInsideEffect* effect) { m_cubeInsideEffects.append(effect); } void CubeEffect::unregisterCubeInsideEffect(CubeInsideEffect* effect) { m_cubeInsideEffects.removeAll(effect); } bool CubeEffect::isActive() const { return activated && !effects->isScreenLocked(); } } // namespace diff --git a/effects/cube/cube.h b/effects/cube/cube.h index 0de8ad53e..c53d9215c 100644 --- a/effects/cube/cube.h +++ b/effects/cube/cube.h @@ -1,257 +1,258 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2008 Martin Gräßlin 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 . *********************************************************************/ #ifndef KWIN_CUBE_H #define KWIN_CUBE_H #include #include #include #include #include #include #include #include "cube_inside.h" #include "cube_proxy.h" namespace KWin { class CubeEffect : public Effect { Q_OBJECT Q_PROPERTY(qreal cubeOpacity READ configuredCubeOpacity) Q_PROPERTY(bool opacityDesktopOnly READ isOpacityDesktopOnly) Q_PROPERTY(bool displayDesktopName READ isDisplayDesktopName) Q_PROPERTY(bool reflection READ isReflection) Q_PROPERTY(int rotationDuration READ configuredRotationDuration) Q_PROPERTY(QColor backgroundColor READ configuredBackgroundColor) Q_PROPERTY(QColor capColor READ configuredCapColor) Q_PROPERTY(bool paintCaps READ isPaintCaps) Q_PROPERTY(bool closeOnMouseRelease READ isCloseOnMouseRelease) Q_PROPERTY(qreal zPosition READ configuredZPosition) Q_PROPERTY(bool useForTabBox READ isUseForTabBox) Q_PROPERTY(bool invertKeys READ isInvertKeys) Q_PROPERTY(bool invertMouse READ isInvertMouse) Q_PROPERTY(qreal capDeformationFactor READ configuredCapDeformationFactor) Q_PROPERTY(bool useZOrdering READ isUseZOrdering) Q_PROPERTY(bool texturedCaps READ isTexturedCaps) // TODO: electric borders: not a registered type public: CubeEffect(); ~CubeEffect(); virtual void reconfigure(ReconfigureFlags); virtual void prePaintScreen(ScreenPrePaintData& data, int time); virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); virtual void postPaintScreen(); virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); virtual bool borderActivated(ElectricBorder border); virtual void grabbedKeyboardEvent(QKeyEvent* e); virtual void windowInputMouseEvent(QEvent* e); virtual bool isActive() const; int requestedEffectChainPosition() const override { return 50; } // proxy functions virtual void* proxy(); void registerCubeInsideEffect(CubeInsideEffect* effect); void unregisterCubeInsideEffect(CubeInsideEffect* effect); static bool supported(); // for properties qreal configuredCubeOpacity() const { return cubeOpacity; } bool isOpacityDesktopOnly() const { return opacityDesktopOnly; } bool isDisplayDesktopName() const { return displayDesktopName; } bool isReflection() const { return reflection; } int configuredRotationDuration() const { return rotationDuration; } QColor configuredBackgroundColor() const { return backgroundColor; } QColor configuredCapColor() const { return capColor; } bool isPaintCaps() const { return paintCaps; } bool isCloseOnMouseRelease() const { return closeOnMouseRelease; } qreal configuredZPosition() const { return zPosition; } bool isUseForTabBox() const { return useForTabBox; } bool isInvertKeys() const { return invertKeys; } bool isInvertMouse() const { return invertMouse; } qreal configuredCapDeformationFactor() const { return capDeformationFactor; } bool isUseZOrdering() const { return useZOrdering; } bool isTexturedCaps() const { return texturedCaps; } private Q_SLOTS: void toggleCube(); void toggleCylinder(); void toggleSphere(); // slots for global shortcut changed // needed to toggle the effect void globalShortcutChanged(QAction *action, const QKeySequence &seq); void slotTabBoxAdded(int mode); void slotTabBoxUpdated(); void slotTabBoxClosed(); void slotCubeCapLoaded(); void slotWallPaperLoaded(); private: enum RotationDirection { Left, Right, Upwards, Downwards }; enum VerticalRotationPosition { Up, Normal, Down }; enum CubeMode { Cube, Cylinder, Sphere }; void toggle(CubeMode newMode = Cube); void paintCube(int mask, QRegion region, ScreenPaintData& data); void paintCap(bool frontFirst, float zOffset, const QMatrix4x4 &projection); void paintCubeCap(); void paintCylinderCap(); void paintSphereCap(); bool loadShader(); void rotateCube(); void rotateToDesktop(int desktop); void setActive(bool active); QImage loadCubeCap(const QString &capPath); QImage loadWallPaper(const QString &file); bool activated; bool cube_painting; bool keyboard_grab; bool schedule_close; QList borderActivate; QList borderActivateCylinder; QList borderActivateSphere; int painting_desktop; int frontDesktop; float cubeOpacity; bool opacityDesktopOnly; bool displayDesktopName; EffectFrame* desktopNameFrame; QFont desktopNameFont; bool reflection; bool rotating; bool verticalRotating; bool desktopChangedWhileRotating; bool paintCaps; + bool multisampling; QTimeLine timeLine; QTimeLine verticalTimeLine; RotationDirection rotationDirection; RotationDirection verticalRotationDirection; VerticalRotationPosition verticalPosition; QQueue rotations; QQueue verticalRotations; QColor backgroundColor; QColor capColor; GLTexture* wallpaper; bool texturedCaps; GLTexture* capTexture; float manualAngle; float manualVerticalAngle; QTimeLine::CurveShape currentShape; bool start; bool stop; bool reflectionPainting; int rotationDuration; int activeScreen; bool bottomCap; bool closeOnMouseRelease; float zoom; float zPosition; bool useForTabBox; bool invertKeys; bool invertMouse; bool tabBoxMode; bool shortcutsRegistered; CubeMode mode; bool useShaders; GLShader* cylinderShader; GLShader* sphereShader; GLShader* m_reflectionShader; GLShader* m_capShader; float capDeformationFactor; bool useZOrdering; float zOrderingFactor; bool useList; // needed for reflection float mAddedHeightCoeff1; float mAddedHeightCoeff2; QMatrix4x4 m_rotationMatrix; QMatrix4x4 m_reflectionMatrix; QMatrix4x4 m_textureMirrorMatrix; QMatrix4x4 m_currentFaceMatrix; GLVertexBuffer *m_cubeCapBuffer; // Shortcuts - needed to toggle the effect QList cubeShortcut; QList cylinderShortcut; QList sphereShortcut; // proxy CubeEffectProxy m_proxy; QList< CubeInsideEffect* > m_cubeInsideEffects; QAction *m_cubeAction; QAction *m_cylinderAction; QAction *m_sphereAction; }; } // namespace #endif diff --git a/effects/cube/cube.kcfg b/effects/cube/cube.kcfg index f0c5fda7e..1b563465d 100644 --- a/effects/cube/cube.kcfg +++ b/effects/cube/cube.kcfg @@ -1,68 +1,71 @@ 0 80 false true true QColor(Qt::black) QColor(KColorScheme(QPalette::Active, KColorScheme::Window).background().color()) QStandardPaths::locate(QStandardPaths::DataLocation, QStringLiteral("cubecap.png")) true true false false 100 0 false false false + + true + diff --git a/effects/cube/cube_config.ui b/effects/cube/cube_config.ui index ec79f1c59..05c04b604 100644 --- a/effects/cube/cube_config.ui +++ b/effects/cube/cube_config.ui @@ -1,569 +1,573 @@ KWin::CubeEffectConfigForm 0 0 747 566 - 0 + 1 Tab 1 Background - Background color: + &Background color: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter kcfg_BackgroundColor 0 0 - Wallpaper: + Wa&llpaper: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter kcfg_Wallpaper 0 0 Activation - + 0 200 - - KShortcutsEditor::GlobalAction - Appearance Display desktop name Reflection - Rotation duration: + Rotat&ion duration: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter kcfg_RotationDuration 0 0 100 0 Default 5000 10 Qt::Vertical 20 0 Windows hover above cube Opacity 200 0 100 1 100 Qt::Horizontal QSlider::TicksBelow 10 75 0 % 100 100 Transparent Opaque Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Do not change opacity of windows Qt::Vertical 20 40 Tab 2 Caps Show caps - Cap color: + Cap co&lor: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter kcfg_CapColor 0 0 Display image on caps Qt::Vertical 20 40 Zoom Near Far Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Define how far away the object should appear 3000 10 100 Qt::Horizontal QSlider::TicksBelow 100 Qt::Vertical 20 0 Additional Options If enabled the effect will be deactivated after rotating the cube with the mouse, otherwise it will remain active Close after mouse dragging Use this effect for walking through the desktops Invert cursor keys Invert mouse + + + + Use multisampling + + + Sphere Cap Deformation 100 Qt::Horizontal QSlider::TicksBelow 25 Sphere Plane Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - KColorButton - QPushButton -
kcolorbutton.h
+ KShortcutsEditor + QWidget +
kshortcutseditor.h
+ 1
KUrlRequester - QFrame + QWidget
kurlrequester.h
1
- KShortcutsEditor - QWidget -
KShortcutsEditor
- 1 + KColorButton + QPushButton +
kcolorbutton.h
tabWidget kcfg_DisplayDesktopName kcfg_Reflection kcfg_ZOrdering kcfg_RotationDuration kcfg_Opacity kcfg_OpacitySpin kcfg_OpacityDesktopOnly kcfg_BackgroundColor kcfg_Wallpaper kcfg_Caps kcfg_CapColor kcfg_TexturedCaps kcfg_CloseOnMouseRelease kcfg_TabBox kcfg_InvertKeys kcfg_InvertMouse kcfg_ZPosition kcfg_CapDeformation kcfg_OpacitySpin valueChanged(int) kcfg_Opacity setValue(int) 727 85 611 88 kcfg_Opacity valueChanged(int) kcfg_OpacitySpin setValue(int) 611 88 727 85
diff --git a/effects/cube/cubeslide.cpp b/effects/cube/cubeslide.cpp index 3d4db3151..be1631dfd 100644 --- a/effects/cube/cubeslide.cpp +++ b/effects/cube/cubeslide.cpp @@ -1,609 +1,613 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2009 Martin Gräßlin 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 . *********************************************************************/ #include "cubeslide.h" // KConfigSkeleton #include "cubeslideconfig.h" #include #include #include #include namespace KWin { CubeSlideEffect::CubeSlideEffect() : windowMoving(false) , desktopChangedWhileMoving(false) , progressRestriction(0.0f) { initConfig(); connect(effects, SIGNAL(desktopChanged(int,int)), this, SLOT(slotDesktopChanged(int,int))); connect(effects, SIGNAL(windowStepUserMovedResized(KWin::EffectWindow*,QRect)), this, SLOT(slotWindowStepUserMovedResized(KWin::EffectWindow*))); connect(effects, SIGNAL(windowFinishUserMovedResized(KWin::EffectWindow*)), this, SLOT(slotWindowFinishUserMovedResized(KWin::EffectWindow*))); reconfigure(ReconfigureAll); } CubeSlideEffect::~CubeSlideEffect() { } bool CubeSlideEffect::supported() { return effects->isOpenGLCompositing() && effects->animationsSupported(); } void CubeSlideEffect::reconfigure(ReconfigureFlags) { CubeSlideConfig::self()->read(); // TODO: rename rotationDuration to duration rotationDuration = animationTime(CubeSlideConfig::rotationDuration() != 0 ? CubeSlideConfig::rotationDuration() : 500); timeLine.setCurveShape(QTimeLine::EaseInOutCurve); timeLine.setDuration(rotationDuration); dontSlidePanels = CubeSlideConfig::dontSlidePanels(); dontSlideStickyWindows = CubeSlideConfig::dontSlideStickyWindows(); usePagerLayout = CubeSlideConfig::usePagerLayout(); useWindowMoving = CubeSlideConfig::useWindowMoving(); + multisampling = CubeSlideConfig::multisampling(); } void CubeSlideEffect::prePaintScreen(ScreenPrePaintData& data, int time) { if (!slideRotations.empty()) { data.mask |= PAINT_SCREEN_TRANSFORMED | Effect::PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS | PAINT_SCREEN_BACKGROUND_FIRST; + if (multisampling) { + data.mask |= PAINT_SCREEN_MULTISAMPLE; + } timeLine.setCurrentTime(timeLine.currentTime() + time); if (windowMoving && timeLine.currentTime() > progressRestriction * (qreal)timeLine.duration()) timeLine.setCurrentTime(progressRestriction * (qreal)timeLine.duration()); if (dontSlidePanels) panels.clear(); stickyWindows.clear(); } effects->prePaintScreen(data, time); } void CubeSlideEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) { if (!slideRotations.empty()) { glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); paintSlideCube(mask, region, data); glCullFace(GL_BACK); paintSlideCube(mask, region, data); glDisable(GL_CULL_FACE); if (dontSlidePanels) { foreach (EffectWindow * w, panels) { WindowPaintData wData(w); effects->paintWindow(w, 0, infiniteRegion(), wData); } } foreach (EffectWindow * w, stickyWindows) { WindowPaintData wData(w); effects->paintWindow(w, 0, infiniteRegion(), wData); } } else effects->paintScreen(mask, region, data); } void CubeSlideEffect::paintSlideCube(int mask, QRegion region, ScreenPaintData& data) { // slide cube only paints to desktops at a time // first the horizontal rotations followed by vertical rotations QRect rect = effects->clientArea(FullArea, effects->activeScreen(), effects->currentDesktop()); float point = rect.width() / 2 * tan(45.0f * M_PI / 180.0f); cube_painting = true; painting_desktop = front_desktop; ScreenPaintData firstFaceData = data; ScreenPaintData secondFaceData = data; RotationDirection direction = slideRotations.head(); int secondDesktop; switch(direction) { case Left: firstFaceData.setRotationAxis(Qt::YAxis); secondFaceData.setRotationAxis(Qt::YAxis); if (usePagerLayout) secondDesktop = effects->desktopToLeft(front_desktop, true); else { secondDesktop = front_desktop - 1; if (secondDesktop == 0) secondDesktop = effects->numberOfDesktops(); } firstFaceData.setRotationAngle(90.0f * timeLine.currentValue()); secondFaceData.setRotationAngle(-90.0f * (1.0f - timeLine.currentValue())); break; case Right: firstFaceData.setRotationAxis(Qt::YAxis); secondFaceData.setRotationAxis(Qt::YAxis); if (usePagerLayout) secondDesktop = effects->desktopToRight(front_desktop, true); else { secondDesktop = front_desktop + 1; if (secondDesktop > effects->numberOfDesktops()) secondDesktop = 1; } firstFaceData.setRotationAngle(-90.0f * timeLine.currentValue()); secondFaceData.setRotationAngle(90.0f * (1.0f - timeLine.currentValue())); break; case Upwards: firstFaceData.setRotationAxis(Qt::XAxis); secondFaceData.setRotationAxis(Qt::XAxis); secondDesktop = effects->desktopAbove(front_desktop, true); firstFaceData.setRotationAngle(-90.0f * timeLine.currentValue()); secondFaceData.setRotationAngle(90.0f * (1.0f - timeLine.currentValue())); point = rect.height() / 2 * tan(45.0f * M_PI / 180.0f); break; case Downwards: firstFaceData.setRotationAxis(Qt::XAxis); secondFaceData.setRotationAxis(Qt::XAxis); secondDesktop = effects->desktopBelow(front_desktop, true); firstFaceData.setRotationAngle(90.0f * timeLine.currentValue()); secondFaceData.setRotationAngle(-90.0f * (1.0f - timeLine.currentValue())); point = rect.height() / 2 * tan(45.0f * M_PI / 180.0f); break; default: // totally impossible return; } // front desktop firstFaceData.setRotationOrigin(QVector3D(rect.width() / 2, rect.height() / 2, -point)); other_desktop = secondDesktop; firstDesktop = true; effects->paintScreen(mask, region, firstFaceData); // second desktop other_desktop = painting_desktop; painting_desktop = secondDesktop; firstDesktop = false; secondFaceData.setRotationOrigin(QVector3D(rect.width() / 2, rect.height() / 2, -point)); effects->paintScreen(mask, region, secondFaceData); cube_painting = false; painting_desktop = effects->currentDesktop(); } void CubeSlideEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) { if (!slideRotations.empty() && cube_painting) { QRect rect = effects->clientArea(FullArea, effects->activeScreen(), painting_desktop); if (dontSlidePanels && w->isDock()) { w->setData(WindowForceBlurRole, QVariant(true)); panels.insert(w); } if (!w->isManaged()) { w->setData(WindowForceBlurRole, QVariant(true)); stickyWindows.insert(w); } else if (dontSlideStickyWindows && !w->isDock() && !w->isDesktop() && w->isOnAllDesktops()) { w->setData(WindowForceBlurRole, QVariant(true)); stickyWindows.insert(w); } if (w->isOnDesktop(painting_desktop)) { if (w->x() < rect.x()) { data.quads = data.quads.splitAtX(-w->x()); } if (w->x() + w->width() > rect.x() + rect.width()) { data.quads = data.quads.splitAtX(rect.width() - w->x()); } if (w->y() < rect.y()) { data.quads = data.quads.splitAtY(-w->y()); } if (w->y() + w->height() > rect.y() + rect.height()) { data.quads = data.quads.splitAtY(rect.height() - w->y()); } w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } else if (w->isOnDesktop(other_desktop)) { RotationDirection direction = slideRotations.head(); bool enable = false; if (w->x() < rect.x() && (direction == Left || direction == Right)) { data.quads = data.quads.splitAtX(-w->x()); enable = true; } if (w->x() + w->width() > rect.x() + rect.width() && (direction == Left || direction == Right)) { data.quads = data.quads.splitAtX(rect.width() - w->x()); enable = true; } if (w->y() < rect.y() && (direction == Upwards || direction == Downwards)) { data.quads = data.quads.splitAtY(-w->y()); enable = true; } if (w->y() + w->height() > rect.y() + rect.height() && (direction == Upwards || direction == Downwards)) { data.quads = data.quads.splitAtY(rect.height() - w->y()); enable = true; } if (enable) { data.setTransformed(); data.setTranslucent(); w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } else w->disablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } else w->disablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } effects->prePaintWindow(w, data, time); } void CubeSlideEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) { if (!slideRotations.empty() && cube_painting) { if (dontSlidePanels && w->isDock()) return; if (stickyWindows.contains(w)) return; // filter out quads overlapping the edges QRect rect = effects->clientArea(FullArea, effects->activeScreen(), painting_desktop); if (w->isOnDesktop(painting_desktop)) { if (w->x() < rect.x()) { WindowQuadList new_quads; foreach (const WindowQuad & quad, data.quads) { if (quad.right() > -w->x()) { new_quads.append(quad); } } data.quads = new_quads; } if (w->x() + w->width() > rect.x() + rect.width()) { WindowQuadList new_quads; foreach (const WindowQuad & quad, data.quads) { if (quad.right() <= rect.width() - w->x()) { new_quads.append(quad); } } data.quads = new_quads; } if (w->y() < rect.y()) { WindowQuadList new_quads; foreach (const WindowQuad & quad, data.quads) { if (quad.bottom() > -w->y()) { new_quads.append(quad); } } data.quads = new_quads; } if (w->y() + w->height() > rect.y() + rect.height()) { WindowQuadList new_quads; foreach (const WindowQuad & quad, data.quads) { if (quad.bottom() <= rect.height() - w->y()) { new_quads.append(quad); } } data.quads = new_quads; } } // paint windows overlapping edges from other desktop if (w->isOnDesktop(other_desktop) && (mask & PAINT_WINDOW_TRANSFORMED)) { RotationDirection direction = slideRotations.head(); if (w->x() < rect.x() && (direction == Left || direction == Right)) { WindowQuadList new_quads; data.setXTranslation(rect.width()); foreach (const WindowQuad & quad, data.quads) { if (quad.right() <= -w->x()) { new_quads.append(quad); } } data.quads = new_quads; } if (w->x() + w->width() > rect.x() + rect.width() && (direction == Left || direction == Right)) { WindowQuadList new_quads; data.setXTranslation(-rect.width()); foreach (const WindowQuad & quad, data.quads) { if (quad.right() > rect.width() - w->x()) { new_quads.append(quad); } } data.quads = new_quads; } if (w->y() < rect.y() && (direction == Upwards || direction == Downwards)) { WindowQuadList new_quads; data.setYTranslation(rect.height()); foreach (const WindowQuad & quad, data.quads) { if (quad.bottom() <= -w->y()) { new_quads.append(quad); } } data.quads = new_quads; } if (w->y() + w->height() > rect.y() + rect.height() && (direction == Upwards || direction == Downwards)) { WindowQuadList new_quads; data.setYTranslation(-rect.height()); foreach (const WindowQuad & quad, data.quads) { if (quad.bottom() > rect.height() - w->y()) { new_quads.append(quad); } } data.quads = new_quads; } if (firstDesktop) data.multiplyOpacity(timeLine.currentValue()); else data.multiplyOpacity((1.0 - timeLine.currentValue())); } } effects->paintWindow(w, mask, region, data); } void CubeSlideEffect::postPaintScreen() { effects->postPaintScreen(); if (!slideRotations.empty()) { if (timeLine.currentValue() == 1.0) { RotationDirection direction = slideRotations.dequeue(); switch(direction) { case Left: if (usePagerLayout) front_desktop = effects->desktopToLeft(front_desktop, true); else { front_desktop--; if (front_desktop == 0) front_desktop = effects->numberOfDesktops(); } break; case Right: if (usePagerLayout) front_desktop = effects->desktopToRight(front_desktop, true); else { front_desktop++; if (front_desktop > effects->numberOfDesktops()) front_desktop = 1; } break; case Upwards: front_desktop = effects->desktopAbove(front_desktop, true); break; case Downwards: front_desktop = effects->desktopBelow(front_desktop, true); break; } timeLine.setCurrentTime(0); if (slideRotations.count() == 1) timeLine.setCurveShape(QTimeLine::EaseOutCurve); else timeLine.setCurveShape(QTimeLine::LinearCurve); if (slideRotations.empty()) { foreach (EffectWindow * w, panels) w->setData(WindowForceBlurRole, QVariant(false)); foreach (EffectWindow * w, stickyWindows) w->setData(WindowForceBlurRole, QVariant(false)); stickyWindows.clear(); panels.clear(); effects->setActiveFullScreenEffect(0); } } effects->addRepaintFull(); } } void CubeSlideEffect::slotDesktopChanged(int old, int current) { if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return; if (old > effects->numberOfDesktops()) { // number of desktops has been reduced -> no animation return; } if (windowMoving) { desktopChangedWhileMoving = true; progressRestriction = 1.0 - progressRestriction; effects->addRepaintFull(); return; } bool activate = true; if (!slideRotations.empty()) { // last slide still in progress activate = false; RotationDirection direction = slideRotations.dequeue(); slideRotations.clear(); slideRotations.enqueue(direction); switch(direction) { case Left: if (usePagerLayout) old = effects->desktopToLeft(front_desktop, true); else { old = front_desktop - 1; if (old == 0) old = effects->numberOfDesktops(); } break; case Right: if (usePagerLayout) old = effects->desktopToRight(front_desktop, true); else { old = front_desktop + 1; if (old > effects->numberOfDesktops()) old = 1; } break; case Upwards: old = effects->desktopAbove(front_desktop, true); break; case Downwards: old = effects->desktopBelow(front_desktop, true); break; } } if (usePagerLayout) { // calculate distance in respect to pager QPoint diff = effects->desktopGridCoords(effects->currentDesktop()) - effects->desktopGridCoords(old); if (qAbs(diff.x()) > effects->desktopGridWidth() / 2) { int sign = -1 * (diff.x() / qAbs(diff.x())); diff.setX(sign *(effects->desktopGridWidth() - qAbs(diff.x()))); } if (diff.x() > 0) { for (int i = 0; i < diff.x(); i++) { slideRotations.enqueue(Right); } } else if (diff.x() < 0) { diff.setX(-diff.x()); for (int i = 0; i < diff.x(); i++) { slideRotations.enqueue(Left); } } if (qAbs(diff.y()) > effects->desktopGridHeight() / 2) { int sign = -1 * (diff.y() / qAbs(diff.y())); diff.setY(sign *(effects->desktopGridHeight() - qAbs(diff.y()))); } if (diff.y() > 0) { for (int i = 0; i < diff.y(); i++) { slideRotations.enqueue(Downwards); } } if (diff.y() < 0) { diff.setY(-diff.y()); for (int i = 0; i < diff.y(); i++) { slideRotations.enqueue(Upwards); } } } else { // ignore pager layout int left = old - current; if (left < 0) left = effects->numberOfDesktops() + left; int right = current - old; if (right < 0) right = effects->numberOfDesktops() + right; if (left < right) { for (int i = 0; i < left; i++) { slideRotations.enqueue(Left); } } else { for (int i = 0; i < right; i++) { slideRotations.enqueue(Right); } } } timeLine.setDuration((float)rotationDuration / (float)slideRotations.count()); if (activate) { if (slideRotations.count() == 1) timeLine.setCurveShape(QTimeLine::EaseInOutCurve); else timeLine.setCurveShape(QTimeLine::EaseInCurve); effects->setActiveFullScreenEffect(this); timeLine.setCurrentTime(0); front_desktop = old; effects->addRepaintFull(); } } void CubeSlideEffect::slotWindowStepUserMovedResized(EffectWindow* w) { if (!useWindowMoving) return; if (!effects->kwinOption(SwitchDesktopOnScreenEdgeMovingWindows).toBool()) return; if (w->isUserResize()) return; const QSize screenSize = effects->virtualScreenSize(); const QPoint cursor = effects->cursorPos(); const int horizontal = screenSize.width() * 0.1; const int vertical = screenSize.height() * 0.1; const QRect leftRect(0, screenSize.height() * 0.1, horizontal, screenSize.height() * 0.8); const QRect rightRect(screenSize.width() - horizontal, screenSize.height() * 0.1, horizontal, screenSize.height() * 0.8); const QRect topRect(horizontal, 0, screenSize.width() * 0.8, vertical); const QRect bottomRect(horizontal, screenSize.height() - vertical, screenSize.width() - horizontal * 2, vertical); if (leftRect.contains(cursor)) { if (effects->desktopToLeft(effects->currentDesktop()) != effects->currentDesktop()) windowMovingChanged(0.3 *(float)(horizontal - cursor.x()) / (float)horizontal, Left); } else if (rightRect.contains(cursor)) { if (effects->desktopToRight(effects->currentDesktop()) != effects->currentDesktop()) windowMovingChanged(0.3 *(float)(cursor.x() - screenSize.width() + horizontal) / (float)horizontal, Right); } else if (topRect.contains(cursor)) { if (effects->desktopAbove(effects->currentDesktop()) != effects->currentDesktop()) windowMovingChanged(0.3 *(float)(vertical - cursor.y()) / (float)vertical, Upwards); } else if (bottomRect.contains(cursor)) { if (effects->desktopBelow(effects->currentDesktop()) != effects->currentDesktop()) windowMovingChanged(0.3 *(float)(cursor.y() - screenSize.height() + vertical) / (float)vertical, Downwards); } else { // not in one of the areas windowMoving = false; desktopChangedWhileMoving = false; timeLine.setCurrentTime(0); if (!slideRotations.isEmpty()) slideRotations.clear(); effects->setActiveFullScreenEffect(0); effects->addRepaintFull(); } } void CubeSlideEffect::slotWindowFinishUserMovedResized(EffectWindow* w) { if (!useWindowMoving) return; if (!effects->kwinOption(SwitchDesktopOnScreenEdgeMovingWindows).toBool()) return; if (w->isUserResize()) return; if (!desktopChangedWhileMoving) { if (slideRotations.isEmpty()) return; const RotationDirection direction = slideRotations.dequeue(); switch(direction) { case Left: slideRotations.enqueue(Right); break; case Right: slideRotations.enqueue(Left); break; case Upwards: slideRotations.enqueue(Downwards); break; case Downwards: slideRotations.enqueue(Upwards); break; default: break; // impossible } timeLine.setCurrentTime(timeLine.duration() - timeLine.currentTime()); } desktopChangedWhileMoving = false; windowMoving = false; effects->addRepaintFull(); } void CubeSlideEffect::windowMovingChanged(float progress, RotationDirection direction) { if (desktopChangedWhileMoving) progressRestriction = 1.0 - progress; else progressRestriction = progress; front_desktop = effects->currentDesktop(); if (slideRotations.isEmpty()) { slideRotations.enqueue(direction); timeLine.setCurveShape(QTimeLine::EaseInOutCurve); windowMoving = true; effects->setActiveFullScreenEffect(this); } effects->addRepaintFull(); } bool CubeSlideEffect::isActive() const { return !slideRotations.isEmpty(); } } // namespace diff --git a/effects/cube/cubeslide.h b/effects/cube/cubeslide.h index 92369f18a..493ae151c 100644 --- a/effects/cube/cubeslide.h +++ b/effects/cube/cubeslide.h @@ -1,108 +1,109 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2009 Martin Gräßlin 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 . *********************************************************************/ #ifndef KWIN_CUBESLIDE_H #define KWIN_CUBESLIDE_H #include #include #include #include #include namespace KWin { class CubeSlideEffect : public Effect { Q_OBJECT Q_PROPERTY(int rotationDuration READ configuredRotationDuration) Q_PROPERTY(bool dontSlidePanels READ isDontSlidePanels) Q_PROPERTY(bool dontSlideStickyWindows READ isDontSlideStickyWindows) Q_PROPERTY(bool usePagerLayout READ isUsePagerLayout) Q_PROPERTY(bool useWindowMoving READ isUseWindowMoving) public: CubeSlideEffect(); ~CubeSlideEffect(); virtual void reconfigure(ReconfigureFlags); virtual void prePaintScreen(ScreenPrePaintData& data, int time); virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); virtual void postPaintScreen(); virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); virtual bool isActive() const; int requestedEffectChainPosition() const override { return 50; } static bool supported(); // for properties int configuredRotationDuration() const { return rotationDuration; } bool isDontSlidePanels() const { return dontSlidePanels; } bool isDontSlideStickyWindows() const { return dontSlideStickyWindows; } bool isUsePagerLayout() const { return usePagerLayout; } bool isUseWindowMoving() const { return useWindowMoving; } private Q_SLOTS: void slotDesktopChanged(int old, int current); void slotWindowStepUserMovedResized(KWin::EffectWindow *w); void slotWindowFinishUserMovedResized(KWin::EffectWindow *w); private: enum RotationDirection { Left, Right, Upwards, Downwards }; void paintSlideCube(int mask, QRegion region, ScreenPaintData& data); void windowMovingChanged(float progress, RotationDirection direction); bool cube_painting; int front_desktop; int painting_desktop; int other_desktop; bool firstDesktop; QTimeLine timeLine; QQueue slideRotations; QSet panels; QSet stickyWindows; bool dontSlidePanels; bool dontSlideStickyWindows; bool usePagerLayout; int rotationDuration; bool useWindowMoving; bool windowMoving; bool desktopChangedWhileMoving; double progressRestriction; + bool multisampling; }; } #endif diff --git a/effects/cube/cubeslide.kcfg b/effects/cube/cubeslide.kcfg index 3a6f2cbd8..4e132a3c5 100644 --- a/effects/cube/cubeslide.kcfg +++ b/effects/cube/cubeslide.kcfg @@ -1,25 +1,28 @@ 0 true false true false + + true + diff --git a/effects/cube/cubeslide_config.ui b/effects/cube/cubeslide_config.ui index 44acfe9ad..077670ff0 100644 --- a/effects/cube/cubeslide_config.ui +++ b/effects/cube/cubeslide_config.ui @@ -1,105 +1,112 @@ KWin::CubeSlideEffectConfigForm 0 0 431 161 Do not animate windows on all desktops - + Qt::Vertical 20 40 0 0 100 0 Default msec 5000 10 Do not animate panels - Rotation duration: + Ro&tation duration: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter kcfg_RotationDuration Use pager layout for animation Start animation when moving windows towards screen edges + + + + Use multisampling + + + kcfg_RotationDuration kcfg_DontSlidePanels kcfg_DontSlideStickyWindows diff --git a/effects/flipswitch/flipswitch.cpp b/effects/flipswitch/flipswitch.cpp index 533797946..f030abe54 100644 --- a/effects/flipswitch/flipswitch.cpp +++ b/effects/flipswitch/flipswitch.cpp @@ -1,989 +1,993 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2008, 2009 Martin Gräßlin 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 . *********************************************************************/ #include "flipswitch.h" // KConfigSkeleton #include "flipswitchconfig.h" #include #include #include #include #include #include #include #include #include #include namespace KWin { FlipSwitchEffect::FlipSwitchEffect() : m_selectedWindow(nullptr) , m_currentAnimationShape(QTimeLine::EaseInOutCurve) , m_active(false) , m_start(false) , m_stop(false) , m_animation(false) , m_hasKeyboardGrab(false) , m_captionFrame(NULL) { initConfig(); reconfigure(ReconfigureAll); // Caption frame m_captionFont.setBold(true); m_captionFont.setPointSize(m_captionFont.pointSize() * 2); QAction* flipSwitchCurrentAction = new QAction(this); flipSwitchCurrentAction->setObjectName(QStringLiteral("FlipSwitchCurrent")); flipSwitchCurrentAction->setText(i18n("Toggle Flip Switch (Current desktop)")); KGlobalAccel::self()->setShortcut(flipSwitchCurrentAction, QList()); m_shortcutCurrent = KGlobalAccel::self()->shortcut(flipSwitchCurrentAction); effects->registerGlobalShortcut(QKeySequence(), flipSwitchCurrentAction); connect(flipSwitchCurrentAction, SIGNAL(triggered(bool)), this, SLOT(toggleActiveCurrent())); QAction* flipSwitchAllAction = new QAction(this); flipSwitchAllAction->setObjectName(QStringLiteral("FlipSwitchAll")); flipSwitchAllAction->setText(i18n("Toggle Flip Switch (All desktops)")); KGlobalAccel::self()->setShortcut(flipSwitchAllAction, QList()); effects->registerGlobalShortcut(QKeySequence(), flipSwitchAllAction); m_shortcutAll = KGlobalAccel::self()->shortcut(flipSwitchAllAction); connect(flipSwitchAllAction, SIGNAL(triggered(bool)), this, SLOT(toggleActiveAllDesktops())); connect(KGlobalAccel::self(), &KGlobalAccel::globalShortcutChanged, this, &FlipSwitchEffect::globalShortcutChanged); connect(effects, SIGNAL(windowAdded(KWin::EffectWindow*)), this, SLOT(slotWindowAdded(KWin::EffectWindow*))); connect(effects, SIGNAL(windowClosed(KWin::EffectWindow*)), this, SLOT(slotWindowClosed(KWin::EffectWindow*))); connect(effects, SIGNAL(tabBoxAdded(int)), this, SLOT(slotTabBoxAdded(int))); connect(effects, SIGNAL(tabBoxClosed()), this, SLOT(slotTabBoxClosed())); connect(effects, SIGNAL(tabBoxUpdated()), this, SLOT(slotTabBoxUpdated())); connect(effects, SIGNAL(tabBoxKeyEvent(QKeyEvent*)), this, SLOT(slotTabBoxKeyEvent(QKeyEvent*))); } FlipSwitchEffect::~FlipSwitchEffect() { delete m_captionFrame; } bool FlipSwitchEffect::supported() { return effects->isOpenGLCompositing() && effects->animationsSupported(); } void FlipSwitchEffect::reconfigure(ReconfigureFlags) { FlipSwitchConfig::self()->read(); m_tabbox = FlipSwitchConfig::tabBox(); m_tabboxAlternative = FlipSwitchConfig::tabBoxAlternative(); const int duration = animationTime(200); m_timeLine.setDuration(duration); m_startStopTimeLine.setDuration(duration); m_angle = FlipSwitchConfig::angle(); m_xPosition = FlipSwitchConfig::xPosition() / 100.0f; m_yPosition = FlipSwitchConfig::yPosition() / 100.0f; m_windowTitle = FlipSwitchConfig::windowTitle(); + m_multisampling = FlipSwitchConfig::multisampling(); } void FlipSwitchEffect::prePaintScreen(ScreenPrePaintData& data, int time) { if (m_active) { data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; + if (m_multisampling) { + data.mask |= PAINT_SCREEN_MULTISAMPLE; + } if (m_start) m_startStopTimeLine.setCurrentTime(m_startStopTimeLine.currentTime() + time); if (m_stop && m_scheduledDirections.isEmpty()) m_startStopTimeLine.setCurrentTime(m_startStopTimeLine.currentTime() - time); if (m_animation) m_timeLine.setCurrentTime(m_timeLine.currentTime() + time); } effects->prePaintScreen(data, time); } void FlipSwitchEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) { effects->paintScreen(mask, region, data); if (m_active) { EffectWindowList tempList; if (m_mode == TabboxMode) tempList = effects->currentTabBoxWindowList(); else { // we have to setup the list // using stacking order directly is not possible // as not each window in stacking order is shown // TODO: store list instead of calculating in each frame? foreach (EffectWindow * w, effects->stackingOrder()) { if (m_windows.contains(w)) tempList.append(w); } } m_flipOrderedWindows.clear(); int index = tempList.indexOf(m_selectedWindow); int tabIndex = index; if (m_mode == TabboxMode) { foreach (SwitchingDirection direction, m_scheduledDirections) { // krazy:exclude=foreach if (direction == DirectionBackward) index++; else index--; if (index < 0) index = tempList.count() + index; if (index >= tempList.count()) index = index % tempList.count(); } tabIndex = index; EffectWindow* w = NULL; if (!m_scheduledDirections.isEmpty() && m_scheduledDirections.head() == DirectionBackward) { index--; if (index < 0) index = tempList.count() + index; w = tempList.at(index); } for (int i = index - 1; i >= 0; i--) m_flipOrderedWindows.append(tempList.at(i)); for (int i = effects->currentTabBoxWindowList().count() - 1; i >= index; i--) m_flipOrderedWindows.append(tempList.at(i)); if (w) { m_flipOrderedWindows.removeAll(w); m_flipOrderedWindows.append(w); } } else { foreach (SwitchingDirection direction, m_scheduledDirections) { // krazy:exclude=foreach if (direction == DirectionForward) index++; else index--; if (index < 0) index = tempList.count() - 1; if (index >= tempList.count()) index = 0; } tabIndex = index; EffectWindow* w = NULL; if (!m_scheduledDirections.isEmpty() && m_scheduledDirections.head() == DirectionBackward) { index++; if (index >= tempList.count()) index = 0; } // sort from stacking order for (int i = index + 1; i < tempList.count(); i++) m_flipOrderedWindows.append(tempList.at(i)); for (int i = 0; i <= index; i++) m_flipOrderedWindows.append(tempList.at(i)); if (w) { m_flipOrderedWindows.removeAll(w); m_flipOrderedWindows.append(w); } } int winMask = PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_TRANSLUCENT; // fade in/out one window at the end of the stack during animation if (m_animation && !m_scheduledDirections.isEmpty()) { EffectWindow* w = m_flipOrderedWindows.last(); if (ItemInfo *info = m_windows.value(w,0)) { WindowPaintData data(w); if (effects->numScreens() > 1) { data.setProjectionMatrix(m_projectionMatrix); data.setModelViewMatrix(m_modelviewMatrix); } data.setRotationAxis(Qt::YAxis); data.setRotationAngle(m_angle * m_startStopTimeLine.currentValue()); data.setOpacity(info->opacity); data.setBrightness(info->brightness); data.setSaturation(info->saturation); int distance = tempList.count() - 1; float zDistance = 500.0f; data.translate(- (w->x() - m_screenArea.x() + data.xTranslation()) * m_startStopTimeLine.currentValue()); data.translate(m_screenArea.width() * m_xPosition * m_startStopTimeLine.currentValue(), (m_screenArea.y() + m_screenArea.height() * m_yPosition - (w->y() + w->height() + data.yTranslation())) * m_startStopTimeLine.currentValue()); data.translate(- (m_screenArea.width() * 0.25f) * distance * m_startStopTimeLine.currentValue(), - (m_screenArea.height() * 0.10f) * distance * m_startStopTimeLine.currentValue(), - (zDistance * distance) * m_startStopTimeLine.currentValue()); if (m_scheduledDirections.head() == DirectionForward) data.multiplyOpacity(0.8 * m_timeLine.currentValue()); else data.multiplyOpacity(0.8 * (1.0 - m_timeLine.currentValue())); if (effects->numScreens() > 1) { adjustWindowMultiScreen(w, data); } effects->drawWindow(w, winMask, infiniteRegion(), data); } } foreach (EffectWindow *w, m_flipOrderedWindows) { ItemInfo *info = m_windows.value(w,0); if (!info) continue; WindowPaintData data(w); if (effects->numScreens() > 1) { data.setProjectionMatrix(m_projectionMatrix); data.setModelViewMatrix(m_modelviewMatrix); } data.setRotationAxis(Qt::YAxis); data.setRotationAngle(m_angle * m_startStopTimeLine.currentValue()); data.setOpacity(info->opacity); data.setBrightness(info->brightness); data.setSaturation(info->saturation); int windowIndex = tempList.indexOf(w); int distance; if (m_mode == TabboxMode) { if (windowIndex < tabIndex) distance = tempList.count() - (tabIndex - windowIndex); else if (windowIndex > tabIndex) distance = windowIndex - tabIndex; else distance = 0; } else { distance = m_flipOrderedWindows.count() - m_flipOrderedWindows.indexOf(w) - 1; if (!m_scheduledDirections.isEmpty() && m_scheduledDirections.head() == DirectionBackward) { distance--; } } if (!m_scheduledDirections.isEmpty() && m_scheduledDirections.head() == DirectionBackward) { if (w == m_flipOrderedWindows.last()) { distance = -1; data.multiplyOpacity(m_timeLine.currentValue()); } } float zDistance = 500.0f; data.translate(- (w->x() - m_screenArea.x() + data.xTranslation()) * m_startStopTimeLine.currentValue()); data.translate(m_screenArea.width() * m_xPosition * m_startStopTimeLine.currentValue(), (m_screenArea.y() + m_screenArea.height() * m_yPosition - (w->y() + w->height() + data.yTranslation())) * m_startStopTimeLine.currentValue()); data.translate(-(m_screenArea.width() * 0.25f) * distance * m_startStopTimeLine.currentValue(), -(m_screenArea.height() * 0.10f) * distance * m_startStopTimeLine.currentValue(), -(zDistance * distance) * m_startStopTimeLine.currentValue()); if (m_animation && !m_scheduledDirections.isEmpty()) { if (m_scheduledDirections.head() == DirectionForward) { data.translate((m_screenArea.width() * 0.25f) * m_timeLine.currentValue(), (m_screenArea.height() * 0.10f) * m_timeLine.currentValue(), zDistance * m_timeLine.currentValue()); if (distance == 0) data.multiplyOpacity((1.0 - m_timeLine.currentValue())); } else { data.translate(- (m_screenArea.width() * 0.25f) * m_timeLine.currentValue(), - (m_screenArea.height() * 0.10f) * m_timeLine.currentValue(), - zDistance * m_timeLine.currentValue()); } } data.multiplyOpacity((0.8 + 0.2 * (1.0 - m_startStopTimeLine.currentValue()))); if (effects->numScreens() > 1) { adjustWindowMultiScreen(w, data); } effects->drawWindow(w, winMask, infiniteRegion(), data); } if (m_windowTitle) { // Render the caption frame if (m_animation) { m_captionFrame->setCrossFadeProgress(m_timeLine.currentValue()); } m_captionFrame->render(region, m_startStopTimeLine.currentValue()); } } } void FlipSwitchEffect::postPaintScreen() { if (m_active) { if (m_start && m_startStopTimeLine.currentValue() == 1.0f) { m_start = false; if (!m_scheduledDirections.isEmpty()) { m_animation = true; m_timeLine.setCurrentTime(0); if (m_scheduledDirections.count() == 1) { m_currentAnimationShape = QTimeLine::EaseOutCurve; m_timeLine.setCurveShape(m_currentAnimationShape); } else { m_currentAnimationShape = QTimeLine::LinearCurve; m_timeLine.setCurveShape(m_currentAnimationShape); } } effects->addRepaintFull(); } if (m_stop && m_startStopTimeLine.currentValue() == 0.0f) { m_stop = false; m_active = false; m_captionFrame->free(); effects->setActiveFullScreenEffect(0); effects->addRepaintFull(); qDeleteAll(m_windows); m_windows.clear(); } if (m_animation && m_timeLine.currentValue() == 1.0f) { m_timeLine.setCurrentTime(0); m_scheduledDirections.dequeue(); if (m_scheduledDirections.isEmpty()) { m_animation = false; effects->addRepaintFull(); } else { if (m_scheduledDirections.count() == 1) { if (m_stop) m_currentAnimationShape = QTimeLine::LinearCurve; else m_currentAnimationShape = QTimeLine::EaseOutCurve; } else { m_currentAnimationShape = QTimeLine::LinearCurve; } m_timeLine.setCurveShape(m_currentAnimationShape); } } if (m_start || m_stop || m_animation) effects->addRepaintFull(); } effects->postPaintScreen(); } void FlipSwitchEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) { if (m_active) { if (m_windows.contains(w)) { data.setTransformed(); data.setTranslucent(); if (!w->isOnCurrentDesktop()) w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); if (w->isMinimized()) w->enablePainting(EffectWindow::PAINT_DISABLED_BY_MINIMIZE); if (!w->isCurrentTab()) w->enablePainting(EffectWindow::PAINT_DISABLED_BY_TAB_GROUP); } else { if ((m_start || m_stop) && !w->isDesktop() && w->isOnCurrentDesktop()) data.setTranslucent(); else if (!w->isDesktop()) w->disablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } } effects->prePaintWindow(w, data, time); } void FlipSwitchEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) { if (m_active) { ItemInfo *info = m_windows.value(w,0); if (info) { info->opacity = data.opacity(); info->brightness = data.brightness(); info->saturation = data.saturation(); } // fade out all windows not in window list except the desktops const bool isFader = (m_start || m_stop) && !info && !w->isDesktop(); if (isFader) data.multiplyOpacity((1.0 - m_startStopTimeLine.currentValue())); // if not a fader or the desktop, skip painting here to prevent flicker if (!(isFader || w->isDesktop())) return; } effects->paintWindow(w, mask, region, data); } //************************************************************* // Tabbox handling //************************************************************* void FlipSwitchEffect::slotTabBoxAdded(int mode) { if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return; // only for windows mode effects->setShowingDesktop(false); if (((mode == TabBoxWindowsMode && m_tabbox) || (mode == TabBoxWindowsAlternativeMode && m_tabboxAlternative) || (mode == TabBoxCurrentAppWindowsMode && m_tabbox) || (mode == TabBoxCurrentAppWindowsAlternativeMode && m_tabboxAlternative)) && (!m_active || (m_active && m_stop)) && !effects->currentTabBoxWindowList().isEmpty()) { setActive(true, TabboxMode); if (m_active) effects->refTabBox(); } } void FlipSwitchEffect::slotTabBoxClosed() { if (m_active) { setActive(false, TabboxMode); effects->unrefTabBox(); } } void FlipSwitchEffect::slotTabBoxUpdated() { if (m_active && !m_stop) { if (!effects->currentTabBoxWindowList().isEmpty()) { // determine the switch direction if (m_selectedWindow != effects->currentTabBoxWindow()) { if (m_selectedWindow != NULL) { int old_index = effects->currentTabBoxWindowList().indexOf(m_selectedWindow); int new_index = effects->currentTabBoxWindowList().indexOf(effects->currentTabBoxWindow()); SwitchingDirection new_direction; int distance = new_index - old_index; if (distance > 0) new_direction = DirectionForward; if (distance < 0) new_direction = DirectionBackward; if (effects->currentTabBoxWindowList().count() == 2) { new_direction = DirectionForward; distance = 1; } if (distance != 0) { distance = abs(distance); int tempDistance = effects->currentTabBoxWindowList().count() - distance; if (tempDistance < abs(distance)) { distance = tempDistance; if (new_direction == DirectionForward) new_direction = DirectionBackward; else new_direction = DirectionForward; } scheduleAnimation(new_direction, distance); } } m_selectedWindow = effects->currentTabBoxWindow(); updateCaption(); } } effects->addRepaintFull(); } } //************************************************************* // Window adding/removing handling //************************************************************* void FlipSwitchEffect::slotWindowAdded(EffectWindow* w) { if (m_active && isSelectableWindow(w)) { m_windows[ w ] = new ItemInfo; } } void FlipSwitchEffect::slotWindowClosed(EffectWindow* w) { if (m_selectedWindow == w) m_selectedWindow = 0; if (m_active) { QHash< const EffectWindow*, ItemInfo* >::iterator it = m_windows.find(w); if (it != m_windows.end()) { delete *it; m_windows.erase(it); } } } //************************************************************* // Activation //************************************************************* void FlipSwitchEffect::setActive(bool activate, FlipSwitchMode mode) { if (activate) { // effect already active, do some sanity checks if (m_active) { if (m_stop) { if (mode != m_mode) { // only the same mode may reactivate the effect return; } } else { // active, but not scheduled for closing -> abort return; } } m_mode = mode; foreach (EffectWindow * w, effects->stackingOrder()) { if (isSelectableWindow(w) && !m_windows.contains(w)) m_windows[ w ] = new ItemInfo; } if (m_windows.isEmpty()) return; effects->setActiveFullScreenEffect(this); m_active = true; m_start = true; m_startStopTimeLine.setCurveShape(QTimeLine::EaseInOutCurve); m_activeScreen = effects->activeScreen(); m_screenArea = effects->clientArea(ScreenArea, m_activeScreen, effects->currentDesktop()); if (effects->numScreens() > 1) { // unfortunatelly we have to change the projection matrix in dual screen mode // code is copied from Coverswitch QRect fullRect = effects->clientArea(FullArea, m_activeScreen, effects->currentDesktop()); float fovy = 60.0f; float aspect = 1.0f; float zNear = 0.1f; float zFar = 100.0f; float ymax = zNear * std::tan(fovy * M_PI / 360.0f); float ymin = -ymax; float xmin = ymin * aspect; float xmax = ymax * aspect; if (m_screenArea.width() != fullRect.width()) { if (m_screenArea.x() == 0) { // horizontal layout: left screen xmin *= (float)m_screenArea.width() / (float)fullRect.width(); xmax *= (fullRect.width() - 0.5f * m_screenArea.width()) / (0.5f * fullRect.width()); } else { // horizontal layout: right screen xmin *= (fullRect.width() - 0.5f * m_screenArea.width()) / (0.5f * fullRect.width()); xmax *= (float)m_screenArea.width() / (float)fullRect.width(); } } if (m_screenArea.height() != fullRect.height()) { if (m_screenArea.y() == 0) { // vertical layout: top screen ymin *= (fullRect.height() - 0.5f * m_screenArea.height()) / (0.5f * fullRect.height()); ymax *= (float)m_screenArea.height() / (float)fullRect.height(); } else { // vertical layout: bottom screen ymin *= (float)m_screenArea.height() / (float)fullRect.height(); ymax *= (fullRect.height() - 0.5f * m_screenArea.height()) / (0.5f * fullRect.height()); } } m_projectionMatrix = QMatrix4x4(); m_projectionMatrix.frustum(xmin, xmax, ymin, ymax, zNear, zFar); const float scaleFactor = 1.1f / zNear; // Create a second matrix that transforms screen coordinates // to world coordinates. QMatrix4x4 matrix; matrix.translate(xmin * scaleFactor, ymax * scaleFactor, -1.1); matrix.scale( (xmax - xmin) * scaleFactor / fullRect.width(), -(ymax - ymin) * scaleFactor / fullRect.height(), 0.001); // Combine the matrices m_projectionMatrix *= matrix; m_modelviewMatrix = QMatrix4x4(); m_modelviewMatrix.translate(m_screenArea.x(), m_screenArea.y(), 0.0); } if (m_stop) { // effect is still closing from last usage m_stop = false; } else { // things to do only when there is no closing animation m_scheduledDirections.clear(); } switch(m_mode) { case TabboxMode: m_selectedWindow = effects->currentTabBoxWindow(); effects->startMouseInterception(this, Qt::ArrowCursor); break; case CurrentDesktopMode: m_selectedWindow = effects->activeWindow(); effects->startMouseInterception(this, Qt::BlankCursor); m_hasKeyboardGrab = effects->grabKeyboard(this); break; case AllDesktopsMode: m_selectedWindow = effects->activeWindow(); effects->startMouseInterception(this, Qt::BlankCursor); m_hasKeyboardGrab = effects->grabKeyboard(this); break; } // Setup caption frame geometry QRect frameRect = QRect(m_screenArea.width() * 0.25f + m_screenArea.x(), m_screenArea.height() * 0.1f + m_screenArea.y() - QFontMetrics(m_captionFont).height(), m_screenArea.width() * 0.5f, QFontMetrics(m_captionFont).height()); if (!m_captionFrame) { m_captionFrame = effects->effectFrame(EffectFrameStyled); m_captionFrame->setFont(m_captionFont); m_captionFrame->enableCrossFade(true); } m_captionFrame->setGeometry(frameRect); m_captionFrame->setIconSize(QSize(frameRect.height(), frameRect.height())); updateCaption(); effects->addRepaintFull(); } else { // only deactivate if mode is current mode if (mode != m_mode) return; if (m_start && m_scheduledDirections.isEmpty()) { m_start = false; } m_stop = true; if (m_animation) { m_startStopTimeLine.setCurveShape(QTimeLine::EaseOutCurve); if (m_scheduledDirections.count() == 1) { if (m_currentAnimationShape == QTimeLine::EaseInOutCurve) m_currentAnimationShape = QTimeLine::EaseInCurve; else if (m_currentAnimationShape == QTimeLine::EaseOutCurve) m_currentAnimationShape = QTimeLine::LinearCurve; m_timeLine.setCurveShape(m_currentAnimationShape); } } else m_startStopTimeLine.setCurveShape(QTimeLine::EaseInOutCurve); effects->stopMouseInterception(this); if (m_hasKeyboardGrab) { effects->ungrabKeyboard(); m_hasKeyboardGrab = false; } effects->addRepaintFull(); } } void FlipSwitchEffect::toggleActiveAllDesktops() { if (m_active) { if (m_stop) { // reactivate if stopping setActive(true, AllDesktopsMode); } else { // deactivate if not stopping setActive(false, AllDesktopsMode); } } else { setActive(true, AllDesktopsMode); } } void FlipSwitchEffect::toggleActiveCurrent() { if (m_active) { if (m_stop) { // reactivate if stopping setActive(true, CurrentDesktopMode); } else { // deactivate if not stopping setActive(false, CurrentDesktopMode); } } else { setActive(true, CurrentDesktopMode); } } //************************************************************* // Helper function //************************************************************* bool FlipSwitchEffect::isSelectableWindow(EffectWindow* w) const { // desktop windows might be included if ((w->isSpecialWindow() && !w->isDesktop()) || w->isUtility()) return false; if (w->isDesktop()) return (m_mode == TabboxMode && effects->currentTabBoxWindowList().contains(w)); if (w->isDeleted()) return false; if (!w->acceptsFocus()) return false; switch(m_mode) { case TabboxMode: return effects->currentTabBoxWindowList().contains(w); case CurrentDesktopMode: return w->isOnCurrentDesktop(); case AllDesktopsMode: //nothing special break; } return true; } void FlipSwitchEffect::scheduleAnimation(const SwitchingDirection& direction, int distance) { if (m_start) { // start is still active so change the shape to have a nice transition m_startStopTimeLine.setCurveShape(QTimeLine::EaseInCurve); } if (!m_animation && !m_start) { m_animation = true; m_scheduledDirections.enqueue(direction); distance--; // reset shape just to make sure m_currentAnimationShape = QTimeLine::EaseInOutCurve; m_timeLine.setCurveShape(m_currentAnimationShape); } for (int i = 0; i < distance; i++) { if (m_scheduledDirections.count() > 1 && m_scheduledDirections.last() != direction) m_scheduledDirections.pop_back(); else m_scheduledDirections.enqueue(direction); if (m_scheduledDirections.count() == m_windows.count() + 1) { SwitchingDirection temp = m_scheduledDirections.dequeue(); m_scheduledDirections.clear(); m_scheduledDirections.enqueue(temp); } } if (m_scheduledDirections.count() > 1) { QTimeLine::CurveShape newShape = QTimeLine::EaseInOutCurve; switch(m_currentAnimationShape) { case QTimeLine::EaseInOutCurve: newShape = QTimeLine::EaseInCurve; break; case QTimeLine::EaseOutCurve: newShape = QTimeLine::LinearCurve; break; default: newShape = m_currentAnimationShape; } if (newShape != m_currentAnimationShape) { m_currentAnimationShape = newShape; m_timeLine.setCurveShape(m_currentAnimationShape); } } } void FlipSwitchEffect::adjustWindowMultiScreen(const KWin::EffectWindow* w, WindowPaintData& data) { if (effects->numScreens() <= 1) return; QRect clientRect = effects->clientArea(FullScreenArea, w->screen(), effects->currentDesktop()); QRect rect = effects->clientArea(ScreenArea, m_activeScreen, effects->currentDesktop()); QRect fullRect = effects->clientArea(FullArea, m_activeScreen, effects->currentDesktop()); if (w->screen() == m_activeScreen) { if (clientRect.width() != fullRect.width() && clientRect.x() != fullRect.x()) { data.translate(- clientRect.x()); } if (clientRect.height() != fullRect.height() && clientRect.y() != fullRect.y()) { data.translate(0.0, - clientRect.y()); } } else { if (clientRect.width() != fullRect.width() && clientRect.x() < rect.x()) { data.translate(- (m_screenArea.x() - clientRect.x())); } if (clientRect.height() != fullRect.height() && clientRect.y() < m_screenArea.y()) { data.translate(0.0, - (m_screenArea.y() - clientRect.y())); } } } void FlipSwitchEffect::selectNextOrPreviousWindow(bool forward) { if (!m_active || !m_selectedWindow) { return; } const int index = effects->currentTabBoxWindowList().indexOf(m_selectedWindow); int newIndex = index; if (forward) { ++newIndex; } else { --newIndex; } if (newIndex == effects->currentTabBoxWindowList().size()) { newIndex = 0; } else if (newIndex < 0) { newIndex = effects->currentTabBoxWindowList().size() -1; } if (index == newIndex) { return; } effects->setTabBoxWindow(effects->currentTabBoxWindowList().at(newIndex)); } //************************************************************* // Keyboard handling //************************************************************* void FlipSwitchEffect::globalShortcutChanged(QAction *action, QKeySequence shortcut) { if (action->objectName() == QStringLiteral("FlipSwitchAll")) { m_shortcutAll.clear(); m_shortcutAll.append(shortcut); } else if (action->objectName() == QStringLiteral("FlipSwitchCurrent")) { m_shortcutCurrent.clear(); m_shortcutCurrent.append(shortcut); } } void FlipSwitchEffect::grabbedKeyboardEvent(QKeyEvent* e) { if (e->type() == QEvent::KeyPress) { // check for global shortcuts // HACK: keyboard grab disables the global shortcuts so we have to check for global shortcut (bug 156155) if (m_mode == CurrentDesktopMode && m_shortcutCurrent.contains(e->key() + e->modifiers())) { toggleActiveCurrent(); return; } if (m_mode == AllDesktopsMode && m_shortcutAll.contains(e->key() + e->modifiers())) { toggleActiveAllDesktops(); return; } switch(e->key()) { case Qt::Key_Escape: setActive(false, m_mode); return; case Qt::Key_Tab: { // find next window if (m_windows.isEmpty()) return; // sanity check bool found = false; for (int i = effects->stackingOrder().indexOf(m_selectedWindow) - 1; i >= 0; i--) { if (isSelectableWindow(effects->stackingOrder().at(i))) { m_selectedWindow = effects->stackingOrder().at(i); found = true; break; } } if (!found) { for (int i = effects->stackingOrder().count() - 1; i > effects->stackingOrder().indexOf(m_selectedWindow); i--) { if (isSelectableWindow(effects->stackingOrder().at(i))) { m_selectedWindow = effects->stackingOrder().at(i); found = true; break; } } } if (found) { updateCaption(); scheduleAnimation(DirectionForward); } break; } case Qt::Key_Backtab: { // find previous window if (m_windows.isEmpty()) return; // sanity check bool found = false; for (int i = effects->stackingOrder().indexOf(m_selectedWindow) + 1; i < effects->stackingOrder().count(); i++) { if (isSelectableWindow(effects->stackingOrder().at(i))) { m_selectedWindow = effects->stackingOrder().at(i); found = true; break; } } if (!found) { for (int i = 0; i < effects->stackingOrder().indexOf(m_selectedWindow); i++) { if (isSelectableWindow(effects->stackingOrder().at(i))) { m_selectedWindow = effects->stackingOrder().at(i); found = true; break; } } } if (found) { updateCaption(); scheduleAnimation(DirectionBackward); } break; } case Qt::Key_Return: case Qt::Key_Enter: case Qt::Key_Space: if (m_selectedWindow) effects->activateWindow(m_selectedWindow); setActive(false, m_mode); break; default: break; } effects->addRepaintFull(); } } void FlipSwitchEffect::slotTabBoxKeyEvent(QKeyEvent *event) { if (event->type() == QEvent::KeyPress) { switch (event->key()) { case Qt::Key_Up: case Qt::Key_Left: selectPreviousWindow(); break; case Qt::Key_Down: case Qt::Key_Right: selectNextWindow(); break; default: // nothing break; } } } bool FlipSwitchEffect::isActive() const { return m_active && !effects->isScreenLocked(); } void FlipSwitchEffect::updateCaption() { if (!m_selectedWindow) { return; } if (m_selectedWindow->isDesktop()) { m_captionFrame->setText(i18nc("Special entry in alt+tab list for minimizing all windows", "Show Desktop")); static QPixmap pix = QIcon::fromTheme(QStringLiteral("user-desktop")).pixmap(m_captionFrame->iconSize()); m_captionFrame->setIcon(pix); } else { m_captionFrame->setText(m_selectedWindow->caption()); m_captionFrame->setIcon(m_selectedWindow->icon()); } } //************************************************************* // Mouse handling //************************************************************* void FlipSwitchEffect::windowInputMouseEvent(QEvent* e) { if (e->type() != QEvent::MouseButtonPress) return; // we don't want click events during animations if (m_animation) return; QMouseEvent* event = static_cast< QMouseEvent* >(e); switch (event->button()) { case Qt::XButton1: // wheel up selectPreviousWindow(); break; case Qt::XButton2: // wheel down selectNextWindow(); break; case Qt::LeftButton: case Qt::RightButton: case Qt::MidButton: default: // TODO: Change window on mouse button click break; } } //************************************************************* // Item Info //************************************************************* FlipSwitchEffect::ItemInfo::ItemInfo() : deleted(false) , opacity(0.0) , brightness(0.0) , saturation(0.0) { } FlipSwitchEffect::ItemInfo::~ItemInfo() { } } // namespace diff --git a/effects/flipswitch/flipswitch.h b/effects/flipswitch/flipswitch.h index add05b4ff..372f6f310 100644 --- a/effects/flipswitch/flipswitch.h +++ b/effects/flipswitch/flipswitch.h @@ -1,165 +1,166 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2008, 2009 Martin Gräßlin 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 . *********************************************************************/ #ifndef KWIN_FLIPSWITCH_H #define KWIN_FLIPSWITCH_H #include #include #include #include #include namespace KWin { class FlipSwitchEffect : public Effect { Q_OBJECT Q_PROPERTY(bool tabBox READ isTabBox) Q_PROPERTY(bool tabBoxAlternative READ isTabBoxAlternative) Q_PROPERTY(int duration READ duration) Q_PROPERTY(int angle READ angle) Q_PROPERTY(qreal xPosition READ xPosition) Q_PROPERTY(qreal yPosition READ yPosition) Q_PROPERTY(bool windowTitle READ isWindowTitle) public: FlipSwitchEffect(); ~FlipSwitchEffect(); virtual void reconfigure(ReconfigureFlags); virtual void prePaintScreen(ScreenPrePaintData& data, int time); virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); virtual void postPaintScreen(); virtual void prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time); virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); virtual void grabbedKeyboardEvent(QKeyEvent* e); virtual void windowInputMouseEvent(QEvent* e); virtual bool isActive() const; int requestedEffectChainPosition() const override { return 50; } static bool supported(); // for properties bool isTabBox() const { return m_tabbox; } bool isTabBoxAlternative() const { return m_tabboxAlternative; } int duration() const { return m_timeLine.duration(); } int angle() const { return m_angle; } qreal xPosition() const { return m_xPosition; } qreal yPosition() const { return m_yPosition; } bool isWindowTitle() const { return m_windowTitle; } private Q_SLOTS: void toggleActiveCurrent(); void toggleActiveAllDesktops(); void globalShortcutChanged(QAction *action, QKeySequence shortcut); void slotWindowAdded(KWin::EffectWindow* w); void slotWindowClosed(KWin::EffectWindow *w); void slotTabBoxAdded(int mode); void slotTabBoxClosed(); void slotTabBoxUpdated(); void slotTabBoxKeyEvent(QKeyEvent* event); private: class ItemInfo; enum SwitchingDirection { DirectionForward, DirectionBackward }; enum FlipSwitchMode { TabboxMode, CurrentDesktopMode, AllDesktopsMode }; void setActive(bool activate, FlipSwitchMode mode); bool isSelectableWindow(EffectWindow *w) const; void scheduleAnimation(const SwitchingDirection& direction, int distance = 1); void adjustWindowMultiScreen(const EffectWindow *w, WindowPaintData& data); void selectNextOrPreviousWindow(bool forward); inline void selectNextWindow() { selectNextOrPreviousWindow(true); } inline void selectPreviousWindow() { selectNextOrPreviousWindow(false); } /** * Updates the caption of the caption frame. * Taking care of rewording the desktop client. * As well sets the icon for the caption frame. **/ void updateCaption(); QQueue< SwitchingDirection> m_scheduledDirections; EffectWindow* m_selectedWindow; QTimeLine m_timeLine; QTimeLine m_startStopTimeLine; QTimeLine::CurveShape m_currentAnimationShape; QRect m_screenArea; int m_activeScreen; bool m_active; bool m_start; bool m_stop; bool m_animation; bool m_hasKeyboardGrab; FlipSwitchMode m_mode; EffectFrame* m_captionFrame; QFont m_captionFont; EffectWindowList m_flipOrderedWindows; QHash< const EffectWindow*, ItemInfo* > m_windows; QMatrix4x4 m_projectionMatrix; QMatrix4x4 m_modelviewMatrix; // options bool m_tabbox; bool m_tabboxAlternative; float m_angle; float m_xPosition; float m_yPosition; bool m_windowTitle; + bool m_multisampling; // Shortcuts QList m_shortcutCurrent; QList m_shortcutAll; }; class FlipSwitchEffect::ItemInfo { public: ItemInfo(); ~ItemInfo(); bool deleted; double opacity; double brightness; double saturation; }; } // namespace #endif diff --git a/effects/flipswitch/flipswitch.kcfg b/effects/flipswitch/flipswitch.kcfg index 37c2e7599..1e436a58c 100644 --- a/effects/flipswitch/flipswitch.kcfg +++ b/effects/flipswitch/flipswitch.kcfg @@ -1,30 +1,33 @@ false false 0 30 33 100 true + + true + diff --git a/effects/flipswitch/flipswitch_config.ui b/effects/flipswitch/flipswitch_config.ui index 02a925f6b..05c9d93a3 100644 --- a/effects/flipswitch/flipswitch_config.ui +++ b/effects/flipswitch/flipswitch_config.ui @@ -1,238 +1,242 @@ KWin::FlipSwitchEffectConfigForm 0 0 400 - 316 + 400 Appearance - Flip animation duration: + &Flip animation duration: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter kcfg_Duration 0 0 Default 5000 10 - Angle: + A&ngle: kcfg_Angle 0 0 ° 360 - + - Horizontal position of front: + &Horizontal position of front: kcfg_XPosition - + 100 Qt::Horizontal Left Qt::Horizontal 40 20 Right - + - Vertical position of front: + &Vertical position of front: kcfg_YPosition - + 100 Qt::Vertical Top Qt::Vertical 20 40 Bottom Display window &titles + + + + Use multisampling + + + Activation - + 0 0 - - KShortcutsEditor::GlobalAction - KShortcutsEditor QWidget -
KShortcutsEditor
+
kshortcutseditor.h
1
kcfg_Duration
diff --git a/effects/magiclamp/magiclamp.cpp b/effects/magiclamp/magiclamp.cpp index a392d4942..62f55df50 100644 --- a/effects/magiclamp/magiclamp.cpp +++ b/effects/magiclamp/magiclamp.cpp @@ -1,366 +1,371 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2008 Martin Gräßlin 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 . *********************************************************************/ // based on minimize animation by Rivo Laks #include "magiclamp.h" // KConfigSkeleton #include "magiclampconfig.h" #include #include #include #include namespace KWin { MagicLampEffect::MagicLampEffect() { initConfig(); mActiveAnimations = 0; reconfigure(ReconfigureAll); connect(effects, SIGNAL(windowDeleted(KWin::EffectWindow*)), this, SLOT(slotWindowDeleted(KWin::EffectWindow*))); connect(effects, SIGNAL(windowMinimized(KWin::EffectWindow*)), this, SLOT(slotWindowMinimized(KWin::EffectWindow*))); connect(effects, SIGNAL(windowUnminimized(KWin::EffectWindow*)), this, SLOT(slotWindowUnminimized(KWin::EffectWindow*))); } bool MagicLampEffect::supported() { return effects->isOpenGLCompositing() && effects->animationsSupported(); } void MagicLampEffect::reconfigure(ReconfigureFlags) { MagicLampConfig::self()->read(); // TODO: rename animationDuration to duration mAnimationDuration = animationTime(MagicLampConfig::animationDuration() != 0 ? MagicLampConfig::animationDuration() : 250); + mMultisampling = MagicLampConfig::multisampling(); } void MagicLampEffect::prePaintScreen(ScreenPrePaintData& data, int time) { QHash< EffectWindow*, QTimeLine* >::iterator entry = mTimeLineWindows.begin(); bool erase = false; while (entry != mTimeLineWindows.end()) { QTimeLine *timeline = entry.value(); if (entry.key()->isMinimized()) { timeline->setCurrentTime(timeline->currentTime() + time); erase = (timeline->currentValue() >= 1.0f); } else { timeline->setCurrentTime(timeline->currentTime() - time); erase = (timeline->currentValue() <= 0.0f); } if (erase) { delete timeline; entry = mTimeLineWindows.erase(entry); } else ++entry; } mActiveAnimations = mTimeLineWindows.count(); - if (mActiveAnimations > 0) + if (mActiveAnimations > 0) { // We need to mark the screen windows as transformed. Otherwise the // whole screen won't be repainted, resulting in artefacts data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; + if (mMultisampling) { + data.mask |= PAINT_SCREEN_MULTISAMPLE; + } + } effects->prePaintScreen(data, time); } void MagicLampEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) { // Schedule window for transformation if the animation is still in // progress if (mTimeLineWindows.contains(w)) { // We'll transform this window data.setTransformed(); data.quads = data.quads.makeGrid(40); w->enablePainting(EffectWindow::PAINT_DISABLED_BY_MINIMIZE); } effects->prePaintWindow(w, data, time); } void MagicLampEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) { if (mTimeLineWindows.contains(w)) { // 0 = not minimized, 1 = fully minimized float progress = mTimeLineWindows[w]->currentValue(); QRect geo = w->geometry(); QRect icon = w->iconGeometry(); IconPosition position = Top; // If there's no icon geometry, minimize to the center of the screen if (!icon.isValid()) { QRect extG = geo; QPoint pt = cursorPos(); // focussing inside the window is no good, leads to ugly artefacts, find nearest border if (extG.contains(pt)) { const int d[2][2] = { {pt.x() - extG.x(), extG.right() - pt.x()}, {pt.y() - extG.y(), extG.bottom() - pt.y()} }; int di = d[1][0]; position = Top; if (d[0][0] < di) { di = d[0][0]; position = Left; } if (d[1][1] < di) { di = d[1][1]; position = Bottom; } if (d[0][1] < di) position = Right; switch(position) { case Top: pt.setY(extG.y()); break; case Left: pt.setX(extG.x()); break; case Bottom: pt.setY(extG.bottom()); break; case Right: pt.setX(extG.right()); break; } } else { if (pt.y() < geo.y()) position = Top; else if (pt.x() < geo.x()) position = Left; else if (pt.y() > geo.bottom()) position = Bottom; else if (pt.x() > geo.right()) position = Right; } icon = QRect(pt, QSize(0, 0)); } else { // Assumption: there is a panel containing the icon position EffectWindow* panel = NULL; foreach (EffectWindow * window, effects->stackingOrder()) { if (!window->isDock()) continue; // we have to use intersects as there seems to be a Plasma bug // the published icon geometry might be bigger than the panel if (window->geometry().intersects(icon)) { panel = window; break; } } if (panel) { // Assumption: width of horizonal panel is greater than its height and vice versa // The panel has to border one screen edge, so get it's screen area QRect panelScreen = effects->clientArea(ScreenArea, panel); if (panel->width() >= panel->height()) { // horizontal panel if (panel->y() == panelScreen.y()) position = Top; else position = Bottom; } else { // vertical panel if (panel->x() == panelScreen.x()) position = Left; else position = Right; } } else { // we did not find a panel, so it might be autohidden QRect iconScreen = effects->clientArea(ScreenArea, icon.topLeft(), effects->currentDesktop()); // as the icon geometry could be overlap a screen edge we use an intersection QRect rect = iconScreen.intersected(icon); // here we need a different assumption: icon geometry borders one screen edge // this assumption might be wrong for e.g. task applet being the only applet in panel // in this case the icon borders two screen edges // there might be a wrong animation, but not distorted if (rect.x() == iconScreen.x()) { position = Left; } else if (rect.x() + rect.width() == iconScreen.x() + iconScreen.width()) { position = Right; } else if (rect.y() == iconScreen.y()) { position = Top; } else { position = Bottom; } } } #define SANITIZE_PROGRESS if (p_progress[0] < 0)\ p_progress[0] = -p_progress[0];\ if (p_progress[1] < 0)\ p_progress[1] = -p_progress[1] #define SET_QUADS(_SET_A_, _A_, _DA_, _SET_B_, _B_, _O0_, _O1_, _O2_, _O3_) quad[0]._SET_A_((icon._A_() + icon._DA_()*(quad[0]._A_() / geo._DA_()) - (quad[0]._A_() + geo._A_()))*p_progress[_O0_] + quad[0]._A_());\ quad[1]._SET_A_((icon._A_() + icon._DA_()*(quad[1]._A_() / geo._DA_()) - (quad[1]._A_() + geo._A_()))*p_progress[_O1_] + quad[1]._A_());\ quad[2]._SET_A_((icon._A_() + icon._DA_()*(quad[2]._A_() / geo._DA_()) - (quad[2]._A_() + geo._A_()))*p_progress[_O2_] + quad[2]._A_());\ quad[3]._SET_A_((icon._A_() + icon._DA_()*(quad[3]._A_() / geo._DA_()) - (quad[3]._A_() + geo._A_()))*p_progress[_O3_] + quad[3]._A_());\ \ quad[0]._SET_B_(quad[0]._B_() + offset[_O0_]);\ quad[1]._SET_B_(quad[1]._B_() + offset[_O1_]);\ quad[2]._SET_B_(quad[2]._B_() + offset[_O2_]);\ quad[3]._SET_B_(quad[3]._B_() + offset[_O3_]) WindowQuadList newQuads; float quadFactor; // defines how fast a quad is vertically moved: y coordinates near to window top are slowed down // it is used as quadFactor^3/windowHeight^3 // quadFactor is the y position of the quad but is changed towards becomming the window height // by that the factor becomes 1 and has no influence any more float offset[2] = {0,0}; // how far has a quad to be moved? Distance between icon and window multiplied by the progress and by the quadFactor float p_progress[2] = {0,0}; // the factor which defines how far the x values have to be changed // factor is the current moved y value diveded by the distance between icon and window WindowQuad lastQuad(WindowQuadError); lastQuad[0].setX(-1); lastQuad[0].setY(-1); lastQuad[1].setX(-1); lastQuad[1].setY(-1); lastQuad[2].setX(-1); lastQuad[2].setY(-1); if (position == Bottom) { float height_cube = float(geo.height()) * float(geo.height()) * float(geo.height()); foreach (WindowQuad quad, data.quads) { // krazy:exclude=foreach if (quad[0].y() != lastQuad[0].y() || quad[2].y() != lastQuad[2].y()) { quadFactor = quad[0].y() + (geo.height() - quad[0].y()) * progress; offset[0] = (icon.y() + quad[0].y() - geo.y()) * progress * ((quadFactor * quadFactor * quadFactor) / height_cube); quadFactor = quad[2].y() + (geo.height() - quad[2].y()) * progress; offset[1] = (icon.y() + quad[2].y() - geo.y()) * progress * ((quadFactor * quadFactor * quadFactor) / height_cube); p_progress[1] = qMin(offset[1] / (icon.y() + icon.height() - geo.y() - float(quad[2].y())), 1.0f); p_progress[0] = qMin(offset[0] / (icon.y() + icon.height() - geo.y() - float(quad[0].y())), 1.0f); } else lastQuad = quad; SANITIZE_PROGRESS; // x values are moved towards the center of the icon SET_QUADS(setX, x, width, setY, y, 0,0,1,1); newQuads.append(quad); } } else if (position == Top) { float height_cube = float(geo.height()) * float(geo.height()) * float(geo.height()); foreach (WindowQuad quad, data.quads) { // krazy:exclude=foreach if (quad[0].y() != lastQuad[0].y() || quad[2].y() != lastQuad[2].y()) { quadFactor = geo.height() - quad[0].y() + (quad[0].y()) * progress; offset[0] = (geo.y() - icon.height() + geo.height() + quad[0].y() - icon.y()) * progress * ((quadFactor * quadFactor * quadFactor) / height_cube); quadFactor = geo.height() - quad[2].y() + (quad[2].y()) * progress; offset[1] = (geo.y() - icon.height() + geo.height() + quad[2].y() - icon.y()) * progress * ((quadFactor * quadFactor * quadFactor) / height_cube); p_progress[0] = qMin(offset[0] / (geo.y() - icon.height() + geo.height() - icon.y() - float(geo.height() - quad[0].y())), 1.0f); p_progress[1] = qMin(offset[1] / (geo.y() - icon.height() + geo.height() - icon.y() - float(geo.height() - quad[2].y())), 1.0f); } else lastQuad = quad; offset[0] = -offset[0]; offset[1] = -offset[1]; SANITIZE_PROGRESS; // x values are moved towards the center of the icon SET_QUADS(setX, x, width, setY, y, 0,0,1,1); newQuads.append(quad); } } else if (position == Left) { float width_cube = float(geo.width()) * float(geo.width()) * float(geo.width()); foreach (WindowQuad quad, data.quads) { // krazy:exclude=foreach if (quad[0].x() != lastQuad[0].x() || quad[1].x() != lastQuad[1].x()) { quadFactor = geo.width() - quad[0].x() + (quad[0].x()) * progress; offset[0] = (geo.x() - icon.width() + geo.width() + quad[0].x() - icon.x()) * progress * ((quadFactor * quadFactor * quadFactor) / width_cube); quadFactor = geo.width() - quad[1].x() + (quad[1].x()) * progress; offset[1] = (geo.x() - icon.width() + geo.width() + quad[1].x() - icon.x()) * progress * ((quadFactor * quadFactor * quadFactor) / width_cube); p_progress[0] = qMin(offset[0] / (geo.x() - icon.width() + geo.width() - icon.x() - float(geo.width() - quad[0].x())), 1.0f); p_progress[1] = qMin(offset[1] / (geo.x() - icon.width() + geo.width() - icon.x() - float(geo.width() - quad[1].x())), 1.0f); } else lastQuad = quad; offset[0] = -offset[0]; offset[1] = -offset[1]; SANITIZE_PROGRESS; // y values are moved towards the center of the icon SET_QUADS(setY, y, height, setX, x, 0,1,1,0); newQuads.append(quad); } } else if (position == Right) { float width_cube = float(geo.width()) * float(geo.width()) * float(geo.width()); foreach (WindowQuad quad, data.quads) { // krazy:exclude=foreach if (quad[0].x() != lastQuad[0].x() || quad[1].x() != lastQuad[1].x()) { quadFactor = quad[0].x() + (geo.width() - quad[0].x()) * progress; offset[0] = (icon.x() + quad[0].x() - geo.x()) * progress * ((quadFactor * quadFactor * quadFactor) / width_cube); quadFactor = quad[1].x() + (geo.width() - quad[1].x()) * progress; offset[1] = (icon.x() + quad[1].x() - geo.x()) * progress * ((quadFactor * quadFactor * quadFactor) / width_cube); p_progress[0] = qMin(offset[0] / (icon.x() + icon.width() - geo.x() - float(quad[0].x())), 1.0f); p_progress[1] = qMin(offset[1] / (icon.x() + icon.width() - geo.x() - float(quad[1].x())), 1.0f); } else lastQuad = quad; SANITIZE_PROGRESS; // y values are moved towards the center of the icon SET_QUADS(setY, y, height, setX, x, 0,1,1,0); newQuads.append(quad); } } data.quads = newQuads; } // Call the next effect. effects->paintWindow(w, mask, region, data); } void MagicLampEffect::postPaintScreen() { if (mActiveAnimations > 0) // Repaint the workspace so that everything would be repainted next time effects->addRepaintFull(); mActiveAnimations = mTimeLineWindows.count(); // Call the next effect. effects->postPaintScreen(); } void MagicLampEffect::slotWindowDeleted(EffectWindow* w) { delete mTimeLineWindows.take(w); } void MagicLampEffect::slotWindowMinimized(EffectWindow* w) { if (effects->activeFullScreenEffect()) return; if (!mTimeLineWindows.contains(w)) { mTimeLineWindows.insert(w, new QTimeLine(mAnimationDuration, this)); mTimeLineWindows[w]->setCurveShape(QTimeLine::LinearCurve); } mTimeLineWindows[w]->setCurrentTime(0); } void MagicLampEffect::slotWindowUnminimized(EffectWindow* w) { if (effects->activeFullScreenEffect()) return; if (!mTimeLineWindows.contains(w)) { mTimeLineWindows.insert(w, new QTimeLine(mAnimationDuration, this)); mTimeLineWindows[w]->setCurveShape(QTimeLine::LinearCurve); } mTimeLineWindows[w]->setCurrentTime(mAnimationDuration); } bool MagicLampEffect::isActive() const { return !mTimeLineWindows.isEmpty(); } } // namespace diff --git a/effects/magiclamp/magiclamp.h b/effects/magiclamp/magiclamp.h index 95865d4c1..8243cd50b 100644 --- a/effects/magiclamp/magiclamp.h +++ b/effects/magiclamp/magiclamp.h @@ -1,76 +1,77 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2008 Martin Gräßlin 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 . *********************************************************************/ #ifndef KWIN_MAGICLAMP_H #define KWIN_MAGICLAMP_H #include class QTimeLine; namespace KWin { class MagicLampEffect : public Effect { Q_OBJECT Q_PROPERTY(int animationDuration READ animationDuration) public: MagicLampEffect(); virtual void reconfigure(ReconfigureFlags); virtual void prePaintScreen(ScreenPrePaintData& data, int time); virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); virtual void postPaintScreen(); virtual bool isActive() const; int requestedEffectChainPosition() const override { return 50; } static bool supported(); // for properties int animationDuration() const { return mAnimationDuration; } public Q_SLOTS: void slotWindowDeleted(KWin::EffectWindow *w); void slotWindowMinimized(KWin::EffectWindow *w); void slotWindowUnminimized(KWin::EffectWindow *w); private: QHash< EffectWindow*, QTimeLine* > mTimeLineWindows; int mActiveAnimations; int mAnimationDuration; + bool mMultisampling; enum IconPosition { Top, Bottom, Left, Right }; }; } // namespace #endif diff --git a/effects/magiclamp/magiclamp.kcfg b/effects/magiclamp/magiclamp.kcfg index 67c8ba0c1..80cd96786 100644 --- a/effects/magiclamp/magiclamp.kcfg +++ b/effects/magiclamp/magiclamp.kcfg @@ -1,12 +1,15 @@ 0 + + true + diff --git a/effects/magiclamp/magiclamp_config.ui b/effects/magiclamp/magiclamp_config.ui index 9e1063ac6..ba589e9ec 100644 --- a/effects/magiclamp/magiclamp_config.ui +++ b/effects/magiclamp/magiclamp_config.ui @@ -1,53 +1,77 @@ KWin::MagicLampEffectConfigForm 0 0 - 400 - 300 + 383 + 191 - - - + + + + + + + A&nimation duration: + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + kcfg_AnimationDuration + + + + + + + + 0 + 0 + + + + Default + + + milliseconds + + + 5000 + + + 10 + + + + + + + - Animation duration: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - kcfg_AnimationDuration + Use multisampling - - - - - 0 - 0 - - - - Default + + + + Qt::Vertical - - milliseconds + + + 20 + 40 + - - 5000 - - - 10 - - + diff --git a/libkwineffects/kwineffects.h b/libkwineffects/kwineffects.h index 04e77aa1f..ee076576b 100644 --- a/libkwineffects/kwineffects.h +++ b/libkwineffects/kwineffects.h @@ -1,3497 +1,3501 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak Copyright (C) 2009 Lucas Murray Copyright (C) 2010, 2011 Martin Gräßlin 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 . *********************************************************************/ #ifndef KWINEFFECTS_H #define KWINEFFECTS_H #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include class KConfigGroup; class QFont; class QGraphicsScale; class QKeyEvent; class QMatrix4x4; class QAction; /** * Logging category to be used inside the KWin effects. * Do not use in this library. **/ Q_DECLARE_LOGGING_CATEGORY(KWINEFFECTS) namespace KWayland { namespace Server { class SurfaceInterface; class Display; } } namespace KWin { class PaintDataPrivate; class WindowPaintDataPrivate; class EffectWindow; class EffectWindowGroup; class EffectFrame; class EffectFramePrivate; class Effect; class WindowQuad; class GLShader; class XRenderPicture; class WindowQuadList; class WindowPrePaintData; class WindowPaintData; class ScreenPrePaintData; class ScreenPaintData; typedef QPair< QString, Effect* > EffectPair; typedef QList< KWin::EffectWindow* > EffectWindowList; /** @defgroup kwineffects KWin effects library * KWin effects library contains necessary classes for creating new KWin * compositing effects. * * @section creating Creating new effects * This example will demonstrate the basics of creating an effect. We'll use * CoolEffect as the class name, cooleffect as internal name and * "Cool Effect" as user-visible name of the effect. * * This example doesn't demonstrate how to write the effect's code. For that, * see the documentation of the Effect class. * * @subsection creating-class CoolEffect class * First you need to create CoolEffect class which has to be a subclass of * @ref KWin::Effect. In that class you can reimplement various virtual * methods to control how and where the windows are drawn. * * @subsection creating-macro KWIN_EFFECT_FACTORY macro * This library provides a specialized KPluginFactory subclass and macros to * create a sub class. This subclass of KPluginFactory has to be used, otherwise * KWin won't load the plugin. Use the @ref KWIN_EFFECT_FACTORY macro to create the * plugin factory. * * @subsection creating-buildsystem Buildsystem * To build the effect, you can use the KWIN_ADD_EFFECT() cmake macro which * can be found in effects/CMakeLists.txt file in KWin's source. First * argument of the macro is the name of the library that will contain * your effect. Although not strictly required, it is usually a good idea to * use the same name as your effect's internal name there. Following arguments * to the macro are the files containing your effect's source. If our effect's * source is in cooleffect.cpp, we'd use following: * @code * KWIN_ADD_EFFECT(cooleffect cooleffect.cpp) * @endcode * * This macro takes care of compiling your effect. You'll also need to install * your effect's .desktop file, so the example CMakeLists.txt file would be * as follows: * @code * KWIN_ADD_EFFECT(cooleffect cooleffect.cpp) * install( FILES cooleffect.desktop DESTINATION ${SERVICES_INSTALL_DIR}/kwin ) * @endcode * * @subsection creating-desktop Effect's .desktop file * You will also need to create .desktop file to set name, description, icon * and other properties of your effect. Important fields of the .desktop file * are: * @li Name User-visible name of your effect * @li Icon Name of the icon of the effect * @li Comment Short description of the effect * @li Type must be "Service" * @li X-KDE-ServiceTypes must be "KWin/Effect" * @li X-KDE-PluginInfo-Name effect's internal name as passed to the KWIN_EFFECT macro plus "kwin4_effect_" prefix * @li X-KDE-PluginInfo-Category effect's category. Should be one of Appearance, Accessibility, Window Management, Demos, Tests, Misc * @li X-KDE-PluginInfo-EnabledByDefault whether the effect should be enabled by default (use sparingly). Default is false * @li X-KDE-Library name of the library containing the effect. This is the first argument passed to the KWIN_ADD_EFFECT macro in cmake file plus "kwin4_effect_" prefix. * * Example cooleffect.desktop file follows: * @code [Desktop Entry] Name=Cool Effect Comment=The coolest effect you've ever seen Icon=preferences-system-windows-effect-cooleffect Type=Service X-KDE-ServiceTypes=KWin/Effect X-KDE-PluginInfo-Author=My Name X-KDE-PluginInfo-Email=my@email.here X-KDE-PluginInfo-Name=kwin4_effect_cooleffect X-KDE-PluginInfo-Category=Misc X-KDE-Library=kwin4_effect_cooleffect * @endcode * * * @section accessing Accessing windows and workspace * Effects can gain access to the properties of windows and workspace via * EffectWindow and EffectsHandler classes. * * There is one global EffectsHandler object which you can access using the * @ref effects pointer. * For each window, there is an EffectWindow object which can be used to read * window properties such as position and also to change them. * * For more information about this, see the documentation of the corresponding * classes. * * @{ **/ #define KWIN_EFFECT_API_MAKE_VERSION( major, minor ) (( major ) << 8 | ( minor )) #define KWIN_EFFECT_API_VERSION_MAJOR 0 #define KWIN_EFFECT_API_VERSION_MINOR 224 #define KWIN_EFFECT_API_VERSION KWIN_EFFECT_API_MAKE_VERSION( \ KWIN_EFFECT_API_VERSION_MAJOR, KWIN_EFFECT_API_VERSION_MINOR ) enum WindowQuadType { WindowQuadError, // for the stupid default ctor WindowQuadContents, WindowQuadDecoration, // Shadow Quad types WindowQuadShadow, // OpenGL only. The other shadow types are only used by Xrender WindowQuadShadowTop, WindowQuadShadowTopRight, WindowQuadShadowRight, WindowQuadShadowBottomRight, WindowQuadShadowBottom, WindowQuadShadowBottomLeft, WindowQuadShadowLeft, WindowQuadShadowTopLeft, EFFECT_QUAD_TYPE_START = 100 ///< @internal }; /** * EffectWindow::setData() and EffectWindow::data() global roles. * All values between 0 and 999 are reserved for global roles. */ enum DataRole { // Grab roles are used to force all other animations to ignore the window. // The value of the data is set to the Effect's `this` value. WindowAddedGrabRole = 1, WindowClosedGrabRole, WindowMinimizedGrabRole, WindowUnminimizedGrabRole, WindowForceBlurRole, ///< For fullscreen effects to enforce blurring of windows, WindowBlurBehindRole, ///< For single windows to blur behind WindowForceBackgroundContrastRole, ///< For fullscreen effects to enforce the background contrast, WindowBackgroundContrastRole, ///< For single windows to enable Background contrast LanczosCacheRole }; /** * Style types used by @ref EffectFrame. * @since 4.6 */ enum EffectFrameStyle { EffectFrameNone, ///< Displays no frame around the contents. EffectFrameUnstyled, ///< Displays a basic box around the contents. EffectFrameStyled ///< Displays a Plasma-styled frame around the contents. }; /** * Infinite region (i.e. a special region type saying that everything needs to be painted). */ KWINEFFECTS_EXPORT inline QRect infiniteRegion() { // INT_MIN / 2 because width/height is used (INT_MIN+INT_MAX==-1) return QRect(INT_MIN / 2, INT_MIN / 2, INT_MAX, INT_MAX); } /** * @short Base class for all KWin effects * * This is the base class for all effects. By reimplementing virtual methods * of this class, you can customize how the windows are painted. * * The virtual methods are used for painting and need to be implemented for * custom painting. * * In order to react to state changes (e.g. a window gets closed) the effect * should provide slots for the signals emitted by the EffectsHandler. * * @section Chaining * Most methods of this class are called in chain style. This means that when * effects A and B area active then first e.g. A::paintWindow() is called and * then from within that method B::paintWindow() is called (although * indirectly). To achieve this, you need to make sure to call corresponding * method in EffectsHandler class from each such method (using @ref effects * pointer): * @code * void MyEffect::postPaintScreen() * { * // Do your own processing here * ... * // Call corresponding EffectsHandler method * effects->postPaintScreen(); * } * @endcode * * @section Effectsptr Effects pointer * @ref effects pointer points to the global EffectsHandler object that you can * use to interact with the windows. * * @section painting Painting stages * Painting of windows is done in three stages: * @li First, the prepaint pass.
* Here you can specify how the windows will be painted, e.g. that they will * be translucent and transformed. * @li Second, the paint pass.
* Here the actual painting takes place. You can change attributes such as * opacity of windows as well as apply transformations to them. You can also * paint something onto the screen yourself. * @li Finally, the postpaint pass.
* Here you can mark windows, part of windows or even the entire screen for * repainting to create animations. * * For each stage there are *Screen() and *Window() methods. The window method * is called for every window which the screen method is usually called just * once. * * @section OpenGL * Effects can use OpenGL if EffectsHandler::isOpenGLCompositing() returns @c true. * The OpenGL context may not always be current when code inside the effect is * executed. The framework ensures that the OpenGL context is current when the Effect * gets created, destroyed or reconfigured and during the painting stages. All virtual * methods which have the OpenGL context current are documented. * * If OpenGL code is going to be executed outside the painting stages, e.g. in reaction * to a global shortcut, it is the task of the Effect to make the OpenGL context current: * @code * effects->makeOpenGLContextCurrent(); * @endcode * * There is in general no need to call the matching doneCurrent method. **/ class KWINEFFECTS_EXPORT Effect : public QObject { Q_OBJECT public: /** Flags controlling how painting is done. */ // TODO: is that ok here? enum { /** * Window (or at least part of it) will be painted opaque. **/ PAINT_WINDOW_OPAQUE = 1 << 0, /** * Window (or at least part of it) will be painted translucent. **/ PAINT_WINDOW_TRANSLUCENT = 1 << 1, /** * Window will be painted with transformed geometry. **/ PAINT_WINDOW_TRANSFORMED = 1 << 2, /** * Paint only a region of the screen (can be optimized, cannot * be used together with TRANSFORMED flags). **/ PAINT_SCREEN_REGION = 1 << 3, /** * The whole screen will be painted with transformed geometry. * Forces the entire screen to be painted. **/ PAINT_SCREEN_TRANSFORMED = 1 << 4, /** * At least one window will be painted with transformed geometry. * Forces the entire screen to be painted. **/ PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS = 1 << 5, /** * Clear whole background as the very first step, without optimizing it **/ PAINT_SCREEN_BACKGROUND_FIRST = 1 << 6, // PAINT_DECORATION_ONLY = 1 << 7 has been deprecated /** * Window will be painted with a lanczos filter. **/ - PAINT_WINDOW_LANCZOS = 1 << 8 + PAINT_WINDOW_LANCZOS = 1 << 8, // PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS_WITHOUT_FULL_REPAINTS = 1 << 9 has been removed + /** + * Use multisampling. + **/ + PAINT_SCREEN_MULTISAMPLE = 1 << 10 }; enum Feature { Nothing = 0, Resize, GeometryTip, Outline, ScreenInversion, Blur, Contrast, HighlightWindows }; /** * Constructs new Effect object. * * In OpenGL based compositing, the frameworks ensures that the context is current * when the Effect is constructed. **/ Effect(); /** * Destructs the Effect object. * * In OpenGL based compositing, the frameworks ensures that the context is current * when the Effect is destroyed. **/ virtual ~Effect(); /** * Flags describing which parts of configuration have changed. */ enum ReconfigureFlag { ReconfigureAll = 1 << 0 /// Everything needs to be reconfigured. }; Q_DECLARE_FLAGS(ReconfigureFlags, ReconfigureFlag) /** * Called when configuration changes (either the effect's or KWin's global). * * In OpenGL based compositing, the frameworks ensures that the context is current * when the Effect is reconfigured. If this method is called from within the Effect it is * required to ensure that the context is current if the implementation does OpenGL calls. */ virtual void reconfigure(ReconfigureFlags flags); /** * Called when another effect requests the proxy for this effect. */ virtual void* proxy(); /** * Called before starting to paint the screen. * In this method you can: * @li set whether the windows or the entire screen will be transformed * @li change the region of the screen that will be painted * @li do various housekeeping tasks such as initing your effect's variables for the upcoming paint pass or updating animation's progress * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void prePaintScreen(ScreenPrePaintData& data, int time); /** * In this method you can: * @li paint something on top of the windows (by painting after calling * effects->paintScreen()) * @li paint multiple desktops and/or multiple copies of the same desktop * by calling effects->paintScreen() multiple times * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); /** * Called after all the painting has been finished. * In this method you can: * @li schedule next repaint in case of animations * You shouldn't paint anything here. * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void postPaintScreen(); /** * Called for every window before the actual paint pass * In this method you can: * @li enable or disable painting of the window (e.g. enable paiting of minimized window) * @li set window to be painted with translucency * @li set window to be transformed * @li request the window to be divided into multiple parts * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); /** * This is the main method for painting windows. * In this method you can: * @li do various transformations * @li change opacity of the window * @li change brightness and/or saturation, if it's supported * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); /** * Called for every window after all painting has been finished. * In this method you can: * @li schedule next repaint for individual window(s) in case of animations * You shouldn't paint anything here. * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void postPaintWindow(EffectWindow* w); /** * This method is called directly before painting an @ref EffectFrame. * You can implement this method if you need to bind a shader or perform * other operations before the frame is rendered. * @param frame The EffectFrame which will be rendered * @param region Region to restrict painting to * @param opacity Opacity of text/icon * @param frameOpacity Opacity of background * @since 4.6 * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void paintEffectFrame(EffectFrame* frame, QRegion region, double opacity, double frameOpacity); /** * Called on Transparent resizes. * return true if your effect substitutes questioned feature */ virtual bool provides(Feature); /** * Performs the @p feature with the @p arguments. * * This allows to have specific protocols between KWin core and an Effect. * * The method is supposed to return @c true if it performed the features, * @c false otherwise. * * The default implementation returns @c false. * @since 5.8 **/ virtual bool perform(Feature feature, const QVariantList &arguments); /** * Can be called to draw multiple copies (e.g. thumbnails) of a window. * You can change window's opacity/brightness/etc here, but you can't * do any transformations. * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void drawWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); /** * Define new window quads so that they can be transformed by other effects. * It's up to the effect to keep track of them. **/ virtual void buildQuads(EffectWindow* w, WindowQuadList& quadList); virtual void windowInputMouseEvent(QEvent* e); virtual void grabbedKeyboardEvent(QKeyEvent* e); /** * Overwrite this method to indicate whether your effect will be doing something in * the next frame to be rendered. If the method returns @c false the effect will be * excluded from the chained methods in the next rendered frame. * * This method is called always directly before the paint loop begins. So it is totally * fine to e.g. react on a window event, issue a repaint to trigger an animation and * change a flag to indicate that this method returns @c true. * * As the method is called each frame, you should not perform complex calculations. * Best use just a boolean flag. * * The default implementation of this method returns @c true. * @since 4.8 **/ virtual bool isActive() const; /** * Reimplement this method to provide online debugging. * This could be as trivial as printing specific detail informations about the effect state * but could also be used to move the effect in and out of a special debug modes, clear bogus * data, etc. * Notice that the functions is const by intent! Whenever you alter the state of the object * due to random user input, you should do so with greatest care, hence const_cast<> your * object - signalling "let me alone, i know what i'm doing" * @param parameter A freeform string user input for your effect to interpret. * @since 4.11 */ virtual QString debug(const QString ¶meter) const; /** * Reimplement this method to indicate where in the Effect chain the Effect should be placed. * * A low number indicates early chain position, thus before other Effects got called, a high * number indicates a late position. The returned number should be in the interval [0, 100]. * The default value is 0. * * In KWin4 this information was provided in the Effect's desktop file as property * X-KDE-Ordering. In the case of Scripted Effects this property is still used. * * @since 5.0 **/ virtual int requestedEffectChainPosition() const; /** * A touch point was pressed. * * If the effect wants to exclusively use the touch event it should return @c true. * If @c false is returned the touch event is passed to further effects. * * In general an Effect should only return @c true if it is the exclusive effect getting * input events. E.g. has grabbed mouse events. * * Default implementation returns @c false. * * @param id The unique id of the touch point * @param pos The position of the touch point in global coordinates * @param time Timestamp * * @see touchMotion * @see touchUp * @since 5.8 **/ virtual bool touchDown(quint32 id, const QPointF &pos, quint32 time); /** * A touch point moved. * * If the effect wants to exclusively use the touch event it should return @c true. * If @c false is returned the touch event is passed to further effects. * * In general an Effect should only return @c true if it is the exclusive effect getting * input events. E.g. has grabbed mouse events. * * Default implementation returns @c false. * * @param id The unique id of the touch point * @param pos The position of the touch point in global coordinates * @param time Timestamp * * @see touchDown * @see touchUp * @since 5.8 **/ virtual bool touchMotion(quint32 id, const QPointF &pos, quint32 time); /** * A touch point was released. * * If the effect wants to exclusively use the touch event it should return @c true. * If @c false is returned the touch event is passed to further effects. * * In general an Effect should only return @c true if it is the exclusive effect getting * input events. E.g. has grabbed mouse events. * * Default implementation returns @c false. * * @param id The unique id of the touch point * @param time Timestamp * * @see touchDown * @see touchMotion * @since 5.8 **/ virtual bool touchUp(quint32 id, quint32 time); static QPoint cursorPos(); /** * Read animation time from the configuration and possibly adjust using animationTimeFactor(). * The configuration value in the effect should also have special value 'default' (set using * QSpinBox::setSpecialValueText()) with the value 0. This special value is adjusted * using the global animation speed, otherwise the exact time configured is returned. * @param cfg configuration group to read value from * @param key configuration key to read value from * @param defaultTime default animation time in milliseconds */ // return type is intentionally double so that one can divide using it without losing data static double animationTime(const KConfigGroup& cfg, const QString& key, int defaultTime); /** * @overload Use this variant if the animation time is hardcoded and not configurable * in the effect itself. */ static double animationTime(int defaultTime); /** * @overload Use this variant if animation time is provided through a KConfigXT generated class * having a property called "duration". **/ template int animationTime(int defaultDuration); /** * Linearly interpolates between @p x and @p y. * * Returns @p x when @p a = 0; returns @p y when @p a = 1. **/ static double interpolate(double x, double y, double a) { return x * (1 - a) + y * a; } /** Helper to set WindowPaintData and QRegion to necessary transformations so that * a following drawWindow() would put the window at the requested geometry (useful for thumbnails) **/ static void setPositionTransformations(WindowPaintData& data, QRect& region, EffectWindow* w, const QRect& r, Qt::AspectRatioMode aspect); public Q_SLOTS: virtual bool borderActivated(ElectricBorder border); protected: xcb_connection_t *xcbConnection() const; xcb_window_t x11RootWindow() const; /** * An implementing class can call this with it's kconfig compiled singleton class. * This method will perform the instance on the class. * @since 5.9 **/ template void initConfig(); }; /** * Prefer the KWIN_EFFECT_FACTORY macros. */ class KWINEFFECTS_EXPORT EffectPluginFactory : public KPluginFactory { Q_OBJECT public: EffectPluginFactory(); virtual ~EffectPluginFactory(); /** * Returns whether the Effect is supported. * * An Effect can implement this method to determine at runtime whether the Effect is supported. * * If the current compositing backend is not supported it should return @c false. * * This method is optional, by default @c true is returned. */ virtual bool isSupported() const; /** * Returns whether the Effect should get enabled by default. * * This function provides a way for an effect to override the default at runtime, * e.g. based on the capabilities of the hardware. * * This method is optional; the effect doesn't have to provide it. * * Note that this function is only called if the supported() function returns true, * and if X-KDE-PluginInfo-EnabledByDefault is set to true in the .desktop file. * * This method is optional, by default @c true is returned. */ virtual bool enabledByDefault() const; /** * This method returns the created Effect. */ virtual KWin::Effect *createEffect() const = 0; }; /** * Defines an EffectPluginFactory sub class with customized isSupported and enabledByDefault methods. * * If the Effect to be created does not need the isSupported or enabledByDefault methods prefer * the simplified KWIN_EFFECT_FACTORY, KWIN_EFFECT_FACTORY_SUPPORTED or KWIN_EFFECT_FACTORY_ENABLED * macros which create an EffectPluginFactory with a useable default value. * * The macro also adds a useable K_EXPORT_PLUGIN_VERSION to the definition. KWin will not load * any Effect with a non-matching plugin version. This API is not providing binary compatibility * and thus the effect plugin must be compiled against the same kwineffects library version as * KWin. * * @param factoryName The name to be used for the EffectPluginFactory * @param className The class name of the Effect sub class which is to be created by the factory * @param jsonFile Name of the json file to be compiled into the plugin as metadata * @param supported Source code to go into the isSupported() method, must return a boolean * @param enabled Source code to go into the enabledByDefault() method, must return a boolean **/ #define KWIN_EFFECT_FACTORY_SUPPORTED_ENABLED( factoryName, className, jsonFile, supported, enabled ) \ class factoryName : public KWin::EffectPluginFactory \ { \ Q_OBJECT \ Q_PLUGIN_METADATA(IID KPluginFactory_iid FILE jsonFile) \ Q_INTERFACES(KPluginFactory) \ public: \ explicit factoryName() {} \ ~factoryName() {} \ bool isSupported() const override { \ supported \ } \ bool enabledByDefault() const override { \ enabled \ } \ KWin::Effect *createEffect() const override { \ return new className(); \ } \ }; \ K_EXPORT_PLUGIN_VERSION(quint32(KWIN_EFFECT_API_VERSION)) #define KWIN_EFFECT_FACTORY_ENABLED( factoryName, className, jsonFile, enabled ) \ KWIN_EFFECT_FACTORY_SUPPORTED_ENABLED( factoryName, className, jsonFile, return true;, enabled ) #define KWIN_EFFECT_FACTORY_SUPPORTED( factoryName, classname, jsonFile, supported ) \ KWIN_EFFECT_FACTORY_SUPPORTED_ENABLED( factoryName, className, jsonFile, supported, return true; ) #define KWIN_EFFECT_FACTORY( factoryName, classname, jsonFile ) \ KWIN_EFFECT_FACTORY_SUPPORTED_ENABLED( factoryName, className, jsonFile, return true;, return true; ) /** * @short Manager class that handles all the effects. * * This class creates Effect objects and calls it's appropriate methods. * * Effect objects can call methods of this class to interact with the * workspace, e.g. to activate or move a specific window, change current * desktop or create a special input window to receive mouse and keyboard * events. **/ class KWINEFFECTS_EXPORT EffectsHandler : public QObject { Q_OBJECT Q_PROPERTY(int currentDesktop READ currentDesktop WRITE setCurrentDesktop NOTIFY desktopChanged) Q_PROPERTY(QString currentActivity READ currentActivity NOTIFY currentActivityChanged) Q_PROPERTY(KWin::EffectWindow *activeWindow READ activeWindow WRITE activateWindow NOTIFY windowActivated) Q_PROPERTY(QSize desktopGridSize READ desktopGridSize) Q_PROPERTY(int desktopGridWidth READ desktopGridWidth) Q_PROPERTY(int desktopGridHeight READ desktopGridHeight) Q_PROPERTY(int workspaceWidth READ workspaceWidth) Q_PROPERTY(int workspaceHeight READ workspaceHeight) /** * The number of desktops currently used. Minimum number of desktops is 1, maximum 20. **/ Q_PROPERTY(int desktops READ numberOfDesktops WRITE setNumberOfDesktops NOTIFY numberDesktopsChanged) Q_PROPERTY(bool optionRollOverDesktops READ optionRollOverDesktops) Q_PROPERTY(int activeScreen READ activeScreen) Q_PROPERTY(int numScreens READ numScreens NOTIFY numberScreensChanged) /** * Factor by which animation speed in the effect should be modified (multiplied). * If configurable in the effect itself, the option should have also 'default' * animation speed. The actual value should be determined using animationTime(). * Note: The factor can be also 0, so make sure your code can cope with 0ms time * if used manually. */ Q_PROPERTY(qreal animationTimeFactor READ animationTimeFactor) Q_PROPERTY(QList< KWin::EffectWindow* > stackingOrder READ stackingOrder) /** * Whether window decorations use the alpha channel. **/ Q_PROPERTY(bool decorationsHaveAlpha READ decorationsHaveAlpha) /** * Whether the window decorations support blurring behind the decoration. **/ Q_PROPERTY(bool decorationSupportsBlurBehind READ decorationSupportsBlurBehind) Q_PROPERTY(CompositingType compositingType READ compositingType CONSTANT) Q_PROPERTY(QPoint cursorPos READ cursorPos) Q_PROPERTY(QSize virtualScreenSize READ virtualScreenSize NOTIFY virtualScreenSizeChanged) Q_PROPERTY(QRect virtualScreenGeometry READ virtualScreenGeometry NOTIFY virtualScreenGeometryChanged) friend class Effect; public: explicit EffectsHandler(CompositingType type); virtual ~EffectsHandler(); // for use by effects virtual void prePaintScreen(ScreenPrePaintData& data, int time) = 0; virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data) = 0; virtual void postPaintScreen() = 0; virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) = 0; virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) = 0; virtual void postPaintWindow(EffectWindow* w) = 0; virtual void paintEffectFrame(EffectFrame* frame, QRegion region, double opacity, double frameOpacity) = 0; virtual void drawWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) = 0; virtual void buildQuads(EffectWindow* w, WindowQuadList& quadList) = 0; virtual QVariant kwinOption(KWinOption kwopt) = 0; /** * Sets the cursor while the mouse is intercepted. * @see startMouseInterception * @since 4.11 **/ virtual void defineCursor(Qt::CursorShape shape) = 0; virtual QPoint cursorPos() const = 0; virtual bool grabKeyboard(Effect* effect) = 0; virtual void ungrabKeyboard() = 0; /** * Ensures that all mouse events are sent to the @p effect. * No window will get the mouse events. Only fullscreen effects providing a custom user interface should * be using this method. The input events are delivered to Effect::windowInputMouseEvent. * * NOTE: this method does not perform an X11 mouse grab. On X11 a fullscreen input window is raised above * all other windows, but no grab is performed. * * @param shape Sets the cursor to be used while the mouse is intercepted * @see stopMouseInterception * @see Effect::windowInputMouseEvent * @since 4.11 **/ virtual void startMouseInterception(Effect *effect, Qt::CursorShape shape) = 0; /** * Releases the hold mouse interception for @p effect * @see startMouseInterception * @since 4.11 **/ virtual void stopMouseInterception(Effect *effect) = 0; /** * @brief Registers a global shortcut with the provided @p action. * * @param shortcut The global shortcut which should trigger the action * @param action The action which gets triggered when the shortcut matches */ virtual void registerGlobalShortcut(const QKeySequence &shortcut, QAction *action) = 0; /** * @brief Registers a global pointer shortcut with the provided @p action. * * @param modifiers The keyboard modifiers which need to be holded * @param pointerButtons The pointer buttons which need to be pressed * @param action The action which gets triggered when the shortcut matches **/ virtual void registerPointerShortcut(Qt::KeyboardModifiers modifiers, Qt::MouseButton pointerButtons, QAction *action) = 0; /** * @brief Registers a global axis shortcut with the provided @p action. * * @param modifiers The keyboard modifiers which need to be holded * @param axis The direction in which the axis needs to be moved * @param action The action which gets triggered when the shortcut matches **/ virtual void registerAxisShortcut(Qt::KeyboardModifiers modifiers, PointerAxisDirection axis, QAction *action) = 0; /** * @brief Registers a global touchpad swipe gesture shortcut with the provided @p action. * * @param direction The direction for the swipe * @param action The action which gets triggered when the gesture triggers * @since 5.10 **/ virtual void registerTouchpadSwipeShortcut(SwipeDirection direction, QAction *action) = 0; /** * Retrieve the proxy class for an effect if it has one. Will return NULL if * the effect isn't loaded or doesn't have a proxy class. */ virtual void* getProxy(QString name) = 0; // Mouse polling virtual void startMousePolling() = 0; virtual void stopMousePolling() = 0; virtual void reserveElectricBorder(ElectricBorder border, Effect *effect) = 0; virtual void unreserveElectricBorder(ElectricBorder border, Effect *effect) = 0; /** * Registers the given @p action for the given @p border to be activated through * a touch swipe gesture. * * If the @p border gets triggered through a touch swipe gesture the @link{QAction::triggered} * signal gets invoked. * * To unregister the touch screen action either delete the @p action or * invoke @link{unregisterTouchBorder}. * * @see unregisterTouchBorder * @since 5.10 **/ virtual void registerTouchBorder(ElectricBorder border, QAction *action) = 0; /** * Unregisters the given @p action for the given touch @p border. * * @see registerTouchBorder * @since 5.10 **/ virtual void unregisterTouchBorder(ElectricBorder border, QAction *action) = 0; // functions that allow controlling windows/desktop virtual void activateWindow(KWin::EffectWindow* c) = 0; virtual KWin::EffectWindow* activeWindow() const = 0 ; Q_SCRIPTABLE virtual void moveWindow(KWin::EffectWindow* w, const QPoint& pos, bool snap = false, double snapAdjust = 1.0) = 0; Q_SCRIPTABLE virtual void windowToDesktop(KWin::EffectWindow* w, int desktop) = 0; Q_SCRIPTABLE virtual void windowToScreen(KWin::EffectWindow* w, int screen) = 0; virtual void setShowingDesktop(bool showing) = 0; // Activities /** * @returns The ID of the current activity. */ virtual QString currentActivity() const = 0; // Desktops /** * @returns The ID of the current desktop. */ virtual int currentDesktop() const = 0; /** * @returns Total number of desktops currently in existence. */ virtual int numberOfDesktops() const = 0; /** * Set the current desktop to @a desktop. */ virtual void setCurrentDesktop(int desktop) = 0; /** * Sets the total number of desktops to @a desktops. */ virtual void setNumberOfDesktops(int desktops) = 0; /** * @returns The size of desktop layout in grid units. */ virtual QSize desktopGridSize() const = 0; /** * @returns The width of desktop layout in grid units. */ virtual int desktopGridWidth() const = 0; /** * @returns The height of desktop layout in grid units. */ virtual int desktopGridHeight() const = 0; /** * @returns The width of desktop layout in pixels. */ virtual int workspaceWidth() const = 0; /** * @returns The height of desktop layout in pixels. */ virtual int workspaceHeight() const = 0; /** * @returns The ID of the desktop at the point @a coords or 0 if no desktop exists at that * point. @a coords is to be in grid units. */ virtual int desktopAtCoords(QPoint coords) const = 0; /** * @returns The coords of desktop @a id in grid units. */ virtual QPoint desktopGridCoords(int id) const = 0; /** * @returns The coords of the top-left corner of desktop @a id in pixels. */ virtual QPoint desktopCoords(int id) const = 0; /** * @returns The ID of the desktop above desktop @a id. Wraps around to the bottom of * the layout if @a wrap is set. If @a id is not set use the current one. */ Q_SCRIPTABLE virtual int desktopAbove(int desktop = 0, bool wrap = true) const = 0; /** * @returns The ID of the desktop to the right of desktop @a id. Wraps around to the * left of the layout if @a wrap is set. If @a id is not set use the current one. */ Q_SCRIPTABLE virtual int desktopToRight(int desktop = 0, bool wrap = true) const = 0; /** * @returns The ID of the desktop below desktop @a id. Wraps around to the top of the * layout if @a wrap is set. If @a id is not set use the current one. */ Q_SCRIPTABLE virtual int desktopBelow(int desktop = 0, bool wrap = true) const = 0; /** * @returns The ID of the desktop to the left of desktop @a id. Wraps around to the * right of the layout if @a wrap is set. If @a id is not set use the current one. */ Q_SCRIPTABLE virtual int desktopToLeft(int desktop = 0, bool wrap = true) const = 0; Q_SCRIPTABLE virtual QString desktopName(int desktop) const = 0; virtual bool optionRollOverDesktops() const = 0; virtual int activeScreen() const = 0; // Xinerama virtual int numScreens() const = 0; // Xinerama Q_SCRIPTABLE virtual int screenNumber(const QPoint& pos) const = 0; // Xinerama virtual QRect clientArea(clientAreaOption, int screen, int desktop) const = 0; virtual QRect clientArea(clientAreaOption, const EffectWindow* c) const = 0; virtual QRect clientArea(clientAreaOption, const QPoint& p, int desktop) const = 0; /** * The bounding size of all screens combined. Overlapping areas * are not counted multiple times. * * @see virtualScreenGeometry() * @see virtualScreenSizeChanged() * @since 5.0 **/ virtual QSize virtualScreenSize() const = 0; /** * The bounding geometry of all outputs combined. Always starts at (0,0) and has * virtualScreenSize as it's size. * * @see virtualScreenSize() * @see virtualScreenGeometryChanged() * @since 5.0 **/ virtual QRect virtualScreenGeometry() const = 0; /** * Factor by which animation speed in the effect should be modified (multiplied). * If configurable in the effect itself, the option should have also 'default' * animation speed. The actual value should be determined using animationTime(). * Note: The factor can be also 0, so make sure your code can cope with 0ms time * if used manually. */ virtual double animationTimeFactor() const = 0; virtual WindowQuadType newWindowQuadType() = 0; Q_SCRIPTABLE virtual KWin::EffectWindow* findWindow(WId id) const = 0; Q_SCRIPTABLE virtual KWin::EffectWindow* findWindow(KWayland::Server::SurfaceInterface *surf) const = 0; virtual EffectWindowList stackingOrder() const = 0; // window will be temporarily painted as if being at the top of the stack Q_SCRIPTABLE virtual void setElevatedWindow(KWin::EffectWindow* w, bool set) = 0; virtual void setTabBoxWindow(EffectWindow*) = 0; virtual void setTabBoxDesktop(int) = 0; virtual EffectWindowList currentTabBoxWindowList() const = 0; virtual void refTabBox() = 0; virtual void unrefTabBox() = 0; virtual void closeTabBox() = 0; virtual QList< int > currentTabBoxDesktopList() const = 0; virtual int currentTabBoxDesktop() const = 0; virtual EffectWindow* currentTabBoxWindow() const = 0; virtual void setActiveFullScreenEffect(Effect* e) = 0; virtual Effect* activeFullScreenEffect() const = 0; /** * Schedules the entire workspace to be repainted next time. * If you call it during painting (including prepaint) then it does not * affect the current painting. **/ Q_SCRIPTABLE virtual void addRepaintFull() = 0; Q_SCRIPTABLE virtual void addRepaint(const QRect& r) = 0; Q_SCRIPTABLE virtual void addRepaint(const QRegion& r) = 0; Q_SCRIPTABLE virtual void addRepaint(int x, int y, int w, int h) = 0; CompositingType compositingType() const; /** * @brief Whether the Compositor is OpenGL based (either GL 1 or 2). * * @return bool @c true in case of OpenGL based Compositor, @c false otherwise **/ bool isOpenGLCompositing() const; virtual unsigned long xrenderBufferPicture() = 0; /** * @brief Provides access to the QPainter which is rendering to the back buffer. * * Only relevant for CompositingType QPainterCompositing. For all other compositing types * @c null is returned. * * @return QPainter* The Scene's QPainter or @c null. */ virtual QPainter *scenePainter() = 0; virtual void reconfigure() = 0; virtual QByteArray readRootProperty(long atom, long type, int format) const = 0; /** * @brief Announces support for the feature with the given name. If no other Effect * has announced support for this feature yet, an X11 property will be installed on * the root window. * * The Effect will be notified for events through the signal propertyNotify(). * * To remove the support again use @link removeSupportProperty. When an Effect is * destroyed it is automatically taken care of removing the support. It is not * required to call @link removeSupportProperty in the Effect's cleanup handling. * * @param propertyName The name of the property to announce support for * @param effect The effect which announces support * @return xcb_atom_t The created X11 atom * @see removeSupportProperty * @since 4.11 **/ virtual xcb_atom_t announceSupportProperty(const QByteArray &propertyName, Effect *effect) = 0; /** * @brief Removes support for the feature with the given name. If there is no other Effect left * which has announced support for the given property, the property will be removed from the * root window. * * In case the Effect had not registered support, calling this function does not change anything. * * @param propertyName The name of the property to remove support for * @param effect The effect which had registered the property. * @see announceSupportProperty * @since 4.11 **/ virtual void removeSupportProperty(const QByteArray &propertyName, Effect *effect) = 0; /** * Returns @a true if the active window decoration has shadow API hooks. */ virtual bool hasDecorationShadows() const = 0; /** * Returns @a true if the window decorations use the alpha channel, and @a false otherwise. * @since 4.5 */ virtual bool decorationsHaveAlpha() const = 0; /** * Returns @a true if the window decorations support blurring behind the decoration, and @a false otherwise * @since 4.6 */ virtual bool decorationSupportsBlurBehind() const = 0; /** * Creates a new frame object. If the frame does not have a static size * then it will be located at @a position with @a alignment. A * non-static frame will automatically adjust its size to fit the contents. * @returns A new @ref EffectFrame. It is the responsibility of the caller to delete the * EffectFrame. * @since 4.6 */ virtual EffectFrame* effectFrame(EffectFrameStyle style, bool staticSize = true, const QPoint& position = QPoint(-1, -1), Qt::Alignment alignment = Qt::AlignCenter) const = 0; /** * Allows an effect to trigger a reload of itself. * This can be used by an effect which needs to be reloaded when screen geometry changes. * It is possible that the effect cannot be loaded again as it's supported method does no longer * hold. * @param effect The effect to reload * @since 4.8 **/ virtual void reloadEffect(Effect *effect) = 0; /** * Whether the screen is currently considered as locked. * Note for technical reasons this is not always possible to detect. The screen will only * be considered as locked if the screen locking process implements the * org.freedesktop.ScreenSaver interface. * * @returns @c true if the screen is currently locked, @c false otherwise * @see screenLockingChanged * @since 4.11 **/ virtual bool isScreenLocked() const = 0; /** * @brief Makes the OpenGL compositing context current. * * If the compositing backend is not using OpenGL, this method returns @c false. * * @return bool @c true if the context became current, @c false otherwise. */ virtual bool makeOpenGLContextCurrent() = 0; /** * @brief Makes a null OpenGL context current resulting in no context * being current. * * If the compositing backend is not OpenGL based, this method is a noop. * * There is normally no reason for an Effect to call this method. */ virtual void doneOpenGLContextCurrent() = 0; virtual xcb_connection_t *xcbConnection() const = 0; virtual xcb_window_t x11RootWindow() const = 0; /** * Interface to the Wayland display: this is relevant only * on Wayland, on X11 it will be nullptr * @since 5.5 */ virtual KWayland::Server::Display *waylandDisplay() const = 0; /** * Whether animations are supported by the Scene. * If this method returns @c false Effects are supposed to not * animate transitions. * * @returns Whether the Scene can drive animations * @since 5.8 **/ virtual bool animationsSupported() const = 0; /** * The current cursor image of the Platform. * @see cursorPos * @since 5.9 **/ virtual PlatformCursorImage cursorImage() const = 0; /** * The cursor image should be hidden. * @see showCursor * @since 5.9 **/ virtual void hideCursor() = 0; /** * The cursor image should be shown again after having been hidden.. * @see hideCursor * @since 5.9 **/ virtual void showCursor() = 0; /** * Starts an interactive window selection process. * * Once the user selected a window the @p callback is invoked with the selected EffectWindow as * argument. In case the user cancels the interactive window selection or selecting a window is currently * not possible (e.g. screen locked) the @p callback is invoked with a @c nullptr argument. * * During the interactive window selection the cursor is turned into a crosshair cursor. * * @param callback The function to invoke once the interactive window selection ends * @since 5.9 **/ virtual void startInteractiveWindowSelection(std::function callback) = 0; /** * Starts an interactive position selection process. * * Once the user selected a position on the screen the @p callback is invoked with * the selected point as argument. In case the user cancels the interactive position selection * or selecting a position is currently not possible (e.g. screen locked) the @p callback * is invoked with a point at @c -1 as x and y argument. * * During the interactive window selection the cursor is turned into a crosshair cursor. * * @param callback The function to invoke once the interactive position selection ends * @since 5.9 **/ virtual void startInteractivePositionSelection(std::function callback) = 0; /** * Shows an on-screen-message. To hide it again use @link{hideOnScreenMessage}. * * @param message The message to show * @param iconName The optional themed icon name * @see hideOnScreenMessage * @since 5.9 **/ virtual void showOnScreenMessage(const QString &message, const QString &iconName = QString()) = 0; /** * Flags for how to hide a shown on-screen-message * @see hideOnScreenMessage * @since 5.9 **/ enum class OnScreenMessageHideFlag { /** * The on-screen-message should skip the close window animation. * @see EffectWindow::skipsCloseAnimation **/ SkipsCloseAnimation = 1 }; Q_DECLARE_FLAGS(OnScreenMessageHideFlags, OnScreenMessageHideFlag) /** * Hides a previously shown on-screen-message again. * @param flags The flags for how to hide the message * @see showOnScreenMessage * @since 5.9 **/ virtual void hideOnScreenMessage(OnScreenMessageHideFlags flags = OnScreenMessageHideFlags()) = 0; /* * @returns The configuration used by the EffectsHandler. * @since 5.10 **/ virtual KSharedConfigPtr config() const = 0; /** * @returns The global input configuration (kcminputrc) * @since 5.10 **/ virtual KSharedConfigPtr inputConfig() const = 0; Q_SIGNALS: /** * Signal emitted when the current desktop changed. * @param oldDesktop The previously current desktop * @param newDesktop The new current desktop * @param with The window which is taken over to the new desktop, can be NULL * @since 4.9 */ void desktopChanged(int oldDesktop, int newDesktop, KWin::EffectWindow *with); /** * @since 4.7 * @deprecated */ void desktopChanged(int oldDesktop, int newDesktop); /** * Signal emitted when a window moved to another desktop * NOTICE that this does NOT imply that the desktop has changed * The @param window which is moved to the new desktop * @param oldDesktop The previous desktop of the window * @param newDesktop The new desktop of the window * @since 4.11.4 */ void desktopPresenceChanged(KWin::EffectWindow *window, int oldDesktop, int newDesktop); /** * Signal emitted when the number of currently existing desktops is changed. * @param old The previous number of desktops in used. * @see EffectsHandler::numberOfDesktops. * @since 4.7 */ void numberDesktopsChanged(uint old); /** * Signal emitted when the number of screens changed. * @since 5.0 **/ void numberScreensChanged(); /** * Signal emitted when the desktop showing ("dashboard") state changed * The desktop is risen to the keepAbove layer, you may want to elevate * windows or such. * @since 5.3 **/ void showingDesktopChanged(bool); /** * Signal emitted when a new window has been added to the Workspace. * @param w The added window * @since 4.7 **/ void windowAdded(KWin::EffectWindow *w); /** * Signal emitted when a window is being removed from the Workspace. * An effect which wants to animate the window closing should connect * to this signal and reference the window by using * @link EffectWindow::refWindow * @param w The window which is being closed * @since 4.7 **/ void windowClosed(KWin::EffectWindow *w); /** * Signal emitted when a window get's activated. * @param w The new active window, or @c NULL if there is no active window. * @since 4.7 **/ void windowActivated(KWin::EffectWindow *w); /** * Signal emitted when a window is deleted. * This means that a closed window is not referenced any more. * An effect bookkeeping the closed windows should connect to this * signal to clean up the internal references. * @param w The window which is going to be deleted. * @see EffectWindow::refWindow * @see EffectWindow::unrefWindow * @see windowClosed * @since 4.7 **/ void windowDeleted(KWin::EffectWindow *w); /** * Signal emitted when a user begins a window move or resize operation. * To figure out whether the user resizes or moves the window use * @link EffectWindow::isUserMove or @link EffectWindow::isUserResize. * Whenever the geometry is updated the signal @link windowStepUserMovedResized * is emitted with the current geometry. * The move/resize operation ends with the signal @link windowFinishUserMovedResized. * Only one window can be moved/resized by the user at the same time! * @param w The window which is being moved/resized * @see windowStepUserMovedResized * @see windowFinishUserMovedResized * @see EffectWindow::isUserMove * @see EffectWindow::isUserResize * @since 4.7 **/ void windowStartUserMovedResized(KWin::EffectWindow *w); /** * Signal emitted during a move/resize operation when the user changed the geometry. * Please note: KWin supports two operation modes. In one mode all changes are applied * instantly. This means the window's geometry matches the passed in @p geometry. In the * other mode the geometry is changed after the user ended the move/resize mode. * The @p geometry differs from the window's geometry. Also the window's pixmap still has * the same size as before. Depending what the effect wants to do it would be recommended * to scale/translate the window. * @param w The window which is being moved/resized * @param geometry The geometry of the window in the current move/resize step. * @see windowStartUserMovedResized * @see windowFinishUserMovedResized * @see EffectWindow::isUserMove * @see EffectWindow::isUserResize * @since 4.7 **/ void windowStepUserMovedResized(KWin::EffectWindow *w, const QRect &geometry); /** * Signal emitted when the user finishes move/resize of window @p w. * @param w The window which has been moved/resized * @see windowStartUserMovedResized * @see windowFinishUserMovedResized * @since 4.7 **/ void windowFinishUserMovedResized(KWin::EffectWindow *w); /** * Signal emitted when the maximized state of the window @p w changed. * A window can be in one of four states: * @li restored: both @p horizontal and @p vertical are @c false * @li horizontally maximized: @p horizontal is @c true and @p vertical is @c false * @li vertically maximized: @p horizontal is @c false and @p vertical is @c true * @li completely maximized: both @p horizontal and @p vertical are @C true * @param w The window whose maximized state changed * @param horizontal If @c true maximized horizontally * @param vertical If @c true maximized vertically * @since 4.7 **/ void windowMaximizedStateChanged(KWin::EffectWindow *w, bool horizontal, bool vertical); /** * Signal emitted when the geometry or shape of a window changed. * This is caused if the window changes geometry without user interaction. * E.g. the decoration is changed. This is in opposite to windowUserMovedResized * which is caused by direct user interaction. * @param w The window whose geometry changed * @param old The previous geometry * @see windowUserMovedResized * @since 4.7 **/ void windowGeometryShapeChanged(KWin::EffectWindow *w, const QRect &old); /** * Signal emitted when the padding of a window changed. (eg. shadow size) * @param w The window whose geometry changed * @param old The previous expandedGeometry() * @since 4.9 **/ void windowPaddingChanged(KWin::EffectWindow *w, const QRect &old); /** * Signal emitted when the windows opacity is changed. * @param w The window whose opacity level is changed. * @param oldOpacity The previous opacity level * @param newOpacity The new opacity level * @since 4.7 **/ void windowOpacityChanged(KWin::EffectWindow *w, qreal oldOpacity, qreal newOpacity); /** * Signal emitted when a window got minimized. * @param w The window which was minimized * @since 4.7 **/ void windowMinimized(KWin::EffectWindow *w); /** * Signal emitted when a window got unminimized. * @param w The window which was unminimized * @since 4.7 **/ void windowUnminimized(KWin::EffectWindow *w); /** * Signal emitted when a window either becomes modal (ie. blocking for its main client) or looses that state. * @param w The window which was unminimized * @since 4.11 **/ void windowModalityChanged(KWin::EffectWindow *w); /** * Signal emitted when a window either became unresponsive (eg. app froze or crashed) * or respoonsive * @param w The window that became (un)responsive * @param unresponsive Whether the window is responsive or unresponsive * @since 5.10 */ void windowUnresponsiveChanged(KWin::EffectWindow *w, bool unresponsive); /** * Signal emitted when an area of a window is scheduled for repainting. * Use this signal in an effect if another area needs to be synced as well. * @param w The window which is scheduled for repainting * @param r Always empty. * @since 4.7 **/ void windowDamaged(KWin::EffectWindow *w, const QRect &r); /** * Signal emitted when a tabbox is added. * An effect who wants to replace the tabbox with itself should use @link refTabBox. * @param mode The TabBoxMode. * @see refTabBox * @see tabBoxClosed * @see tabBoxUpdated * @see tabBoxKeyEvent * @since 4.7 **/ void tabBoxAdded(int mode); /** * Signal emitted when the TabBox was closed by KWin core. * An effect which referenced the TabBox should use @link unrefTabBox to unref again. * @see unrefTabBox * @see tabBoxAdded * @since 4.7 **/ void tabBoxClosed(); /** * Signal emitted when the selected TabBox window changed or the TabBox List changed. * An effect should only response to this signal if it referenced the TabBox with @link refTabBox. * @see refTabBox * @see currentTabBoxWindowList * @see currentTabBoxDesktopList * @see currentTabBoxWindow * @see currentTabBoxDesktop * @since 4.7 **/ void tabBoxUpdated(); /** * Signal emitted when a key event, which is not handled by TabBox directly is, happens while * TabBox is active. An effect might use the key event to e.g. change the selected window. * An effect should only response to this signal if it referenced the TabBox with @link refTabBox. * @param event The key event not handled by TabBox directly * @see refTabBox * @since 4.7 **/ void tabBoxKeyEvent(QKeyEvent* event); void currentTabAboutToChange(KWin::EffectWindow* from, KWin::EffectWindow* to); void tabAdded(KWin::EffectWindow* from, KWin::EffectWindow* to); // from merged with to void tabRemoved(KWin::EffectWindow* c, KWin::EffectWindow* group); // c removed from group /** * Signal emitted when mouse changed. * If an effect needs to get updated mouse positions, it needs to first call @link startMousePolling. * For a fullscreen effect it is better to use an input window and react on @link windowInputMouseEvent. * @param pos The new mouse position * @param oldpos The previously mouse position * @param buttons The pressed mouse buttons * @param oldbuttons The previously pressed mouse buttons * @param modifiers Pressed keyboard modifiers * @param oldmodifiers Previously pressed keyboard modifiers. * @see startMousePolling * @since 4.7 **/ void mouseChanged(const QPoint& pos, const QPoint& oldpos, Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers); /** * Signal emitted when the cursor shape changed. * You'll likely want to query the current cursor as reaction: xcb_xfixes_get_cursor_image_unchecked * Connection to this signal is tracked, so if you don't need it anymore, disconnect from it to stop cursor event filtering */ void cursorShapeChanged(); /** * Receives events registered for using @link registerPropertyType. * Use readProperty() to get the property data. * Note that the property may be already set on the window, so doing the same * processing from windowAdded() (e.g. simply calling propertyNotify() from it) * is usually needed. * @param w The window whose property changed, is @c null if it is a root window property * @param atom The property * @since 4.7 */ void propertyNotify(KWin::EffectWindow* w, long atom); /** * Signal emitted after the screen geometry changed (e.g. add of a monitor). * Effects using displayWidth()/displayHeight() to cache information should * react on this signal and update the caches. * @param size The new screen size * @since 4.8 **/ void screenGeometryChanged(const QSize &size); /** * This signal is emitted when the global * activity is changed * @param id id of the new current activity * @since 4.9 **/ void currentActivityChanged(const QString &id); /** * This signal is emitted when a new activity is added * @param id id of the new activity * @since 4.9 */ void activityAdded(const QString &id); /** * This signal is emitted when the activity * is removed * @param id id of the removed activity * @since 4.9 */ void activityRemoved(const QString &id); /** * This signal is emitted when the screen got locked or unlocked. * @param locked @c true if the screen is now locked, @c false if it is now unlocked * @since 4.11 **/ void screenLockingChanged(bool locked); /** * This signels is emitted when ever the stacking order is change, ie. a window is risen * or lowered * @since 4.10 */ void stackingOrderChanged(); /** * This signal is emitted when the user starts to approach the @p border with the mouse. * The @p factor describes how far away the mouse is in a relative mean. The values are in * [0.0, 1.0] with 0.0 being emitted when first entered and on leaving. The value 1.0 means that * the @p border is reached with the mouse. So the values are well suited for animations. * The signal is always emitted when the mouse cursor position changes. * @param border The screen edge which is being approached * @param factor Value in range [0.0,1.0] to describe how close the mouse is to the border * @param geometry The geometry of the edge which is being approached * @since 4.11 **/ void screenEdgeApproaching(ElectricBorder border, qreal factor, const QRect &geometry); /** * Emitted whenever the virtualScreenSize changes. * @see virtualScreenSize() * @since 5.0 **/ void virtualScreenSizeChanged(); /** * Emitted whenever the virtualScreenGeometry changes. * @see virtualScreenGeometry() * @since 5.0 **/ void virtualScreenGeometryChanged(); /** * The window @p w gets shown again. The window was previously * initially shown with @link{windowAdded} and hidden with @link{windowHidden}. * * @see windowHidden * @see windowAdded * @since 5.8 **/ void windowShown(KWin::EffectWindow *w); /** * The window @p w got hidden but not yet closed. * This can happen when a window is still being used and is supposed to be shown again * with @link{windowShown}. On X11 an example is autohiding panels. On Wayland every * window first goes through the window hidden state and might get shown again, or might * get closed the normal way. * * @see windowShown * @see windowClosed * @since 5.8 **/ void windowHidden(KWin::EffectWindow *w); /** * This signal gets emitted when the data on EffectWindow @p w for @p role changed. * * An Effect can connect to this signal to read the new value and react on it. * E.g. an Effect which does not operate on windows grabbed by another Effect wants * to cancel the already scheduled animation if another Effect adds a grab. * * @param w The EffectWindow for which the data changed * @param role The data role which changed * @see EffectWindow::setData * @see EffectWindow::data * @since 5.8.4 **/ void windowDataChanged(KWin::EffectWindow *w, int role); /** * The xcb connection changed, either a new xcbConnection got created or the existing one * got destroyed. * Effects can use this to refetch the properties they want to set. * * When the xcbConnection changes also the @link{x11RootWindow} becomes invalid. * @see xcbConnection * @see x11RootWindow * @since 5.11 **/ void xcbConnectionChanged(); protected: QVector< EffectPair > loaded_effects; //QHash< QString, EffectFactory* > effect_factories; CompositingType compositing_type; }; /** * @short Representation of a window used by/for Effect classes. * * The purpose is to hide internal data and also to serve as a single * representation for the case when Client/Unmanaged becomes Deleted. **/ class KWINEFFECTS_EXPORT EffectWindow : public QObject { Q_OBJECT Q_PROPERTY(bool alpha READ hasAlpha CONSTANT) Q_PROPERTY(QRect geometry READ geometry) Q_PROPERTY(QRect expandedGeometry READ expandedGeometry) Q_PROPERTY(int height READ height) Q_PROPERTY(qreal opacity READ opacity) Q_PROPERTY(QPoint pos READ pos) Q_PROPERTY(int screen READ screen) Q_PROPERTY(QSize size READ size) Q_PROPERTY(int width READ width) Q_PROPERTY(int x READ x) Q_PROPERTY(int y READ y) Q_PROPERTY(int desktop READ desktop) Q_PROPERTY(bool onAllDesktops READ isOnAllDesktops) Q_PROPERTY(bool onCurrentDesktop READ isOnCurrentDesktop) Q_PROPERTY(QRect rect READ rect) Q_PROPERTY(QString windowClass READ windowClass) Q_PROPERTY(QString windowRole READ windowRole) /** * Returns whether the window is a desktop background window (the one with wallpaper). * See _NET_WM_WINDOW_TYPE_DESKTOP at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool desktopWindow READ isDesktop) /** * Returns whether the window is a dock (i.e. a panel). * See _NET_WM_WINDOW_TYPE_DOCK at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool dock READ isDock) /** * Returns whether the window is a standalone (detached) toolbar window. * See _NET_WM_WINDOW_TYPE_TOOLBAR at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool toolbar READ isToolbar) /** * Returns whether the window is a torn-off menu. * See _NET_WM_WINDOW_TYPE_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool menu READ isMenu) /** * Returns whether the window is a "normal" window, i.e. an application or any other window * for which none of the specialized window types fit. * See _NET_WM_WINDOW_TYPE_NORMAL at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool normalWindow READ isNormalWindow) /** * Returns whether the window is a dialog window. * See _NET_WM_WINDOW_TYPE_DIALOG at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool dialog READ isDialog) /** * Returns whether the window is a splashscreen. Note that many (especially older) applications * do not support marking their splash windows with this type. * See _NET_WM_WINDOW_TYPE_SPLASH at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool splash READ isSplash) /** * Returns whether the window is a utility window, such as a tool window. * See _NET_WM_WINDOW_TYPE_UTILITY at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool utility READ isUtility) /** * Returns whether the window is a dropdown menu (i.e. a popup directly or indirectly open * from the applications menubar). * See _NET_WM_WINDOW_TYPE_DROPDOWN_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool dropdownMenu READ isDropdownMenu) /** * Returns whether the window is a popup menu (that is not a torn-off or dropdown menu). * See _NET_WM_WINDOW_TYPE_POPUP_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool popupMenu READ isPopupMenu) /** * Returns whether the window is a tooltip. * See _NET_WM_WINDOW_TYPE_TOOLTIP at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool tooltip READ isTooltip) /** * Returns whether the window is a window with a notification. * See _NET_WM_WINDOW_TYPE_NOTIFICATION at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool notification READ isNotification) /** * Returns whether the window is an on screen display window * using the non-standard _KDE_NET_WM_WINDOW_TYPE_ON_SCREEN_DISPLAY */ Q_PROPERTY(bool onScreenDisplay READ isOnScreenDisplay) /** * Returns whether the window is a combobox popup. * See _NET_WM_WINDOW_TYPE_COMBO at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool comboBox READ isComboBox) /** * Returns whether the window is a Drag&Drop icon. * See _NET_WM_WINDOW_TYPE_DND at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool dndIcon READ isDNDIcon) /** * Returns the NETWM window type * See http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(int windowType READ windowType) /** * Whether this EffectWindow is managed by KWin (it has control over its placement and other * aspects, as opposed to override-redirect windows that are entirely handled by the application). **/ Q_PROPERTY(bool managed READ isManaged) /** * Whether this EffectWindow represents an already deleted window and only kept for the compositor for animations. **/ Q_PROPERTY(bool deleted READ isDeleted) /** * Whether the window has an own shape **/ Q_PROPERTY(bool shaped READ hasOwnShape) /** * The Window's shape **/ Q_PROPERTY(QRegion shape READ shape) /** * The Caption of the window. Read from WM_NAME property together with a suffix for hostname and shortcut. **/ Q_PROPERTY(QString caption READ caption) /** * Whether the window is set to be kept above other windows. **/ Q_PROPERTY(bool keepAbove READ keepAbove) /** * Whether the window is minimized. **/ Q_PROPERTY(bool minimized READ isMinimized WRITE setMinimized) /** * Whether the window represents a modal window. **/ Q_PROPERTY(bool modal READ isModal) /** * Whether the window is moveable. Even if it is not moveable, it might be possible to move * it to another screen. * @see moveableAcrossScreens **/ Q_PROPERTY(bool moveable READ isMovable) /** * Whether the window can be moved to another screen. * @see moveable **/ Q_PROPERTY(bool moveableAcrossScreens READ isMovableAcrossScreens) /** * By how much the window wishes to grow/shrink at least. Usually QSize(1,1). * MAY BE DISOBEYED BY THE WM! It's only for information, do NOT rely on it at all. */ Q_PROPERTY(QSize basicUnit READ basicUnit) /** * Whether the window is currently being moved by the user. **/ Q_PROPERTY(bool move READ isUserMove) /** * Whether the window is currently being resized by the user. **/ Q_PROPERTY(bool resize READ isUserResize) /** * The optional geometry representing the minimized Client in e.g a taskbar. * See _NET_WM_ICON_GEOMETRY at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . **/ Q_PROPERTY(QRect iconGeometry READ iconGeometry) /** * Returns whether the window is any of special windows types (desktop, dock, splash, ...), * i.e. window types that usually don't have a window frame and the user does not use window * management (moving, raising,...) on them. **/ Q_PROPERTY(bool specialWindow READ isSpecialWindow) Q_PROPERTY(QIcon icon READ icon) /** * Whether the window should be excluded from window switching effects. **/ Q_PROPERTY(bool skipSwitcher READ isSkipSwitcher) /** * Geometry of the actual window contents inside the whole (including decorations) window. */ Q_PROPERTY(QRect contentsRect READ contentsRect) /** * Geometry of the transparent rect in the decoration. * May be different from contentsRect if the decoration is extended into the client area. */ Q_PROPERTY(QRect decorationInnerRect READ decorationInnerRect) Q_PROPERTY(bool hasDecoration READ hasDecoration) Q_PROPERTY(QStringList activities READ activities) Q_PROPERTY(bool onCurrentActivity READ isOnCurrentActivity) Q_PROPERTY(bool onAllActivities READ isOnAllActivities) /** * Whether the decoration currently uses an alpha channel. * @since 4.10 **/ Q_PROPERTY(bool decorationHasAlpha READ decorationHasAlpha) /** * Whether the window is currently visible to the user, that is: *
    *
  • Not minimized
  • *
  • On current desktop
  • *
  • On current activity
  • *
* @since 4.11 **/ Q_PROPERTY(bool visible READ isVisible) /** * Whether the window does not want to be animated on window close. * In case this property is @c true it is not useful to start an animation on window close. * The window will not be visible, but the animation hooks are executed. * @since 5.0 **/ Q_PROPERTY(bool skipsCloseAnimation READ skipsCloseAnimation) /** * Interface to the corresponding wayland surface. * relevant only in Wayland, on X11 it will be nullptr */ Q_PROPERTY(KWayland::Server::SurfaceInterface *surface READ surface) /** * Whether the window is fullscreen. * @since 5.6 **/ Q_PROPERTY(bool fullScreen READ isFullScreen) /** * Whether this client is unresponsive. * * When an application failed to react on a ping request in time, it is * considered unresponsive. This usually indicates that the application froze or crashed. * * @since 5.10 */ Q_PROPERTY(bool unresponsive READ isUnresponsive) public: /** Flags explaining why painting should be disabled */ enum { /** Window will not be painted */ PAINT_DISABLED = 1 << 0, /** Window will not be painted because it is deleted */ PAINT_DISABLED_BY_DELETE = 1 << 1, /** Window will not be painted because of which desktop it's on */ PAINT_DISABLED_BY_DESKTOP = 1 << 2, /** Window will not be painted because it is minimized */ PAINT_DISABLED_BY_MINIMIZE = 1 << 3, /** Window will not be painted because it is not the active window in a client group */ PAINT_DISABLED_BY_TAB_GROUP = 1 << 4, /** Window will not be painted because it's not on the current activity */ PAINT_DISABLED_BY_ACTIVITY = 1 << 5 }; explicit EffectWindow(QObject *parent = nullptr); virtual ~EffectWindow(); virtual void enablePainting(int reason) = 0; virtual void disablePainting(int reason) = 0; virtual bool isPaintingEnabled() = 0; Q_SCRIPTABLE void addRepaint(const QRect& r); Q_SCRIPTABLE void addRepaint(int x, int y, int w, int h); Q_SCRIPTABLE void addRepaintFull(); Q_SCRIPTABLE void addLayerRepaint(const QRect& r); Q_SCRIPTABLE void addLayerRepaint(int x, int y, int w, int h); virtual void refWindow() = 0; virtual void unrefWindow() = 0; bool isDeleted() const; bool isMinimized() const; double opacity() const; bool hasAlpha() const; bool isOnCurrentActivity() const; Q_SCRIPTABLE bool isOnActivity(QString id) const; bool isOnAllActivities() const; QStringList activities() const; bool isOnDesktop(int d) const; bool isOnCurrentDesktop() const; bool isOnAllDesktops() const; int desktop() const; // prefer isOnXXX() int x() const; int y() const; int width() const; int height() const; /** * By how much the window wishes to grow/shrink at least. Usually QSize(1,1). * MAY BE DISOBEYED BY THE WM! It's only for information, do NOT rely on it at all. */ QSize basicUnit() const; QRect geometry() const; /** * Geometry of the window including decoration and potentially shadows. * May be different from geometry() if the window has a shadow. * @since 4.9 */ QRect expandedGeometry() const; virtual QRegion shape() const = 0; int screen() const; /** @internal Do not use */ bool hasOwnShape() const; // only for shadow effect, for now QPoint pos() const; QSize size() const; QRect rect() const; bool isMovable() const; bool isMovableAcrossScreens() const; bool isUserMove() const; bool isUserResize() const; QRect iconGeometry() const; /** * Geometry of the actual window contents inside the whole (including decorations) window. */ QRect contentsRect() const; /** * Geometry of the transparent rect in the decoration. * May be different from contentsRect() if the decoration is extended into the client area. * @since 4.5 */ virtual QRect decorationInnerRect() const = 0; bool hasDecoration() const; bool decorationHasAlpha() const; virtual QByteArray readProperty(long atom, long type, int format) const = 0; virtual void deleteProperty(long atom) const = 0; QString caption() const; QIcon icon() const; QString windowClass() const; QString windowRole() const; virtual const EffectWindowGroup* group() const = 0; /** * Returns whether the window is a desktop background window (the one with wallpaper). * See _NET_WM_WINDOW_TYPE_DESKTOP at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isDesktop() const; /** * Returns whether the window is a dock (i.e. a panel). * See _NET_WM_WINDOW_TYPE_DOCK at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isDock() const; /** * Returns whether the window is a standalone (detached) toolbar window. * See _NET_WM_WINDOW_TYPE_TOOLBAR at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isToolbar() const; /** * Returns whether the window is a torn-off menu. * See _NET_WM_WINDOW_TYPE_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isMenu() const; /** * Returns whether the window is a "normal" window, i.e. an application or any other window * for which none of the specialized window types fit. * See _NET_WM_WINDOW_TYPE_NORMAL at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isNormalWindow() const; // normal as in 'NET::Normal or NET::Unknown non-transient' /** * Returns whether the window is any of special windows types (desktop, dock, splash, ...), * i.e. window types that usually don't have a window frame and the user does not use window * management (moving, raising,...) on them. */ bool isSpecialWindow() const; /** * Returns whether the window is a dialog window. * See _NET_WM_WINDOW_TYPE_DIALOG at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isDialog() const; /** * Returns whether the window is a splashscreen. Note that many (especially older) applications * do not support marking their splash windows with this type. * See _NET_WM_WINDOW_TYPE_SPLASH at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isSplash() const; /** * Returns whether the window is a utility window, such as a tool window. * See _NET_WM_WINDOW_TYPE_UTILITY at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isUtility() const; /** * Returns whether the window is a dropdown menu (i.e. a popup directly or indirectly open * from the applications menubar). * See _NET_WM_WINDOW_TYPE_DROPDOWN_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isDropdownMenu() const; /** * Returns whether the window is a popup menu (that is not a torn-off or dropdown menu). * See _NET_WM_WINDOW_TYPE_POPUP_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isPopupMenu() const; // a context popup, not dropdown, not torn-off /** * Returns whether the window is a tooltip. * See _NET_WM_WINDOW_TYPE_TOOLTIP at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isTooltip() const; /** * Returns whether the window is a window with a notification. * See _NET_WM_WINDOW_TYPE_NOTIFICATION at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isNotification() const; /** * Returns whether the window is an on screen display window * using the non-standard _KDE_NET_WM_WINDOW_TYPE_ON_SCREEN_DISPLAY */ bool isOnScreenDisplay() const; /** * Returns whether the window is a combobox popup. * See _NET_WM_WINDOW_TYPE_COMBO at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isComboBox() const; /** * Returns whether the window is a Drag&Drop icon. * See _NET_WM_WINDOW_TYPE_DND at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isDNDIcon() const; /** * Returns the NETWM window type * See http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ NET::WindowType windowType() const; /** * Returns whether the window is managed by KWin (it has control over its placement and other * aspects, as opposed to override-redirect windows that are entirely handled by the application). */ bool isManaged() const; // whether it's managed or override-redirect /** * Returns whether or not the window can accept keyboard focus. */ bool acceptsFocus() const; /** * Returns whether or not the window is kept above all other windows. */ bool keepAbove() const; bool isModal() const; Q_SCRIPTABLE virtual KWin::EffectWindow* findModal() = 0; Q_SCRIPTABLE virtual QList mainWindows() const = 0; /** * Returns whether the window should be excluded from window switching effects. * @since 4.5 */ bool isSkipSwitcher() const; /** * Returns the unmodified window quad list. Can also be used to force rebuilding. */ virtual WindowQuadList buildQuads(bool force = false) const = 0; void setMinimized(bool minimize); void minimize(); void unminimize(); Q_SCRIPTABLE void closeWindow() const; bool isCurrentTab() const; /** * @since 4.11 **/ bool isVisible() const; /** * @since 5.0 **/ bool skipsCloseAnimation() const; /** * @since 5.5 */ KWayland::Server::SurfaceInterface *surface() const; /** * @since 5.6 **/ bool isFullScreen() const; /** * @since 5.10 */ bool isUnresponsive() const; /** * Can be used to by effects to store arbitrary data in the EffectWindow. * * Invoking this method will emit the signal EffectsHandler::windowDataChanged. * @see EffectsHandler::windowDataChanged */ Q_SCRIPTABLE virtual void setData(int role, const QVariant &data) = 0; Q_SCRIPTABLE virtual QVariant data(int role) const = 0; /** * @brief References the previous window pixmap to prevent discarding. * * This method allows to reference the previous window pixmap in case that a window changed * its size, which requires a new window pixmap. By referencing the previous (and then outdated) * window pixmap an effect can for example cross fade the current window pixmap with the previous * one. This allows for smoother transitions for window geometry changes. * * If an effect calls this method on a window it also needs to call @link unreferencePreviousWindowPixmap * once it does no longer need the previous window pixmap. * * Note: the window pixmap is not kept forever even when referenced. If the geometry changes again, so that * a new window pixmap is created, the previous window pixmap will be exchanged with the current one. This * means it's still possible to have rendering glitches. An effect is supposed to track for itself the changes * to the window's geometry and decide how the transition should continue in such a situation. * * @see unreferencePreviousWindowPixmap * @since 4.11 */ virtual void referencePreviousWindowPixmap() = 0; /** * @brief Unreferences the previous window pixmap. Only relevant after @link referencePreviousWindowPixmap had * been called. * * @see referencePreviousWindowPixmap * @since 4.11 */ virtual void unreferencePreviousWindowPixmap() = 0; }; class KWINEFFECTS_EXPORT EffectWindowGroup { public: virtual ~EffectWindowGroup(); virtual EffectWindowList members() const = 0; }; struct GLVertex2D { QVector2D position; QVector2D texcoord; }; struct GLVertex3D { QVector3D position; QVector2D texcoord; }; /** * @short Vertex class * * A vertex is one position in a window. WindowQuad consists of four WindowVertex objects * and represents one part of a window. **/ class KWINEFFECTS_EXPORT WindowVertex { public: WindowVertex(); WindowVertex(const QPointF &position, const QPointF &textureCoordinate); WindowVertex(double x, double y, double tx, double ty); double x() const { return px; } double y() const { return py; } double u() const { return tx; } double v() const { return ty; } double originalX() const { return ox; } double originalY() const { return oy; } double textureX() const { return tx; } double textureY() const { return ty; } void move(double x, double y); void setX(double x); void setY(double y); private: friend class WindowQuad; friend class WindowQuadList; double px, py; // position double ox, oy; // origional position double tx, ty; // texture coords }; /** * @short Class representing one area of a window. * * WindowQuads consists of four WindowVertex objects and represents one part of a window. */ // NOTE: This class expects the (original) vertices to be in the clockwise order starting from topleft. class KWINEFFECTS_EXPORT WindowQuad { public: explicit WindowQuad(WindowQuadType type, int id = -1); WindowQuad makeSubQuad(double x1, double y1, double x2, double y2) const; WindowVertex& operator[](int index); const WindowVertex& operator[](int index) const; WindowQuadType type() const; void setUVAxisSwapped(bool value) { uvSwapped = value; } bool uvAxisSwapped() const { return uvSwapped; } int id() const; bool decoration() const; bool effect() const; double left() const; double right() const; double top() const; double bottom() const; double originalLeft() const; double originalRight() const; double originalTop() const; double originalBottom() const; bool smoothNeeded() const; bool isTransformed() const; private: friend class WindowQuadList; WindowVertex verts[ 4 ]; WindowQuadType quadType; // 0 - contents, 1 - decoration bool uvSwapped; int quadID; }; class KWINEFFECTS_EXPORT WindowQuadList : public QList< WindowQuad > { public: WindowQuadList splitAtX(double x) const; WindowQuadList splitAtY(double y) const; WindowQuadList makeGrid(int maxquadsize) const; WindowQuadList makeRegularGrid(int xSubdivisions, int ySubdivisions) const; WindowQuadList select(WindowQuadType type) const; WindowQuadList filterOut(WindowQuadType type) const; bool smoothNeeded() const; void makeInterleavedArrays(unsigned int type, GLVertex2D *vertices, const QMatrix4x4 &matrix) const; void makeArrays(float** vertices, float** texcoords, const QSizeF &size, bool yInverted) const; bool isTransformed() const; }; class KWINEFFECTS_EXPORT WindowPrePaintData { public: int mask; /** * Region that will be painted, in screen coordinates. **/ QRegion paint; /** * The clip region will be subtracted from paint region of following windows. * I.e. window will definitely cover it's clip region **/ QRegion clip; WindowQuadList quads; /** * Simple helper that sets data to say the window will be painted as non-opaque. * Takes also care of changing the regions. */ void setTranslucent(); /** * Helper to mark that this window will be transformed **/ void setTransformed(); }; class KWINEFFECTS_EXPORT PaintData { public: virtual ~PaintData(); /** * @returns scale factor in X direction. * @since 4.10 **/ qreal xScale() const; /** * @returns scale factor in Y direction. * @since 4.10 **/ qreal yScale() const; /** * @returns scale factor in Z direction. * @since 4.10 **/ qreal zScale() const; /** * Sets the scale factor in X direction to @p scale * @param scale The scale factor in X direction * @since 4.10 **/ void setXScale(qreal scale); /** * Sets the scale factor in Y direction to @p scale * @param scale The scale factor in Y direction * @since 4.10 **/ void setYScale(qreal scale); /** * Sets the scale factor in Z direction to @p scale * @param scale The scale factor in Z direction * @since 4.10 **/ void setZScale(qreal scale); /** * Sets the scale factor in X and Y direction. * @param scale The scale factor for X and Y direction * @since 4.10 **/ void setScale(const QVector2D &scale); /** * Sets the scale factor in X, Y and Z direction * @param scale The scale factor for X, Y and Z direction * @since 4.10 **/ void setScale(const QVector3D &scale); const QGraphicsScale &scale() const; const QVector3D &translation() const; /** * @returns the translation in X direction. * @since 4.10 **/ qreal xTranslation() const; /** * @returns the translation in Y direction. * @since 4.10 **/ qreal yTranslation() const; /** * @returns the translation in Z direction. * @since 4.10 **/ qreal zTranslation() const; /** * Sets the translation in X direction to @p translate. * @since 4.10 **/ void setXTranslation(qreal translate); /** * Sets the translation in Y direction to @p translate. * @since 4.10 **/ void setYTranslation(qreal translate); /** * Sets the translation in Z direction to @p translate. * @since 4.10 **/ void setZTranslation(qreal translate); /** * Performs a translation by adding the values component wise. * @param x Translation in X direction * @param y Translation in Y direction * @param z Translation in Z direction * @since 4.10 **/ void translate(qreal x, qreal y = 0.0, qreal z = 0.0); /** * Performs a translation by adding the values component wise. * Overloaded method for convenience. * @param translate The translation * @since 4.10 **/ void translate(const QVector3D &translate); /** * Sets the rotation angle. * @param angle The new rotation angle. * @since 4.10 * @see rotationAngle() **/ void setRotationAngle(qreal angle); /** * Returns the rotation angle. * Initially 0.0. * @returns The current rotation angle. * @since 4.10 * @see setRotationAngle **/ qreal rotationAngle() const; /** * Sets the rotation origin. * @param origin The new rotation origin. * @since 4.10 * @see rotationOrigin() **/ void setRotationOrigin(const QVector3D &origin); /** * Returns the rotation origin. That is the point in space which is fixed during the rotation. * Initially this is 0/0/0. * @returns The rotation's origin * @since 4.10 * @see setRotationOrigin() **/ QVector3D rotationOrigin() const; /** * Sets the rotation axis. * Set a component to 1.0 to rotate around this axis and to 0.0 to disable rotation around the * axis. * @param axis A vector holding information on which axis to rotate * @since 4.10 * @see rotationAxis() **/ void setRotationAxis(const QVector3D &axis); /** * Sets the rotation axis. * Overloaded method for convenience. * @param axis The axis around which should be rotated. * @since 4.10 * @see rotationAxis() **/ void setRotationAxis(Qt::Axis axis); /** * The current rotation axis. * By default the rotation is (0/0/1) which means a rotation around the z axis. * @returns The current rotation axis. * @since 4.10 * @see setRotationAxis **/ QVector3D rotationAxis() const; protected: PaintData(); PaintData(const PaintData &other); private: PaintDataPrivate * const d; }; class KWINEFFECTS_EXPORT WindowPaintData : public PaintData { public: explicit WindowPaintData(EffectWindow* w); explicit WindowPaintData(EffectWindow* w, const QMatrix4x4 &screenProjectionMatrix); WindowPaintData(const WindowPaintData &other); virtual ~WindowPaintData(); /** * Scales the window by @p scale factor. * Multiplies all three components by the given factor. * @since 4.10 **/ WindowPaintData& operator*=(qreal scale); /** * Scales the window by @p scale factor. * Performs a component wise multiplication on x and y components. * @since 4.10 **/ WindowPaintData& operator*=(const QVector2D &scale); /** * Scales the window by @p scale factor. * Performs a component wise multiplication. * @since 4.10 **/ WindowPaintData& operator*=(const QVector3D &scale); /** * Translates the window by the given @p translation and returns a reference to the ScreenPaintData. * @since 4.10 **/ WindowPaintData& operator+=(const QPointF &translation); /** * Translates the window by the given @p translation and returns a reference to the ScreenPaintData. * Overloaded method for convenience. * @since 4.10 **/ WindowPaintData& operator+=(const QPoint &translation); /** * Translates the window by the given @p translation and returns a reference to the ScreenPaintData. * Overloaded method for convenience. * @since 4.10 **/ WindowPaintData& operator+=(const QVector2D &translation); /** * Translates the window by the given @p translation and returns a reference to the ScreenPaintData. * Overloaded method for convenience. * @since 4.10 **/ WindowPaintData& operator+=(const QVector3D &translation); /** * Window opacity, in range 0 = transparent to 1 = fully opaque * @see setOpacity * @since 4.10 */ qreal opacity() const; /** * Sets the window opacity to the new @p opacity. * If you want to modify the existing opacity level consider using multiplyOpacity. * @param opacity The new opacity level * @since 4.10 **/ void setOpacity(qreal opacity); /** * Multiplies the current opacity with the @p factor. * @param factor Factor with which the opacity should be multiplied * @return New opacity level * @since 4.10 **/ qreal multiplyOpacity(qreal factor); /** * Saturation of the window, in range [0; 1] * 1 means that the window is unchanged, 0 means that it's completely * unsaturated (greyscale). 0.5 would make the colors less intense, * but not completely grey * Use EffectsHandler::saturationSupported() to find out whether saturation * is supported by the system, otherwise this value has no effect. * @return The current saturation * @see setSaturation() * @since 4.10 **/ qreal saturation() const; /** * Sets the window saturation level to @p saturation. * If you want to modify the existing saturation level consider using multiplySaturation. * @param saturation The new saturation level * @since 4.10 **/ void setSaturation(qreal saturation) const; /** * Multiplies the current saturation with @p factor. * @param factor with which the saturation should be multiplied * @return New saturation level * @since 4.10 **/ qreal multiplySaturation(qreal factor); /** * Brightness of the window, in range [0; 1] * 1 means that the window is unchanged, 0 means that it's completely * black. 0.5 would make it 50% darker than usual **/ qreal brightness() const; /** * Sets the window brightness level to @p brightness. * If you want to modify the existing brightness level consider using multiplyBrightness. * @param brightness The new brightness level **/ void setBrightness(qreal brightness); /** * Multiplies the current brightness level with @p factor. * @param factor with which the brightness should be multiplied. * @return New brightness level * @since 4.10 **/ qreal multiplyBrightness(qreal factor); /** * The screen number for which the painting should be done. * This affects color correction (different screens may need different * color correction lookup tables because they have different ICC profiles). * @return screen for which painting should be done */ int screen() const; /** * @param screen New screen number * A value less than 0 will indicate that a default profile should be done. */ void setScreen(int screen) const; /** * @brief Sets the cross fading @p factor to fade over with previously sized window. * If @c 1.0 only the current window is used, if @c 0.0 only the previous window is used. * * By default only the current window is used. This factor can only make any visual difference * if the previous window get referenced. * * @param factor The cross fade factor between @c 0.0 (previous window) and @c 1.0 (current window) * @see crossFadeProgress */ void setCrossFadeProgress(qreal factor); /** * @see setCrossFadeProgress */ qreal crossFadeProgress() const; /** * Sets the projection matrix that will be used when painting the window. * * The default projection matrix can be overridden by setting this matrix * to a non-identity matrix. */ void setProjectionMatrix(const QMatrix4x4 &matrix); /** * Returns the current projection matrix. * * The default value for this matrix is the identity matrix. */ QMatrix4x4 projectionMatrix() const; /** * Returns a reference to the projection matrix. */ QMatrix4x4 &rprojectionMatrix(); /** * Sets the model-view matrix that will be used when painting the window. * * The default model-view matrix can be overridden by setting this matrix * to a non-identity matrix. */ void setModelViewMatrix(const QMatrix4x4 &matrix); /** * Returns the current model-view matrix. * * The default value for this matrix is the identity matrix. */ QMatrix4x4 modelViewMatrix() const; /** * Returns a reference to the model-view matrix. */ QMatrix4x4 &rmodelViewMatrix(); /** * Returns The projection matrix as used by the current screen painting pass * including screen transformations. * * @since 5.6 **/ QMatrix4x4 screenProjectionMatrix() const; WindowQuadList quads; /** * Shader to be used for rendering, if any. */ GLShader* shader; private: WindowPaintDataPrivate * const d; }; class KWINEFFECTS_EXPORT ScreenPaintData : public PaintData { public: ScreenPaintData(); ScreenPaintData(const QMatrix4x4 &projectionMatrix, const QRect &outputGeometry = QRect()); ScreenPaintData(const ScreenPaintData &other); virtual ~ScreenPaintData(); /** * Scales the screen by @p scale factor. * Multiplies all three components by the given factor. * @since 4.10 **/ ScreenPaintData& operator*=(qreal scale); /** * Scales the screen by @p scale factor. * Performs a component wise multiplication on x and y components. * @since 4.10 **/ ScreenPaintData& operator*=(const QVector2D &scale); /** * Scales the screen by @p scale factor. * Performs a component wise multiplication. * @since 4.10 **/ ScreenPaintData& operator*=(const QVector3D &scale); /** * Translates the screen by the given @p translation and returns a reference to the ScreenPaintData. * @since 4.10 **/ ScreenPaintData& operator+=(const QPointF &translation); /** * Translates the screen by the given @p translation and returns a reference to the ScreenPaintData. * Overloaded method for convenience. * @since 4.10 **/ ScreenPaintData& operator+=(const QPoint &translation); /** * Translates the screen by the given @p translation and returns a reference to the ScreenPaintData. * Overloaded method for convenience. * @since 4.10 **/ ScreenPaintData& operator+=(const QVector2D &translation); /** * Translates the screen by the given @p translation and returns a reference to the ScreenPaintData. * Overloaded method for convenience. * @since 4.10 **/ ScreenPaintData& operator+=(const QVector3D &translation); ScreenPaintData& operator=(const ScreenPaintData &rhs); /** * The projection matrix used by the scene for the current rendering pass. * On non-OpenGL compositors it's set to Identity matrix. * @since 5.6 **/ QMatrix4x4 projectionMatrix() const; /** * The geometry of the currently rendered output. * Only set for per-output rendering (e.g. Wayland). * * This geometry can be used as a hint about the native window the OpenGL context * is bound. OpenGL calls need to be translated to this geometry. * @since 5.9 **/ QRect outputGeometry() const; private: class Private; QScopedPointer d; }; class KWINEFFECTS_EXPORT ScreenPrePaintData { public: int mask; QRegion paint; }; /** * @short Helper class for restricting painting area only to allowed area. * * This helper class helps specifying areas that should be painted, clipping * out the rest. The simplest usage is creating an object on the stack * and giving it the area that is allowed to be painted to. When the object * is destroyed, the restriction will be removed. * Note that all painting code must use paintArea() to actually perform the clipping. */ class KWINEFFECTS_EXPORT PaintClipper { public: /** * Calls push(). */ explicit PaintClipper(const QRegion& allowed_area); /** * Calls pop(). */ ~PaintClipper(); /** * Allows painting only in the given area. When areas have been already * specified, painting is allowed only in the intersection of all areas. */ static void push(const QRegion& allowed_area); /** * Removes the given area. It must match the top item in the stack. */ static void pop(const QRegion& allowed_area); /** * Returns true if any clipping should be performed. */ static bool clip(); /** * If clip() returns true, this function gives the resulting area in which * painting is allowed. It is usually simpler to use the helper Iterator class. */ static QRegion paintArea(); /** * Helper class to perform the clipped painting. The usage is: * @code * for ( PaintClipper::Iterator iterator; * !iterator.isDone(); * iterator.next()) * { // do the painting, possibly use iterator.boundingRect() * } * @endcode */ class KWINEFFECTS_EXPORT Iterator { public: Iterator(); ~Iterator(); bool isDone(); void next(); QRect boundingRect() const; private: struct Data; Data* data; }; private: QRegion area; static QStack< QRegion >* areas; }; /** * @internal */ template class KWINEFFECTS_EXPORT Motion { public: /** * Creates a new motion object. "Strength" is the amount of * acceleration that is applied to the object when the target * changes and "smoothness" relates to how fast the object * can change its direction and speed. */ explicit Motion(T initial, double strength, double smoothness); /** * Creates an exact copy of another motion object, including * position, target and velocity. */ Motion(const Motion &other); ~Motion(); inline T value() const { return m_value; } inline void setValue(const T value) { m_value = value; } inline T target() const { return m_target; } inline void setTarget(const T target) { m_start = m_value; m_target = target; } inline T velocity() const { return m_velocity; } inline void setVelocity(const T velocity) { m_velocity = velocity; } inline double strength() const { return m_strength; } inline void setStrength(const double strength) { m_strength = strength; } inline double smoothness() const { return m_smoothness; } inline void setSmoothness(const double smoothness) { m_smoothness = smoothness; } inline T startValue() { return m_start; } /** * The distance between the current position and the target. */ inline T distance() const { return m_target - m_value; } /** * Calculates the new position if not at the target. Called * once per frame only. */ void calculate(const int msec); /** * Place the object on top of the target immediately, * bypassing all movement calculation. */ void finish(); private: T m_value; T m_start; T m_target; T m_velocity; double m_strength; double m_smoothness; }; /** * @short A single 1D motion dynamics object. * * This class represents a single object that can be moved around a * 1D space. Although it can be used directly by itself it is * recommended to use a motion manager instead. */ class KWINEFFECTS_EXPORT Motion1D : public Motion { public: explicit Motion1D(double initial = 0.0, double strength = 0.08, double smoothness = 4.0); Motion1D(const Motion1D &other); ~Motion1D(); }; /** * @short A single 2D motion dynamics object. * * This class represents a single object that can be moved around a * 2D space. Although it can be used directly by itself it is * recommended to use a motion manager instead. */ class KWINEFFECTS_EXPORT Motion2D : public Motion { public: explicit Motion2D(QPointF initial = QPointF(), double strength = 0.08, double smoothness = 4.0); Motion2D(const Motion2D &other); ~Motion2D(); }; /** * @short Helper class for motion dynamics in KWin effects. * * This motion manager class is intended to help KWin effect authors * move windows across the screen smoothly and naturally. Once * windows are registered by the manager the effect can issue move * commands with the moveWindow() methods. The position of any * managed window can be determined in realtime by the * transformedGeometry() method. As the manager knows if any windows * are moving at any given time it can also be used as a notifier as * to see whether the effect is active or not. */ class KWINEFFECTS_EXPORT WindowMotionManager { public: /** * Creates a new window manager object. */ explicit WindowMotionManager(bool useGlobalAnimationModifier = true); ~WindowMotionManager(); /** * Register a window for managing. */ void manage(EffectWindow *w); /** * Register a list of windows for managing. */ inline void manage(EffectWindowList list) { for (int i = 0; i < list.size(); i++) manage(list.at(i)); } /** * Deregister a window. All transformations applied to the * window will be permanently removed and cannot be recovered. */ void unmanage(EffectWindow *w); /** * Deregister all windows, returning the manager to its * originally initiated state. */ void unmanageAll(); /** * Determine the new positions for windows that have not * reached their target. Called once per frame, usually in * prePaintScreen(). Remember to set the * Effect::PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS flag. */ void calculate(int time); /** * Modify a registered window's paint data to make it appear * at its real location on the screen. Usually called in * paintWindow(). Remember to flag the window as having been * transformed in prePaintWindow() by calling * WindowPrePaintData::setTransformed() */ void apply(EffectWindow *w, WindowPaintData &data); /** * Set all motion targets and values back to where the * windows were before transformations. The same as * unmanaging then remanaging all windows. */ void reset(); /** * Resets the motion target and current value of a single * window. */ void reset(EffectWindow *w); /** * Ask the manager to move the window to the target position * with the specified scale. If `yScale` is not provided or * set to 0.0, `scale` will be used as the scale in the * vertical direction as well as in the horizontal direction. */ void moveWindow(EffectWindow *w, QPoint target, double scale = 1.0, double yScale = 0.0); /** * This is an overloaded method, provided for convenience. * * Ask the manager to move the window to the target rectangle. * Automatically determines scale. */ inline void moveWindow(EffectWindow *w, QRect target) { // TODO: Scale might be slightly different in the comparison due to rounding moveWindow(w, target.topLeft(), target.width() / double(w->width()), target.height() / double(w->height())); } /** * Retrieve the current tranformed geometry of a registered * window. */ QRectF transformedGeometry(EffectWindow *w) const; /** * Sets the current transformed geometry of a registered window to the given geometry. * @see transformedGeometry * @since 4.5 */ void setTransformedGeometry(EffectWindow *w, const QRectF &geometry); /** * Retrieve the current target geometry of a registered * window. */ QRectF targetGeometry(EffectWindow *w) const; /** * Return the window that has its transformed geometry under * the specified point. It is recommended to use the stacking * order as it's what the user sees, but it is slightly * slower to process. */ EffectWindow* windowAtPoint(QPoint point, bool useStackingOrder = true) const; /** * Return a list of all currently registered windows. */ inline EffectWindowList managedWindows() const { return m_managedWindows.keys(); } /** * Returns whether or not a specified window is being managed * by this manager object. */ inline bool isManaging(EffectWindow *w) const { return m_managedWindows.contains(w); } /** * Returns whether or not this manager object is actually * managing any windows or not. */ inline bool managingWindows() const { return !m_managedWindows.empty(); } /** * Returns whether all windows have reached their targets yet * or not. Can be used to see if an effect should be * processed and displayed or not. */ inline bool areWindowsMoving() const { return !m_movingWindowsSet.isEmpty(); } /** * Returns whether a window has reached its targets yet * or not. */ inline bool isWindowMoving(EffectWindow *w) const { return m_movingWindowsSet.contains(w); } private: bool m_useGlobalAnimationModifier; struct WindowMotion { // TODO: Rotation, etc? Motion2D translation; // Absolute position Motion2D scale; // xScale and yScale }; QHash m_managedWindows; QSet m_movingWindowsSet; }; /** * @short Helper class for displaying text and icons in frames. * * Paints text and/or and icon with an optional frame around them. The * available frames includes one that follows the default Plasma theme and * another that doesn't. * It is recommended to use this class whenever displaying text. */ class KWINEFFECTS_EXPORT EffectFrame { public: EffectFrame(); virtual ~EffectFrame(); /** * Delete any existing textures to free up graphics memory. They will * be automatically recreated the next time they are required. */ virtual void free() = 0; /** * Render the frame. */ virtual void render(QRegion region = infiniteRegion(), double opacity = 1.0, double frameOpacity = 1.0) = 0; virtual void setPosition(const QPoint& point) = 0; /** * Set the text alignment for static frames and the position alignment * for non-static. */ virtual void setAlignment(Qt::Alignment alignment) = 0; virtual Qt::Alignment alignment() const = 0; virtual void setGeometry(const QRect& geometry, bool force = false) = 0; virtual const QRect& geometry() const = 0; virtual void setText(const QString& text) = 0; virtual const QString& text() const = 0; virtual void setFont(const QFont& font) = 0; virtual const QFont& font() const = 0; /** * Set the icon that will appear on the left-hand size of the frame. */ virtual void setIcon(const QIcon& icon) = 0; virtual const QIcon& icon() const = 0; virtual void setIconSize(const QSize& size) = 0; virtual const QSize& iconSize() const = 0; /** * Sets the geometry of a selection. * To remove the selection set a null rect. * @param selection The geometry of the selection in screen coordinates. **/ virtual void setSelection(const QRect& selection) = 0; /** * @param shader The GLShader for rendering. **/ virtual void setShader(GLShader* shader) = 0; /** * @returns The GLShader used for rendering or null if none. **/ virtual GLShader* shader() const = 0; /** * @returns The style of this EffectFrame. **/ virtual EffectFrameStyle style() const = 0; /** * If @p enable is @c true cross fading between icons and text is enabled * By default disabled. Use setCrossFadeProgress to cross fade. * Cross Fading is currently only available if OpenGL is used. * @param enable @c true enables cross fading, @c false disables it again * @see isCrossFade * @see setCrossFadeProgress * @since 4.6 **/ void enableCrossFade(bool enable); /** * @returns @c true if cross fading is enabled, @c false otherwise * @see enableCrossFade * @since 4.6 **/ bool isCrossFade() const; /** * Sets the current progress for cross fading the last used icon/text * with current icon/text to @p progress. * A value of 0.0 means completely old icon/text, a value of 1.0 means * completely current icon/text. * Default value is 1.0. You have to enable cross fade before using it. * Cross Fading is currently only available if OpenGL is used. * @see enableCrossFade * @see isCrossFade * @see crossFadeProgress * @since 4.6 **/ void setCrossFadeProgress(qreal progress); /** * @returns The current progress for cross fading * @see setCrossFadeProgress * @see enableCrossFade * @see isCrossFade * @since 4.6 **/ qreal crossFadeProgress() const; /** * Returns The projection matrix as used by the current screen painting pass * including screen transformations. * * This matrix is only valid during a rendering pass started by render. * * @since 5.6 * @see render * @see EffectsHandler::paintEffectFrame * @see Effect::paintEffectFrame **/ QMatrix4x4 screenProjectionMatrix() const; protected: void setScreenProjectionMatrix(const QMatrix4x4 &projection); private: EffectFramePrivate* const d; }; /** * Pointer to the global EffectsHandler object. **/ extern KWINEFFECTS_EXPORT EffectsHandler* effects; /*************************************************************** WindowVertex ***************************************************************/ inline WindowVertex::WindowVertex() : px(0), py(0), ox(0), oy(0), tx(0), ty(0) { } inline WindowVertex::WindowVertex(double _x, double _y, double _tx, double _ty) : px(_x), py(_y), ox(_x), oy(_y), tx(_tx), ty(_ty) { } inline WindowVertex::WindowVertex(const QPointF &position, const QPointF &texturePosition) : px(position.x()), py(position.y()), ox(position.x()), oy(position.y()), tx(texturePosition.x()), ty(texturePosition.y()) { } inline void WindowVertex::move(double x, double y) { px = x; py = y; } inline void WindowVertex::setX(double x) { px = x; } inline void WindowVertex::setY(double y) { py = y; } /*************************************************************** WindowQuad ***************************************************************/ inline WindowQuad::WindowQuad(WindowQuadType t, int id) : quadType(t) , uvSwapped(false) , quadID(id) { } inline WindowVertex& WindowQuad::operator[](int index) { assert(index >= 0 && index < 4); return verts[ index ]; } inline const WindowVertex& WindowQuad::operator[](int index) const { assert(index >= 0 && index < 4); return verts[ index ]; } inline WindowQuadType WindowQuad::type() const { assert(quadType != WindowQuadError); return quadType; } inline int WindowQuad::id() const { return quadID; } inline bool WindowQuad::decoration() const { assert(quadType != WindowQuadError); return quadType == WindowQuadDecoration; } inline bool WindowQuad::effect() const { assert(quadType != WindowQuadError); return quadType >= EFFECT_QUAD_TYPE_START; } inline bool WindowQuad::isTransformed() const { return !(verts[ 0 ].px == verts[ 0 ].ox && verts[ 0 ].py == verts[ 0 ].oy && verts[ 1 ].px == verts[ 1 ].ox && verts[ 1 ].py == verts[ 1 ].oy && verts[ 2 ].px == verts[ 2 ].ox && verts[ 2 ].py == verts[ 2 ].oy && verts[ 3 ].px == verts[ 3 ].ox && verts[ 3 ].py == verts[ 3 ].oy); } inline double WindowQuad::left() const { return qMin(verts[ 0 ].px, qMin(verts[ 1 ].px, qMin(verts[ 2 ].px, verts[ 3 ].px))); } inline double WindowQuad::right() const { return qMax(verts[ 0 ].px, qMax(verts[ 1 ].px, qMax(verts[ 2 ].px, verts[ 3 ].px))); } inline double WindowQuad::top() const { return qMin(verts[ 0 ].py, qMin(verts[ 1 ].py, qMin(verts[ 2 ].py, verts[ 3 ].py))); } inline double WindowQuad::bottom() const { return qMax(verts[ 0 ].py, qMax(verts[ 1 ].py, qMax(verts[ 2 ].py, verts[ 3 ].py))); } inline double WindowQuad::originalLeft() const { return verts[ 0 ].ox; } inline double WindowQuad::originalRight() const { return verts[ 2 ].ox; } inline double WindowQuad::originalTop() const { return verts[ 0 ].oy; } inline double WindowQuad::originalBottom() const { return verts[ 2 ].oy; } /*************************************************************** Motion ***************************************************************/ template Motion::Motion(T initial, double strength, double smoothness) : m_value(initial) , m_start(initial) , m_target(initial) , m_velocity() , m_strength(strength) , m_smoothness(smoothness) { } template Motion::Motion(const Motion &other) : m_value(other.value()) , m_start(other.target()) , m_target(other.target()) , m_velocity(other.velocity()) , m_strength(other.strength()) , m_smoothness(other.smoothness()) { } template Motion::~Motion() { } template void Motion::calculate(const int msec) { if (m_value == m_target && m_velocity == T()) // At target and not moving return; // Poor man's time independent calculation int steps = qMax(1, msec / 5); for (int i = 0; i < steps; i++) { T diff = m_target - m_value; T strength = diff * m_strength; m_velocity = (m_smoothness * m_velocity + strength) / (m_smoothness + 1.0); m_value += m_velocity; } } template void Motion::finish() { m_value = m_target; m_velocity = T(); } /*************************************************************** Effect ***************************************************************/ template int Effect::animationTime(int defaultDuration) { return animationTime(T::duration() != 0 ? T::duration() : defaultDuration); } template void Effect::initConfig() { T::instance(effects->config()); } } // namespace Q_DECLARE_METATYPE(KWin::EffectWindow*) Q_DECLARE_METATYPE(QList) /** @} */ #endif // KWINEFFECTS_H