File: x-window-thumbnail.cpp

package info (click to toggle)
ukui-panel 4.0.0.6-1.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,148 kB
  • sloc: cpp: 28,423; xml: 476; sh: 51; makefile: 18
file content (995 lines) | stat: -rw-r--r-- 32,608 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
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
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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
/*
 *   Copyright 2013 by 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 Library General Public License as
 *   published by the Free Software Foundation; either version 2, 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 Library 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.
 */
#include "x-window-thumbnail.h"
// KF5
#include <kwindowsystem.h>
// Qt
#include <QGuiApplication>
#include <QIcon>
#include <QOpenGLContext>
#include <QQuickWindow>
#include <QRunnable>
#include <QSGSimpleRectNode>
// X11

#if HAVE_GLX
#include <GL/glx.h>
typedef void (*glXBindTexImageEXT_func)(Display *dpy, GLXDrawable drawable,
                                        int buffer, const int *attrib_list);
typedef void (*glXReleaseTexImageEXT_func)(Display *dpy, GLXDrawable drawable, int buffer);
#endif
#if HAVE_EGL
typedef EGLImageKHR(*eglCreateImageKHR_func)(EGLDisplay, EGLContext, EGLenum, EGLClientBuffer, const EGLint *);
typedef EGLBoolean(*eglDestroyImageKHR_func)(EGLDisplay, EGLImageKHR);
typedef GLvoid(*glEGLImageTargetTexture2DOES_func)(GLenum, GLeglImageOES);
#endif // HAVE_EGL
#include <X11/Xlib.h>

#include <cstdlib>

#if HAVE_XCB_COMPOSITE
#if HAVE_GLX
class DiscardGlxPixmapRunnable : public QRunnable {
public:
    DiscardGlxPixmapRunnable(
        uint,
        QFunctionPointer,
        xcb_pixmap_t
    );
    void run() override;
private:
    uint m_texture;
    QFunctionPointer m_releaseTexImage;
    xcb_pixmap_t m_glxPixmap;
};

DiscardGlxPixmapRunnable::DiscardGlxPixmapRunnable(uint texture, QFunctionPointer deleteFunction, xcb_pixmap_t pixmap)
    : QRunnable(),
    m_texture(texture),
    m_releaseTexImage(deleteFunction),
    m_glxPixmap(pixmap)
{}

void DiscardGlxPixmapRunnable::run()
{
    if (m_glxPixmap != XCB_PIXMAP_NONE) {
        Display *d = QX11Info::display();
        ((glXReleaseTexImageEXT_func)(m_releaseTexImage))(d, m_glxPixmap, GLX_FRONT_LEFT_EXT);
        glXDestroyPixmap(d, m_glxPixmap);
        glDeleteTextures(1, &m_texture);
    }
}
#endif //HAVE_GLX

#if HAVE_EGL
class DiscardEglPixmapRunnable : public QRunnable {
public:
    DiscardEglPixmapRunnable(
        uint,
        QFunctionPointer,
        EGLImageKHR
    );
    void run() override;
private:
    uint m_texture;
    QFunctionPointer m_eglDestroyImageKHR;
    EGLImageKHR m_image;
};

DiscardEglPixmapRunnable::DiscardEglPixmapRunnable(uint texture, QFunctionPointer deleteFunction, EGLImageKHR image)
    : QRunnable(),
    m_texture(texture),
    m_eglDestroyImageKHR(deleteFunction),
    m_image(image)
{}

void DiscardEglPixmapRunnable::run()
{
    if (m_image != EGL_NO_IMAGE_KHR) {
        ((eglDestroyImageKHR_func)(m_eglDestroyImageKHR))(eglGetCurrentDisplay(), m_image);
        glDeleteTextures(1, &m_texture);
    }
}
#endif//HAVE_EGL
#endif //HAVE_XCB_COMPOSITE

    WindowTextureNode::WindowTextureNode()
            : QSGSimpleTextureNode()
    {
    }

    WindowTextureNode::~WindowTextureNode()
    {
    }

    void WindowTextureNode::reset(QSGTexture *texture)
    {
        setTexture(texture);
        m_texture.reset(texture);
    }

    XWindowThumbnail::XWindowThumbnail(QQuickItem *parent)
            : QQuickItem(parent)
            , QAbstractNativeEventFilter()
            , m_xcb(false)
            , m_composite(false)
            , m_winId(0)
            , m_paintedSize(QSizeF())
            , m_thumbnailAvailable(false)
            , m_redirecting(false)
            , m_damaged(false)
            , m_depth(0)
