diff --git a/clients/b2/config/config.cpp b/clients/b2/config/config.cpp index 773922360..08b7860c2 100644 --- a/clients/b2/config/config.cpp +++ b/clients/b2/config/config.cpp @@ -1,202 +1,198 @@ /******************************************************************** This file contains the B2 configuration widget Copyright (c) 2001 Karol Szwed http://gallium.n3.net/ Copyright (c) 2007 Luciano Montanaro Automove titlebar bits Copyright (c) 2009 Jussi Kekkonen 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 "config.h" #include #include //Added by qt3to4: #include #include #include #include #include #include extern "C" KDE_EXPORT QObject *allocate_config(KConfig *conf, QWidget *parent) { return(new B2Config(conf, parent)); } /* NOTE: * 'conf' is a pointer to the kwindecoration modules open kwin config, * and is by default set to the "Style" group. * * 'parent' is the parent of the QObject, which is a VBox inside the * Configure tab in kwindecoration */ B2Config::B2Config(KConfig *conf, QWidget *parent) : QObject(parent) { Q_UNUSED( conf ); KGlobal::locale()->insertCatalog("kwin_b2_config"); b2Config = new KConfig("kwinb2rc"); gb = new KVBox(parent); cbColorBorder = new QCheckBox( i18n("Draw window frames using &titlebar colors"), gb); cbColorBorder->setWhatsThis( i18n("When selected, the window borders " "are drawn using the titlebar colors; otherwise, they are " "drawn using normal border colors.")); // Grab Handle showGrabHandleCb = new QCheckBox( i18n("Draw &resize handle"), gb); showGrabHandleCb->setWhatsThis( i18n("When selected, decorations are drawn with a \"grab handle\" " "in the bottom right corner of the windows; " "otherwise, no grab handle is drawn.")); // Automove Titlebar autoMoveTitlebarCb = new QCheckBox( i18n("Auto-move titlebar"), gb); autoMoveTitlebarCb->setWhatsThis( i18n("When selected, titlebars are automatically relocated " "to visible positions; " "otherwise, they are only moved manually using shift+drag.")); // Double click menu option support actionsGB = new QGroupBox(i18n("Actions Settings"), gb); //actionsGB->setOrientation(Qt::Horizontal); QLabel *menuDblClickLabel = new QLabel(actionsGB); menuDblClickLabel->setText(i18n("Double click on menu button:")); menuDblClickOp = new KComboBox(actionsGB); menuDblClickOp->addItem(i18n("Do Nothing")); menuDblClickOp->addItem(i18n("Minimize Window")); menuDblClickOp->addItem(i18n("Shade Window")); menuDblClickOp->addItem(i18n("Close Window")); menuDblClickOp->setWhatsThis( i18n("An action can be associated to a double click " "of the menu button. Leave it to none if in doubt.")); QGridLayout *actionsLayout = new QGridLayout(); QSpacerItem *actionsSpacer = new QSpacerItem(8, 8, QSizePolicy::Expanding, QSizePolicy::Fixed); actionsLayout->addWidget(menuDblClickLabel, 0, 0, Qt::AlignRight); actionsLayout->addWidget(menuDblClickOp, 0, 1); actionsLayout->addItem(actionsSpacer, 0, 2); actionsGB->setLayout(actionsLayout); // Load configuration options KConfigGroup cg(b2Config, "General"); load(cg); // Ensure we track user changes properly - connect(cbColorBorder, SIGNAL(clicked()), - this, SLOT(slotSelectionChanged())); - connect(showGrabHandleCb, SIGNAL(clicked()), - this, SLOT(slotSelectionChanged())); - connect(autoMoveTitlebarCb, SIGNAL(clicked()), - this, SLOT(slotSelectionChanged())); - connect(menuDblClickOp, SIGNAL(activated(int)), - this, SLOT(slotSelectionChanged())); + connect(cbColorBorder, SIGNAL(clicked()), SIGNAL(changed())); + connect(showGrabHandleCb, SIGNAL(clicked()), SIGNAL(changed())); + connect(autoMoveTitlebarCb, SIGNAL(clicked()), SIGNAL(changed())); + connect(menuDblClickOp, SIGNAL(activated(int)), SIGNAL(changed())); // Make the widgets visible in kwindecoration gb->show(); } B2Config::~B2Config() { delete b2Config; delete gb; } void B2Config::slotSelectionChanged() { emit changed(); } // Loads the configurable options from the kwinrc config file // It is passed the open config from kwindecoration to improve efficiency void B2Config::load(const KConfigGroup & /*conf*/) { KConfigGroup cg(b2Config, "General"); bool override = cg.readEntry("UseTitleBarBorderColors", false); cbColorBorder->setChecked(override); override = cg.readEntry("DrawGrabHandle", true); showGrabHandleCb->setChecked(override); override = cg.readEntry( "AutoMoveTitleBar", true ); autoMoveTitlebarCb->setChecked(override); QString returnString = cg.readEntry( "MenuButtonDoubleClickOperation", "NoOp"); int op; if (returnString == "Close") { op = 3; } else if (returnString == "Shade") { op = 2; } else if (returnString == "Minimize") { op = 1; } else { op = 0; } menuDblClickOp->setCurrentIndex(op); } static QString opToString(int op) { switch (op) { case 1: return "Minimize"; case 2: return "Shade"; case 3: return "Close"; case 0: default: return "NoOp"; } } // Saves the configurable options to the kwinrc config file void B2Config::save(KConfigGroup & /*conf*/) { KConfigGroup cg(b2Config, "General"); cg.writeEntry("UseTitleBarBorderColors", cbColorBorder->isChecked()); cg.writeEntry("DrawGrabHandle", showGrabHandleCb->isChecked()); cg.writeEntry("AutoMoveTitleBar", autoMoveTitlebarCb->isChecked()); cg.writeEntry("MenuButtonDoubleClickOperation", opToString(menuDblClickOp->currentIndex())); // Ensure others trying to read this config get updated b2Config->sync(); } // Sets UI widget defaults which must correspond to style defaults void B2Config::defaults() { cbColorBorder->setChecked(false); showGrabHandleCb->setChecked(true); autoMoveTitlebarCb->setChecked(true); menuDblClickOp->setCurrentIndex(0); } #include "config.moc" // vi: sw=4 ts=8 diff --git a/effects/cube/cube.cpp b/effects/cube/cube.cpp index 817a2b8e8..4acd11f6f 100644 --- a/effects/cube/cube.cpp +++ b/effects/cube/cube.cpp @@ -1,2124 +1,2125 @@ /******************************************************************** 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 #include #include namespace KWin { KWIN_EFFECT(cube, CubeEffect) KWIN_EFFECT_SUPPORTED(cube, CubeEffect::supported()) 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_shadersDir(QStringLiteral("kwin/shaders/1.10/")) , m_cubeCapBuffer(NULL) , m_proxy(this) { desktopNameFont.setBold(true); desktopNameFont.setPointSize(14); #ifdef KWIN_HAVE_OPENGLES const qint64 coreVersionNumber = kVersionNumber(3, 0); #else const qint64 coreVersionNumber = kVersionNumber(1, 40); #endif if (GLPlatform::instance()->glslVersion() >= coreVersionNumber) m_shadersDir = QStringLiteral("kwin/shaders/1.40/"); if (effects->compositingType() == OpenGL2Compositing) { const QString fragmentshader = QStandardPaths::locate(QStandardPaths::GenericDataLocation, m_shadersDir + QStringLiteral("cube-reflection.glsl")); m_reflectionShader = ShaderManager::instance()->loadFragmentShader(ShaderManager::GenericShader, fragmentshader); const QString capshader = QStandardPaths::locate(QStandardPaths::GenericDataLocation, m_shadersDir + QStringLiteral("cube-cap.glsl")); m_capShader = ShaderManager::instance()->loadFragmentShader(ShaderManager::GenericShader, capshader); } 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())); connect(effects, SIGNAL(screenGeometryChanged(const QSize&)), this, SLOT(slotResetShaders())); reconfigure(ReconfigureAll); } bool CubeEffect::supported() { return effects->isOpenGLCompositing(); } void CubeEffect::reconfigure(ReconfigureFlags) { CubeConfig::self()->readConfig(); 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(); 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) { KActionCollection* actionCollection = new KActionCollection(this); QAction* cubeAction = actionCollection->addAction(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); cubeShortcut = KGlobalAccel::self()->shortcut(cubeAction); QAction* cylinderAction = actionCollection->addAction(QStringLiteral("Cylinder")); cylinderAction->setText(i18n("Desktop Cylinder")); KGlobalAccel::self()->setShortcut(cylinderAction, QList()); cylinderShortcut = KGlobalAccel::self()->shortcut(cylinderAction); QAction* sphereAction = actionCollection->addAction(QStringLiteral("Sphere")); sphereAction->setText(i18n("Desktop Sphere")); KGlobalAccel::self()->setShortcut(sphereAction, QList()); sphereShortcut = KGlobalAccel::self()->shortcut(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("u_capColor", capColor); } } 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()) { capTexture = new GLTexture(img); capTexture->setFilter(GL_LINEAR); #ifndef KWIN_HAVE_OPENGLES capTexture->setWrapMode(GL_CLAMP_TO_BORDER); #endif // 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()) { wallpaper = new GLTexture(img); effects->addRepaintFull(); } watcher->deleteLater(); } void CubeEffect::slotResetShaders() { ShaderManager::instance()->resetShader(m_capShader, ShaderManager::GenericShader); ShaderManager::instance()->resetShader(m_reflectionShader, ShaderManager::GenericShader); ShaderManager::instance()->resetShader(cylinderShader, ShaderManager::GenericShader); ShaderManager::instance()->resetShader(sphereShader, ShaderManager::GenericShader); } bool CubeEffect::loadShader() { if (!(GLPlatform::instance()->supports(GLSL) && (effects->compositingType() == OpenGL2Compositing))) return false; QString cylinderVertexshader = QStandardPaths::locate(QStandardPaths::GenericDataLocation, m_shadersDir + QStringLiteral("cylinder.vert")); QString sphereVertexshader = QStandardPaths::locate(QStandardPaths::GenericDataLocation, m_shadersDir + QStringLiteral("sphere.vert")); if (cylinderVertexshader.isEmpty() || sphereVertexshader.isEmpty()) { qCritical() << "Couldn't locate shader files" << endl; return false; } cylinderShader = ShaderManager::instance()->loadVertexShader(ShaderManager::GenericShader, cylinderVertexshader); if (!cylinderShader->isValid()) { qCritical() << "The cylinder shader failed to load!" << endl; return false; } else { ShaderBinder binder(cylinderShader); cylinderShader->setUniform("sampler", 0); QMatrix4x4 projection; float fovy = 60.0f; float aspect = 1.0f; float zNear = 0.1f; float zFar = 100.0f; float ymax = zNear * tan(fovy * M_PI / 360.0f); float ymin = -ymax; float xmin = ymin * aspect; float xmax = ymax * aspect; projection.frustum(xmin, xmax, ymin, ymax, zNear, zFar); cylinderShader->setUniform(GLShader::ProjectionMatrix, projection); QMatrix4x4 modelview; float scaleFactor = 1.1 * tan(fovy * M_PI / 360.0f) / ymax; modelview.translate(xmin * scaleFactor, ymax * scaleFactor, -1.1); modelview.scale((xmax - xmin)*scaleFactor / displayWidth(), -(ymax - ymin)*scaleFactor / displayHeight(), 0.001); cylinderShader->setUniform(GLShader::ModelViewMatrix, modelview); const QMatrix4x4 identity; cylinderShader->setUniform(GLShader::ScreenTransformation, identity); cylinderShader->setUniform(GLShader::WindowTransformation, identity); QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); cylinderShader->setUniform("width", (float)rect.width() * 0.5f); } sphereShader = ShaderManager::instance()->loadVertexShader(ShaderManager::GenericShader, sphereVertexshader); if (!sphereShader->isValid()) { qCritical() << "The sphere shader failed to load!" << endl; return false; } else { ShaderBinder binder(sphereShader); sphereShader->setUniform("sampler", 0); QMatrix4x4 projection; float fovy = 60.0f; float aspect = 1.0f; float zNear = 0.1f; float zFar = 100.0f; float ymax = zNear * tan(fovy * M_PI / 360.0f); float ymin = -ymax; float xmin = ymin * aspect; float xmax = ymax * aspect; projection.frustum(xmin, xmax, ymin, ymax, zNear, zFar); sphereShader->setUniform(GLShader::ProjectionMatrix, projection); QMatrix4x4 modelview; float scaleFactor = 1.1 * tan(fovy * M_PI / 360.0f) / ymax; modelview.translate(xmin * scaleFactor, ymax * scaleFactor, -1.1); modelview.scale((xmax - xmin)*scaleFactor / displayWidth(), -(ymax - ymin)*scaleFactor / displayHeight(), 0.001); sphereShader->setUniform(GLShader::ModelViewMatrix, modelview); const QMatrix4x4 identity; sphereShader->setUniform(GLShader::ScreenTransformation, identity); sphereShader->setUniform(GLShader::WindowTransformation, identity); 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)); checkGLError("Loading Sphere Shader"); } 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 (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(ShaderManager::SimpleShader); 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); } pushMatrix(m_reflectionMatrix); #ifndef KWIN_HAVE_OPENGLES // TODO: find a solution for GLES glEnable(GL_CLIP_PLANE0); #endif reflectionPainting = true; glEnable(GL_CULL_FACE); paintCap(true, -point - zTranslate); // cube glCullFace(GL_BACK); pushMatrix(m_rotationMatrix); paintCube(mask, region, data); popMatrix(); // call the inside cube effects #ifdef KWIN_HAVE_OPENGL_1 foreach (CubeInsideEffect * inside, m_cubeInsideEffects) { pushMatrix(m_rotationMatrix); glTranslatef(rect.width() / 2, rect.height() / 2, -point - zTranslate); glRotatef((1 - frontDesktop) * 360.0f / effects->numberOfDesktops(), 0.0, 1.0, 0.0); inside->paint(); popMatrix(); } #endif glCullFace(GL_FRONT); pushMatrix(m_rotationMatrix); paintCube(mask, region, data); popMatrix(); paintCap(false, -point - zTranslate); glDisable(GL_CULL_FACE); reflectionPainting = false; #ifndef KWIN_HAVE_OPENGLES // TODO: find a solution for GLES glDisable(GL_CLIP_PLANE0); #endif popMatrix(); 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); ShaderManager *shaderManager = ShaderManager::instance(); if (shaderManager->isValid() && m_reflectionShader && m_reflectionShader->isValid()) { // ensure blending is enabled - no attribute stack ShaderBinder binder(m_reflectionShader); QMatrix4x4 windowTransformation; windowTransformation.translate(rect.x() + rect.width() * 0.5f, 0.0, 0.0); m_reflectionShader->setUniform("windowTransformation", 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); } else { #ifdef KWIN_HAVE_OPENGL_1 glColor4f(0.0, 0.0, 0.0, alpha); glPushMatrix(); glTranslatef(rect.x() + rect.width() * 0.5f, 0.0, 0.0); glBegin(GL_POLYGON); glVertex3f(vertices[0], vertices[1], vertices[2]); glVertex3f(vertices[3], vertices[4], vertices[5]); // rearground alpha = -1.0; glColor4f(0.0, 0.0, 0.0, alpha); glVertex3f(vertices[6], vertices[7], vertices[8]); glVertex3f(vertices[9], vertices[10], vertices[11]); glEnd(); glPopMatrix(); #endif } glDisable(GL_BLEND); } glEnable(GL_CULL_FACE); // caps paintCap(false, -point - zTranslate); // cube glCullFace(GL_FRONT); pushMatrix(m_rotationMatrix); paintCube(mask, region, data); popMatrix(); // call the inside cube effects #ifdef KWIN_HAVE_OPENGL_1 foreach (CubeInsideEffect * inside, m_cubeInsideEffects) { pushMatrix(m_rotationMatrix); glTranslatef(rect.width() / 2, rect.height() / 2, -point - zTranslate); glRotatef((1 - frontDesktop) * 360.0f / effects->numberOfDesktops(), 0.0, 1.0, 0.0); inside->paint(); popMatrix(); } #endif glCullFace(GL_BACK); pushMatrix(m_rotationMatrix); paintCube(mask, region, data); popMatrix(); // cap paintCap(true, -point - zTranslate); 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); } // restore the ScreenTransformation after all desktops are painted // if not done GenericShader keeps the rotation data and transforms windows incorrectly in other rendering calls if (effects->compositingType() == OpenGL2Compositing) { GLShader *shader = ShaderManager::instance()->pushShader(KWin::ShaderManager::GenericShader); shader->setUniform(GLShader::ScreenTransformation, QMatrix4x4()); ShaderManager::instance()->popShader(); } } 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(); } ScreenPaintData newData = data; newData.setRotationAxis(Qt::YAxis); newData.setRotationAngle(internalCubeAngle * i); newData.setRotationOrigin(QVector3D(rect.width() / 2, 0.0, -point)); newData.setZTranslation(-zTranslate); effects->paintScreen(mask, region, newData); } cube_painting = false; painting_desktop = effects->currentDesktop(); } void CubeEffect::paintCap(bool frontFirst, float zOffset) { 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 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) { m_capShader->setUniform(GLShader::ScreenTransformation, m_reflectionMatrix * m_rotationMatrix); } else { m_capShader->setUniform(GLShader::ScreenTransformation, m_rotationMatrix); } m_capShader->setUniform(GLShader::WindowTransformation, capMatrix); m_capShader->setUniform("u_untextured", texturedCaps ? 0 : 1); if (texturedCaps && effects->numberOfDesktops() > 3 && capTexture) { capTexture->bind(); } } else { #ifdef KWIN_HAVE_OPENGL_1 pushMatrix(m_rotationMatrix * capMatrix); glMatrixMode(GL_TEXTURE); pushMatrix(); loadMatrix(m_textureMirrorMatrix); glMatrixMode(GL_MODELVIEW); glColor4f(capColor.redF(), capColor.greenF(), capColor.blueF(), cubeOpacity); if (texturedCaps && effects->numberOfDesktops() > 3 && capTexture) { // modulate the cap texture: cap color should be background for translucent pixels // cube opacity should be used for all pixels // blend with cap color float color[4] = { static_cast(capColor.redF()), static_cast(capColor.greenF()), static_cast(capColor.blueF()), cubeOpacity }; glActiveTexture(GL_TEXTURE0); capTexture->bind(); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); glColor4fv(color); // set Opacity to cube opacity // TODO: change opacity during start/stop animation glActiveTexture(GL_TEXTURE1); capTexture->bind(); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_REPLACE); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PREVIOUS); glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_CONSTANT); glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, color); glActiveTexture(GL_TEXTURE0); glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, color); } #endif } 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("windowTransformation", capMatrix); m_capShader->setUniform("u_mirror", 0); } else { #ifndef KWIN_HAVE_OPENGLES glMatrixMode(GL_TEXTURE); popMatrix(); glMatrixMode(GL_MODELVIEW); #endif popMatrix(); pushMatrix(m_rotationMatrix * capMatrix); } glCullFace(secondCull); m_cubeCapBuffer->render(GL_TRIANGLES); glDisable(GL_BLEND); if (capShader) { ShaderManager::instance()->popShader(); if (texturedCaps && effects->numberOfDesktops() > 3 && capTexture) { capTexture->unbind(); } } else { popMatrix(); if (texturedCaps && effects->numberOfDesktops() > 3 && capTexture) { #ifndef KWIN_HAVE_OPENGLES glActiveTexture(GL_TEXTURE1); glDisable(capTexture->target()); glActiveTexture(GL_TEXTURE0); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glColor4f(0.0f, 0.0f, 0.0f, 0.0f); capTexture->unbind(); #endif } } } 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(); GLShader *shader = NULL; QMatrix4x4 origMatrix; if (activated && cube_painting) { + region= infiniteRegion(); // we need to explicitly prevent any clipping, bug #325432 shader = shaderManager->pushShader(ShaderManager::GenericShader); //qDebug() << 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 (!shader) { pushMatrix(); } 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; if (shader) { data.setXTranslation(-rect.width()); } else { data.setRotationAxis(Qt::YAxis); data.setRotationOrigin(QVector3D(rect.width() - w->x(), 0.0, 0.0)); data.setRotationAngle(-360.0f / effects->numberOfDesktops()); 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); QMatrix4x4 matrix; matrix.translate(rect.width() / 2, 0.0, -point); matrix.rotate(-360.0f / effects->numberOfDesktops(), 0.0, 1.0, 0.0); matrix.translate(-rect.width() / 2, 0.0, point); multiplyMatrix(matrix); } } 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; if (shader) { data.setXTranslation(rect.width()); } else { data.setRotationAxis(Qt::YAxis); data.setRotationOrigin(QVector3D(-w->x(), 0.0, 0.0)); data.setRotationAngle(-360.0f / effects->numberOfDesktops()); 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); QMatrix4x4 matrix; matrix.translate(rect.width() / 2, 0.0, -point); matrix.rotate(360.0f / effects->numberOfDesktops(), 0.0, 1.0, 0.0); matrix.translate(-rect.width() / 2, 0.0, point); multiplyMatrix(matrix); } } 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; } if (shader) { origMatrix = shader->getUniformMatrix4x4("screenTransformation"); GLShader *currentShader = shader; 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); data.shader = cylinderShader; 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); data.shader = sphereShader; currentShader = sphereShader; } if (reflectionPainting) { currentShader->setUniform(GLShader::ScreenTransformation, m_reflectionMatrix * m_rotationMatrix * origMatrix); } else { currentShader->setUniform(GLShader::ScreenTransformation, m_rotationMatrix*origMatrix); } } } effects->paintWindow(w, mask, region, data); if (activated && cube_painting) { if (shader) { if (mode == Cylinder || mode == Sphere) { shaderManager->popShader(); } else { shader->setUniform(GLShader::ScreenTransformation, origMatrix); } 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); if (reflectionPainting) { m_capShader->setUniform(GLShader::ScreenTransformation, m_reflectionMatrix * m_rotationMatrix * origMatrix); } else { m_capShader->setUniform(GLShader::ScreenTransformation, m_rotationMatrix * origMatrix); } m_capShader->setUniform(GLShader::WindowTransformation, QMatrix4x4()); } 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); } } if (!shader) { popMatrix(); } } } 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() { qDebug() << "toggle cube"; toggle(Cube); } void CubeEffect::toggleCylinder() { qDebug() << "toggle cylinder"; if (!useShaders) useShaders = loadShader(); if (useShaders) toggle(Cylinder); else qCritical() << "Sorry shaders are not available - cannot activate Cylinder"; } void CubeEffect::toggleSphere() { qDebug() << "toggle sphere"; if (!useShaders) useShaders = loadShader(); if (useShaders) toggle(Sphere); else qCritical() << "Sorry shaders are not available - cannot activate 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 qDebug() << "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 qDebug() << "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: qDebug() << "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: qDebug() << "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); qDebug() << "Cube is activated"; verticalPosition = Normal; verticalRotating = false; manualAngle = 0.0; manualVerticalAngle = 0.0; if (reflection) { QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); #ifndef KWIN_HAVE_OPENGLES // clip parts above the reflection area double eqn[4] = {0.0, 1.0, 0.0, 0.0}; glPushMatrix(); glTranslatef(0.0, rect.height(), 0.0); glClipPlane(GL_CLIP_PLANE0, eqn); glPopMatrix(); #endif 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() == displayWidth() - 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; } } // namespace diff --git a/effects/mouseclick/mouseclick.cpp b/effects/mouseclick/mouseclick.cpp index c9c723e28..f2d34bda3 100644 --- a/effects/mouseclick/mouseclick.cpp +++ b/effects/mouseclick/mouseclick.cpp @@ -1,393 +1,383 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2012 Filip Wieladek 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 "mouseclick.h" // KConfigSkeleton #include "mouseclickconfig.h" #include #include #ifdef KWIN_HAVE_XRENDER_COMPOSITING #include #include #include #endif #include #include #include #include namespace KWin { KWIN_EFFECT(mouseclick, MouseClickEffect) MouseClickEffect::MouseClickEffect() { m_enabled = false; KActionCollection* actionCollection = new KActionCollection(this); QAction* a = actionCollection->addAction(QStringLiteral("ToggleMouseClick")); a->setText(i18n("Toggle Effect")); KGlobalAccel::self()->setDefaultShortcut(a, QList() << Qt::META + Qt::Key_Asterisk); KGlobalAccel::self()->setShortcut(a, QList() << Qt::META + Qt::Key_Asterisk); connect(a, SIGNAL(triggered(bool)), this, SLOT(toggleEnabled())); connect(effects, SIGNAL(mouseChanged(QPoint,QPoint,Qt::MouseButtons,Qt::MouseButtons,Qt::KeyboardModifiers,Qt::KeyboardModifiers)), this, SLOT(slotMouseChanged(QPoint,QPoint,Qt::MouseButtons,Qt::MouseButtons,Qt::KeyboardModifiers,Qt::KeyboardModifiers))); reconfigure(ReconfigureAll); m_buttons[0] = new MouseButton(i18n("Left"), Qt::LeftButton); m_buttons[1] = new MouseButton(i18n("Middle"), Qt::MiddleButton); m_buttons[2] = new MouseButton(i18n("Right"), Qt::RightButton); } MouseClickEffect::~MouseClickEffect() { if (m_enabled) effects->stopMousePolling(); foreach (const MouseEvent* click, m_clicks) { delete click; } m_clicks.clear(); for (int i = 0; i < BUTTON_COUNT; ++i) { delete m_buttons[i]; } } void MouseClickEffect::reconfigure(ReconfigureFlags) { MouseClickConfig::self()->readConfig(); m_colors[0] = MouseClickConfig::color1(); m_colors[1] = MouseClickConfig::color2(); m_colors[2] = MouseClickConfig::color3(); m_lineWidth = MouseClickConfig::lineWidth(); m_ringLife = MouseClickConfig::ringLife(); m_ringMaxSize = MouseClickConfig::ringSize(); m_ringCount = MouseClickConfig::ringCount(); m_showText = MouseClickConfig::showText(); m_font = MouseClickConfig::font(); } void MouseClickEffect::prePaintScreen(ScreenPrePaintData& data, int time) { foreach (MouseEvent* click, m_clicks) { click->m_time += time; } for (int i = 0; i < BUTTON_COUNT; ++i) { if (m_buttons[i]->m_isPressed) { m_buttons[i]->m_time += time; } } while (m_clicks.size() > 0) { MouseEvent* first = m_clicks[0]; if (first->m_time <= m_ringLife) { break; } m_clicks.pop_front(); delete first; } effects->prePaintScreen(data, time); } void MouseClickEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) { effects->paintScreen(mask, region, data); paintScreenSetup(mask, region, data); foreach (const MouseEvent* click, m_clicks) { for (int i = 0; i < m_ringCount; ++i) { float alpha = computeAlpha(click, i); float size = computeRadius(click, i); if (size > 0 && alpha > 0) { QColor color = m_colors[click->m_button]; color.setAlphaF(alpha); drawCircle(color, click->m_pos.x(), click->m_pos.y(), size); } } if (m_showText && click->m_frame) { float frameAlpha = (click->m_time * 2.0f - m_ringLife) / m_ringLife; frameAlpha = frameAlpha < 0 ? 1 : -(frameAlpha * frameAlpha) + 1; click->m_frame->render(infiniteRegion(), frameAlpha, frameAlpha); } } paintScreenFinish(mask, region, data); } void MouseClickEffect::postPaintScreen() { effects->postPaintScreen(); repaint(); } float MouseClickEffect::computeRadius(const MouseEvent* click, int ring) { float ringDistance = m_ringLife / (m_ringCount * 3); if (click->m_press) { return ((click->m_time - ringDistance * ring) / m_ringLife) * m_ringMaxSize; } return ((m_ringLife - click->m_time - ringDistance * ring) / m_ringLife) * m_ringMaxSize; } float MouseClickEffect::computeAlpha(const MouseEvent* click, int ring) { float ringDistance = m_ringLife / (m_ringCount * 3); return (m_ringLife - (float)click->m_time - ringDistance * (ring)) / m_ringLife; } void MouseClickEffect::slotMouseChanged(const QPoint& pos, const QPoint&, Qt::MouseButtons buttons, Qt::MouseButtons oldButtons, Qt::KeyboardModifiers, Qt::KeyboardModifiers) { if (buttons == oldButtons) return; MouseEvent* m = NULL; for (int i = 0; i < BUTTON_COUNT; ++i) { MouseButton* b = m_buttons[i]; if (isPressed(b->m_button, buttons, oldButtons)) { m = new MouseEvent(i, pos, 0, createEffectFrame(pos, b->m_labelDown), true); } else if (isReleased(b->m_button, buttons, oldButtons) && (!b->m_isPressed || b->m_time > m_ringLife)) { // we might miss a press, thus also check !b->m_isPressed, bug #314762 m = new MouseEvent(i, pos, 0, createEffectFrame(pos, b->m_labelUp), false); } b->setPressed(b->m_button & buttons); } if (m) { m_clicks.append(m); } repaint(); } EffectFrame* MouseClickEffect::createEffectFrame(const QPoint& pos, const QString& text) { if (!m_showText) { return NULL; } QPoint point(pos.x() + m_ringMaxSize, pos.y()); EffectFrame* frame = effects->effectFrame(EffectFrameStyled, false, point, Qt::AlignLeft); frame->setFont(m_font); frame->setText(text); return frame; } void MouseClickEffect::repaint() { if (m_clicks.size() > 0) { - int xmin = effects->workspaceWidth(); - int ymin = effects->workspaceHeight(); - int xmax = 0; - int ymax = 0; - int yfontMax = 0; + QRegion dirtyRegion; + const int radius = m_ringMaxSize + m_lineWidth; foreach (MouseEvent* click, m_clicks) { - QRect fontGeo; + dirtyRegion |= QRect(click->m_pos.x() - radius, click->m_pos.y() - radius, 2*radius, 2*radius); if (click->m_frame) { - fontGeo = click->m_frame->geometry(); + // we grant the plasma style 32px padding for stuff like shadows... + dirtyRegion |= click->m_frame->geometry().adjusted(-32,-32,32,32); } - xmin = qMin(xmin, click->m_pos.x()); - ymin = qMin(ymin, click->m_pos.y()); - xmax = qMax(xmax, click->m_pos.x() + (fontGeo.width() + 10)); - ymax = qMax(ymax, click->m_pos.y()); - yfontMax = qMax(yfontMax, fontGeo.height() + 10); } - int radius = m_ringMaxSize + m_lineWidth; - int yradius = yfontMax / 2 > radius ? yfontMax / 2 : radius; - QRect repaint(xmin - radius, ymin - yradius, xmax - xmin + radius * 2 , ymax - ymin + yradius * 2); - effects->addRepaint(repaint); + effects->addRepaint(dirtyRegion); } } bool MouseClickEffect::isReleased(Qt::MouseButtons button, Qt::MouseButtons buttons, Qt::MouseButtons oldButtons) { return !(button & buttons) && (button & oldButtons); } bool MouseClickEffect::isPressed(Qt::MouseButtons button, Qt::MouseButtons buttons, Qt::MouseButtons oldButtons) { return (button & buttons) && !(button & oldButtons); } void MouseClickEffect::toggleEnabled() { m_enabled = !m_enabled; if (m_clicks.size() > 0) { foreach (const MouseEvent* click, m_clicks) { delete click; } } m_clicks.clear(); for (int i = 0; i < BUTTON_COUNT; ++i) { m_buttons[i]->m_time = 0; m_buttons[i]->m_isPressed = false; } if (m_enabled) { effects->startMousePolling(); } else { effects->stopMousePolling(); } } bool MouseClickEffect::isActive() const { return m_enabled && (m_clicks.size() > 0); } void MouseClickEffect::drawCircle(const QColor& color, float cx, float cy, float r) { if (effects->isOpenGLCompositing()) drawCircleGl(color, cx, cy, r); if (effects->compositingType() == XRenderCompositing) drawCircleXr(color, cx, cy, r); } void MouseClickEffect::paintScreenSetup(int mask, QRegion region, ScreenPaintData& data) { if (effects->isOpenGLCompositing()) paintScreenSetupGl(mask, region, data); } void MouseClickEffect::paintScreenFinish(int mask, QRegion region, ScreenPaintData& data) { if (effects->isOpenGLCompositing()) paintScreenFinishGl(mask, region, data); } void MouseClickEffect::drawCircleGl(const QColor& color, float cx, float cy, float r) { static int num_segments = 80; static float theta = 2 * 3.1415926 / float(num_segments); static float c = cosf(theta); //precalculate the sine and cosine static float s = sinf(theta); float t; float x = r;//we start at angle = 0 float y = 0; GLVertexBuffer* vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); vbo->setUseColor(true); vbo->setColor(color); QVector verts; verts.reserve(num_segments * 2); for (int ii = 0; ii < num_segments; ++ii) { verts << x + cx << y + cy;//output vertex //apply the rotation matrix t = x; x = c * x - s * y; y = s * t + c * y; } vbo->setData(verts.size() / 2, 2, verts.data(), NULL); vbo->render(GL_LINE_LOOP); } void MouseClickEffect::drawCircleXr(const QColor& color, float cx, float cy, float r) { #ifdef KWIN_HAVE_XRENDER_COMPOSITING if (r <= m_lineWidth) return; int num_segments = r+8; float theta = 2.0 * 3.1415926 / num_segments; float cos = cosf(theta); //precalculate the sine and cosine float sin = sinf(theta); float x[2] = {r, r-m_lineWidth}; float y[2] = {0, 0}; #define DOUBLE_TO_FIXED(d) ((xcb_render_fixed_t) ((d) * 65536)) QVector strip; strip.reserve(2*num_segments+2); xcb_render_pointfix_t point; point.x = DOUBLE_TO_FIXED(x[1]+cx); point.y = DOUBLE_TO_FIXED(y[1]+cy); strip << point; for (int i = 0; i < num_segments; ++i) { //apply the rotation matrix const float h[2] = {x[0], x[1]}; x[0] = cos * x[0] - sin * y[0]; x[1] = cos * x[1] - sin * y[1]; y[0] = sin * h[0] + cos * y[0]; y[1] = sin * h[1] + cos * y[1]; point.x = DOUBLE_TO_FIXED(x[0]+cx); point.y = DOUBLE_TO_FIXED(y[0]+cy); strip << point; point.x = DOUBLE_TO_FIXED(x[1]+cx); point.y = DOUBLE_TO_FIXED(y[1]+cy); strip << point; } const float h = x[0]; x[0] = cos * x[0] - sin * y[0]; y[0] = sin * h + cos * y[0]; point.x = DOUBLE_TO_FIXED(x[0]+cx); point.y = DOUBLE_TO_FIXED(y[0]+cy); strip << point; XRenderPicture fill = xRenderFill(color); xcb_render_tri_strip(connection(), XCB_RENDER_PICT_OP_OVER, fill, effects->xrenderBufferPicture(), 0, 0, 0, strip.count(), strip.constData()); #undef DOUBLE_TO_FIXED #else Q_UNUSED(color) Q_UNUSED(cx) Q_UNUSED(cy) Q_UNUSED(r) #endif } void MouseClickEffect::paintScreenSetupGl(int, QRegion, ScreenPaintData&) { if (ShaderManager::instance()->isValid()) { ShaderManager::instance()->pushShader(ShaderManager::ColorShader); } glLineWidth(m_lineWidth); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } void MouseClickEffect::paintScreenFinishGl(int, QRegion, ScreenPaintData&) { glDisable(GL_BLEND); if (ShaderManager::instance()->isValid()) { ShaderManager::instance()->popShader(); } } } // namespace #include "mouseclick.moc" diff --git a/effects/showfps/showfps.cpp b/effects/showfps/showfps.cpp index 1ab7d57f6..01bce31c8 100644 --- a/effects/showfps/showfps.cpp +++ b/effects/showfps/showfps.cpp @@ -1,485 +1,483 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak 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 "showfps.h" // KConfigSkeleton #include "showfpsconfig.h" #include #include #ifdef KWIN_HAVE_XRENDER_COMPOSITING #include #include #endif #include #include #include #include namespace KWin { KWIN_EFFECT(showfps, ShowFpsEffect) const int FPS_WIDTH = 10; const int MAX_TIME = 100; ShowFpsEffect::ShowFpsEffect() : paints_pos(0) , frames_pos(0) - , fpsText(0) , m_noBenchmark(effects->effectFrame(EffectFrameUnstyled, false)) { for (int i = 0; i < NUM_PAINTS; ++i) { paints[ i ] = 0; paint_size[ i ] = 0; } for (int i = 0; i < MAX_FPS; ++i) frames[ i ] = 0; m_noBenchmark->setAlignment(Qt::AlignTop | Qt::AlignRight); m_noBenchmark->setText(i18n("This effect is not a benchmark")); reconfigure(ReconfigureAll); } void ShowFpsEffect::reconfigure(ReconfigureFlags) { ShowFpsConfig::self()->readConfig(); alpha = ShowFpsConfig::alpha(); x = ShowFpsConfig::x(); y = ShowFpsConfig::y(); if (x == -10000) // there's no -0 :( x = displayWidth() - 2 * NUM_PAINTS - FPS_WIDTH; else if (x < 0) x = displayWidth() - 2 * NUM_PAINTS - FPS_WIDTH - x; if (y == -10000) y = displayHeight() - MAX_TIME; else if (y < 0) y = displayHeight() - MAX_TIME - y; fps_rect = QRect(x, y, FPS_WIDTH + 2 * NUM_PAINTS, MAX_TIME); m_noBenchmark->setPosition(fps_rect.bottomRight() + QPoint(-6, 6)); int textPosition = ShowFpsConfig::textPosition(); textFont = ShowFpsConfig::textFont(); textColor = ShowFpsConfig::textColor(); double textAlpha = ShowFpsConfig::textAlpha(); if (!textColor.isValid()) textColor = QPalette().color(QPalette::Active, QPalette::WindowText); textColor.setAlphaF(textAlpha); switch(textPosition) { case TOP_LEFT: fpsTextRect = QRect(0, 0, 100, 100); textAlign = Qt::AlignTop | Qt::AlignLeft; break; case TOP_RIGHT: fpsTextRect = QRect(displayWidth() - 100, 0, 100, 100); textAlign = Qt::AlignTop | Qt::AlignRight; break; case BOTTOM_LEFT: fpsTextRect = QRect(0, displayHeight() - 100, 100, 100); textAlign = Qt::AlignBottom | Qt::AlignLeft; break; case BOTTOM_RIGHT: fpsTextRect = QRect(displayWidth() - 100, displayHeight() - 100, 100, 100); textAlign = Qt::AlignBottom | Qt::AlignRight; break; case NOWHERE: fpsTextRect = QRect(); break; case INSIDE_GRAPH: default: fpsTextRect = QRect(x, y, FPS_WIDTH + NUM_PAINTS, MAX_TIME); textAlign = Qt::AlignTop | Qt::AlignRight; break; } } void ShowFpsEffect::prePaintScreen(ScreenPrePaintData& data, int time) { if (time == 0) { // TODO optimized away } t.start(); frames[ frames_pos ] = t.minute() * 60000 + t.second() * 1000 + t.msec(); if (++frames_pos == MAX_FPS) frames_pos = 0; effects->prePaintScreen(data, time); data.paint += fps_rect; paint_size[ paints_pos ] = 0; } void ShowFpsEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) { effects->paintWindow(w, mask, region, data); // Take intersection of region and actual window's rect, minus the fps area // (since we keep repainting it) and count the pixels. QRegion r2 = region & QRect(w->x(), w->y(), w->width(), w->height()); r2 -= fps_rect; int winsize = 0; foreach (const QRect & r, r2.rects()) winsize += r.width() * r.height(); paint_size[ paints_pos ] += winsize; } void ShowFpsEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) { effects->paintScreen(mask, region, data); int fps = 0; for (int i = 0; i < MAX_FPS; ++i) if (abs(t.minute() * 60000 + t.second() * 1000 + t.msec() - frames[ i ]) < 1000) ++fps; // count all frames in the last second if (fps > MAX_TIME) fps = MAX_TIME; // keep it the same height if (effects->isOpenGLCompositing()) { paintGL(fps); glFinish(); // make sure all rendering is done } #ifdef KWIN_HAVE_XRENDER_COMPOSITING if (effects->compositingType() == XRenderCompositing) { paintXrender(fps); XSync(display(), False); // make sure all rendering is done } #endif m_noBenchmark->render(infiniteRegion(), 1.0, alpha); } void ShowFpsEffect::paintGL(int fps) { int x = this->x; int y = this->y; glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // TODO painting first the background white and then the contents // means that the contents also blend with the background, I guess ShaderBinder binder(ShaderManager::ColorShader); GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); QColor color(255, 255, 255); color.setAlphaF(alpha); vbo->setColor(color); QVector verts; verts.reserve(12); verts << x + 2 * NUM_PAINTS + FPS_WIDTH << y; verts << x << y; verts << x << y + MAX_TIME; verts << x << y + MAX_TIME; verts << x + 2 * NUM_PAINTS + FPS_WIDTH << y + MAX_TIME; verts << x + 2 * NUM_PAINTS + FPS_WIDTH << y; vbo->setData(6, 2, verts.constData(), NULL); vbo->render(GL_TRIANGLES); y += MAX_TIME; // paint up from the bottom color.setRed(0); color.setGreen(0); vbo->setColor(color); verts.clear(); verts << x + FPS_WIDTH << y - fps; verts << x << y - fps; verts << x << y; verts << x << y; verts << x + FPS_WIDTH << y; verts << x + FPS_WIDTH << y - fps; vbo->setData(6, 2, verts.constData(), NULL); vbo->render(GL_TRIANGLES); color.setBlue(0); vbo->setColor(color); QVector vertices; for (int i = 10; i < MAX_TIME; i += 10) { vertices << x << y - i; vertices << x + FPS_WIDTH << y - i; } vbo->setData(vertices.size() / 2, 2, vertices.constData(), NULL); vbo->render(GL_LINES); x += FPS_WIDTH; // Paint FPS graph paintFPSGraph(x, y); x += NUM_PAINTS; // Paint amount of rendered pixels graph paintDrawSizeGraph(x, y); // Paint FPS numerical value if (fpsTextRect.isValid()) { - delete fpsText; - fpsText = new GLTexture(fpsTextImage(fps)); + fpsText.reset(new GLTexture(fpsTextImage(fps))); fpsText->bind(); ShaderBinder binder(ShaderManager::SimpleShader); if (effects->compositingType() == OpenGL2Compositing) { binder.shader()->setUniform("offset", QVector2D(0, 0)); } fpsText->render(QRegion(fpsTextRect), fpsTextRect); fpsText->unbind(); effects->addRepaint(fpsTextRect); } // Paint paint sizes glDisable(GL_BLEND); } #ifdef KWIN_HAVE_XRENDER_COMPOSITING /* Differences between OpenGL and XRender: - differently specified rectangles (X: width/height, O: x2,y2) - XRender uses pre-multiplied alpha */ void ShowFpsEffect::paintXrender(int fps) { xcb_pixmap_t pixmap = xcb_generate_id(connection()); xcb_create_pixmap(connection(), 32, pixmap, rootWindow(), FPS_WIDTH, MAX_TIME); XRenderPicture p(pixmap, 32); xcb_free_pixmap(connection(), pixmap); xcb_render_color_t col; col.alpha = int(alpha * 0xffff); col.red = int(alpha * 0xffff); // white col.green = int(alpha * 0xffff); col.blue = int(alpha * 0xffff); xcb_rectangle_t rect = {0, 0, FPS_WIDTH, MAX_TIME}; xcb_render_fill_rectangles(connection(), XCB_RENDER_PICT_OP_SRC, p, col, 1, &rect); col.red = 0; // blue col.green = 0; col.blue = int(alpha * 0xffff); rect.y = MAX_TIME - fps; rect.width = FPS_WIDTH; rect.height = fps; xcb_render_fill_rectangles(connection(), XCB_RENDER_PICT_OP_SRC, p, col, 1, &rect); col.red = 0; // black col.green = 0; col.blue = 0; QVector rects; for (int i = 10; i < MAX_TIME; i += 10) { xcb_rectangle_t rect = {0, int16_t(MAX_TIME - i), uint16_t(FPS_WIDTH), 1}; rects << rect; } xcb_render_fill_rectangles(connection(), XCB_RENDER_PICT_OP_SRC, p, col, rects.count(), rects.constData()); xcb_render_composite(connection(), alpha != 1.0 ? XCB_RENDER_PICT_OP_OVER : XCB_RENDER_PICT_OP_SRC, p, XCB_RENDER_PICTURE_NONE, effects->xrenderBufferPicture(), 0, 0, 0, 0, x, y, FPS_WIDTH, MAX_TIME); // Paint FPS graph paintFPSGraph(x + FPS_WIDTH, y); // Paint amount of rendered pixels graph paintDrawSizeGraph(x + FPS_WIDTH + MAX_TIME, y); // Paint FPS numerical value if (fpsTextRect.isValid()) { QImage textImg(fpsTextImage(fps)); XRenderPicture textPic(textImg); xcb_render_composite(connection(), XCB_RENDER_PICT_OP_OVER, textPic, XCB_RENDER_PICTURE_NONE, effects->xrenderBufferPicture(), 0, 0, 0, 0, fpsTextRect.x(), fpsTextRect.y(), textImg.width(), textImg.height()); effects->addRepaint(fpsTextRect); } } #endif void ShowFpsEffect::paintFPSGraph(int x, int y) { // Paint FPS graph QList lines; lines << 10 << 20 << 50; QList values; for (int i = 0; i < NUM_PAINTS; ++i) { values.append(paints[(i + paints_pos) % NUM_PAINTS ]); } paintGraph(x, y, values, lines, true); } void ShowFpsEffect::paintDrawSizeGraph(int x, int y) { int max_drawsize = 0; for (int i = 0; i < NUM_PAINTS; i++) max_drawsize = qMax(max_drawsize, paint_size[ i ]); // Log of min/max values shown on graph const float max_pixels_log = 7.2f; const float min_pixels_log = 2.0f; const int minh = 5; // Minimum height of the bar when value > 0 float drawscale = (MAX_TIME - minh) / (max_pixels_log - min_pixels_log); QList drawlines; for (int logh = (int)min_pixels_log; logh <= max_pixels_log; logh++) drawlines.append((int)((logh - min_pixels_log) * drawscale) + minh); QList drawvalues; for (int i = 0; i < NUM_PAINTS; ++i) { int value = paint_size[(i + paints_pos) % NUM_PAINTS ]; int h = 0; if (value > 0) { h = (int)((log10((double)value) - min_pixels_log) * drawscale); h = qMin(qMax(0, h) + minh, MAX_TIME); } drawvalues.append(h); } paintGraph(x, y, drawvalues, drawlines, false); } void ShowFpsEffect::paintGraph(int x, int y, QList values, QList lines, bool colorize) { if (effects->isOpenGLCompositing()) { QColor color(0, 0, 0); color.setAlphaF(alpha); GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); vbo->setColor(color); QVector verts; // First draw the lines foreach (int h, lines) { verts << x << y - h; verts << x + values.count() << y - h; } vbo->setData(verts.size() / 2, 2, verts.constData(), NULL); vbo->render(GL_LINES); // Then the graph values int lastValue = 0; verts.clear(); for (int i = 0; i < values.count(); i++) { int value = values[ i ]; if (colorize && value != lastValue) { if (!verts.isEmpty()) { vbo->setData(verts.size() / 2, 2, verts.constData(), NULL); vbo->render(GL_LINES); } verts.clear(); if (value <= 10) { color = QColor(0, 255, 0); } else if (value <= 20) { color = QColor(255, 255, 0); } else if (value <= 50) { color = QColor(255, 0, 0); } else { color = QColor(0, 0, 0); } vbo->setColor(color); } verts << x + values.count() - i << y; verts << x + values.count() - i << y - value; lastValue = value; } if (!verts.isEmpty()) { vbo->setData(verts.size() / 2, 2, verts.constData(), NULL); vbo->render(GL_LINES); } } #ifdef KWIN_HAVE_XRENDER_COMPOSITING if (effects->compositingType() == XRenderCompositing) { xcb_pixmap_t pixmap = xcb_generate_id(connection()); xcb_create_pixmap(connection(), 32, pixmap, rootWindow(), values.count(), MAX_TIME); XRenderPicture p(pixmap, 32); xcb_free_pixmap(connection(), pixmap); xcb_render_color_t col; col.alpha = int(alpha * 0xffff); // Draw background col.red = col.green = col.blue = int(alpha * 0xffff); // white xcb_rectangle_t rect = {0, 0, uint16_t(values.count()), uint16_t(MAX_TIME)}; xcb_render_fill_rectangles(connection(), XCB_RENDER_PICT_OP_SRC, p, col, 1, &rect); // Then the values col.red = col.green = col.blue = int(alpha * 0x8000); // grey for (int i = 0; i < values.count(); i++) { int value = values[ i ]; if (colorize) { if (value <= 10) { // green col.red = 0; col.green = int(alpha * 0xffff); col.blue = 0; } else if (value <= 20) { // yellow col.red = int(alpha * 0xffff); col.green = int(alpha * 0xffff); col.blue = 0; } else if (value <= 50) { // red col.red = int(alpha * 0xffff); col.green = 0; col.blue = 0; } else { // black col.red = 0; col.green = 0; col.blue = 0; } } xcb_rectangle_t rect = {int16_t(values.count() - i), int16_t(MAX_TIME - value), 1, uint16_t(value)}; xcb_render_fill_rectangles(connection(), XCB_RENDER_PICT_OP_SRC, p, col, 1, &rect); } // Then the lines col.red = col.green = col.blue = 0; // black QVector rects; foreach (int h, lines) { xcb_rectangle_t rect = {0, int16_t(MAX_TIME - h), uint16_t(values.count()), 1}; rects << rect; } xcb_render_fill_rectangles(connection(), XCB_RENDER_PICT_OP_SRC, p, col, rects.count(), rects.constData()); // Finally render the pixmap onto screen xcb_render_composite(connection(), alpha != 1.0 ? XCB_RENDER_PICT_OP_OVER : XCB_RENDER_PICT_OP_SRC, p, XCB_RENDER_PICTURE_NONE, effects->xrenderBufferPicture(), 0, 0, 0, 0, x, y, values.count(), MAX_TIME); } #endif } void ShowFpsEffect::postPaintScreen() { effects->postPaintScreen(); paints[ paints_pos ] = t.elapsed(); if (++paints_pos == NUM_PAINTS) paints_pos = 0; effects->addRepaint(fps_rect); } QImage ShowFpsEffect::fpsTextImage(int fps) { QImage im(100, 100, QImage::Format_ARGB32); im.fill(Qt::transparent); QPainter painter(&im); painter.setFont(textFont); painter.setPen(textColor); painter.drawText(QRect(0, 0, 100, 100), textAlign, QString::number(fps)); painter.end(); return im; } } // namespace diff --git a/effects/showfps/showfps.h b/effects/showfps/showfps.h index 3c30c39be..27900b8f7 100644 --- a/effects/showfps/showfps.h +++ b/effects/showfps/showfps.h @@ -1,107 +1,107 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak 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_SHOWFPS_H #define KWIN_SHOWFPS_H #include #include namespace KWin { class GLTexture; class ShowFpsEffect : public Effect { Q_OBJECT Q_PROPERTY(qreal alpha READ configuredAlpha) Q_PROPERTY(int x READ configuredX) Q_PROPERTY(int y READ configuredY) Q_PROPERTY(QRect fpsTextRect READ configuredFpsTextRect) Q_PROPERTY(int textAlign READ configuredTextAlign) Q_PROPERTY(QFont textFont READ configuredTextFont) Q_PROPERTY(QColor textColor READ configuredTextColor) public: ShowFpsEffect(); virtual void reconfigure(ReconfigureFlags); virtual void prePaintScreen(ScreenPrePaintData& data, int time); virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); virtual void postPaintScreen(); enum { INSIDE_GRAPH, NOWHERE, TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT }; // fps text position // for properties qreal configuredAlpha() const { return alpha; } int configuredX() const { return x; } int configuredY() const { return y; } QRect configuredFpsTextRect() const { return fpsTextRect; } int configuredTextAlign() const { return textAlign; } QFont configuredTextFont() const { return textFont; } QColor configuredTextColor() const { return textColor; } private: void paintGL(int fps); #ifdef KWIN_HAVE_XRENDER_COMPOSITING void paintXrender(int fps); #endif void paintFPSGraph(int x, int y); void paintDrawSizeGraph(int x, int y); void paintGraph(int x, int y, QList values, QList lines, bool colorize); QImage fpsTextImage(int fps); QTime t; enum { NUM_PAINTS = 100 }; // remember time needed to paint this many paints int paints[ NUM_PAINTS ]; // time needed to paint int paint_size[ NUM_PAINTS ]; // number of pixels painted int paints_pos; // position in the queue enum { MAX_FPS = 200 }; int frames[ MAX_FPS ]; // (sec*1000+msec) of the time the frame was done int frames_pos; // position in the queue double alpha; int x; int y; QRect fps_rect; - GLTexture *fpsText; + QScopedPointer fpsText; int textPosition; QFont textFont; QColor textColor; QRect fpsTextRect; int textAlign; QScopedPointer m_noBenchmark; }; } // namespace #endif diff --git a/kcmkwin/kwindecoration/configdialog.cpp b/kcmkwin/kwindecoration/configdialog.cpp index a2e816f50..4820eb0fa 100644 --- a/kcmkwin/kwindecoration/configdialog.cpp +++ b/kcmkwin/kwindecoration/configdialog.cpp @@ -1,172 +1,175 @@ /******************************************************************** 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 "configdialog.h" #include #include #include #include #include #include namespace KWin { static const char* const border_names[ KDecorationDefines::BordersCount ] = { I18N_NOOP2("@item:inlistbox Border size:", "Tiny"), I18N_NOOP2("@item:inlistbox Border size:", "Normal"), I18N_NOOP2("@item:inlistbox Border size:", "Large"), I18N_NOOP2("@item:inlistbox Border size:", "Very Large"), I18N_NOOP2("@item:inlistbox Border size:", "Huge"), I18N_NOOP2("@item:inlistbox Border size:", "Very Huge"), I18N_NOOP2("@item:inlistbox Border size:", "Oversized"), I18N_NOOP2("@item:inlistbox Border size:", "No Side Border"), I18N_NOOP2("@item:inlistbox Border size:", "No Border"), }; KWinAuroraeConfigForm::KWinAuroraeConfigForm(QWidget* parent) : QWidget(parent) { setupUi(this); + connect(borderSizesCombo, SIGNAL(currentIndexChanged(int)), SIGNAL(changed())); + connect(buttonSizesCombo, SIGNAL(currentIndexChanged(int)), SIGNAL(changed())); + connect(closeWindowsDoubleClick, SIGNAL(clicked()), SIGNAL(changed())); } void KWinAuroraeConfigForm::enableNoSideBorderSupport(bool enable) { if (!enable) { return; } borderSizesCombo->addItem(i18nc("@item:inlistbox Border size:", border_names[KDecorationDefines::BorderNoSides])); borderSizesCombo->addItem(i18nc("@item:inlistbox Border size:", border_names[KDecorationDefines::BorderNone])); } KWinDecorationConfigForm::KWinDecorationConfigForm(QWidget* parent) : QWidget(parent) { setupUi(this); } KWinDecorationConfigDialog::KWinDecorationConfigDialog(QString deco, const QList& borderSizes, KDecorationDefines::BorderSize size, QWidget* parent, Qt::WFlags flags) : KDialog(parent, flags) , m_borderSizes(borderSizes) , m_kwinConfig(KSharedConfig::openConfig("kwinrc")) , m_pluginObject(0) , m_pluginConfigWidget(0) { m_ui = new KWinDecorationConfigForm(this); setWindowTitle(i18n("Decoration Options")); setButtons(KDialog::Ok | KDialog::Cancel | KDialog::Default | KDialog::Reset); enableButton(KDialog::Reset, false); QVBoxLayout* layout = new QVBoxLayout; layout->addWidget(m_ui); KLibrary library(styleToConfigLib(deco)); if (library.load()) { KLibrary::void_function_ptr alloc_ptr = library.resolveFunction("allocate_config"); if (alloc_ptr != NULL) { allocatePlugin = (QObject * (*)(KConfigGroup & conf, QWidget * parent))alloc_ptr; KConfigGroup config(m_kwinConfig, "Style"); m_pluginConfigWidget = new KVBox(this); m_pluginObject = (QObject*)(allocatePlugin(config, m_pluginConfigWidget)); // connect required signals and slots together... connect(this, SIGNAL(accepted()), this, SLOT(slotAccepted())); connect(m_pluginObject, SIGNAL(changed()), this, SLOT(slotSelectionChanged())); connect(this, SIGNAL(pluginSave(KConfigGroup&)), m_pluginObject, SLOT(save(KConfigGroup&))); connect(this, SIGNAL(defaultClicked()), m_pluginObject, SLOT(defaults())); connect(this, SIGNAL(defaultClicked()), SLOT(slotDefault())); } } if (m_pluginConfigWidget) { layout->addWidget(m_pluginConfigWidget); } if (borderSizes.count() >= 2) { foreach (const QVariant & borderSize, borderSizes) { KDecorationDefines::BorderSize currentSize = static_cast(borderSize.toInt()); m_ui->bordersCombo->addItem(i18nc("@item:inlistbox Border size:", border_names[currentSize]), borderSizeToIndex(currentSize, borderSizes)); } m_ui->bordersCombo->setCurrentIndex(borderSizeToIndex(size, borderSizes)); } else { m_ui->bordersCombo->hide(); m_ui->borderLabel->hide(); } QWidget* main = new QWidget(this); main->setLayout(layout); setMainWidget(main); } KWinDecorationConfigDialog::~KWinDecorationConfigDialog() { delete m_pluginObject; } KDecorationDefines::BorderSize KWinDecorationConfigDialog::borderSize() const { if (m_borderSizes.count() >= 2) return (KDecorationDefines::BorderSize)m_borderSizes.at(m_ui->bordersCombo->currentIndex()).toInt(); return KDecorationDefines::BorderNormal; } int KWinDecorationConfigDialog::borderSizeToIndex(KDecorationDefines::BorderSize size, const QList< QVariant >& sizes) { int pos = 0; for (QList< QVariant >::ConstIterator it = sizes.constBegin(); it != sizes.constEnd(); ++it, ++pos) if (size <= (*it).toInt()) break; return pos; } void KWinDecorationConfigDialog::slotAccepted() { KConfigGroup config(m_kwinConfig, "Style"); emit pluginSave(config); config.sync(); } void KWinDecorationConfigDialog::slotSelectionChanged() { enableButton(KDialog::Reset, true); } QString KWinDecorationConfigDialog::styleToConfigLib(const QString& styleLib) const { if (styleLib.startsWith(QLatin1String("kwin3_"))) return "kwin_" + styleLib.mid(6) + "_config"; else return styleLib + "_config"; } void KWinDecorationConfigDialog::slotDefault() { if (m_borderSizes.count() >= 2) m_ui->bordersCombo->setCurrentIndex(borderSizeToIndex(BorderNormal, m_borderSizes)); } } // namespace KWin #include "configdialog.moc" diff --git a/kcmkwin/kwindecoration/configdialog.h b/kcmkwin/kwindecoration/configdialog.h index fac8732ec..c2ace175b 100644 --- a/kcmkwin/kwindecoration/configdialog.h +++ b/kcmkwin/kwindecoration/configdialog.h @@ -1,83 +1,85 @@ /******************************************************************** 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 KWINDECORATIONCONFIGDIALOG_H #define KWINDECORATIONCONFIGDIALOG_H #include #include #include #include "ui_config.h" #include "ui_auroraeconfig.h" namespace KWin { class KWinAuroraeConfigForm : public QWidget, public Ui::KWinAuroraeConfigForm { Q_OBJECT public: explicit KWinAuroraeConfigForm(QWidget* parent); void enableNoSideBorderSupport(bool enable); +Q_SIGNALS: + void changed(); }; class KWinDecorationConfigForm : public QWidget, public Ui::KWinDecorationConfigForm { Q_OBJECT public: explicit KWinDecorationConfigForm(QWidget* parent); }; class KWinDecorationConfigDialog : public KDialog, public KDecorationDefines { Q_OBJECT public: KWinDecorationConfigDialog(QString decoLib, const QList& borderSizes, KDecorationDefines::BorderSize size, QWidget* parent = 0, Qt::WFlags flags = 0); ~KWinDecorationConfigDialog(); KDecorationDefines::BorderSize borderSize() const; Q_SIGNALS: void pluginSave(KConfigGroup& group); private Q_SLOTS: void slotSelectionChanged(); void slotAccepted(); void slotDefault(); private: int borderSizeToIndex(KDecorationDefines::BorderSize size, const QList& sizes); QString styleToConfigLib(const QString& styleLib) const; private: KWinDecorationConfigForm* m_ui; QList m_borderSizes; KSharedConfigPtr m_kwinConfig; QObject*(*allocatePlugin)(KConfigGroup& conf, QWidget* parent); QObject* m_pluginObject; QWidget* m_pluginConfigWidget; }; } // namespace KWin #endif // KWINDECORATIONCONFIGDIALOG_H diff --git a/kcmkwin/kwindecoration/kwindecoration.cpp b/kcmkwin/kwindecoration/kwindecoration.cpp index 4dc2367b3..4c289daf5 100644 --- a/kcmkwin/kwindecoration/kwindecoration.cpp +++ b/kcmkwin/kwindecoration/kwindecoration.cpp @@ -1,612 +1,610 @@ /* This is the new kwindecoration kcontrol module Copyright (c) 2001 Karol Szwed http://gallium.n3.net/ Copyright 2009, 2010 Martin Gräßlin Supports new kwin configuration plugins, and titlebar button position modification via dnd interface. Based on original "kwintheme" (Window Borders) Copyright (C) 2001 Rik Hemsley (rikkus) 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // own #include "kwindecoration.h" #include "buttonsconfigdialog.h" #include "configdialog.h" #include "decorationmodel.h" #include "auroraetheme.h" // Qt #include #include #include #include #include #include #include #include #include #include // KDE #include #include #include #include #include #include #include #include // KCModule plugin interface // ========================= K_PLUGIN_FACTORY(KWinDecoFactory, registerPlugin(); ) namespace KWin { KWinDecorationForm::KWinDecorationForm(QWidget* parent) : QWidget(parent) { setupUi(this); } KWinDecorationModule::KWinDecorationModule(QWidget* parent, const QVariantList &) : KCModule(parent) , kwinConfig(KSharedConfig::openConfig("kwinrc")) , m_showTooltips(false) , m_model(NULL) , m_proxyModel(NULL) , m_configLoaded(false) , m_decorationButtons(new DecorationButtons(this)) , m_lastPreviewWidth(-1) , m_previewUpdateTimer(NULL) , m_listView(new QQuickView()) { qmlRegisterType("org.kde.kwin.aurorae", 0, 1, "AuroraeTheme"); m_ui = new KWinDecorationForm(this); m_ui->configureDecorationButton->setIcon(QIcon::fromTheme("configure")); m_ui->configureButtonsButton->setIcon(QIcon::fromTheme("configure")); m_ui->ghnsButton->setIcon(QIcon::fromTheme("get-hot-new-stuff")); QWidget *container = QWidget::createWindowContainer(m_listView.data(), m_ui->decorationList->viewport()); QVBoxLayout *containerLayout = new QVBoxLayout(m_ui->decorationList->viewport()); containerLayout->addWidget(container); QVBoxLayout* layout = new QVBoxLayout(this); layout->addWidget(m_ui); KAboutData *about = new KAboutData(i18n("kcmkwindecoration"), QString(), i18n("Window Decoration Control Module"), QString(), QString(), KAboutData::License_GPL, i18n("(c) 2001 Karol Szwed")); about->addAuthor(i18n("Karol Szwed"), QString(), "gallium@kde.org"); setAboutData(about); } KWinDecorationModule::~KWinDecorationModule() { } void KWinDecorationModule::showEvent(QShowEvent *ev) { KCModule::showEvent(ev); init(); } void KWinDecorationModule::init() { if (m_model) { // init already called return; } const QString mainQmlPath = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kwin/kcm_kwindecoration/main.qml"); if (mainQmlPath.isNull()) { // TODO 4.11 i18n this KMessageBox::error(this, "

Installation error

" "The resource

kwin/kcm_kwindecoration/main.qml

could not be located in any application data path." "

Please contact your distribution

" "The application will now abort", "Installation Error"); abort(); } KConfigGroup style(kwinConfig, "Style"); // Set up the decoration lists and other UI settings m_model = new DecorationModel(kwinConfig, this); m_proxyModel = new QSortFilterProxyModel(this); m_proxyModel->setSourceModel(m_model); m_proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); m_listView->setResizeMode(QQuickView::SizeRootObjectToView); m_listView->rootContext()->setContextProperty("decorationModel", m_proxyModel); m_listView->rootContext()->setContextProperty("decorationBaseModel", m_model); m_listView->rootContext()->setContextProperty("options", m_decorationButtons); m_listView->rootContext()->setContextProperty("highlightColor", m_ui->decorationList->palette().color(QPalette::Highlight)); m_listView->rootContext()->setContextProperty("auroraeSource", QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kwin/aurorae/aurorae.qml")); m_listView->rootContext()->setContextProperty("decorationActiveCaptionColor", KDecoration::options()->color(ColorFont, true)); m_listView->rootContext()->setContextProperty("decorationInactiveCaptionColor", KDecoration::options()->color(ColorFont, false)); m_listView->rootContext()->setContextProperty("decorationActiveTitleBarColor", KDecoration::options()->color(ColorTitleBar, true)); m_listView->rootContext()->setContextProperty("decorationInactiveTitleBarColor", KDecoration::options()->color(ColorTitleBar, false)); m_listView->setSource(QUrl::fromLocalFile(mainQmlPath)); readConfig(style); connect(m_listView->rootObject(), SIGNAL(currentIndexChanged()), SLOT(slotSelectionChanged())); connect(m_listView->rootObject(), SIGNAL(widthChanged()), SLOT(updatePreviewWidth())); connect(m_ui->configureButtonsButton, SIGNAL(clicked(bool)), this, SLOT(slotConfigureButtons())); connect(m_ui->ghnsButton, SIGNAL(clicked(bool)), SLOT(slotGHNSClicked())); connect(m_ui->searchEdit, SIGNAL(textChanged(QString)), m_proxyModel, SLOT(setFilterFixedString(QString))); connect(m_ui->searchEdit, SIGNAL(textChanged(QString)), m_listView->rootObject(), SLOT(returnToBounds()), Qt::QueuedConnection); connect(m_ui->searchEdit, SIGNAL(textChanged(QString)), SLOT(updateScrollbarRange()), Qt::QueuedConnection); connect(m_ui->configureDecorationButton, SIGNAL(clicked(bool)), SLOT(slotConfigureDecoration())); m_ui->decorationList->disconnect(m_ui->decorationList->verticalScrollBar()); m_ui->decorationList->verticalScrollBar()->disconnect(m_ui->decorationList); connect(m_listView->rootObject(), SIGNAL(contentYChanged()), SLOT(updateScrollbarValue())); connect(m_listView->rootObject(), SIGNAL(contentHeightChanged()), SLOT(updateScrollbarRange())); connect(m_ui->decorationList->verticalScrollBar(), SIGNAL(rangeChanged(int,int)), SLOT(updateScrollbarRange())); connect(m_ui->decorationList->verticalScrollBar(), SIGNAL(valueChanged(int)), SLOT(updateViewPosition(int))); m_ui->decorationList->installEventFilter(this); m_ui->decorationList->viewport()->installEventFilter(this); QMetaObject::invokeMethod(this, "updatePreviews", Qt::QueuedConnection); updateScrollbarRange(); } int KWinDecorationModule::itemWidth() const { return m_listView->rootObject()->property("width").toInt(); } // This is the selection handler setting void KWinDecorationModule::slotSelectionChanged() { emit KCModule::changed(true); } // Reads the kwin config settings, and sets all UI controls to those settings // Updating the config plugin if required void KWinDecorationModule::readConfig(const KConfigGroup & conf) { m_showTooltips = conf.readEntry("ShowToolTips", true); // Find the corresponding decoration name to that of // the current plugin library name QString libraryName = conf.readEntry("PluginLib", "kwin3_oxygen"); if (libraryName.isEmpty()) { // Selected decoration doesn't exist, use the default libraryName = "kwin3_oxygen"; } const int bsize = conf.readEntry("BorderSize", (int)BorderNormal); BorderSize borderSize = BorderNormal; if (bsize >= BorderTiny && bsize < BordersCount) borderSize = static_cast< BorderSize >(bsize); if (libraryName == "kwin3_aurorae") { KConfig auroraeConfig("auroraerc"); KConfigGroup group(&auroraeConfig, "Engine"); const QString themeName = group.readEntry("ThemeName", "example-deco"); const QString type = group.readEntry("EngineType", "aurorae"); const QModelIndex index = m_proxyModel->mapFromSource(m_model->indexOfAuroraeName(themeName, type)); if (index.isValid()) { m_listView->rootObject()->setProperty("currentIndex", index.row()); } } else { const QModelIndex index = m_proxyModel->mapFromSource(m_model->indexOfLibrary(libraryName)); if (index.isValid()) { m_model->setBorderSize(index, borderSize); m_listView->rootObject()->setProperty("currentIndex", index.row()); } } // Buttons tab // ============ m_decorationButtons->setCustomPositions(conf.readEntry("CustomButtonPositions", false)); // Menu and onAllDesktops buttons are default on LHS m_decorationButtons->setLeftButtons(conf.readEntry("ButtonsOnLeft", KDecorationOptions::defaultTitleButtonsLeft())); // Help, Minimize, Maximize and Close are default on RHS m_decorationButtons->setRightButtons(conf.readEntry("ButtonsOnRight", KDecorationOptions::defaultTitleButtonsRight())); if (m_configLoaded) m_model->changeButtons(m_decorationButtons); else { m_configLoaded = true; m_model->setButtons(m_decorationButtons->customPositions(), m_decorationButtons->leftButtons(), m_decorationButtons->rightButtons()); } emit KCModule::changed(false); } // Writes the selected user configuration to the kwin config file void KWinDecorationModule::writeConfig(KConfigGroup & conf) { const QModelIndex index = m_proxyModel->mapToSource(m_proxyModel->index(m_listView->rootObject()->property("currentIndex").toInt(), 0)); const QString libName = m_model->data(index, DecorationModel::LibraryNameRole).toString(); // General settings conf.writeEntry("PluginLib", libName); conf.writeEntry("CustomButtonPositions", m_decorationButtons->customPositions()); conf.writeEntry("ShowToolTips", m_showTooltips); // Button settings conf.writeEntry("ButtonsOnLeft", m_decorationButtons->leftButtons()); conf.writeEntry("ButtonsOnRight", m_decorationButtons->rightButtons()); conf.writeEntry("BorderSize", static_cast(m_model->data(index, DecorationModel::BorderSizeRole).toInt())); if (m_model->data(index, DecorationModel::TypeRole).toInt() == DecorationModelData::AuroraeDecoration || m_model->data(index, DecorationModel::TypeRole).toInt() == DecorationModelData::QmlDecoration) { KConfig auroraeConfig("auroraerc"); KConfigGroup group(&auroraeConfig, "Engine"); group.writeEntry("ThemeName", m_model->data(index, DecorationModel::AuroraeNameRole).toString()); if (m_model->data(index, DecorationModel::TypeRole).toInt() == DecorationModelData::QmlDecoration) { group.writeEntry("EngineType", "qml"); } else { group.deleteEntry("EngineType"); } group.sync(); } // We saved, so tell kcmodule that there have been no new user changes made. emit KCModule::changed(false); } // Virutal functions required by KCModule void KWinDecorationModule::load() { const KConfigGroup config(kwinConfig, "Style"); // Reset by re-reading the config readConfig(config); } void KWinDecorationModule::save() { KConfigGroup config(kwinConfig, "Style"); writeConfig(config); config.sync(); // Send signal to all kwin instances QDBusMessage message = QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); QDBusConnection::sessionBus().send(message); } void KWinDecorationModule::defaults() { // Set the KDE defaults m_showTooltips = true; const QModelIndex index = m_proxyModel->mapFromSource(m_model->indexOfName(i18n("Oxygen"))); if (index.isValid()) m_listView->rootObject()->setProperty("currentIndex", index.row()); m_decorationButtons->resetToDefaults(); m_model->changeButtons(m_decorationButtons); emit changed(true); } QString KWinDecorationModule::quickHelp() const { return i18n("

