scene_qpainter.cpp 31.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/********************************************************************
 KWin - the KDE window manager
 This file is part of the KDE project.

Copyright (C) 2013 Martin Gräßlin <mgraesslin@kde.org>

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

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

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*********************************************************************/
#include "scene_qpainter.h"
// KWin
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
22
#include "x11client.h"
23
#include "composite.h"
24
#include "cursor.h"
25
26
#include "deleted.h"
#include "effects.h"
27
#include "main.h"
28
#include "screens.h"
29
#include "toplevel.h"
30
#include "platform.h"
31
#include "wayland_server.h"
32
33
34

#include <kwineffectquickview.h>

35
#include <KWayland/Server/buffer_interface.h>
36
#include <KWayland/Server/subcompositor_interface.h>
37
#include <KWayland/Server/surface_interface.h>
38
#include "decorations/decoratedclient.h"
39
40
41
// Qt
#include <QDebug>
#include <QPainter>
42
#include <KDecoration2/Decoration>
43

44
45
#include <cmath>

46
47
48
49
50
51
namespace KWin
{

//****************************************
// SceneQPainter
//****************************************
52
SceneQPainter *SceneQPainter::createScene(QObject *parent)
53
{
54
55
56
    QScopedPointer<QPainterBackend> backend(kwinApp()->platform()->createQPainterBackend());
    if (backend.isNull()) {
        return nullptr;
57
    }
58
    if (backend->isFailed()) {
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
59
        return nullptr;
60
61
    }
    return new SceneQPainter(backend.take(), parent);
62
63
}

64
65
SceneQPainter::SceneQPainter(QPainterBackend *backend, QObject *parent)
    : Scene(parent)
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
    , m_backend(backend)
    , m_painter(new QPainter())
{
}

SceneQPainter::~SceneQPainter()
{
}

CompositingType SceneQPainter::compositingType() const
{
    return QPainterCompositing;
}

bool SceneQPainter::initFailed() const
{
    return false;
}

void SceneQPainter::paintGenericScreen(int mask, ScreenPaintData data)
{
    m_painter->save();
    m_painter->translate(data.xTranslation(), data.yTranslation());
    m_painter->scale(data.xScale(), data.yScale());
    Scene::paintGenericScreen(mask, data);
    m_painter->restore();
}

qint64 SceneQPainter::paint(QRegion damage, ToplevelList toplevels)
{
    QElapsedTimer renderTimer;
    renderTimer.start();

    createStackingOrder(toplevels);

    int mask = 0;
    m_backend->prepareRenderingFrame();
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
    if (m_backend->perScreenRendering()) {
        const bool needsFullRepaint = m_backend->needsFullRepaint();
        if (needsFullRepaint) {
            mask |= Scene::PAINT_SCREEN_BACKGROUND_FIRST;
            damage = screens()->geometry();
        }
        QRegion overallUpdate;
        for (int i = 0; i < screens()->count(); ++i) {
            const QRect geometry = screens()->geometry(i);
            QImage *buffer = m_backend->bufferForScreen(i);
            if (!buffer || buffer->isNull()) {
                continue;
            }
            m_painter->begin(buffer);
            m_painter->save();
            m_painter->setWindow(geometry);

            QRegion updateRegion, validRegion;
            paintScreen(&mask, damage.intersected(geometry), QRegion(), &updateRegion, &validRegion);
            overallUpdate = overallUpdate.united(updateRegion);
123
            paintCursor();
124
125
126
127
128
129
130
131

            m_painter->restore();
            m_painter->end();
        }
        m_backend->showOverlay();
        m_backend->present(mask, overallUpdate);
    } else {
        m_painter->begin(m_backend->buffer());
132
133
        m_painter->setClipping(true);
        m_painter->setClipRegion(damage);
134
135
        if (m_backend->needsFullRepaint()) {
            mask |= Scene::PAINT_SCREEN_BACKGROUND_FIRST;
136
            damage = screens()->geometry();
137
138
139
        }
        QRegion updateRegion, validRegion;
        paintScreen(&mask, damage, QRegion(), &updateRegion, &validRegion);
140

141
        paintCursor();
142
143
144
145
146
        m_backend->showOverlay();

        m_painter->end();
        m_backend->present(mask, updateRegion);
    }
147
148
149
150

    // do cleanup
    clearStackingOrder();

151
152
    emit frameRendered();

153
154
155
156
157
158
    return renderTimer.nsecsElapsed();
}

void SceneQPainter::paintBackground(QRegion region)
{
    m_painter->setBrush(Qt::black);
159
160
161
    for (const QRect &rect : region) {
        m_painter->drawRect(rect);
    }
162
163
}

164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
void SceneQPainter::paintCursor()
{
    if (!kwinApp()->platform()->usesSoftwareCursor()) {
        return;
    }
    const QImage img = kwinApp()->platform()->softwareCursor();
    if (img.isNull()) {
        return;
    }
    const QPoint cursorPos = Cursor::pos();
    const QPoint hotspot = kwinApp()->platform()->softwareCursorHotspot();
    m_painter->drawImage(cursorPos - hotspot, img);
    kwinApp()->platform()->markCursorAsRendered();
}

179
180
181
182
183
184
185
186
187
188
void SceneQPainter::paintEffectQuickView(EffectQuickView *w)
{
    QPainter *painter = effects->scenePainter();
    const QImage buffer = w->bufferAsImage();
    if (buffer.isNull()) {
        return;
    }
    painter->drawImage(w->geometry(), buffer);
}

189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
Scene::Window *SceneQPainter::createWindow(Toplevel *toplevel)
{
    return new SceneQPainter::Window(this, toplevel);
}

Scene::EffectFrame *SceneQPainter::createEffectFrame(EffectFrameImpl *frame)
{
    return new QPainterEffectFrame(frame, this);
}

Shadow *SceneQPainter::createShadow(Toplevel *toplevel)
{
    return new SceneQPainterShadow(toplevel);
}

204
205
206
207
208
209
void SceneQPainter::screenGeometryChanged(const QSize &size)
{
    Scene::screenGeometryChanged(size);
    m_backend->screenGeometryChanged(size);
}

210
211
212
213
214
QImage *SceneQPainter::qpainterRenderBuffer() const
{
    return m_backend->buffer();
}

215
216
217
218
219
220
221
222
223
224
225
226
227
//****************************************
// SceneQPainter::Window
//****************************************
SceneQPainter::Window::Window(SceneQPainter *scene, Toplevel *c)
    : Scene::Window(c)
    , m_scene(scene)
{
}

SceneQPainter::Window::~Window()
{
}

228
229
230
231
232
233
static void paintSubSurface(QPainter *painter, const QPoint &pos, QPainterWindowPixmap *pixmap)
{
    QPoint p = pos;
    if (!pixmap->subSurface().isNull()) {
        p += pixmap->subSurface()->position();
    }
234
235

    painter->drawImage(QRect(pos, pixmap->size()), pixmap->image());
236
237
238
239
240
241
242
243
244
245
    const auto &children = pixmap->children();
    for (auto it = children.begin(); it != children.end(); ++it) {
        auto pixmap = static_cast<QPainterWindowPixmap*>(*it);
        if (pixmap->subSurface().isNull() || pixmap->subSurface()->surface().isNull() || !pixmap->subSurface()->surface()->isMapped()) {
            continue;
        }
        paintSubSurface(painter, p, pixmap);
    }
}

246
247
248
249
250
251
252
253
254
255
256
257
void SceneQPainter::Window::performPaint(int mask, QRegion region, WindowPaintData data)
{
    if (!(mask & (PAINT_WINDOW_TRANSFORMED | PAINT_SCREEN_TRANSFORMED)))
        region &= toplevel->visibleRect();

    if (region.isEmpty())
        return;
    QPainterWindowPixmap *pixmap = windowPixmap<QPainterWindowPixmap>();
    if (!pixmap || !pixmap->isValid()) {
        return;
    }
    if (!toplevel->damage().isEmpty()) {
258
        pixmap->updateBuffer();
259
260
261
        toplevel->resetDamage();
    }

262
    QPainter *scenePainter = m_scene->scenePainter();
263
    QPainter *painter = scenePainter;
264
    painter->save();
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
    painter->setClipRegion(region);
    painter->setClipping(true);

    painter->translate(x(), y());
    if (mask & PAINT_WINDOW_TRANSFORMED) {
        painter->translate(data.xTranslation(), data.yTranslation());
        painter->scale(data.xScale(), data.yScale());
    }

    const bool opaque = qFuzzyCompare(1.0, data.opacity());
    QImage tempImage;
    QPainter tempPainter;
    if (!opaque) {
        // need a temp render target which we later on blit to the screen
        tempImage = QImage(toplevel->visibleRect().size(), QImage::Format_ARGB32_Premultiplied);
        tempImage.fill(Qt::transparent);
        tempPainter.begin(&tempImage);
        tempPainter.save();
        tempPainter.translate(toplevel->geometry().topLeft() - toplevel->visibleRect().topLeft());
        painter = &tempPainter;
    }
    renderShadow(painter);
    renderWindowDecorations(painter);

    // render content
290
    const QRect target = QRect(toplevel->clientPos(), toplevel->clientSize());
291
292
293
294
295
296
    QSize srcSize = pixmap->image().size();
    if (pixmap->surface() && pixmap->surface()->scale() == 1 && srcSize != toplevel->clientSize()) {
        // special case for XWayland windows
        srcSize = toplevel->clientSize();
    }
    const QRect src = QRect(toplevel->clientPos() + toplevel->clientContentPos(), srcSize);
297
    painter->drawImage(target, pixmap->image(), src);
298

299
300
301
302
303
304
305
306
307
    // render subsurfaces
    const auto &children = pixmap->children();
    for (auto pixmap : children) {
        if (pixmap->subSurface().isNull() || pixmap->subSurface()->surface().isNull() || !pixmap->subSurface()->surface()->isMapped()) {
            continue;
        }
        paintSubSurface(painter, toplevel->clientPos(), static_cast<QPainterWindowPixmap*>(pixmap));
    }

308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
    if (!opaque) {
        tempPainter.restore();
        tempPainter.setCompositionMode(QPainter::CompositionMode_DestinationIn);
        QColor translucent(Qt::transparent);
        translucent.setAlphaF(data.opacity());
        tempPainter.fillRect(QRect(QPoint(0, 0), toplevel->visibleRect().size()), translucent);
        tempPainter.end();
        painter = scenePainter;
        painter->drawImage(toplevel->visibleRect().topLeft() - toplevel->geometry().topLeft(), tempImage);
    }

    painter->restore();
}

void SceneQPainter::Window::renderShadow(QPainter* painter)
{
    if (!toplevel->shadow()) {
        return;
    }
    SceneQPainterShadow *shadow = static_cast<SceneQPainterShadow *>(toplevel->shadow());
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342

    const QImage &shadowTexture = shadow->shadowTexture();
    const WindowQuadList &shadowQuads = shadow->shadowQuads();

    for (const auto &q : shadowQuads) {
        auto topLeft = q[0];
        auto bottomRight = q[2];
        QRectF target(topLeft.x(), topLeft.y(),
                      bottomRight.x() - topLeft.x(),
                      bottomRight.y() - topLeft.y());
        QRectF source(topLeft.textureX(), topLeft.textureY(),
                      bottomRight.textureX() - topLeft.textureX(),
                      bottomRight.textureY() - topLeft.textureY());
        painter->drawImage(target, shadowTexture, source);
    }
343
344
345
346
347
}

void SceneQPainter::Window::renderWindowDecorations(QPainter *painter)
{
    // TODO: custom decoration opacity
348
    AbstractClient *client = dynamic_cast<AbstractClient*>(toplevel);
349
350
351
352
353
354
    Deleted *deleted = dynamic_cast<Deleted*>(toplevel);
    if (!client && !deleted) {
        return;
    }

    bool noBorder = true;
355
    const SceneQPainterDecorationRenderer *renderer = nullptr;
356
357
    QRect dtr, dlr, drr, dbr;
    if (client && !client->noBorder()) {
358
359
        if (client->isDecorated()) {
            if (SceneQPainterDecorationRenderer *r = static_cast<SceneQPainterDecorationRenderer *>(client->decoratedClient()->renderer())) {
360
                r->render();
361
362
363
                renderer = r;
            }
        }
364
        client->layoutDecorationRects(dlr, dtr, drr, dbr);
365
366
367
368
        noBorder = false;
    } else if (deleted && !deleted->noBorder()) {
        noBorder = false;
        deleted->layoutDecorationRects(dlr, dtr, drr, dbr);
369
        renderer = static_cast<const SceneQPainterDecorationRenderer *>(deleted->decorationRenderer());
370
    }
371
    if (noBorder || !renderer) {
372
373
374
        return;
    }

375
376
377
378
    painter->drawImage(dtr, renderer->image(SceneQPainterDecorationRenderer::DecorationPart::Top));
    painter->drawImage(dlr, renderer->image(SceneQPainterDecorationRenderer::DecorationPart::Left));
    painter->drawImage(drr, renderer->image(SceneQPainterDecorationRenderer::DecorationPart::Right));
    painter->drawImage(dbr, renderer->image(SceneQPainterDecorationRenderer::DecorationPart::Bottom));
379
380
381
382
383
384
385
}

WindowPixmap *SceneQPainter::Window::createWindowPixmap()
{
    return new QPainterWindowPixmap(this);
}

386
387
388
389
390
Decoration::Renderer *SceneQPainter::createDecorationRenderer(Decoration::DecoratedClientImpl *impl)
{
    return new SceneQPainterDecorationRenderer(impl);
}

391
392
393
394
395
396
397
398
//****************************************
// QPainterWindowPixmap
//****************************************
QPainterWindowPixmap::QPainterWindowPixmap(Scene::Window *window)
    : WindowPixmap(window)
{
}

399
400
401
402
403
QPainterWindowPixmap::QPainterWindowPixmap(const QPointer<KWayland::Server::SubSurfaceInterface> &subSurface, WindowPixmap *parent)
    : WindowPixmap(subSurface, parent)
{
}

404
405
406
407
408
409
QPainterWindowPixmap::~QPainterWindowPixmap()
{
}

void QPainterWindowPixmap::create()
{
410
411
412
    if (isValid()) {
        return;
    }
413
414
415
416
    KWin::WindowPixmap::create();
    if (!isValid()) {
        return;
    }
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
417
418
419
420
421
    if (!surface()) {
        // That's an internal client.
        m_image = internalImage();
        return;
    }
422
423
    // performing deep copy, this could probably be improved
    m_image = buffer()->data().copy();
424
425
426
    if (auto s = surface()) {
        s->resetTrackedDamage();
    }
427
428
}

429
WindowPixmap *QPainterWindowPixmap::createChild(const QPointer<KWayland::Server::SubSurfaceInterface> &subSurface)
430
{
431
432
433
434
435
436
437
438
    return new QPainterWindowPixmap(subSurface, this);
}

void QPainterWindowPixmap::updateBuffer()
{
    const auto oldBuffer = buffer();
    WindowPixmap::updateBuffer();
    const auto &b = buffer();
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
439
440
441
442
443
    if (!surface()) {
        // That's an internal client.
        m_image = internalImage();
        return;
    }
444
445
446
447
448
449
450
451
452
    if (b.isNull()) {
        m_image = QImage();
        return;
    }
    if (b == oldBuffer) {
        return;
    }
    // perform deep copy
    m_image = b->data().copy();
453
454
    if (auto s = surface()) {
        s->resetTrackedDamage();
455
456
457
    }
}

458
459
460
461
462
463
464
465
bool QPainterWindowPixmap::isValid() const
{
    if (!m_image.isNull()) {
        return true;
    }
    return WindowPixmap::isValid();
}

466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
QPainterEffectFrame::QPainterEffectFrame(EffectFrameImpl *frame, SceneQPainter *scene)
    : Scene::EffectFrame(frame)
    , m_scene(scene)
{
}

QPainterEffectFrame::~QPainterEffectFrame()
{
}

void QPainterEffectFrame::render(QRegion region, double opacity, double frameOpacity)
{
    Q_UNUSED(region)
    Q_UNUSED(opacity)
    // TODO: adjust opacity
    if (m_effectFrame->geometry().isEmpty()) {
        return; // Nothing to display
    }
484
    QPainter *painter = m_scene->scenePainter();
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555


    // Render the actual frame
    if (m_effectFrame->style() == EffectFrameUnstyled) {
        painter->save();
        painter->setPen(Qt::NoPen);
        QColor color(Qt::black);
        color.setAlphaF(frameOpacity);
        painter->setBrush(color);
        painter->setRenderHint(QPainter::Antialiasing);
        painter->drawRoundedRect(m_effectFrame->geometry().adjusted(-5, -5, 5, 5), 5.0, 5.0);
        painter->restore();
    } else if (m_effectFrame->style() == EffectFrameStyled) {
        qreal left, top, right, bottom;
        m_effectFrame->frame().getMargins(left, top, right, bottom);   // m_geometry is the inner geometry
        QRect geom = m_effectFrame->geometry().adjusted(-left, -top, right, bottom);
        painter->drawPixmap(geom, m_effectFrame->frame().framePixmap());
    }
    if (!m_effectFrame->selection().isNull()) {
        painter->drawPixmap(m_effectFrame->selection(), m_effectFrame->selectionFrame().framePixmap());
    }

    // Render icon
    if (!m_effectFrame->icon().isNull() && !m_effectFrame->iconSize().isEmpty()) {
        const QPoint topLeft(m_effectFrame->geometry().x(),
                             m_effectFrame->geometry().center().y() - m_effectFrame->iconSize().height() / 2);

        const QRect geom = QRect(topLeft, m_effectFrame->iconSize());
        painter->drawPixmap(geom, m_effectFrame->icon().pixmap(m_effectFrame->iconSize()));
    }

    // Render text
    if (!m_effectFrame->text().isEmpty()) {
        // Determine position on texture to paint text
        QRect rect(QPoint(0, 0), m_effectFrame->geometry().size());
        if (!m_effectFrame->icon().isNull() && !m_effectFrame->iconSize().isEmpty()) {
            rect.setLeft(m_effectFrame->iconSize().width());
        }

        // If static size elide text as required
        QString text = m_effectFrame->text();
        if (m_effectFrame->isStatic()) {
            QFontMetrics metrics(m_effectFrame->text());
            text = metrics.elidedText(text, Qt::ElideRight, rect.width());
        }

        painter->save();
        painter->setFont(m_effectFrame->font());
        if (m_effectFrame->style() == EffectFrameStyled) {
            painter->setPen(m_effectFrame->styledTextColor());
        } else {
            // TODO: What about no frame? Custom color setting required
            painter->setPen(Qt::white);
        }
        painter->drawText(rect.translated(m_effectFrame->geometry().topLeft()), m_effectFrame->alignment(), text);
        painter->restore();
    }
}

//****************************************
// QPainterShadow
//****************************************
SceneQPainterShadow::SceneQPainterShadow(Toplevel* toplevel)
    : Shadow(toplevel)
{
}

SceneQPainterShadow::~SceneQPainterShadow()
{
}

556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
void SceneQPainterShadow::buildQuads()
{
    // Do not draw shadows if window width or window height is less than
    // 5 px. 5 is an arbitrary choice.
    if (topLevel()->width() < 5 || topLevel()->height() < 5) {
        m_shadowQuads.clear();
        setShadowRegion(QRegion());
        return;
    }

    const QSizeF top(elementSize(ShadowElementTop));
    const QSizeF topRight(elementSize(ShadowElementTopRight));
    const QSizeF right(elementSize(ShadowElementRight));
    const QSizeF bottomRight(elementSize(ShadowElementBottomRight));
    const QSizeF bottom(elementSize(ShadowElementBottom));
    const QSizeF bottomLeft(elementSize(ShadowElementBottomLeft));
    const QSizeF left(elementSize(ShadowElementLeft));
    const QSizeF topLeft(elementSize(ShadowElementTopLeft));

    const QRectF outerRect(QPointF(-leftOffset(), -topOffset()),
                           QPointF(topLevel()->width() + rightOffset(),
                                   topLevel()->height() + bottomOffset()));

    const int width = std::max({topLeft.width(), left.width(), bottomLeft.width()})
                    + std::max(top.width(), bottom.width())
                    + std::max({topRight.width(), right.width(), bottomRight.width()});
    const int height = std::max({topLeft.height(), top.height(), topRight.height()})
                     + std::max(left.height(), right.height())
                     + std::max({bottomLeft.height(), bottom.height(), bottomRight.height()});

    QRectF topLeftRect(outerRect.topLeft(), topLeft);
    QRectF topRightRect(outerRect.topRight() - QPointF(topRight.width(), 0), topRight);
    QRectF bottomRightRect(
        outerRect.bottomRight() - QPointF(bottomRight.width(), bottomRight.height()),
        bottomRight);
    QRectF bottomLeftRect(outerRect.bottomLeft() - QPointF(0, bottomLeft.height()), bottomLeft);

    // Re-distribute the corner tiles so no one of them is overlapping with others.
    // By doing this, we assume that shadow's corner tiles are symmetric
    // and it is OK to not draw top/right/bottom/left tile between corners.
    // For example, let's say top-left and top-right tiles are overlapping.
    // In that case, the right side of the top-left tile will be shifted to left,
    // the left side of the top-right tile will shifted to right, and the top
    // tile won't be rendered.
    bool drawTop = true;
    if (topLeftRect.right() >= topRightRect.left()) {
        const float halfOverlap = qAbs(topLeftRect.right() - topRightRect.left()) / 2;
        topLeftRect.setRight(topLeftRect.right() - std::floor(halfOverlap));
        topRightRect.setLeft(topRightRect.left() + std::ceil(halfOverlap));
        drawTop = false;
    }

    bool drawRight = true;
    if (topRightRect.bottom() >= bottomRightRect.top()) {
        const float halfOverlap = qAbs(topRightRect.bottom() - bottomRightRect.top()) / 2;
        topRightRect.setBottom(topRightRect.bottom() - std::floor(halfOverlap));
        bottomRightRect.setTop(bottomRightRect.top() + std::ceil(halfOverlap));
        drawRight = false;
    }

    bool drawBottom = true;
    if (bottomLeftRect.right() >= bottomRightRect.left()) {
        const float halfOverlap = qAbs(bottomLeftRect.right() - bottomRightRect.left()) / 2;
        bottomLeftRect.setRight(bottomLeftRect.right() - std::floor(halfOverlap));
        bottomRightRect.setLeft(bottomRightRect.left() + std::ceil(halfOverlap));
        drawBottom = false;
    }

    bool drawLeft = true;
    if (topLeftRect.bottom() >= bottomLeftRect.top()) {
        const float halfOverlap = qAbs(topLeftRect.bottom() - bottomLeftRect.top()) / 2;
        topLeftRect.setBottom(topLeftRect.bottom() - std::floor(halfOverlap));
        bottomLeftRect.setTop(bottomLeftRect.top() + std::ceil(halfOverlap));
        drawLeft = false;
    }

    qreal tx1 = 0.0,
          tx2 = 0.0,
          ty1 = 0.0,
          ty2 = 0.0;

    m_shadowQuads.clear();

    tx1 = 0.0;
    ty1 = 0.0;
    tx2 = topLeftRect.width();
    ty2 = topLeftRect.height();
    WindowQuad topLeftQuad(WindowQuadShadow);
    topLeftQuad[0] = WindowVertex(topLeftRect.left(),  topLeftRect.top(),    tx1, ty1);
    topLeftQuad[1] = WindowVertex(topLeftRect.right(), topLeftRect.top(),    tx2, ty1);
    topLeftQuad[2] = WindowVertex(topLeftRect.right(), topLeftRect.bottom(), tx2, ty2);
    topLeftQuad[3] = WindowVertex(topLeftRect.left(),  topLeftRect.bottom(), tx1, ty2);
    m_shadowQuads.append(topLeftQuad);

    tx1 = width - topRightRect.width();
    ty1 = 0.0;
    tx2 = width;
    ty2 = topRightRect.height();
    WindowQuad topRightQuad(WindowQuadShadow);
    topRightQuad[0] = WindowVertex(topRightRect.left(),  topRightRect.top(),    tx1, ty1);
    topRightQuad[1] = WindowVertex(topRightRect.right(), topRightRect.top(),    tx2, ty1);
    topRightQuad[2] = WindowVertex(topRightRect.right(), topRightRect.bottom(), tx2, ty2);
    topRightQuad[3] = WindowVertex(topRightRect.left(),  topRightRect.bottom(), tx1, ty2);
    m_shadowQuads.append(topRightQuad);

    tx1 = width - bottomRightRect.width();
    tx2 = width;
    ty1 = height - bottomRightRect.height();
    ty2 = height;
    WindowQuad bottomRightQuad(WindowQuadShadow);
    bottomRightQuad[0] = WindowVertex(bottomRightRect.left(),  bottomRightRect.top(),    tx1, ty1);
    bottomRightQuad[1] = WindowVertex(bottomRightRect.right(), bottomRightRect.top(),    tx2, ty1);
    bottomRightQuad[2] = WindowVertex(bottomRightRect.right(), bottomRightRect.bottom(), tx2, ty2);
    bottomRightQuad[3] = WindowVertex(bottomRightRect.left(),  bottomRightRect.bottom(), tx1, ty2);
    m_shadowQuads.append(bottomRightQuad);

    tx1 = 0.0;
    tx2 = bottomLeftRect.width();
    ty1 = height - bottomLeftRect.height();
    ty2 = height;
    WindowQuad bottomLeftQuad(WindowQuadShadow);
    bottomLeftQuad[0] = WindowVertex(bottomLeftRect.left(),  bottomLeftRect.top(),    tx1, ty1);
    bottomLeftQuad[1] = WindowVertex(bottomLeftRect.right(), bottomLeftRect.top(),    tx2, ty1);
    bottomLeftQuad[2] = WindowVertex(bottomLeftRect.right(), bottomLeftRect.bottom(), tx2, ty2);
    bottomLeftQuad[3] = WindowVertex(bottomLeftRect.left(),  bottomLeftRect.bottom(), tx1, ty2);
    m_shadowQuads.append(bottomLeftQuad);

    if (drawTop) {
        QRectF topRect(
            topLeftRect.topRight(),
            topRightRect.bottomLeft());
        tx1 = topLeft.width();
        ty1 = 0.0;
        tx2 = width - topRight.width();
        ty2 = topRect.height();
        WindowQuad topQuad(WindowQuadShadow);
        topQuad[0] = WindowVertex(topRect.left(),  topRect.top(),    tx1, ty1);
        topQuad[1] = WindowVertex(topRect.right(), topRect.top(),    tx2, ty1);
        topQuad[2] = WindowVertex(topRect.right(), topRect.bottom(), tx2, ty2);
        topQuad[3] = WindowVertex(topRect.left(),  topRect.bottom(), tx1, ty2);
        m_shadowQuads.append(topQuad);
    }

    if (drawRight) {
        QRectF rightRect(
            topRightRect.bottomLeft(),
            bottomRightRect.topRight());
        tx1 = width - rightRect.width();
        ty1 = topRight.height();
        tx2 = width;
        ty2 = height - bottomRight.height();
        WindowQuad rightQuad(WindowQuadShadow);
        rightQuad[0] = WindowVertex(rightRect.left(),  rightRect.top(),    tx1, ty1);
        rightQuad[1] = WindowVertex(rightRect.right(), rightRect.top(),    tx2, ty1);
        rightQuad[2] = WindowVertex(rightRect.right(), rightRect.bottom(), tx2, ty2);
        rightQuad[3] = WindowVertex(rightRect.left(),  rightRect.bottom(), tx1, ty2);
        m_shadowQuads.append(rightQuad);
    }

    if (drawBottom) {
        QRectF bottomRect(
            bottomLeftRect.topRight(),
            bottomRightRect.bottomLeft());
        tx1 = bottomLeft.width();
        ty1 = height - bottomRect.height();
        tx2 = width - bottomRight.width();
        ty2 = height;
        WindowQuad bottomQuad(WindowQuadShadow);
        bottomQuad[0] = WindowVertex(bottomRect.left(),  bottomRect.top(),    tx1, ty1);
        bottomQuad[1] = WindowVertex(bottomRect.right(), bottomRect.top(),    tx2, ty1);
        bottomQuad[2] = WindowVertex(bottomRect.right(), bottomRect.bottom(), tx2, ty2);
        bottomQuad[3] = WindowVertex(bottomRect.left(),  bottomRect.bottom(), tx1, ty2);
        m_shadowQuads.append(bottomQuad);
    }

    if (drawLeft) {
        QRectF leftRect(
            topLeftRect.bottomLeft(),
            bottomLeftRect.topRight());
        tx1 = 0.0;
        ty1 = topLeft.height();
        tx2 = leftRect.width();
        ty2 = height - bottomRight.height();
        WindowQuad leftQuad(WindowQuadShadow);
        leftQuad[0] = WindowVertex(leftRect.left(),  leftRect.top(),    tx1, ty1);
        leftQuad[1] = WindowVertex(leftRect.right(), leftRect.top(),    tx2, ty1);
        leftQuad[2] = WindowVertex(leftRect.right(), leftRect.bottom(), tx2, ty2);
        leftQuad[3] = WindowVertex(leftRect.left(),  leftRect.bottom(), tx1, ty2);
        m_shadowQuads.append(leftQuad);
    }
}

748
749
bool SceneQPainterShadow::prepareBackend()
{
750
    if (hasDecorationShadow()) {
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
        m_texture = decorationShadowImage();
        return true;
    }

    const QPixmap &topLeft     = shadowPixmap(ShadowElementTopLeft);
    const QPixmap &top         = shadowPixmap(ShadowElementTop);
    const QPixmap &topRight    = shadowPixmap(ShadowElementTopRight);
    const QPixmap &bottomLeft  = shadowPixmap(ShadowElementBottomLeft);
    const QPixmap &bottom      = shadowPixmap(ShadowElementBottom);
    const QPixmap &bottomRight = shadowPixmap(ShadowElementBottomRight);
    const QPixmap &left        = shadowPixmap(ShadowElementLeft);
    const QPixmap &right       = shadowPixmap(ShadowElementRight);

    const int width = std::max({topLeft.width(), left.width(), bottomLeft.width()})
                    + std::max(top.width(), bottom.width())
                    + std::max({topRight.width(), right.width(), bottomRight.width()});
    const int height = std::max({topLeft.height(), top.height(), topRight.height()})
                     + std::max(left.height(), right.height())
                     + std::max({bottomLeft.height(), bottom.height(), bottomRight.height()});

    if (width == 0 || height == 0) {
772
773
        return false;
    }
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791

    QImage image(width, height, QImage::Format_ARGB32_Premultiplied);
    image.fill(Qt::transparent);

    QPainter painter;
    painter.begin(&image);
    painter.drawPixmap(0, 0, topLeft);
    painter.drawPixmap(topLeft.width(), 0, top);
    painter.drawPixmap(width - topRight.width(), 0, topRight);
    painter.drawPixmap(0, height - bottomLeft.height(), bottomLeft);
    painter.drawPixmap(bottomLeft.width(), height - bottom.height(), bottom);
    painter.drawPixmap(width - bottomRight.width(), height - bottomRight.height(), bottomRight);
    painter.drawPixmap(0, topLeft.height(), left);
    painter.drawPixmap(width - right.width(), topRight.height(), right);
    painter.end();

    m_texture = image;

792
793
794
    return true;
}

795
796
797
798
799
800
//****************************************
// QPainterDecorationRenderer
//****************************************
SceneQPainterDecorationRenderer::SceneQPainterDecorationRenderer(Decoration::DecoratedClientImpl *client)
    : Renderer(client)
{
801
    connect(this, &Renderer::renderScheduled, client->client(), static_cast<void (AbstractClient::*)(const QRect&)>(&AbstractClient::addRepaint));
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
}

SceneQPainterDecorationRenderer::~SceneQPainterDecorationRenderer() = default;

QImage SceneQPainterDecorationRenderer::image(SceneQPainterDecorationRenderer::DecorationPart part) const
{
    Q_ASSERT(part != DecorationPart::Count);
    return m_images[int(part)];
}

void SceneQPainterDecorationRenderer::render()
{
    const QRegion scheduled = getScheduled();
    if (scheduled.isEmpty()) {
        return;
    }
    if (areImageSizesDirty()) {
        resizeImages();
        resetImageSizesDirty();
    }

823
824
825
826
827
828
829
830
    auto imageSize = [this](DecorationPart part) {
        return m_images[int(part)].size() / m_images[int(part)].devicePixelRatio();
    };

    const QRect top(QPoint(0, 0), imageSize(DecorationPart::Top));
    const QRect left(QPoint(0, top.height()), imageSize(DecorationPart::Left));
    const QRect right(QPoint(top.width() - imageSize(DecorationPart::Right).width(), top.height()), imageSize(DecorationPart::Right));
    const QRect bottom(QPoint(0, left.y() + left.height()), imageSize(DecorationPart::Bottom));
831
832
833
834
835
836
837
838

    const QRect geometry = scheduled.boundingRect();
    auto renderPart = [this](const QRect &rect, const QRect &partRect, int index) {
        if (rect.isEmpty()) {
            return;
        }
        QPainter painter(&m_images[index]);
        painter.setRenderHint(QPainter::Antialiasing);
839
        painter.setWindow(QRect(partRect.topLeft(), partRect.size() * m_images[index].devicePixelRatio()));
840
841
842
843
        painter.setClipRect(rect);
        painter.save();
        // clear existing part
        painter.setCompositionMode(QPainter::CompositionMode_Source);
844
        painter.fillRect(rect, Qt::transparent);
845
        painter.restore();
846
        client()->decoration()->paint(&painter, rect);
847
848
849
850
851
852
853
854
855
856
857
    };

    renderPart(left.intersected(geometry), left, int(DecorationPart::Left));
    renderPart(top.intersected(geometry), top, int(DecorationPart::Top));
    renderPart(right.intersected(geometry), right, int(DecorationPart::Right));
    renderPart(bottom.intersected(geometry), bottom, int(DecorationPart::Bottom));
}

void SceneQPainterDecorationRenderer::resizeImages()
{
    QRect left, top, right, bottom;
858
    client()->client()->layoutDecorationRects(left, top, right, bottom);
859
860

    auto checkAndCreate = [this](int index, const QSize &size) {
861
        auto dpr = client()->client()->screenScale();
862
863
864
865
866
        if (m_images[index].size() != size * dpr ||
            m_images[index].devicePixelRatio() != dpr)
        {
            m_images[index] = QImage(size * dpr, QImage::Format_ARGB32_Premultiplied);
            m_images[index].setDevicePixelRatio(dpr);
867
868
869
870
871
872
873
874
875
            m_images[index].fill(Qt::transparent);
        }
    };
    checkAndCreate(int(DecorationPart::Left), left.size());
    checkAndCreate(int(DecorationPart::Right), right.size());
    checkAndCreate(int(DecorationPart::Top), top.size());
    checkAndCreate(int(DecorationPart::Bottom), bottom.size());
}

876
877
878
879
880
881
void SceneQPainterDecorationRenderer::reparent(Deleted *deleted)
{
    render();
    Renderer::reparent(deleted);
}

882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899

QPainterFactory::QPainterFactory(QObject *parent)
    : SceneFactory(parent)
{
}

QPainterFactory::~QPainterFactory() = default;

Scene *QPainterFactory::create(QObject *parent) const
{
    auto s = SceneQPainter::createScene(parent);
    if (s && s->initFailed()) {
        delete s;
        s = nullptr;
    }
    return s;
}

900
} // KWin