#if HAVE_XCB_COMPOSITE
    , m_openGLFunctionsResolved(false)
    , m_damageEventBase(0)
    , m_damage(XCB_NONE)
    , m_pixmap(XCB_PIXMAP_NONE)
    , m_texture(0)
#if HAVE_GLX
    , m_glxPixmap(XCB_PIXMAP_NONE)
    , m_bindTexImage(nullptr)
    , m_releaseTexImage(nullptr)
#endif // HAVE_GLX
#if HAVE_EGL
    , m_eglFunctionsResolved(false)
    , m_image(EGL_NO_IMAGE_KHR)
    , m_eglCreateImageKHR(nullptr)
    , m_eglDestroyImageKHR(nullptr)
    , m_glEGLImageTargetTexture2DOES(nullptr)
#endif // HAVE_EGL
#endif
    {
        setFlag(ItemHasContents);

        if (QGuiApplication *gui = dynamic_cast<QGuiApplication *>(QCoreApplication::instance())) {
            m_xcb = (gui->platformName() == QLatin1String("xcb"));
            if (m_xcb) {
                gui->installNativeEventFilter(this);
#if HAVE_XCB_COMPOSITE
                xcb_connection_t *c = QX11Info::connection();
            xcb_prefetch_extension_data(c, &xcb_composite_id);
            const auto *compositeReply = xcb_get_extension_data(c, &xcb_composite_id);
            m_composite = (compositeReply && compositeReply->present);

            xcb_prefetch_extension_data(c, &xcb_damage_id);
            const auto *reply = xcb_get_extension_data(c, &xcb_damage_id);
            m_damageEventBase = reply->first_event;
            if (reply->present) {
                xcb_damage_query_version_unchecked(c, XCB_DAMAGE_MAJOR_VERSION, XCB_DAMAGE_MINOR_VERSION);
            }
#endif
            }
        }
    }

    XWindowThumbnail::~XWindowThumbnail()
    {
        if (m_xcb) {
            QCoreApplication::instance()->removeNativeEventFilter(this);
            stopRedirecting();
        }
    }

    void XWindowThumbnail::itemChange(ItemChange change, const ItemChangeData &data)
    {
        switch (change) {
            case ItemSceneChange:
                if (m_scene) {
                    disconnect(m_scene.data(), &QWindow::visibleChanged, this, &XWindowThumbnail::sceneVisibilityChanged);
                }
                m_scene = data.window;
                if (m_scene) {
                    connect(m_scene.data(), &QWindow::visibleChanged, this, &XWindowThumbnail::sceneVisibilityChanged);
                    // restart the redirection, it might not have been active yet
                    stopRedirecting();
                    if (startRedirecting()) {
                        update();
                    }
                }
                break;

            case ItemEnabledHasChanged:
                        Q_FALLTHROUGH();
            case ItemVisibleHasChanged:
                if (data.boolValue) {
                    if (startRedirecting()) {
                        update();
                    }
                } else {
                    stopRedirecting();
                    releaseResources();
                }
                break;

            default:
                break;
        }
    }

    void XWindowThumbnail::releaseResources()
    {
#if HAVE_XCB_COMPOSITE

        #if HAVE_GLX && HAVE_EGL
    //only one (or none) should be set, but never both
    Q_ASSERT(m_glxPixmap == XCB_PIXMAP_NONE || m_image == EGL_NO_IMAGE_KHR);
#endif
#if HAVE_GLX || HAVE_EGL
    QQuickWindow::RenderStage m_renderStage = QQuickWindow::NoStage;
#endif

    //data is deleted in the render thread (with relevant GLX calls)
    //note runnable may be called *after* this is deleted
    //but the pointer is held by the WindowThumbnail which is in the main thread
#if HAVE_GLX
    if (m_glxPixmap != XCB_PIXMAP_NONE) {
        window()->scheduleRenderJob(new DiscardGlxPixmapRunnable(m_texture,
                                                        m_releaseTexImage,
                                                        m_glxPixmap),
                                                        m_renderStage);

        m_glxPixmap = XCB_PIXMAP_NONE;
        m_texture = 0;
    }
#endif
#if HAVE_EGL
    if (m_image != EGL_NO_IMAGE_KHR) {
        window()->scheduleRenderJob(new DiscardEglPixmapRunnable(m_texture,
                                                        m_eglDestroyImageKHR,
                                                        m_image),
                                                        m_renderStage);

        m_image = EGL_NO_IMAGE_KHR;
        m_texture = 0;
    }
#endif
#endif
    }



    uint32_t XWindowThumbnail::winId() const
    {
        return m_winId;
    }

    void XWindowThumbnail::setWinId(uint32_t winId)
    {
        if (m_winId == winId) {
            return;
        }
        if (!KWindowSystem::self()->hasWId(winId)) {
            // invalid Id, don't updated
            return;
        }
        if (window() && winId == window()->winId()) {
            // don't redirect to yourself
            return;
        }
        stopRedirecting();
        m_winId = winId;

        if (isEnabled() && isVisible()) {
            startRedirecting();
        }

        emit winIdChanged();
    }

    qreal XWindowThumbnail::paintedWidth() const
    {
        return m_paintedSize.width();
    }

    qreal XWindowThumbnail::paintedHeight() const
    {
        return m_paintedSize.height();
    }

    bool XWindowThumbnail::thumbnailAvailable() const
    {
        return m_thumbnailAvailable;
    }

    QSGNode *XWindowThumbnail::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *updatePaintNodeData)
    {
        Q_UNUSED(updatePaintNodeData)
        auto *node = static_cast<WindowTextureNode *>(oldNode);
        if (!node) {
            node = new WindowTextureNode();
            node->setFiltering(QSGTexture::Linear);
        }
        if (!m_xcb || m_winId == 0 || (window() && window()->winId() == m_winId)) {
            iconToTexture(node);
        } else {
            windowToTexture(node);
        }
        node->setRect(boundingRect());
        const QSizeF size(node->texture()->textureSize().scaled(boundingRect().size().toSize(), Qt::KeepAspectRatio));
        if (size != m_paintedSize) {
            m_paintedSize = size;
            emit paintedSizeChanged();
        }
        const qreal x = boundingRect().x() + (boundingRect().width() - size.width()) / 2;
        const qreal y = boundingRect().y() + (boundingRect().height() - size.height()) / 2;
        node->setRect(QRectF(QPointF(x, y), size));
        return node;
    }

    bool XWindowThumbnail::nativeEventFilter(const QByteArray &eventType, void *message, long int *result)
    {
        Q_UNUSED(result)
        if (!m_xcb || !m_composite || eventType != QByteArrayLiteral("xcb_generic_event_t")) {
            // currently we are only interested in XCB events
            return false;
        }
#if HAVE_XCB_COMPOSITE
            xcb_generic_event_t *event = static_cast<xcb_generic_event_t *>(message);
    const uint8_t responseType = event->response_type & ~0x80;
    if (responseType == m_damageEventBase + XCB_DAMAGE_NOTIFY) {
        if (reinterpret_cast<xcb_damage_notify_event_t *>(event)->drawable == m_winId) {
            m_damaged = true;
            update();
        }
    } else if (responseType == XCB_CONFIGURE_NOTIFY) {
        if (reinterpret_cast<xcb_configure_notify_event_t *>(event)->window == m_winId) {
            releaseResources();
            m_damaged = true;
            update();
        }
    } else if (responseType == XCB_MAP_NOTIFY) {
        if (reinterpret_cast<xcb_configure_notify_event_t *>(event)->window == m_winId) {
            releaseResources();
            m_damaged = true;
            update();
        }
    }
#else
        Q_UNUSED(message)
#endif
        // do not filter out any events, there might be further WindowThumbnails for the same window
        return false;
    }

    void XWindowThumbnail::iconToTexture(WindowTextureNode *textureNode)
    {
        QIcon icon;
        if (KWindowSystem::self()->hasWId(m_winId)) {
            icon = KWindowSystem::self()->icon(m_winId, boundingRect().width(), boundingRect().height());
        } else {
            // fallback to plasma icon
            icon = QIcon::fromTheme(QStringLiteral("plasma"));
        }
        QImage image = icon.pixmap(boundingRect().size().toSize()).toImage();
        textureNode->reset(window()->createTextureFromImage(image, QQuickWindow::TextureCanUseAtlas));
    }