Window Manager Decoration

" "

This module allows you to choose the window border decorations, " "as well as titlebar button positions and custom decoration options.

" "To choose a theme for your window decoration click on its name and apply your choice by clicking the \"Apply\" button below." " If you do not want to apply your choice you can click the \"Reset\" button to discard your changes." "

You can configure each theme. There are different options specific for each theme.

" "

On the \"Buttons\" tab check the \"Use custom titlebar button positions\" box " "and you can change the positions of the buttons to your liking.

"); } void KWinDecorationModule::slotConfigureButtons() { QPointer< KWinDecorationButtonsConfigDialog > configDialog = new KWinDecorationButtonsConfigDialog(m_decorationButtons, m_showTooltips, this); if (configDialog->exec() == KDialog::Accepted) { m_decorationButtons->setCustomPositions(configDialog->customPositions()); m_showTooltips = configDialog->showTooltips(); m_decorationButtons->setLeftButtons(configDialog->buttonsLeft()); m_decorationButtons->setRightButtons(configDialog->buttonsRight()); m_model->changeButtons(m_decorationButtons); emit changed(true); } delete configDialog; } void KWinDecorationModule::slotGHNSClicked() { QPointer downloadDialog = new KNS3::DownloadDialog("aurorae.knsrc", this); if (downloadDialog->exec() == KDialog::Accepted) { if (!downloadDialog->changedEntries().isEmpty()) { const QModelIndex index = m_proxyModel->mapToSource(m_proxyModel->index(m_listView->rootObject()->property("currentIndex").toInt(), 0)); const QString libraryName = m_model->data(index, DecorationModel::LibraryNameRole).toString(); bool aurorae = m_model->data(index, DecorationModel::TypeRole).toInt() == DecorationModelData::AuroraeDecoration; bool qml = m_model->data(index, DecorationModel::TypeRole).toInt() == DecorationModelData::QmlDecoration; const QString auroraeName = m_model->data(index, DecorationModel::AuroraeNameRole).toString(); m_model->reload(); if (aurorae) { const QModelIndex proxyIndex = m_proxyModel->mapFromSource(m_model->indexOfAuroraeName(auroraeName, "aurorae")); if (proxyIndex.isValid()) m_listView->rootObject()->setProperty("currentIndex", proxyIndex.row()); } else if (qml) { const QModelIndex proxyIndex = m_proxyModel->mapFromSource(m_model->indexOfAuroraeName(auroraeName, "qml")); if (proxyIndex.isValid()) m_listView->rootObject()->setProperty("currentIndex", proxyIndex.row()); } else { const QModelIndex proxyIndex = m_proxyModel->mapFromSource(m_model->indexOfLibrary(libraryName)); if (proxyIndex.isValid()) m_listView->rootObject()->setProperty("currentIndex", proxyIndex.row()); } m_lastPreviewWidth = 0; updatePreviews(); } } delete downloadDialog; } void KWinDecorationModule::slotConfigureDecoration() { const QModelIndex index = m_proxyModel->mapToSource(m_proxyModel->index(m_listView->rootObject()->property("currentIndex").toInt(), 0)); bool reload = false; if (index.data(DecorationModel::TypeRole).toInt() == DecorationModelData::AuroraeDecoration || index.data(DecorationModel::TypeRole).toInt() == DecorationModelData::QmlDecoration) { QPointer< KDialog > dlg = new KDialog(this); dlg->setCaption(i18n("Decoration Options")); dlg->setButtons(KDialog::Ok | KDialog::Cancel); KWinAuroraeConfigForm *form = new KWinAuroraeConfigForm(dlg); form->enableNoSideBorderSupport(index.data(DecorationModel::TypeRole).toInt() == DecorationModelData::QmlDecoration); dlg->setMainWidget(form); form->borderSizesCombo->setCurrentIndex(index.data(DecorationModel::BorderSizeRole).toInt()); form->buttonSizesCombo->setCurrentIndex(index.data(DecorationModel::ButtonSizeRole).toInt()); form->closeWindowsDoubleClick->setChecked(index.data(DecorationModel::CloseOnDblClickRole).toBool()); // in case of QmlDecoration look for a config.ui in the package structure KConfigDialogManager *configManager = NULL; if (index.data(DecorationModel::TypeRole).toInt() == DecorationModelData::QmlDecoration) { const QString packageName = index.data(DecorationModel::AuroraeNameRole).toString(); const QString uiPath = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kwin/decorations/" + packageName + "/contents/ui/config.ui"); const QString configPath = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kwin/decorations/" + packageName + "/contents/config/main.xml"); if (!uiPath.isEmpty() && !configPath.isEmpty()) { // load the KConfigSkeleton QFile configFile(configPath); KSharedConfigPtr auroraeConfig = KSharedConfig::openConfig("auroraerc"); KConfigGroup configGroup = auroraeConfig->group(packageName); KConfigLoader *skeleton = new KConfigLoader(configGroup, &configFile, dlg); // load the ui file QUiLoader *loader = new QUiLoader(dlg); QFile uiFile(uiPath); uiFile.open(QFile::ReadOnly); QWidget *customConfigForm = loader->load(&uiFile, form); uiFile.close(); form->layout()->addWidget(customConfigForm); // connect the ui file with the skeleton configManager = new KConfigDialogManager(customConfigForm, skeleton); configManager->updateWidgets(); } } if (dlg->exec() == KDialog::Accepted) { m_model->setData(index, form->borderSizesCombo->currentIndex(), DecorationModel::BorderSizeRole); m_model->setData(index, form->buttonSizesCombo->currentIndex(), DecorationModel::ButtonSizeRole); m_model->setData(index, form->closeWindowsDoubleClick->isChecked(), DecorationModel::CloseOnDblClickRole); if (configManager && configManager->hasChanged()) { // we have a config manager and the settings changed configManager->updateSettings(); m_model->notifyConfigChanged(index); } reload = true; } delete dlg; } else { QString name = index.data(DecorationModel::LibraryNameRole).toString(); QList< QVariant > borderSizes = index.data(DecorationModel::BorderSizesRole).toList(); const KDecorationDefines::BorderSize size = static_cast(index.data(DecorationModel::BorderSizeRole).toInt()); QPointer< KWinDecorationConfigDialog > configDialog = new KWinDecorationConfigDialog(name, borderSizes, size, this); if (configDialog->exec() == KDialog::Accepted) { m_model->setData(index, configDialog->borderSize(), DecorationModel::BorderSizeRole); reload = true; } delete configDialog; } if (reload) { - // Send signal to all kwin instances - QDBusMessage message = QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); - QDBusConnection::sessionBus().send(message); + save(); } } bool KWinDecorationModule::eventFilter(QObject *o, QEvent *e) { if (o == m_ui->decorationList) { if (e->type() == QEvent::Resize) updateScrollbarRange(); else if (e->type() == QEvent::KeyPress) { int d = 0; const int currentRow = m_listView->rootObject()->property("currentIndex").toInt(); const int key = static_cast(e)->key(); switch (key) { case Qt::Key_Home: d = -currentRow; break; case Qt::Key_End: d = m_proxyModel->rowCount() - (1 + currentRow); break; case Qt::Key_Up: d = -1; break; case Qt::Key_Down: d = 1; break; case Qt::Key_PageUp: case Qt::Key_PageDown: d = 150; if (QObject *decoItem = m_listView->rootObject()->findChild("decorationItem")) { QVariant v = decoItem->property("height"); if (v.isValid()) d = v.toInt(); } if (d > 0) d = qMax(m_ui->decorationList->height() / d, 1); if (key == Qt::Key_PageUp) d = -d; break; default: break; } if (d) { d = qMin(qMax(0, currentRow + d), m_proxyModel->rowCount()); m_listView->rootObject()->setProperty("currentIndex", d); return true; } } } else if (m_ui->decorationList->viewport()) { if (e->type() == QEvent::Wheel) { return static_cast(e)->orientation() == Qt::Horizontal; } } return KCModule::eventFilter(o, e); } void KWinDecorationModule::updatePreviews() { if (!m_model) { return; } const int newWidth = m_listView->rootObject()->property("width").toInt(); if (newWidth == m_lastPreviewWidth) return; m_lastPreviewWidth = newWidth; const int h = m_listView->rootObject()->property("contentHeight").toInt(); const int y = m_listView->rootObject()->property("contentY").toInt(); // start at first element in sight int row = 0; if (h > 0) row = qMin(qMax(0, y*m_model->rowCount()/h), m_model->rowCount()); m_model->regeneratePreviews(row); } void KWinDecorationModule::updatePreviewWidth() { if (!m_previewUpdateTimer) { m_previewUpdateTimer = new QTimer(this); m_previewUpdateTimer->setSingleShot(true); connect(m_previewUpdateTimer, SIGNAL(timeout()), this, SLOT(updatePreviews())); } m_model->stopPreviewGeneration(); m_previewUpdateTimer->start(100); } void KWinDecorationModule::updateScrollbarRange() { m_ui->decorationList->verticalScrollBar()->blockSignals(true); const bool atMinimum = m_listView->rootObject()->property("atYBeginning").toBool(); const int h = m_listView->rootObject()->property("contentHeight").toInt(); const int y = atMinimum ? m_listView->rootObject()->property("contentY").toInt() : 0; m_ui->decorationList->verticalScrollBar()->setRange(y, y + h - m_ui->decorationList->height()); m_ui->decorationList->verticalScrollBar()->setPageStep(m_ui->decorationList->verticalScrollBar()->maximum()/m_model->rowCount()); m_ui->decorationList->verticalScrollBar()->blockSignals(false); } void KWinDecorationModule::updateScrollbarValue() { const int v = m_listView->rootObject()->property("contentY").toInt(); m_ui->decorationList->verticalScrollBar()->blockSignals(true); // skippig this will kill kinetic scrolling but the scrollwidth is too low m_ui->decorationList->verticalScrollBar()->setValue(v); m_ui->decorationList->verticalScrollBar()->blockSignals(false); } void KWinDecorationModule::updateViewPosition(int v) { m_listView->rootObject()->setProperty("contentY", v); } DecorationButtons::DecorationButtons(QObject *parent) : QObject(parent) , m_customPositions(false) , m_leftButtons(KDecorationOptions::defaultTitleButtonsLeft()) , m_rightButtons(KDecorationOptions::defaultTitleButtonsRight()) { } DecorationButtons::~DecorationButtons() { } bool DecorationButtons::customPositions() const { return m_customPositions; } const QString &DecorationButtons::leftButtons() const { return m_leftButtons; } const QString &DecorationButtons::rightButtons() const { return m_rightButtons; } void DecorationButtons::setCustomPositions(bool set) { if (m_customPositions == set) { return; } m_customPositions = set; emit customPositionsChanged(); } void DecorationButtons::setLeftButtons(const QString &leftButtons) { if (m_leftButtons == leftButtons) { return; } m_leftButtons = leftButtons; emit leftButtonsChanged(); } void DecorationButtons::setRightButtons (const QString &rightButtons) { if (m_rightButtons == rightButtons) { return; } m_rightButtons = rightButtons; emit rightButtonsChanged(); } void DecorationButtons::resetToDefaults() { setCustomPositions(false); setLeftButtons(KDecorationOptions::defaultTitleButtonsLeft()); setRightButtons(KDecorationOptions::defaultTitleButtonsRight()); } } // namespace KWin #include "kwindecoration.moc" diff --git a/scene.cpp b/scene.cpp index a39e5a35d..b93304ece 100644 --- a/scene.cpp +++ b/scene.cpp @@ -1,850 +1,850 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak 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 . *********************************************************************/ /* The base class for compositing, implementing shared functionality between the OpenGL and XRender backends. Design: When compositing is turned on, XComposite extension is used to redirect drawing of windows to pixmaps and XDamage extension is used to get informed about damage (changes) to window contents. This code is mostly in composite.cpp . Compositor::performCompositing() starts one painting pass. Painting is done by painting the screen, which in turn paints every window. Painting can be affected using effects, which are chained. E.g. painting a screen means that actually paintScreen() of the first effect is called, which possibly does modifications and calls next effect's paintScreen() and so on, until Scene::finalPaintScreen() is called. There are 3 phases of every paint (not necessarily done together): The pre-paint phase, the paint phase and the post-paint phase. The pre-paint phase is used to find out about how the painting will be actually done (i.e. what the effects will do). For example when only a part of the screen needs to be updated and no effect will do any transformation it is possible to use an optimized paint function. How the painting will be done is controlled by the mask argument, see PAINT_WINDOW_* and PAINT_SCREEN_* flags in scene.h . For example an effect that decides to paint a normal windows as translucent will need to modify the mask in its prePaintWindow() to include the PAINT_WINDOW_TRANSLUCENT flag. The paintWindow() function will then get the mask with this flag turned on and will also paint using transparency. The paint pass does the actual painting, based on the information collected using the pre-paint pass. After running through the effects' paintScreen() either paintGenericScreen() or optimized paintSimpleScreen() are called. Those call paintWindow() on windows (not necessarily all), possibly using clipping to optimize performance and calling paintWindow() first with only PAINT_WINDOW_OPAQUE to paint the opaque parts and then later with PAINT_WINDOW_TRANSLUCENT to paint the transparent parts. Function paintWindow() again goes through effects' paintWindow() until finalPaintWindow() is called, which calls the window's performPaint() to do the actual painting. The post-paint can be used for cleanups and is also used for scheduling repaints during the next painting pass for animations. Effects wanting to repaint certain parts can manually damage them during post-paint and repaint of these parts will be done during the next paint pass. */ #include "scene.h" #include #include #include "client.h" #include "decorations.h" #include "deleted.h" #include "effects.h" #include "overlaywindow.h" #include "shadow.h" #include "thumbnailitem.h" #include "workspace.h" namespace KWin { //**************************************** // Scene //**************************************** Scene::Scene(Workspace* ws) : QObject(ws) , wspace(ws) { last_time.invalidate(); // Initialize the timer connect(Workspace::self(), SIGNAL(deletedRemoved(KWin::Deleted*)), SLOT(windowDeleted(KWin::Deleted*))); } Scene::~Scene() { } // returns mask and possibly modified region void Scene::paintScreen(int* mask, QRegion* region) { const QRegion displayRegion(0, 0, displayWidth(), displayHeight()); *mask = (*region == displayRegion) ? 0 : PAINT_SCREEN_REGION; updateTimeDiff(); // preparation step static_cast(effects)->startPaint(); ScreenPrePaintData pdata; pdata.mask = *mask; pdata.paint = *region; effects->prePaintScreen(pdata, time_diff); *mask = pdata.mask; *region = pdata.paint; if (*mask & (PAINT_SCREEN_TRANSFORMED | PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS)) { // Region painting is not possible with transformations, // because screen damage doesn't match transformed positions. *mask &= ~PAINT_SCREEN_REGION; *region = infiniteRegion(); } else if (*mask & PAINT_SCREEN_REGION) { // make sure not to go outside visible screen *region &= displayRegion; } else { // whole screen, not transformed, force region to be full *region = displayRegion; } painted_region = *region; if (*mask & PAINT_SCREEN_BACKGROUND_FIRST) { paintBackground(*region); } ScreenPaintData data; effects->paintScreen(*mask, *region, data); foreach (Window * w, stacking_order) { effects->postPaintWindow(effectWindow(w)); } effects->postPaintScreen(); *region |= painted_region; // make sure not to go outside of the screen area *region &= displayRegion; // make sure all clipping is restored Q_ASSERT(!PaintClipper::clip()); } // Compute time since the last painting pass. void Scene::updateTimeDiff() { if (!last_time.isValid()) { // Painting has been idle (optimized out) for some time, // which means time_diff would be huge and would break animations. // Simply set it to one (zero would mean no change at all and could // cause problems). time_diff = 1; last_time.start(); } else time_diff = last_time.restart(); if (time_diff < 0) // check time rollback time_diff = 1; } // Painting pass is optimized away. void Scene::idle() { // Don't break time since last paint for the next pass. last_time.invalidate(); } // the function that'll be eventually called by paintScreen() above void Scene::finalPaintScreen(int mask, QRegion region, ScreenPaintData& data) { if (mask & (PAINT_SCREEN_TRANSFORMED | PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS)) paintGenericScreen(mask, data); else paintSimpleScreen(mask, region); } // The generic painting code that can handle even transformations. // It simply paints bottom-to-top. void Scene::paintGenericScreen(int orig_mask, ScreenPaintData) { if (!(orig_mask & PAINT_SCREEN_BACKGROUND_FIRST)) { paintBackground(infiniteRegion()); } QList< Phase2Data > phase2; foreach (Window * w, stacking_order) { // bottom to top Toplevel* topw = w->window(); // Reset the repaint_region. // This has to be done here because many effects schedule a repaint for // the next frame within Effects::prePaintWindow. topw->resetRepaints(); WindowPrePaintData data; data.mask = orig_mask | (w->isOpaque() ? PAINT_WINDOW_OPAQUE : PAINT_WINDOW_TRANSLUCENT); w->resetPaintingEnabled(); data.paint = infiniteRegion(); // no clipping, so doesn't really matter data.clip = QRegion(); data.quads = w->buildQuads(); // preparation step effects->prePaintWindow(effectWindow(w), data, time_diff); #ifndef NDEBUG if (data.quads.isTransformed()) { qFatal("Pre-paint calls are not allowed to transform quads!"); } #endif if (!w->isPaintingEnabled()) { continue; } phase2.append(Phase2Data(w, infiniteRegion(), data.clip, data.mask, data.quads)); // transformations require window pixmap w->suspendUnredirect(data.mask & (PAINT_WINDOW_TRANSLUCENT | PAINT_SCREEN_TRANSFORMED | PAINT_WINDOW_TRANSFORMED)); } foreach (const Phase2Data & d, phase2) { paintWindow(d.window, d.mask, d.region, d.quads); } } // The optimized case without any transformations at all. // It can paint only the requested region and can use clipping // to reduce painting and improve performance. void Scene::paintSimpleScreen(int orig_mask, QRegion region) { assert((orig_mask & (PAINT_SCREEN_TRANSFORMED | PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS)) == 0); QList< QPair< Window*, Phase2Data > > phase2data; QRegion dirtyArea = region; bool opaqueFullscreen(false); for (int i = 0; // do prePaintWindow bottom to top i < stacking_order.count(); ++i) { Window* w = stacking_order[ i ]; Toplevel* topw = w->window(); WindowPrePaintData data; data.mask = orig_mask | (w->isOpaque() ? PAINT_WINDOW_OPAQUE : PAINT_WINDOW_TRANSLUCENT); w->resetPaintingEnabled(); data.paint = region; data.paint |= topw->repaints(); data.paint |= topw->decorationPendingRegion(); // Reset the repaint_region. // This has to be done here because many effects schedule a repaint for // the next frame within Effects::prePaintWindow. topw->resetRepaints(); // Clip out the decoration for opaque windows; the decoration is drawn in the second pass opaqueFullscreen = false; // TODO: do we care about unmanged windows here (maybe input windows?) if (w->isOpaque()) { Client *c = NULL; if (topw->isClient()) { c = static_cast(topw); opaqueFullscreen = c->isFullScreen(); } // the window is fully opaque if (c && c->decorationHasAlpha()) { // decoration uses alpha channel, so we may not exclude it in clipping data.clip = w->clientShape().translated(w->x(), w->y()); } else { // decoration is fully opaque if (c && c->isShade()) { data.clip = QRegion(); } else { data.clip = w->shape().translated(w->x(), w->y()); } } } else if (topw->hasAlpha() && topw->opacity() == 1.0) { // the window is partially opaque data.clip = (w->clientShape() & topw->opaqueRegion().translated(topw->clientPos())).translated(w->x(), w->y()); } else { data.clip = QRegion(); } data.quads = w->buildQuads(); // preparation step effects->prePaintWindow(effectWindow(w), data, time_diff); #ifndef NDEBUG if (data.quads.isTransformed()) { qFatal("Pre-paint calls are not allowed to transform quads!"); } #endif if (!w->isPaintingEnabled()) { w->suspendUnredirect(true); continue; } dirtyArea |= data.paint; // Schedule the window for painting phase2data.append(QPair< Window*, Phase2Data >(w,Phase2Data(w, data.paint, data.clip, data.mask, data.quads))); // no transformations, but translucency requires window pixmap w->suspendUnredirect(data.mask & PAINT_WINDOW_TRANSLUCENT); } const QRegion displayRegion(0, 0, displayWidth(), displayHeight()); bool fullRepaint(dirtyArea == displayRegion); // spare some expensive region operations if (!fullRepaint) { extendPaintRegion(dirtyArea, opaqueFullscreen); fullRepaint = (dirtyArea == displayRegion); } QRegion allclips, upperTranslucentDamage; // This is the occlusion culling pass for (int i = phase2data.count() - 1; i >= 0; --i) { QPair< Window*, Phase2Data > *entry = &phase2data[i]; Phase2Data *data = &entry->second; if (fullRepaint) data->region = displayRegion; else data->region |= upperTranslucentDamage; // subtract the parts which will possibly been drawn as part of // a higher opaque window data->region -= allclips; // Here we rely on WindowPrePaintData::setTranslucent() to remove // the clip if needed. if (!data->clip.isEmpty() && !(data->mask & PAINT_WINDOW_TRANSFORMED)) { // clip away the opaque regions for all windows below this one allclips |= data->clip; // extend the translucent damage for windows below this by remaining (translucent) regions if (!fullRepaint) upperTranslucentDamage |= data->region - data->clip; } else if (!fullRepaint) { upperTranslucentDamage |= data->region; } } QRegion paintedArea; // Fill any areas of the root window not covered by opaque windows if (!(orig_mask & PAINT_SCREEN_BACKGROUND_FIRST)) { paintedArea = dirtyArea - allclips; paintBackground(paintedArea); } // Now walk the list bottom to top and draw the windows. for (int i = 0; i < phase2data.count(); ++i) { Phase2Data *data = &phase2data[i].second; // add all regions which have been drawn so far paintedArea |= data->region; data->region = paintedArea; paintWindow(data->window, data->mask, data->region, data->quads); } if (fullRepaint) painted_region = displayRegion; else painted_region |= paintedArea; } static Scene::Window *s_recursionCheck = NULL; void Scene::paintWindow(Window* w, int mask, QRegion region, WindowQuadList quads) { // no painting outside visible screen (and no transformations) region &= QRect(0, 0, displayWidth(), displayHeight()); if (region.isEmpty()) // completely clipped return; if (s_recursionCheck == w) { return; } WindowPaintData data(w->window()->effectWindow()); data.quads = quads; effects->paintWindow(effectWindow(w), mask, region, data); // paint thumbnails on top of window paintWindowThumbnails(w, region, data.opacity(), data.brightness(), data.saturation()); // and desktop thumbnails paintDesktopThumbnails(w); } static void adjustClipRegion(AbstractThumbnailItem *item, QRegion &clippingRegion) { if (item->clip() && item->clipTo()) { // the x/y positions of the parent item are not correct. The margins are added, though the size seems fine // that's why we have to get the offset by inspecting the anchors properties QQuickItem *parentItem = item->clipTo(); QPointF offset; QVariant anchors = parentItem->property("anchors"); if (anchors.isValid()) { if (QObject *anchorsObject = anchors.value()) { offset.setX(anchorsObject->property("leftMargin").toReal()); offset.setY(anchorsObject->property("topMargin").toReal()); } } const QRectF rect = parentItem->mapRectToScene(QRectF(parentItem->position() - offset, QSizeF(parentItem->width(), parentItem->height()))); clippingRegion &= rect.adjusted(0,0,-1,-1).translated(item->window()->position()).toRect(); } } void Scene::paintWindowThumbnails(Scene::Window *w, QRegion region, qreal opacity, qreal brightness, qreal saturation) { EffectWindowImpl *wImpl = static_cast(effectWindow(w)); for (QHash >::const_iterator it = wImpl->thumbnails().constBegin(); it != wImpl->thumbnails().constEnd(); ++it) { if (it.value().isNull()) { continue; } WindowThumbnailItem *item = it.key(); if (!item->isVisible()) { continue; } EffectWindowImpl *thumb = it.value().data(); WindowPaintData thumbData(thumb); thumbData.setOpacity(opacity); thumbData.setBrightness(brightness * item->brightness()); thumbData.setSaturation(saturation * item->saturation()); const QRect visualThumbRect(thumb->expandedGeometry()); QSizeF size = QSizeF(visualThumbRect.size()); size.scale(QSizeF(item->width(), item->height()), Qt::KeepAspectRatio); if (size.width() > visualThumbRect.width() || size.height() > visualThumbRect.height()) { size = QSizeF(visualThumbRect.size()); } thumbData.setXScale(size.width() / static_cast(visualThumbRect.width())); thumbData.setYScale(size.height() / static_cast(visualThumbRect.height())); if (!item->window()) { continue; } const QPointF point = item->mapToScene(item->position()); qreal x = point.x() + w->x() + (item->width() - size.width())/2; qreal y = point.y() + w->y() + (item->height() - size.height()) / 2; x -= thumb->x(); y -= thumb->y(); // compensate shadow topleft padding x += (thumb->x()-visualThumbRect.x())*thumbData.xScale(); y += (thumb->y()-visualThumbRect.y())*thumbData.yScale(); thumbData.setXTranslation(x); thumbData.setYTranslation(y); int thumbMask = PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_LANCZOS; if (thumbData.opacity() == 1.0) { thumbMask |= PAINT_WINDOW_OPAQUE; } else { thumbMask |= PAINT_WINDOW_TRANSLUCENT; } QRegion clippingRegion = region; clippingRegion &= QRegion(wImpl->x(), wImpl->y(), wImpl->width(), wImpl->height()); adjustClipRegion(item, clippingRegion); effects->drawWindow(thumb, thumbMask, clippingRegion, thumbData); } } void Scene::paintDesktopThumbnails(Scene::Window *w) { EffectWindowImpl *wImpl = static_cast(effectWindow(w)); for (QList::const_iterator it = wImpl->desktopThumbnails().constBegin(); it != wImpl->desktopThumbnails().constEnd(); ++it) { DesktopThumbnailItem *item = *it; if (!item->isVisible()) { continue; } if (!item->window()) { continue; } s_recursionCheck = w; ScreenPaintData data; QSize size = QSize(displayWidth(), displayHeight()); size.scale(item->width(), item->height(), Qt::KeepAspectRatio); data *= QVector2D(size.width() / double(displayWidth()), size.height() / double(displayHeight())); const QPointF point = item->mapToScene(item->position()); const qreal x = point.x() + w->x() + (item->width() - size.width())/2; const qreal y = point.y() + w->y() + (item->height() - size.height()) / 2; const QRect region = QRect(x, y, item->width(), item->height()); QRegion clippingRegion = region; clippingRegion &= QRegion(wImpl->x(), wImpl->y(), wImpl->width(), wImpl->height()); adjustClipRegion(item, clippingRegion); data += QPointF(x, y); const int desktopMask = PAINT_SCREEN_TRANSFORMED | PAINT_WINDOW_TRANSFORMED | PAINT_SCREEN_BACKGROUND_FIRST; paintDesktop(item->desktop(), desktopMask, clippingRegion, data); s_recursionCheck = NULL; } } void Scene::paintDesktop(int desktop, int mask, const QRegion ®ion, ScreenPaintData &data) { static_cast(effects)->paintDesktop(desktop, mask, region, data); } // the function that'll be eventually called by paintWindow() above void Scene::finalPaintWindow(EffectWindowImpl* w, int mask, QRegion region, WindowPaintData& data) { effects->drawWindow(w, mask, region, data); } // will be eventually called from drawWindow() void Scene::finalDrawWindow(EffectWindowImpl* w, int mask, QRegion region, WindowPaintData& data) { w->sceneWindow()->performPaint(mask, region, data); } void Scene::extendPaintRegion(QRegion ®ion, bool opaqueFullscreen) { Q_UNUSED(region); Q_UNUSED(opaqueFullscreen); } bool Scene::blocksForRetrace() const { return false; } bool Scene::syncsToVBlank() const { return false; } void Scene::screenGeometryChanged(const QSize &size) { overlayWindow()->resize(size); } //**************************************** // Scene::Window //**************************************** Scene::Window::Window(Toplevel * c) : toplevel(c) , filter(ImageFilterFast) , m_shadow(NULL) , m_currentPixmap() , m_previousPixmap() , m_referencePixmapCounter(0) , disable_painting(0) , shape_valid(false) , cached_quad_list(NULL) { } Scene::Window::~Window() { delete cached_quad_list; delete m_shadow; } void Scene::Window::referencePreviousPixmap() { if (!m_previousPixmap.isNull() && m_previousPixmap->isDiscarded()) { m_referencePixmapCounter++; } } void Scene::Window::unreferencePreviousPixmap() { if (m_previousPixmap.isNull() || !m_previousPixmap->isDiscarded()) { return; } m_referencePixmapCounter--; if (m_referencePixmapCounter == 0) { m_previousPixmap.reset(); } } void Scene::Window::pixmapDiscarded() { if (!m_currentPixmap.isNull() && m_currentPixmap->isValid()) { m_previousPixmap.reset(m_currentPixmap.take()); m_previousPixmap->markAsDiscarded(); } } void Scene::Window::discardShape() { // it is created on-demand and cached, simply // reset the flag shape_valid = false; delete cached_quad_list; cached_quad_list = NULL; } // Find out the shape of the window using the XShape extension // or if shape is not set then simply it's the window geometry. const QRegion &Scene::Window::shape() const { if (!shape_valid) { Client* c = dynamic_cast< Client* >(toplevel); if (toplevel->shape() || (c != NULL && !c->mask().isEmpty())) { auto cookie = xcb_shape_get_rectangles_unchecked(connection(), toplevel->frameId(), XCB_SHAPE_SK_BOUNDING); ScopedCPointer reply(xcb_shape_get_rectangles_reply(connection(), cookie, nullptr)); if (!reply.isNull()) { shape_region = QRegion(); auto *rects = xcb_shape_get_rectangles_rectangles(reply.data()); for (int i = 0; i < xcb_shape_get_rectangles_rectangles_length(reply.data()); ++i) shape_region += QRegion(rects[ i ].x, rects[ i ].y, rects[ i ].width, rects[ i ].height); // make sure the shape is sane (X is async, maybe even XShape is broken) shape_region &= QRegion(0, 0, width(), height()); } else shape_region = QRegion(); } else shape_region = QRegion(0, 0, width(), height()); shape_valid = true; } return shape_region; } QRegion Scene::Window::clientShape() const { if (toplevel->isClient()) { Client *c = static_cast< Client * > (toplevel); if (c->isShade()) return QRegion(); } // TODO: cache const QRegion r = shape() & QRect(toplevel->clientPos(), toplevel->clientSize()); return r.isEmpty() ? QRegion() : r; } bool Scene::Window::isVisible() const { if (toplevel->isDeleted()) return false; if (!toplevel->isOnCurrentDesktop()) return false; if (!toplevel->isOnCurrentActivity()) return false; if (toplevel->isClient()) return (static_cast< Client *>(toplevel))->isShown(true); return true; // Unmanaged is always visible } bool Scene::Window::isOpaque() const { return toplevel->opacity() == 1.0 && !toplevel->hasAlpha(); } bool Scene::Window::isPaintingEnabled() const { return !disable_painting; } void Scene::Window::resetPaintingEnabled() { disable_painting = 0; if (toplevel->isDeleted()) disable_painting |= PAINT_DISABLED_BY_DELETE; if (static_cast(effects)->isDesktopRendering()) { if (!toplevel->isOnDesktop(static_cast(effects)->currentRenderedDesktop())) { disable_painting |= PAINT_DISABLED_BY_DESKTOP; } } else { if (!toplevel->isOnCurrentDesktop()) disable_painting |= PAINT_DISABLED_BY_DESKTOP; } if (!toplevel->isOnCurrentActivity()) disable_painting |= PAINT_DISABLED_BY_ACTIVITY; if (toplevel->isClient()) { Client *c = static_cast(toplevel); if (c->isMinimized()) disable_painting |= PAINT_DISABLED_BY_MINIMIZE; if (c->tabGroup() && c != c->tabGroup()->current()) disable_painting |= PAINT_DISABLED_BY_TAB_GROUP; else if (c->isHiddenInternal()) disable_painting |= PAINT_DISABLED; } } void Scene::Window::enablePainting(int reason) { disable_painting &= ~reason; } void Scene::Window::disablePainting(int reason) { disable_painting |= reason; } WindowQuadList Scene::Window::buildQuads(bool force) const { if (cached_quad_list != NULL && !force) return *cached_quad_list; WindowQuadList ret; if (toplevel->clientPos() == QPoint(0, 0) && toplevel->clientSize() == toplevel->decorationRect().size()) ret = makeQuads(WindowQuadContents, shape()); // has no decoration else { Client *client = dynamic_cast(toplevel); QRegion contents = clientShape(); QRegion center = toplevel->transparentRect(); QRegion decoration = (client && decorationPlugin()->hasAlpha() ? QRegion(client->decorationRect()) : shape()) - center; ret = makeQuads(WindowQuadContents, contents); QRect rects[4]; bool isShadedClient = false; if (client) { client->layoutDecorationRects(rects[0], rects[1], rects[2], rects[3], Client::WindowRelative); isShadedClient = client->isShade() || center.isEmpty(); } if (isShadedClient) { const QRect bounding = rects[0] | rects[1] | rects[2] | rects[3]; ret += makeDecorationQuads(rects, bounding); } else { ret += makeDecorationQuads(rects, decoration); } } if (m_shadow) { ret << m_shadow->shadowQuads(); } effects->buildQuads(toplevel->effectWindow(), ret); cached_quad_list = new WindowQuadList(ret); return ret; } WindowQuadList Scene::Window::makeDecorationQuads(const QRect *rects, const QRegion ®ion) const { WindowQuadList list; const QPoint offsets[4] = { QPoint(-rects[0].x(), -rects[0].y()), // Left QPoint(-rects[1].x(), -rects[1].y()), // Top QPoint(-rects[2].x() + rects[0].width(), -rects[2].y()), // Right QPoint(-rects[3].x(), -rects[3].y() + rects[1].height()) // Bottom }; const WindowQuadType types[4] = { WindowQuadDecorationLeftRight, // Left WindowQuadDecorationTopBottom, // Top WindowQuadDecorationLeftRight, // Right WindowQuadDecorationTopBottom // Bottom }; for (int i = 0; i < 4; i++) { foreach (const QRect &r, (region & rects[i]).rects()) { if (!r.isValid()) continue; const int x0 = r.x(); const int y0 = r.y(); const int x1 = r.x() + r.width(); const int y1 = r.y() + r.height(); const int u0 = x0 + offsets[i].x(); const int v0 = y0 + offsets[i].y(); const int u1 = x1 + offsets[i].x(); const int v1 = y1 + offsets[i].y(); WindowQuad quad(types[i]); quad[0] = WindowVertex(x0, y0, u0, v0); // Top-left quad[1] = WindowVertex(x1, y0, u1, v0); // Top-right quad[2] = WindowVertex(x1, y1, u1, v1); // Bottom-right quad[3] = WindowVertex(x0, y1, u0, v1); // Bottom-left list.append(quad); } } return list; } WindowQuadList Scene::Window::makeQuads(WindowQuadType type, const QRegion& reg) const { WindowQuadList ret; foreach (const QRect & r, reg.rects()) { WindowQuad quad(type); // TODO asi mam spatne pravy dolni roh - bud tady, nebo v jinych castech quad[ 0 ] = WindowVertex(r.x(), r.y(), r.x(), r.y()); quad[ 1 ] = WindowVertex(r.x() + r.width(), r.y(), r.x() + r.width(), r.y()); quad[ 2 ] = WindowVertex(r.x() + r.width(), r.y() + r.height(), r.x() + r.width(), r.y() + r.height()); quad[ 3 ] = WindowVertex(r.x(), r.y() + r.height(), r.x(), r.y() + r.height()); ret.append(quad); } return ret; } //**************************************** // WindowPixmap //**************************************** WindowPixmap::WindowPixmap(Scene::Window *window) : m_window(window) , m_pixmap(XCB_PIXMAP_NONE) , m_discarded(false) { } WindowPixmap::~WindowPixmap() { if (isValid()) { xcb_free_pixmap(connection(), m_pixmap); } } void WindowPixmap::create() { - if (isValid()) { + if (isValid() || toplevel()->isDeleted()) { return; } XServerGrabber grabber; xcb_pixmap_t pix = xcb_generate_id(connection()); xcb_void_cookie_t namePixmapCookie = xcb_composite_name_window_pixmap_checked(connection(), toplevel()->frameId(), pix); Xcb::WindowAttributes windowAttributes(toplevel()->frameId()); Xcb::WindowGeometry windowGeometry(toplevel()->frameId()); if (xcb_generic_error_t *error = xcb_request_check(connection(), namePixmapCookie)) { qDebug() << "Creating window pixmap failed: " << error->error_code; free(error); return; } // check that the received pixmap is valid and actually matches what we // know about the window (i.e. size) if (!windowAttributes || windowAttributes->map_state != XCB_MAP_STATE_VIEWABLE) { qDebug() << "Creating window pixmap failed: " << this; xcb_free_pixmap(connection(), pix); return; } if (!windowGeometry || windowGeometry->width != toplevel()->width() || windowGeometry->height != toplevel()->height()) { qDebug() << "Creating window pixmap failed: " << this; xcb_free_pixmap(connection(), pix); return; } m_pixmap = pix; m_pixmapSize = QSize(toplevel()->width(), toplevel()->height()); m_contentsRect = QRect(toplevel()->clientPos(), toplevel()->clientSize()); m_window->unreferencePreviousPixmap(); } //**************************************** // Scene::EffectFrame //**************************************** Scene::EffectFrame::EffectFrame(EffectFrameImpl* frame) : m_effectFrame(frame) { } Scene::EffectFrame::~EffectFrame() { } } // namespace