#if HAVE_XCB_COMPOSITE
    #if HAVE_GLX
bool XWindowThumbnail::windowToTextureGLX(WindowTextureNode *textureNode)
{
    if (glXGetCurrentContext()) {
        if (!m_openGLFunctionsResolved) {
            resolveGLXFunctions();
        }
        if (!m_bindTexImage || !m_releaseTexImage) {
            return false;
        }
        if (m_glxPixmap == XCB_PIXMAP_NONE) {
            xcb_connection_t *c = QX11Info::connection();
            auto attrCookie = xcb_get_window_attributes_unchecked(c, m_winId);
            auto geometryCookie = xcb_get_geometry_unchecked(c, m_pixmap);
            QScopedPointer<xcb_get_window_attributes_reply_t, QScopedPointerPodDeleter> attr(xcb_get_window_attributes_reply(c, attrCookie, nullptr));
            QScopedPointer<xcb_get_geometry_reply_t, QScopedPointerPodDeleter> geo(xcb_get_geometry_reply(c, geometryCookie, nullptr));

            if (attr.isNull()) {
                return false;
            }

            if (geo.isNull()) {
                return false;
            }

            m_depth = geo->depth;
            m_visualid = attr->visual;

            if (!loadGLXTexture()) {
                return false;
            }

            textureNode->reset(window()->createTextureFromId(m_texture, QSize(geo->width, geo->height), QQuickWindow::TextureCanUseAtlas));
        }
        textureNode->texture()->bind();
        bindGLXTexture();
        return true;
    }
    return false;
}
#endif // HAVE_GLX

#if HAVE_EGL
bool XWindowThumbnail::xcbWindowToTextureEGL(WindowTextureNode *textureNode)
{
    EGLContext context = eglGetCurrentContext();

    if (context != EGL_NO_CONTEXT) {
        if (!m_eglFunctionsResolved) {
            resolveEGLFunctions();
        }
        if (QByteArray((char *)glGetString(GL_RENDERER)).contains("llvmpipe")) {
            return false;
        }
        if (!m_eglCreateImageKHR || !m_eglDestroyImageKHR || !m_glEGLImageTargetTexture2DOES) {
            return false;
        }
        if (m_image == EGL_NO_IMAGE_KHR) {
            xcb_connection_t *c = QX11Info::connection();
            auto geometryCookie = xcb_get_geometry_unchecked(c, m_pixmap);

            const EGLint attribs[] = {
                EGL_IMAGE_PRESERVED_KHR, EGL_TRUE,
                EGL_NONE
            };
            m_image = ((eglCreateImageKHR_func)(m_eglCreateImageKHR))(eglGetCurrentDisplay(), EGL_NO_CONTEXT,
                      EGL_NATIVE_PIXMAP_KHR,
                      (EGLClientBuffer)m_pixmap, attribs);

            if (m_image == EGL_NO_IMAGE_KHR) {
                qDebug() << "failed to create egl image";
                return false;
            }

            glGenTextures(1, &m_texture);
            QScopedPointer<xcb_get_geometry_reply_t, QScopedPointerPodDeleter> geo(xcb_get_geometry_reply(c, geometryCookie, nullptr));
            QSize size;
            if (!geo.isNull()) {
                size.setWidth(geo->width);
                size.setHeight(geo->height);
            }
            textureNode->reset(window()->createTextureFromId(m_texture, size, QQuickWindow::TextureCanUseAtlas));
        }
        textureNode->texture()->bind();
        bindEGLTexture();
        return true;
    }
    return false;
}

void XWindowThumbnail::resolveEGLFunctions()
{
    EGLDisplay display = eglGetCurrentDisplay();
    if (display == EGL_NO_DISPLAY) {
        return;
    }
    auto *context = window()->openglContext();
    QList<QByteArray> extensions = QByteArray(eglQueryString(display, EGL_EXTENSIONS)).split(' ');
    if (extensions.contains(QByteArrayLiteral("EGL_KHR_image")) ||
            (extensions.contains(QByteArrayLiteral("EGL_KHR_image_base")) &&
             extensions.contains(QByteArrayLiteral("EGL_KHR_image_pixmap")))) {
        if (context->hasExtension(QByteArrayLiteral("GL_OES_EGL_image"))) {
            qDebug() << "Have EGL texture from pixmap";
            m_eglCreateImageKHR = context->getProcAddress(QByteArrayLiteral("eglCreateImageKHR"));
            m_eglDestroyImageKHR = context->getProcAddress(QByteArrayLiteral("eglDestroyImageKHR"));
            m_glEGLImageTargetTexture2DOES = context->getProcAddress(QByteArrayLiteral("glEGLImageTargetTexture2DOES"));
        }
    }
    m_eglFunctionsResolved = true;
}

void XWindowThumbnail::bindEGLTexture()
{
    ((glEGLImageTargetTexture2DOES_func)(m_glEGLImageTargetTexture2DOES))(GL_TEXTURE_2D, (GLeglImageOES)m_image);
    resetDamaged();
}
#endif // HAVE_EGL

QImage XWindowThumbnail::convertToQImage(XImage* ximage)
{
    QImage::Format format = QImage::Format_ARGB32_Premultiplied;
    if (ximage->depth == 24)
        format = QImage::Format_RGB32;
    else if (ximage->depth == 16)
        format = QImage::Format_RGB16;

    QImage image = QImage(reinterpret_cast<uchar*>(ximage->data),
                          ximage->width, ximage->height,
                          ximage->bytes_per_line, format).copy();

    // 大端还是小端?
    if ((QSysInfo::ByteOrder == QSysInfo::LittleEndian && ximage->byte_order == MSBFirst)
            || (QSysInfo::ByteOrder == QSysInfo::BigEndian && ximage->byte_order == LSBFirst)) {

        for (int i = 0; i < image.height(); i++) {
            if (ximage->depth == 16) {
                ushort* p = reinterpret_cast<ushort*>(image.scanLine(i));
                ushort* end = p + image.width();
                while (p < end) {
                    *p = ((*p << 8) & 0xff00) | ((*p >> 8) & 0x00ff);
                    p++;
                }
            } else {
                uint* p = reinterpret_cast<uint*>(image.scanLine(i));
                uint* end = p + image.width();
                while (p < end) {
                    *p = ((*p << 24) & 0xff000000) | ((*p << 8) & 0x00ff0000)
                         | ((*p >> 8) & 0x0000ff00) | ((*p >> 24) & 0x000000ff);
                    p++;
                }
            }
        }
    }

    // 修复alpha通道
    if (format == QImage::Format_RGB32) {
        QRgb* p = reinterpret_cast<QRgb*>(image.bits());
        for (int y = 0; y < ximage->height; ++y) {
            for (int x = 0; x < ximage->width; ++x)
                p[x] |= 0xff000000;
            p += ximage->bytes_per_line / 4;
        }
    }

    return image;
}
bool XWindowThumbnail::xlibWindowToTexture(WindowTextureNode *textureNode)
{
    XWindowAttributes attr;
    Display *display = QX11Info::display();

    XGetWindowAttributes(display, m_winId, &attr);
    XImage *image = XGetImage(display, m_winId, 0, 0, attr.width, attr.height, 0xffffffff, ZPixmap);

    if (image) {
        QImage thumbnail = convertToQImage(image);
        XDestroyImage(image);

        textureNode->reset(window()->createTextureFromImage(thumbnail, QQuickWindow::TextureCanUseAtlas));
        return true;
    }

    qDebug() << "[Warning]: No window thumbnails from X.";
    return false;
}

#endif // HAVE_XCB_COMPOSITE

void XWindowThumbnail::windowToTexture(WindowTextureNode *textureNode)
{
    if (!m_damaged && textureNode->texture()) {
        return;
    }
#if HAVE_XCB_COMPOSITE
    if (!textureNode->texture()) {
        // the texture got discarded by the scene graph, but our mapping is still valid
        // let's discard the pixmap to have a clean state again
        releaseResources();
    }
    if (m_pixmap == XCB_PIXMAP_NONE) {
        m_pixmap = pixmapForWindow();
    }
    if (m_pixmap == XCB_PIXMAP_NONE) {
        // create above failed
        iconToTexture(textureNode);
        setThumbnailAvailable(false);
        return;
    }
    bool fallbackToIcon = true;
#if HAVE_GLX
    fallbackToIcon = !windowToTextureGLX(textureNode);
#endif // HAVE_GLX
#if HAVE_EGL
    if (fallbackToIcon) {
        // if glx succeeded fallbackToIcon is false, thus we shouldn't try egl
        fallbackToIcon = !xcbWindowToTextureEGL(textureNode);
    }
#endif // HAVE_EGL
    if (fallbackToIcon) {
        // incase both GLX and EGL are unavailable or KWin compositor is not opengl.
        fallbackToIcon = !xlibWindowToTexture(textureNode);
    }
    if (fallbackToIcon) {
        // just for safety to not crash
        iconToTexture(textureNode);
    }
    setThumbnailAvailable(!fallbackToIcon);
    textureNode->markDirty(QSGNode::DirtyForceUpdate);
#else
    iconToTexture(textureNode);
#endif
}

#if HAVE_XCB_COMPOSITE
xcb_pixmap_t XWindowThumbnail::pixmapForWindow()
{
    if (!m_composite) {
        return XCB_PIXMAP_NONE;
    }

    xcb_connection_t *c = QX11Info::connection();
    xcb_pixmap_t pix = xcb_generate_id(c);
    auto cookie = xcb_composite_name_window_pixmap_checked(c, m_winId, pix);
    QScopedPointer<xcb_generic_error_t, QScopedPointerPodDeleter> error(xcb_request_check(c, cookie));
    if (error) {
        return XCB_PIXMAP_NONE;
    }
    return pix;
}

#if HAVE_GLX
void XWindowThumbnail::resolveGLXFunctions()
{
    auto *context = window()->openglContext();
    QList<QByteArray> extensions = QByteArray(glXQueryExtensionsString(QX11Info::display(), QX11Info::appScreen())).split(' ');
    if (extensions.contains(QByteArrayLiteral("GLX_EXT_texture_from_pixmap"))) {
        m_bindTexImage = context->getProcAddress(QByteArrayLiteral("glXBindTexImageEXT"));
        m_releaseTexImage = context->getProcAddress(QByteArrayLiteral("glXReleaseTexImageEXT"));
    } else
        qWarning() << "couldn't resolve GLX_EXT_texture_from_pixmap functions";
    m_openGLFunctionsResolved = true;
}

void XWindowThumbnail::bindGLXTexture()
{
    Display *d = QX11Info::display();
    ((glXReleaseTexImageEXT_func)(m_releaseTexImage))(d, m_glxPixmap, GLX_FRONT_LEFT_EXT);
    ((glXBindTexImageEXT_func)(m_bindTexImage))(d, m_glxPixmap, GLX_FRONT_LEFT_EXT, nullptr);
    resetDamaged();
}

struct FbConfigInfo
{
    GLXFBConfig fbConfig;
    int textureFormat;
};

struct GlxGlobalData
{
    GlxGlobalData() {
	xcb_connection_t * const conn = QX11Info::connection();

        // Fetch the render pict formats
        reply = xcb_render_query_pict_formats_reply(conn,
                        xcb_render_query_pict_formats_unchecked(conn), nullptr);

        // Init the visual ID -> format ID hash table
        for (auto screens = xcb_render_query_pict_formats_screens_iterator(reply); screens.rem; xcb_render_pictscreen_next(&screens)) {
            for (auto depths = xcb_render_pictscreen_depths_iterator(screens.data); depths.rem; xcb_render_pictdepth_next(&depths)) {
                const xcb_render_pictvisual_t *visuals = xcb_render_pictdepth_visuals(depths.data);
                const int len = xcb_render_pictdepth_visuals_length(depths.data);

                for (int i = 0; i < len; i++)
                    visualPictFormatHash.insert(visuals[i].visual, visuals[i].format);
            }
        }

        // Init the format ID -> xcb_render_directformat_t* hash table
        const xcb_render_pictforminfo_t *formats = xcb_render_query_pict_formats_formats(reply);
        const int len = xcb_render_query_pict_formats_formats_length(reply);

        for (int i = 0; i < len; i++) {
            if (formats[i].type == XCB_RENDER_PICT_TYPE_DIRECT)
                formatInfoHash.insert(formats[i].id, &formats[i].direct);
        }

        // Init the visual ID -> depth hash table
        const xcb_setup_t *setup = xcb_get_setup(conn);

        for (auto screen = xcb_setup_roots_iterator(setup); screen.rem; xcb_screen_next(&screen)) {
            for (auto depth = xcb_screen_allowed_depths_iterator(screen.data); depth.rem; xcb_depth_next(&depth)) {
                const int len = xcb_depth_visuals_length(depth.data);
                const xcb_visualtype_t *visuals = xcb_depth_visuals(depth.data);

                for (int i = 0; i < len; i++)
                    visualDepthHash.insert(visuals[i].visual_id, depth.data->depth);
            }
        }
    }

    ~GlxGlobalData() {
        qDeleteAll(visualFbConfigHash);
        std::free(reply);
    }

    xcb_render_query_pict_formats_reply_t *reply;
    QHash<xcb_visualid_t, xcb_render_pictformat_t> visualPictFormatHash;
    QHash<xcb_visualid_t, uint32_t> visualDepthHash;
    QHash<xcb_visualid_t, FbConfigInfo *> visualFbConfigHash;
    QHash<xcb_render_pictformat_t, const xcb_render_directformat_t *> formatInfoHash;
};

Q_GLOBAL_STATIC(GlxGlobalData, g_glxGlobalData)

static xcb_render_pictformat_t findPictFormat(xcb_visualid_t visual)
{
    GlxGlobalData *d = g_glxGlobalData;
    return d->visualPictFormatHash.value(visual);
}

static const xcb_render_directformat_t *findPictFormatInfo(xcb_render_pictformat_t format)
{
    GlxGlobalData *d = g_glxGlobalData;
    return d->formatInfoHash.value(format);
}

static int visualDepth(xcb_visualid_t visual)
{
    GlxGlobalData *d = g_glxGlobalData;
    return d->visualDepthHash.value(visual);
}

FbConfigInfo *getConfig(xcb_visualid_t visual)
{
    Display *dpy = QX11Info::display();
    const xcb_render_pictformat_t format = findPictFormat(visual);
    const xcb_render_directformat_t *direct = findPictFormatInfo(format);

    if (!direct) {
        return nullptr;
    }

    const int red_bits   = qPopulationCount(direct->red_mask);
    const int green_bits = qPopulationCount(direct->green_mask);
    const int blue_bits  = qPopulationCount(direct->blue_mask);
    const int alpha_bits = qPopulationCount(direct->alpha_mask);

    const int depth = visualDepth(visual);

    const auto rgb_sizes = std::tie(red_bits, green_bits, blue_bits);

    const int attribs[] = {
        GLX_RENDER_TYPE,                  GLX_RGBA_BIT,
        GLX_DRAWABLE_TYPE,                GLX_WINDOW_BIT | GLX_PIXMAP_BIT,
        GLX_X_VISUAL_TYPE,                GLX_TRUE_COLOR,
        GLX_X_RENDERABLE,                 True,
        GLX_CONFIG_CAVEAT,                int(GLX_DONT_CARE), // The ARGB32 visual is marked non-conformant in Catalyst
        GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT, int(GLX_DONT_CARE),
        GLX_BUFFER_SIZE,                  red_bits + green_bits + blue_bits + alpha_bits,
        GLX_RED_SIZE,                     red_bits,
        GLX_GREEN_SIZE,                   green_bits,
        GLX_BLUE_SIZE,                    blue_bits,
        GLX_ALPHA_SIZE,                   alpha_bits,
        GLX_STENCIL_SIZE,                 0,
        GLX_DEPTH_SIZE,                   0,
        0
    };

    if (QByteArray((char *)glGetString(GL_RENDERER)).contains("llvmpipe")) {
        return nullptr;
    }

    int count = 0;
    GLXFBConfig *configs = glXChooseFBConfig(dpy, QX11Info::appScreen(), attribs, &count);
    if (count < 1) {
        return nullptr;
    }

    struct FBConfig {
        GLXFBConfig config;
        int depth;
        int stencil;
        int format;
    };

    QList<FBConfig> candidates;

    for (int i = 0; i < count; i++) {
        int red, green, blue;
        glXGetFBConfigAttrib(dpy, configs[i], GLX_RED_SIZE,   &red);
        glXGetFBConfigAttrib(dpy, configs[i], GLX_GREEN_SIZE, &green);
        glXGetFBConfigAttrib(dpy, configs[i], GLX_BLUE_SIZE,  &blue);

        if (std::tie(red, green, blue) != rgb_sizes)
            continue;

        xcb_visualid_t visual;
        glXGetFBConfigAttrib(dpy, configs[i], GLX_VISUAL_ID, (int *) &visual);

        if (visualDepth(visual) != depth)
            continue;

        int bind_rgb, bind_rgba;
        glXGetFBConfigAttrib(dpy, configs[i], GLX_BIND_TO_TEXTURE_RGBA_EXT, &bind_rgba);
        glXGetFBConfigAttrib(dpy, configs[i], GLX_BIND_TO_TEXTURE_RGB_EXT,  &bind_rgb);

        if (!bind_rgb && !bind_rgba)
            continue;

        int texture_targets;
        glXGetFBConfigAttrib(dpy, configs[i], GLX_BIND_TO_TEXTURE_TARGETS_EXT, &texture_targets);

        if ((texture_targets & GLX_TEXTURE_2D_BIT_EXT) == 0)
            continue;

        int depth, stencil;
        glXGetFBConfigAttrib(dpy, configs[i], GLX_DEPTH_SIZE,   &depth);
        glXGetFBConfigAttrib(dpy, configs[i], GLX_STENCIL_SIZE, &stencil);

        int texture_format;
        if (alpha_bits)
            texture_format = bind_rgba ? GLX_TEXTURE_FORMAT_RGBA_EXT : GLX_TEXTURE_FORMAT_RGB_EXT;
        else
            texture_format = bind_rgb ? GLX_TEXTURE_FORMAT_RGB_EXT : GLX_TEXTURE_FORMAT_RGBA_EXT;

        candidates.append(FBConfig{configs[i], depth, stencil, texture_format});
    }

    if (count > 0)
        XFree(configs);

    std::stable_sort(candidates.begin(), candidates.end(), [](const FBConfig &left, const FBConfig &right) {
        if (left.depth < right.depth)
            return true;

        if (left.stencil < right.stencil)
            return true;

        return false;
    });

    FbConfigInfo *info = nullptr;

    if (!candidates.isEmpty()) {
        const FBConfig &candidate = candidates.front();

        info = new FbConfigInfo;
        info->fbConfig      = candidate.config;
        info->textureFormat = candidate.format;
    }


    return info;
}

bool XWindowThumbnail::loadGLXTexture()
{
    GLXContext glxContext = glXGetCurrentContext();
    if (!glxContext) {
        return false;
    }

    FbConfigInfo *info = nullptr;

    auto &hashTable = g_glxGlobalData->visualFbConfigHash;
    auto it = hashTable.constFind(m_visualid);

    if (it != hashTable.constEnd()) {
        info = *it;
    } else {
        info = getConfig(m_visualid);
        hashTable.insert(m_visualid, info);
    }

    if (!info) {
        return false;
    }

    glGenTextures(1, &m_texture);

    const int attrs[] = {
        GLX_TEXTURE_FORMAT_EXT, info->textureFormat,
        GLX_MIPMAP_TEXTURE_EXT, false,
        GLX_TEXTURE_TARGET_EXT, GLX_TEXTURE_2D_EXT,
        XCB_NONE
    };

    m_glxPixmap = glXCreatePixmap(QX11Info::display(), info->fbConfig, m_pixmap, attrs);

    return true;
}
#endif

#endif

void XWindowThumbnail::resetDamaged()
{
    m_damaged = false;
#if HAVE_XCB_COMPOSITE
    if (m_damage == XCB_NONE) {
    return;
}
xcb_damage_subtract(QX11Info::connection(), m_damage, XCB_NONE, XCB_NONE);
#endif
}

void XWindowThumbnail::stopRedirecting()
{
    if (!m_xcb || !m_composite) {
        return;
    }
#if HAVE_XCB_COMPOSITE
    xcb_connection_t *c = QX11Info::connection();
if (m_pixmap != XCB_PIXMAP_NONE) {
    xcb_free_pixmap(c, m_pixmap);
    m_pixmap = XCB_PIXMAP_NONE;
}
if (m_winId == XCB_WINDOW_NONE) {
    return;
}
if (m_redirecting) {
    xcb_composite_unredirect_window(c, m_winId, XCB_COMPOSITE_REDIRECT_AUTOMATIC);
}
m_redirecting = false;
if (m_damage == XCB_NONE) {
    return;
}
xcb_damage_destroy(c, m_damage);
m_damage = XCB_NONE;
#endif
}

bool XWindowThumbnail::startRedirecting()
{
    if (!m_xcb || !m_composite || !window() || !window()->isVisible() || window()->winId() == m_winId || !isEnabled() || !isVisible()) {
        return false;
    }
#if HAVE_XCB_COMPOSITE
    if (m_winId == XCB_WINDOW_NONE) {
    return false;
}
    xcb_connection_t *c = QX11Info::connection();

    // need to get the window attributes for the existing event mask
    const auto attribsCookie = xcb_get_window_attributes_unchecked(c, m_winId);

    // redirect the window
    xcb_composite_redirect_window(c, m_winId, XCB_COMPOSITE_REDIRECT_AUTOMATIC);
    m_redirecting = true;

    // generate the damage handle
    m_damage = xcb_generate_id(c);
    xcb_damage_create(c, m_damage, m_winId, XCB_DAMAGE_REPORT_LEVEL_NON_EMPTY);

    QScopedPointer<xcb_get_window_attributes_reply_t, QScopedPointerPodDeleter> attr(xcb_get_window_attributes_reply(c, attribsCookie, nullptr));
    uint32_t events = XCB_EVENT_MASK_STRUCTURE_NOTIFY;
    if (!attr.isNull()) {
        events = events | attr->your_event_mask;
    }
    // the event mask will not be removed again. We cannot track whether another component also needs STRUCTURE_NOTIFY (e.g. KWindowSystem).
    // if we would remove the event mask again, other areas will break.
    xcb_change_window_attributes(c, m_winId, XCB_CW_EVENT_MASK, &events);
    // force to update the texture
    m_damaged = true;
    return true;
#else
    return false;
#endif
}



void XWindowThumbnail::setThumbnailAvailable(bool thumbnailAvailable)
{
    if (m_thumbnailAvailable != thumbnailAvailable) {
        m_thumbnailAvailable = thumbnailAvailable;
        emit thumbnailAvailableChanged();
    }
}

void XWindowThumbnail::sceneVisibilityChanged(bool visible)
{
    if (visible) {
        if (startRedirecting()) {
            update();
        }
    } else {
        stopRedirecting();
        releaseResources();
    }
}