Libplasma

windowthumbnail.cpp
1/*
2 SPDX-FileCopyrightText: 2013 Martin Gräßlin <mgraesslin@kde.org>
3
4 SPDX-License-Identifier: LGPL-2.0-or-later
5*/
6#include "windowthumbnail.h"
7// KF5
8#include <KWindowSystem>
9#include <KX11Extras>
10// Qt
11#include <QGuiApplication>
12#include <QIcon>
13#include <QOpenGLContext>
14#include <QOpenGLFunctions>
15#include <QQuickWindow>
16#include <QRunnable>
17#include <QSGImageNode>
18
19// X11
20#if HAVE_XCB_COMPOSITE
21#include <xcb/composite.h>
22#if HAVE_GLX
23#include <GL/glx.h>
24typedef void (*glXBindTexImageEXT_func)(Display *dpy, GLXDrawable drawable, int buffer, const int *attrib_list);
25typedef void (*glXReleaseTexImageEXT_func)(Display *dpy, GLXDrawable drawable, int buffer);
26#include <fixx11h.h> // glx.h could include XLib.h
27#endif
28#if HAVE_EGL
29typedef EGLImageKHR (*eglCreateImageKHR_func)(EGLDisplay, EGLContext, EGLenum, EGLClientBuffer, const EGLint *);
30typedef EGLBoolean (*eglDestroyImageKHR_func)(EGLDisplay, EGLImageKHR);
31typedef GLvoid (*glEGLImageTargetTexture2DOES_func)(GLenum, GLeglImageOES);
32#endif // HAVE_EGL
33#endif
34
35#include <cstdlib>
36#include <ranges>
37
38namespace Plasma
39{
40class DiscardTextureProviderRunnable : public QRunnable
41{
42public:
43 explicit DiscardTextureProviderRunnable(WindowTextureProvider *provider)
44 : m_provider(provider)
45 {
46 }
47
48 void run() override
49 {
50 delete m_provider;
51 }
52
53private:
54 WindowTextureProvider *m_provider;
55};
56
57#if HAVE_XCB_COMPOSITE
58
59#if HAVE_GLX
60class DiscardGlxPixmapRunnable : public QRunnable
61{
62public:
63 DiscardGlxPixmapRunnable(uint, QFunctionPointer, xcb_pixmap_t);
64 void run() override;
65
66private:
67 uint m_texture;
68 QFunctionPointer m_releaseTexImage;
69 xcb_pixmap_t m_glxPixmap;
70};
71
72DiscardGlxPixmapRunnable::DiscardGlxPixmapRunnable(uint texture, QFunctionPointer deleteFunction, xcb_pixmap_t pixmap)
73 : QRunnable()
74 , m_texture(texture)
75 , m_releaseTexImage(deleteFunction)
76 , m_glxPixmap(pixmap)
77{
78}
79
80void DiscardGlxPixmapRunnable::run()
81{
82 if (m_glxPixmap != XCB_PIXMAP_NONE) {
83 Display *d = qGuiApp->nativeInterface<QNativeInterface::QX11Application>()->display();
84 ((glXReleaseTexImageEXT_func)(m_releaseTexImage))(d, m_glxPixmap, GLX_FRONT_LEFT_EXT);
85 glXDestroyPixmap(d, m_glxPixmap);
86 glDeleteTextures(1, &m_texture);
87 }
88}
89#endif // HAVE_GLX
90
91#if HAVE_EGL
92class DiscardEglPixmapRunnable : public QRunnable
93{
94public:
95 DiscardEglPixmapRunnable(uint, QFunctionPointer, EGLImageKHR);
96 void run() override;
97
98private:
99 uint m_texture;
100 QFunctionPointer m_eglDestroyImageKHR;
101 EGLImageKHR m_image;
102};
103
104DiscardEglPixmapRunnable::DiscardEglPixmapRunnable(uint texture, QFunctionPointer deleteFunction, EGLImageKHR image)
105 : QRunnable()
106 , m_texture(texture)
107 , m_eglDestroyImageKHR(deleteFunction)
108 , m_image(image)
109{
110}
111
112void DiscardEglPixmapRunnable::run()
113{
114 if (m_image != EGL_NO_IMAGE_KHR) {
115 ((eglDestroyImageKHR_func)(m_eglDestroyImageKHR))(eglGetCurrentDisplay(), m_image);
116 glDeleteTextures(1, &m_texture);
117 }
118}
119#endif // HAVE_EGL
120#endif // HAVE_XCB_COMPOSITE
121
122QSGTexture *WindowTextureProvider::texture() const
123{
124 return m_texture.get();
125}
126
127void WindowTextureProvider::setTexture(QSGTexture *texture)
128{
129 m_texture.reset(texture);
130 Q_EMIT textureChanged();
131}
132
133#if HAVE_XCB_COMPOSITE
134std::optional<bool> WindowThumbnail::s_hasPixmapExtension = std::nullopt;
135#endif
136
137WindowThumbnail::WindowThumbnail(QQuickItem *parent)
138 : QQuickItem(parent)
140{
141 setFlag(ItemHasContents);
142
143 if (QGuiApplication *gui = dynamic_cast<QGuiApplication *>(QCoreApplication::instance())) {
144 m_xcb = (gui->platformName() == QLatin1String("xcb"));
145 if (m_xcb) {
146 gui->installNativeEventFilter(this);
147#if HAVE_XCB_COMPOSITE
148 xcb_connection_t *c = qGuiApp->nativeInterface<QNativeInterface::QX11Application>()->connection();
149 xcb_prefetch_extension_data(c, &xcb_composite_id);
150 const auto *compositeReply = xcb_get_extension_data(c, &xcb_composite_id);
151 m_composite = (compositeReply && compositeReply->present);
152
153 xcb_prefetch_extension_data(c, &xcb_damage_id);
154 const auto *reply = xcb_get_extension_data(c, &xcb_damage_id);
155 m_damageEventBase = reply->first_event;
156 if (reply->present) {
157 xcb_damage_query_version_unchecked(c, XCB_DAMAGE_MAJOR_VERSION, XCB_DAMAGE_MINOR_VERSION);
158 }
159#endif
160 }
161 }
162}
163
164WindowThumbnail::~WindowThumbnail()
165{
166 if (m_xcb) {
168 stopRedirecting();
169 }
170}
171
172void WindowThumbnail::itemChange(ItemChange change, const ItemChangeData &data)
173{
174 switch (change) {
175 case ItemSceneChange:
176 if (m_scene) {
177 disconnect(m_scene.data(), &QWindow::visibleChanged, this, &WindowThumbnail::sceneVisibilityChanged);
178 }
179 m_scene = data.window;
180 if (m_scene) {
181 connect(m_scene.data(), &QWindow::visibleChanged, this, &WindowThumbnail::sceneVisibilityChanged);
182 // restart the redirection, it might not have been active yet
183 stopRedirecting();
184 if (startRedirecting()) {
185 update();
186 }
187 }
188 break;
189
190 case ItemEnabledHasChanged:
191 Q_FALLTHROUGH();
192 case ItemVisibleHasChanged:
193 if (data.boolValue) {
194 if (startRedirecting()) {
195 update();
196 }
197 } else {
198 stopRedirecting();
199 releaseResources();
200 }
201 break;
202
203 default:
204 break;
205 }
206
207 QQuickItem::itemChange(change, data);
208}
209
210void WindowThumbnail::releaseResources()
211{
213 if (m_textureProvider) {
214 window()->scheduleRenderJob(new DiscardTextureProviderRunnable(m_textureProvider), QQuickWindow::AfterSynchronizingStage);
215 m_textureProvider = nullptr;
216 }
217
218#if HAVE_XCB_COMPOSITE
219
220#if HAVE_GLX && HAVE_EGL
221 // only one (or none) should be set, but never both
222 Q_ASSERT(m_glxPixmap == XCB_PIXMAP_NONE || m_image == EGL_NO_IMAGE_KHR);
223#endif
224
225 // data is deleted in the render thread (with relevant GLX calls)
226 // note runnable may be called *after* this is deleted
227 // but the pointer is held by the WindowThumbnail which is in the main thread
228#if HAVE_GLX
229 if (m_glxPixmap != XCB_PIXMAP_NONE) {
230 window()->scheduleRenderJob(new DiscardGlxPixmapRunnable(m_texture, m_releaseTexImage, m_glxPixmap), m_renderStage);
231
232 m_glxPixmap = XCB_PIXMAP_NONE;
233 m_texture = 0;
234 }
235#endif
236#if HAVE_EGL
237 if (m_image != EGL_NO_IMAGE_KHR) {
238 window()->scheduleRenderJob(new DiscardEglPixmapRunnable(m_texture, m_eglDestroyImageKHR, m_image), m_renderStage);
239 m_image = EGL_NO_IMAGE_KHR;
240 m_texture = 0;
241 }
242#endif
243#endif
244}
245
246// this method is invoked automagically from the render thread
247// but with the GUI thread locked
248//
249void WindowThumbnail::invalidateSceneGraph()
250{
251 delete m_textureProvider;
252 m_textureProvider = nullptr;
253#if HAVE_GLX
254 if (m_glxPixmap != XCB_PIXMAP_NONE) {
255 // runnable used just to share code with releaseResources, we're already in the render thread
256 // so run directly
257 auto runnable = new DiscardGlxPixmapRunnable(m_texture, m_releaseTexImage, m_glxPixmap);
258 runnable->run();
259 m_glxPixmap = XCB_PIXMAP_NONE;
260 m_texture = 0;
261 }
262#endif
263#if HAVE_EGL
264 if (m_image != EGL_NO_IMAGE_KHR) {
265 auto runnable = new DiscardEglPixmapRunnable(m_texture, m_eglDestroyImageKHR, m_image);
266 runnable->run();
267 m_image = EGL_NO_IMAGE_KHR;
268 m_texture = 0;
269 }
270#endif
271}
272
273uint32_t WindowThumbnail::winId() const
274{
275 return m_winId;
276}
277
278void WindowThumbnail::setWinId(uint32_t winId)
279{
280 if (m_winId == winId) {
281 return;
282 }
283 if (KWindowSystem::isPlatformX11() && !KX11Extras::self()->hasWId(winId)) {
284 // invalid Id, don't updated
285 return;
286 }
287 if (window() && winId == window()->winId()) {
288 // don't redirect to yourself
289 return;
290 }
291 stopRedirecting();
292 m_winId = winId;
293
294 if (isEnabled() && isVisible()) {
295 startRedirecting();
296 }
297
298 Q_EMIT winIdChanged();
299}
300
301void WindowThumbnail::resetWinId()
302{
303 setWinId(0);
304}
305
306qreal WindowThumbnail::paintedWidth() const
307{
308 return m_paintedSize.width();
309}
310
311qreal WindowThumbnail::paintedHeight() const
312{
313 return m_paintedSize.height();
314}
315
316bool WindowThumbnail::thumbnailAvailable() const
317{
318 return m_thumbnailAvailable;
319}
320
321QSGNode *WindowThumbnail::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *updatePaintNodeData)
322{
323 Q_UNUSED(updatePaintNodeData)
324
325 if (!m_textureProvider) {
326 m_textureProvider = new WindowTextureProvider();
327 }
328
329 if (!m_xcb || m_winId == 0 || (window() && window()->winId() == m_winId)) {
330 iconToTexture(m_textureProvider);
331 } else {
332 windowToTexture(m_textureProvider);
333 }
334
335 QSGImageNode *node = static_cast<QSGImageNode *>(oldNode);
336 if (!node) {
337 node = window()->createImageNode();
338 qsgnode_set_description(node, QStringLiteral("windowthumbnail"));
340 }
341
342 node->setTexture(m_textureProvider->texture());
343 const QSizeF size(node->texture()->textureSize().scaled(boundingRect().size().toSize(), Qt::KeepAspectRatio));
344 if (size != m_paintedSize) {
345 m_paintedSize = size;
346 Q_EMIT paintedSizeChanged();
347 }
348 const qreal x = boundingRect().x() + (boundingRect().width() - size.width()) / 2;
349 const qreal y = boundingRect().y() + (boundingRect().height() - size.height()) / 2;
350 node->setRect(QRectF(QPointF(x, y), size));
351 return node;
352}
353
354bool WindowThumbnail::nativeEventFilter(const QByteArray &eventType, void *message, qintptr *result)
355{
356 Q_UNUSED(result)
357 if (!m_xcb || !m_composite || eventType != QByteArrayLiteral("xcb_generic_event_t")) {
358 // currently we are only interested in XCB events
359 return false;
360 }
361#if HAVE_XCB_COMPOSITE
362 xcb_generic_event_t *event = static_cast<xcb_generic_event_t *>(message);
363 const uint8_t responseType = event->response_type & ~0x80;
364 if (responseType == m_damageEventBase + XCB_DAMAGE_NOTIFY) {
365 if (reinterpret_cast<xcb_damage_notify_event_t *>(event)->drawable == m_winId) {
366 m_damaged = true;
367 update();
368 }
369 } else if (responseType == XCB_CONFIGURE_NOTIFY) {
370 if (reinterpret_cast<xcb_configure_notify_event_t *>(event)->window == m_winId) {
371 releaseResources();
372 if (m_pixmap) {
373 xcb_free_pixmap(qGuiApp->nativeInterface<QNativeInterface::QX11Application>()->connection(), m_pixmap);
374 m_pixmap = XCB_PIXMAP_NONE;
375 }
376 m_damaged = true;
377 update();
378 }
379 } else if (responseType == XCB_MAP_NOTIFY) {
380 if (reinterpret_cast<xcb_map_notify_event_t *>(event)->window == m_winId) {
381 releaseResources();
382 m_damaged = true;
383 update();
384 }
385 }
386#else
387 Q_UNUSED(message)
388#endif
389 // do not filter out any events, there might be further WindowThumbnails for the same window
390 return false;
391}
392
393void WindowThumbnail::iconToTexture(WindowTextureProvider *textureProvider)
394{
395 QIcon icon;
396 if (KWindowSystem::isPlatformX11() && KX11Extras::self()->hasWId(m_winId)) {
397 icon = KX11Extras::self()->icon(m_winId, boundingRect().width(), boundingRect().height());
398 } else {
399 // fallback to plasma icon
400 icon = QIcon::fromTheme(QStringLiteral("plasma"));
401 }
402 QImage image = icon.pixmap(boundingRect().size().toSize(), window()->devicePixelRatio()).toImage();
403 textureProvider->setTexture(window()->createTextureFromImage(image, QQuickWindow::TextureCanUseAtlas));
404}
405
406#if HAVE_XCB_COMPOSITE
407#if HAVE_GLX
408bool WindowThumbnail::windowToTextureGLX(WindowTextureProvider *textureProvider)
409{
410 const auto openglContext = static_cast<QOpenGLContext *>(window()->rendererInterface()->getResource(window(), QSGRendererInterface::OpenGLContextResource));
411 if (openglContext) {
412 if (!m_openGLFunctionsResolved) {
413 resolveGLXFunctions();
414 }
415 if (!m_bindTexImage || !m_releaseTexImage) {
416 return false;
417 }
418 if (m_glxPixmap == XCB_PIXMAP_NONE) {
419 xcb_connection_t *c = qGuiApp->nativeInterface<QNativeInterface::QX11Application>()->connection();
420 auto attrCookie = xcb_get_window_attributes_unchecked(c, m_winId);
421 auto geometryCookie = xcb_get_geometry_unchecked(c, m_pixmap);
422 QScopedPointer<xcb_get_window_attributes_reply_t, QScopedPointerPodDeleter> attr(xcb_get_window_attributes_reply(c, attrCookie, nullptr));
423 QScopedPointer<xcb_get_geometry_reply_t, QScopedPointerPodDeleter> geo(xcb_get_geometry_reply(c, geometryCookie, nullptr));
424
425 if (attr.isNull()) {
426 return false;
427 }
428
429 if (geo.isNull()) {
430 return false;
431 }
432
433 m_depth = geo->depth;
434 m_visualid = attr->visual;
435
436 if (!loadGLXTexture()) {
437 return false;
438 }
439
440 textureProvider->setTexture(
442 }
443 openglContext->functions()->glBindTexture(GL_TEXTURE_2D, m_texture);
444 bindGLXTexture();
445 return true;
446 }
447 return false;
448}
449#endif // HAVE_GLX
450
451#if HAVE_EGL
452bool WindowThumbnail::xcbWindowToTextureEGL(WindowTextureProvider *textureProvider)
453{
454 EGLContext context = eglGetCurrentContext();
455
456 if (context != EGL_NO_CONTEXT) {
457 if (!m_eglFunctionsResolved) {
458 resolveEGLFunctions();
459 }
460 if (QByteArrayView((char *)glGetString(GL_RENDERER)).contains("llvmpipe")) {
461 return false;
462 }
463 if (!m_eglCreateImageKHR || !m_eglDestroyImageKHR || !m_glEGLImageTargetTexture2DOES) {
464 return false;
465 }
466 if (m_image == EGL_NO_IMAGE_KHR) {
467 xcb_connection_t *c = qGuiApp->nativeInterface<QNativeInterface::QX11Application>()->connection();
468 auto geometryCookie = xcb_get_geometry_unchecked(c, m_pixmap);
469
470 const EGLint attribs[] = {EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE};
471 m_image = ((eglCreateImageKHR_func)(m_eglCreateImageKHR))(eglGetCurrentDisplay(),
472 EGL_NO_CONTEXT,
473 EGL_NATIVE_PIXMAP_KHR,
474 (EGLClientBuffer)(uintptr_t)m_pixmap,
475 attribs);
476
477 if (m_image == EGL_NO_IMAGE_KHR) {
478 qDebug() << "failed to create egl image";
479 return false;
480 }
481
482 glGenTextures(1, &m_texture);
483 QScopedPointer<xcb_get_geometry_reply_t, QScopedPointerPodDeleter> geo(xcb_get_geometry_reply(c, geometryCookie, nullptr));
484 QSize size;
485 if (!geo.isNull()) {
486 size.setWidth(geo->width);
487 size.setHeight(geo->height);
488 }
489 textureProvider->setTexture(QNativeInterface::QSGOpenGLTexture::fromNative(m_texture, window(), size, QQuickWindow::TextureCanUseAtlas));
490 }
491 auto *openglContext = static_cast<QOpenGLContext *>(window()->rendererInterface()->getResource(window(), QSGRendererInterface::OpenGLContextResource));
492 openglContext->functions()->glBindTexture(GL_TEXTURE_2D, m_texture);
493 bindEGLTexture();
494 return true;
495 }
496 return false;
497}
498
499void WindowThumbnail::resolveEGLFunctions()
500{
501 EGLDisplay display = eglGetCurrentDisplay();
502 if (display == EGL_NO_DISPLAY) {
503 return;
504 }
505 auto *context = static_cast<QOpenGLContext *>(window()->rendererInterface()->getResource(window(), QSGRendererInterface::OpenGLContextResource));
506 if (!s_hasPixmapExtension.has_value()) {
507#if defined(__clang__) && __clang_major__ < 16
508 QByteArray queryResult(eglQueryString(display, EGL_EXTENSIONS));
509 auto extensions = queryResult.split(' ');
510#else
511 QByteArrayView queryResult(eglQueryString(display, EGL_EXTENSIONS));
512 auto extensions = queryResult | std::views::split(' ');
513#endif
514 auto filter = [](const auto ext) {
515 return std::ranges::equal(ext, QByteArrayView("EGL_KHR_image")) || std::ranges::equal(ext, QByteArrayView("EGL_KHR_image_base"))
516 || std::ranges::equal(ext, QByteArrayView("EGL_KHR_image_pixmap"));
517 };
518 s_hasPixmapExtension = std::ranges::any_of(extensions, filter);
519 }
520
521 if (s_hasPixmapExtension.value()) {
522 qDebug() << "Have EGL texture from pixmap";
523 m_eglCreateImageKHR = context->getProcAddress(QByteArrayLiteral("eglCreateImageKHR"));
524 m_eglDestroyImageKHR = context->getProcAddress(QByteArrayLiteral("eglDestroyImageKHR"));
525 m_glEGLImageTargetTexture2DOES = context->getProcAddress(QByteArrayLiteral("glEGLImageTargetTexture2DOES"));
526 }
527 m_eglFunctionsResolved = true;
528}
529
530void WindowThumbnail::bindEGLTexture()
531{
532 ((glEGLImageTargetTexture2DOES_func)(m_glEGLImageTargetTexture2DOES))(GL_TEXTURE_2D, (GLeglImageOES)m_image);
533 resetDamaged();
534}
535#endif // HAVE_EGL
536
537#endif // HAVE_XCB_COMPOSITE
538
539void WindowThumbnail::windowToTexture(WindowTextureProvider *textureProvider)
540{
541 if (!m_damaged && textureProvider->texture()) {
542 return;
543 }
544#if HAVE_XCB_COMPOSITE
545 if (m_pixmap == XCB_PIXMAP_NONE) {
546 m_pixmap = pixmapForWindow();
547 }
548 if (m_pixmap == XCB_PIXMAP_NONE) {
549 // create above failed
550 iconToTexture(textureProvider);
551 setThumbnailAvailable(false);
552 return;
553 }
554 bool fallbackToIcon = true;
555#if HAVE_GLX
556 fallbackToIcon = !windowToTextureGLX(textureProvider);
557#endif // HAVE_GLX
558#if HAVE_EGL
559 if (fallbackToIcon) {
560 // if glx succeeded fallbackToIcon is false, thus we shouldn't try egl
561 fallbackToIcon = !xcbWindowToTextureEGL(textureProvider);
562 }
563#endif // HAVE_EGL
564 if (fallbackToIcon) {
565 // just for safety to not crash
566 iconToTexture(textureProvider);
567 }
568 setThumbnailAvailable(!fallbackToIcon);
569#else
570 iconToTexture(textureProvider);
571#endif
572}
573
574#if HAVE_XCB_COMPOSITE
575xcb_pixmap_t WindowThumbnail::pixmapForWindow()
576{
577 if (!m_composite) {
578 return XCB_PIXMAP_NONE;
579 }
580
581 xcb_connection_t *c = qGuiApp->nativeInterface<QNativeInterface::QX11Application>()->connection();
582 xcb_pixmap_t pix = xcb_generate_id(c);
583 auto cookie = xcb_composite_name_window_pixmap_checked(c, m_winId, pix);
585 if (error) {
586 return XCB_PIXMAP_NONE;
587 }
588 return pix;
589}
590
591#if HAVE_GLX
592void WindowThumbnail::resolveGLXFunctions()
593{
594 auto *context = static_cast<QOpenGLContext *>(window()->rendererInterface()->getResource(window(), QSGRendererInterface::OpenGLContextResource));
595 auto display = qGuiApp->nativeInterface<QNativeInterface::QX11Application>()->display();
596 if (!s_hasPixmapExtension.has_value()) {
597 auto filter = [](const auto ext) {
598 return std::ranges::equal(ext, QByteArrayView("GLX_EXT_texture_from_pixmap"));
599 };
600#if defined(__clang__) && __clang_major__ < 16
601 QByteArray queryResult(glXQueryExtensionsString(display, DefaultScreen(display)));
602 QList<QByteArray> extensions = queryResult.split(' ');
603#else
604 QByteArrayView queryResult(glXQueryExtensionsString(display, DefaultScreen(display)));
605 auto extensions = queryResult | std::views::split(' ');
606#endif
607 s_hasPixmapExtension = std::ranges::any_of(extensions, filter);
608 }
609 if (s_hasPixmapExtension.value()) {
610 m_bindTexImage = context->getProcAddress(QByteArrayLiteral("glXBindTexImageEXT"));
611 m_releaseTexImage = context->getProcAddress(QByteArrayLiteral("glXReleaseTexImageEXT"));
612 } else {
613 qWarning() << "couldn't resolve GLX_EXT_texture_from_pixmap functions";
614 }
615 m_openGLFunctionsResolved = true;
616}
617
618void WindowThumbnail::bindGLXTexture()
619{
620 Display *d = qGuiApp->nativeInterface<QNativeInterface::QX11Application>()->display();
621 ((glXReleaseTexImageEXT_func)(m_releaseTexImage))(d, m_glxPixmap, GLX_FRONT_LEFT_EXT);
622 ((glXBindTexImageEXT_func)(m_bindTexImage))(d, m_glxPixmap, GLX_FRONT_LEFT_EXT, nullptr);
623 resetDamaged();
624}
625
626struct FbConfigInfo {
627 GLXFBConfig fbConfig;
628 int textureFormat;
629};
630
631struct GlxGlobalData {
632 GlxGlobalData()
633 {
634 xcb_connection_t *const conn = qGuiApp->nativeInterface<QNativeInterface::QX11Application>()->connection();
635
636 // Fetch the render pict formats
637 reply = xcb_render_query_pict_formats_reply(conn, xcb_render_query_pict_formats_unchecked(conn), nullptr);
638
639 // Init the visual ID -> format ID hash table
640 for (auto screens = xcb_render_query_pict_formats_screens_iterator(reply); screens.rem; xcb_render_pictscreen_next(&screens)) {
641 for (auto depths = xcb_render_pictscreen_depths_iterator(screens.data); depths.rem; xcb_render_pictdepth_next(&depths)) {
642 const xcb_render_pictvisual_t *visuals = xcb_render_pictdepth_visuals(depths.data);
643 const int len = xcb_render_pictdepth_visuals_length(depths.data);
644
645 for (int i = 0; i < len; i++) {
646 visualPictFormatHash.insert(visuals[i].visual, visuals[i].format);
647 }
648 }
649 }
650
651 // Init the format ID -> xcb_render_directformat_t* hash table
652 const xcb_render_pictforminfo_t *formats = xcb_render_query_pict_formats_formats(reply);
653 const int len = xcb_render_query_pict_formats_formats_length(reply);
654
655 for (int i = 0; i < len; i++) {
656 if (formats[i].type == XCB_RENDER_PICT_TYPE_DIRECT) {
657 formatInfoHash.insert(formats[i].id, &formats[i].direct);
658 }
659 }
660
661 // Init the visual ID -> depth hash table
662 const xcb_setup_t *setup = xcb_get_setup(conn);
663
664 for (auto screen = xcb_setup_roots_iterator(setup); screen.rem; xcb_screen_next(&screen)) {
665 for (auto depth = xcb_screen_allowed_depths_iterator(screen.data); depth.rem; xcb_depth_next(&depth)) {
666 const int len = xcb_depth_visuals_length(depth.data);
667 const xcb_visualtype_t *visuals = xcb_depth_visuals(depth.data);
668
669 for (int i = 0; i < len; i++) {
670 visualDepthHash.insert(visuals[i].visual_id, depth.data->depth);
671 }
672 }
673 }
674 }
675
676 ~GlxGlobalData()
677 {
678 qDeleteAll(visualFbConfigHash);
679 std::free(reply);
680 }
681
682 xcb_render_query_pict_formats_reply_t *reply;
684 QHash<xcb_visualid_t, uint32_t> visualDepthHash;
685 QHash<xcb_visualid_t, FbConfigInfo *> visualFbConfigHash;
687};
688
689Q_GLOBAL_STATIC(GlxGlobalData, g_glxGlobalData)
690
691static xcb_render_pictformat_t findPictFormat(xcb_visualid_t visual)
692{
693 GlxGlobalData *d = g_glxGlobalData;
694 return d->visualPictFormatHash.value(visual);
695}
696
697static const xcb_render_directformat_t *findPictFormatInfo(xcb_render_pictformat_t format)
698{
699 GlxGlobalData *d = g_glxGlobalData;
700 return d->formatInfoHash.value(format);
701}
702
703static int visualDepth(xcb_visualid_t visual)
704{
705 GlxGlobalData *d = g_glxGlobalData;
706 return d->visualDepthHash.value(visual);
707}
708
709FbConfigInfo *getConfig(xcb_visualid_t visual)
710{
711 Display *dpy = qGuiApp->nativeInterface<QNativeInterface::QX11Application>()->display();
712 const xcb_render_pictformat_t format = findPictFormat(visual);
713 const xcb_render_directformat_t *direct = findPictFormatInfo(format);
714
715 if (!direct) {
716 return nullptr;
717 }
718
719 const int red_bits = qPopulationCount(direct->red_mask);
720 const int green_bits = qPopulationCount(direct->green_mask);
721 const int blue_bits = qPopulationCount(direct->blue_mask);
722 const int alpha_bits = qPopulationCount(direct->alpha_mask);
723
724 const int depth = visualDepth(visual);
725
726 const auto rgb_sizes = std::tie(red_bits, green_bits, blue_bits);
727
728 const int attribs[] = {GLX_RENDER_TYPE,
729 GLX_RGBA_BIT,
730 GLX_DRAWABLE_TYPE,
731 GLX_WINDOW_BIT | GLX_PIXMAP_BIT,
732 GLX_X_VISUAL_TYPE,
733 GLX_TRUE_COLOR,
734 GLX_X_RENDERABLE,
735 True,
736 GLX_CONFIG_CAVEAT,
737 int(GLX_DONT_CARE), // The ARGB32 visual is marked non-conformant in Catalyst
738 GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT,
739 int(GLX_DONT_CARE),
740 GLX_BUFFER_SIZE,
741 red_bits + green_bits + blue_bits + alpha_bits,
742 GLX_RED_SIZE,
743 red_bits,
744 GLX_GREEN_SIZE,
745 green_bits,
746 GLX_BLUE_SIZE,
747 blue_bits,
748 GLX_ALPHA_SIZE,
749 alpha_bits,
750 GLX_STENCIL_SIZE,
751 0,
752 GLX_DEPTH_SIZE,
753 0,
754 0};
755
756 if (QByteArrayView((char *)glGetString(GL_RENDERER)).contains("llvmpipe")) {
757 return nullptr;
758 }
759
760 int count = 0;
761 GLXFBConfig *configs = glXChooseFBConfig(dpy, DefaultScreen(dpy), attribs, &count);
762 if (count < 1) {
763 return nullptr;
764 }
765
766 struct FBConfig {
767 GLXFBConfig config;
768 int depth;
769 int stencil;
770 int format;
771 };
772
773 QList<FBConfig> candidates;
774
775 for (int i = 0; i < count; i++) {
776 int red;
777 int green;
778 int blue;
779 glXGetFBConfigAttrib(dpy, configs[i], GLX_RED_SIZE, &red);
780 glXGetFBConfigAttrib(dpy, configs[i], GLX_GREEN_SIZE, &green);
781 glXGetFBConfigAttrib(dpy, configs[i], GLX_BLUE_SIZE, &blue);
782
783 if (std::tie(red, green, blue) != rgb_sizes) {
784 continue;
785 }
786
787 xcb_visualid_t visual;
788 glXGetFBConfigAttrib(dpy, configs[i], GLX_VISUAL_ID, (int *)&visual);
789
790 if (visualDepth(visual) != depth) {
791 continue;
792 }
793
794 int bind_rgb;
795 int bind_rgba;
796 glXGetFBConfigAttrib(dpy, configs[i], GLX_BIND_TO_TEXTURE_RGBA_EXT, &bind_rgba);
797 glXGetFBConfigAttrib(dpy, configs[i], GLX_BIND_TO_TEXTURE_RGB_EXT, &bind_rgb);
798
799 if (!bind_rgb && !bind_rgba) {
800 continue;
801 }
802
803 int texture_targets;
804 glXGetFBConfigAttrib(dpy, configs[i], GLX_BIND_TO_TEXTURE_TARGETS_EXT, &texture_targets);
805
806 if ((texture_targets & GLX_TEXTURE_2D_BIT_EXT) == 0) {
807 continue;
808 }
809
810 int depth;
811 int stencil;
812 glXGetFBConfigAttrib(dpy, configs[i], GLX_DEPTH_SIZE, &depth);
813 glXGetFBConfigAttrib(dpy, configs[i], GLX_STENCIL_SIZE, &stencil);
814
815 int texture_format;
816 if (alpha_bits) {
817 texture_format = bind_rgba ? GLX_TEXTURE_FORMAT_RGBA_EXT : GLX_TEXTURE_FORMAT_RGB_EXT;
818 } else {
819 texture_format = bind_rgb ? GLX_TEXTURE_FORMAT_RGB_EXT : GLX_TEXTURE_FORMAT_RGBA_EXT;
820 }
821
822 candidates.append(FBConfig{configs[i], depth, stencil, texture_format});
823 }
824
825 XFree(configs);
826
827 std::stable_sort(candidates.begin(), candidates.end(), [](const FBConfig &left, const FBConfig &right) {
828 if (left.depth < right.depth) {
829 return true;
830 }
831
832 if (left.stencil < right.stencil) {
833 return true;
834 }
835
836 return false;
837 });
838
839 FbConfigInfo *info = nullptr;
840
841 if (!candidates.isEmpty()) {
842 const FBConfig &candidate = candidates.front();
843
844 info = new FbConfigInfo;
845 info->fbConfig = candidate.config;
846 info->textureFormat = candidate.format;
847 }
848
849 return info;
850}
851
852bool WindowThumbnail::loadGLXTexture()
853{
854 GLXContext glxContext = glXGetCurrentContext();
855 if (!glxContext) {
856 return false;
857 }
858
859 FbConfigInfo *info = nullptr;
860
861 auto &hashTable = g_glxGlobalData->visualFbConfigHash;
862 auto it = hashTable.constFind(m_visualid);
863
864 if (it != hashTable.constEnd()) {
865 info = *it;
866 } else {
867 info = getConfig(m_visualid);
868 hashTable.insert(m_visualid, info);
869 }
870
871 if (!info) {
872 return false;
873 }
874
875 glGenTextures(1, &m_texture);
876
877 /* clang-format off */
878 const int attrs[] = {
879 GLX_TEXTURE_FORMAT_EXT,
880 info->textureFormat,
881 GLX_MIPMAP_TEXTURE_EXT,
882 false,
883 GLX_TEXTURE_TARGET_EXT,
884 GLX_TEXTURE_2D_EXT,
885 XCB_NONE};
886 /* clang-format on */
887
888 m_glxPixmap = glXCreatePixmap(qGuiApp->nativeInterface<QNativeInterface::QX11Application>()->display(), info->fbConfig, m_pixmap, attrs);
889
890 return true;
891}
892#endif
893
894#endif
895
896void WindowThumbnail::resetDamaged()
897{
898 m_damaged = false;
899#if HAVE_XCB_COMPOSITE
900 if (m_damage == XCB_NONE) {
901 return;
902 }
903 xcb_damage_subtract(qGuiApp->nativeInterface<QNativeInterface::QX11Application>()->connection(), m_damage, XCB_NONE, XCB_NONE);
904#endif
905}
906
907void WindowThumbnail::stopRedirecting()
908{
909 if (!m_xcb || !m_composite) {
910 return;
911 }
912#if HAVE_XCB_COMPOSITE
913 xcb_connection_t *c = qGuiApp->nativeInterface<QNativeInterface::QX11Application>()->connection();
914 if (m_pixmap != XCB_PIXMAP_NONE) {
915 xcb_free_pixmap(c, m_pixmap);
916 m_pixmap = XCB_PIXMAP_NONE;
917 }
918 if (m_winId == XCB_WINDOW_NONE) {
919 return;
920 }
921 if (m_redirecting) {
922 xcb_composite_unredirect_window(c, m_winId, XCB_COMPOSITE_REDIRECT_AUTOMATIC);
923 }
924 m_redirecting = false;
925 if (m_damage == XCB_NONE) {
926 return;
927 }
928 xcb_damage_destroy(c, m_damage);
929 m_damage = XCB_NONE;
930#endif
931}
932
933bool WindowThumbnail::startRedirecting()
934{
935 if (!m_xcb || !m_composite || !window() || !window()->isVisible() || window()->winId() == m_winId || !isEnabled() || !isVisible()) {
936 return false;
937 }
938#if HAVE_XCB_COMPOSITE
939 if (m_winId == XCB_WINDOW_NONE) {
940 return false;
941 }
942 xcb_connection_t *c = qGuiApp->nativeInterface<QNativeInterface::QX11Application>()->connection();
943
944 // need to get the window attributes for the existing event mask
945 const auto attribsCookie = xcb_get_window_attributes_unchecked(c, m_winId);
946
947 // redirect the window
948 xcb_composite_redirect_window(c, m_winId, XCB_COMPOSITE_REDIRECT_AUTOMATIC);
949 m_redirecting = true;
950
951 // generate the damage handle
952 m_damage = xcb_generate_id(c);
953 xcb_damage_create(c, m_damage, m_winId, XCB_DAMAGE_REPORT_LEVEL_NON_EMPTY);
954
955 QScopedPointer<xcb_get_window_attributes_reply_t, QScopedPointerPodDeleter> attr(xcb_get_window_attributes_reply(c, attribsCookie, nullptr));
956 uint32_t events = XCB_EVENT_MASK_STRUCTURE_NOTIFY;
957 if (!attr.isNull()) {
958 events = events | attr->your_event_mask;
959 }
960 // the event mask will not be removed again. We cannot track whether another component also needs STRUCTURE_NOTIFY (e.g. KWindowSystem).
961 // if we would remove the event mask again, other areas will break.
962 xcb_change_window_attributes(c, m_winId, XCB_CW_EVENT_MASK, &events);
963 // force to update the texture
964 m_damaged = true;
965 return true;
966#else
967 return false;
968#endif
969}
970
971void WindowThumbnail::setThumbnailAvailable(bool thumbnailAvailable)
972{
973 if (m_thumbnailAvailable != thumbnailAvailable) {
974 m_thumbnailAvailable = thumbnailAvailable;
975 Q_EMIT thumbnailAvailableChanged();
976 }
977}
978
979void WindowThumbnail::sceneVisibilityChanged(bool visible)
980{
981 if (visible) {
982 if (startRedirecting()) {
983 update();
984 }
985 } else {
986 stopRedirecting();
987 releaseResources();
988 }
989}
990
991bool WindowThumbnail::isTextureProvider() const
992{
993 return true;
994}
995
996QSGTextureProvider *WindowThumbnail::textureProvider() const
997{
998 // When Item::layer::enabled == true, QQuickItem will be a texture
999 // provider. In this case we should prefer to return the layer rather
1000 // than our texture
1003 }
1004
1005 if (!m_textureProvider) {
1006 m_textureProvider = new WindowTextureProvider();
1007 }
1008
1009 return m_textureProvider;
1010}
1011
1012} // namespace
1013
1014#include "moc_windowthumbnail.cpp"
static bool isPlatformX11()
void update(Part *part, const QByteArray &data, qint64 dataSize)
GeoCoordinates geo(const QVariant &location)
QWidget * window(QObject *job)
void error(QWidget *parent, const QString &text, const QString &title, const KGuiItem &buttonOk, Options options=Notify)
Namespace for everything in libplasma.
QCoreApplication * instance()
void removeNativeEventFilter(QAbstractNativeEventFilter *filterObject)
QPixmap pixmap(QWindow *window, const QSize &size, Mode mode, State state) const const
QIcon fromTheme(const QString &name)
void append(QList< T > &&value)
iterator begin()
iterator end()
reference front()
bool isEmpty() const const
QSGTexture * fromNative(GLuint textureId, QQuickWindow *window, const QSize &size, QQuickWindow::CreateTextureOptions options)
int * connection() const const
QOpenGLFunctions * functions() const const
QNativeInterface * nativeInterface() const const
void glBindTexture(GLenum target, GLuint texture)
QImage toImage() const const
virtual bool isTextureProvider() const const
virtual void itemChange(ItemChange change, const ItemChangeData &value)
virtual QSGTextureProvider * textureProvider() const const
virtual void run()=0
virtual void setFiltering(QSGTexture::Filtering filtering)=0
virtual void setRect(const QRectF &rect)=0
virtual void setTexture(QSGTexture *texture)=0
virtual QSGTexture * texture() const const=0
virtual QSize textureSize() const const=0
QSize scaled(const QSize &s, Qt::AspectRatioMode mode) const const
void setHeight(int height)
void setWidth(int width)
KeepAspectRatio
QTextStream & left(QTextStream &stream)
QTextStream & right(QTextStream &stream)
QFuture< void > filter(QThreadPool *pool, Sequence &sequence, KeepFunctor &&filterFunction)
QFuture< T > run(Function function,...)
QFuture< ArgsType< Signal > > connect(Sender *sender, Signal signal)
void visibleChanged(bool arg)
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Fri Oct 11 2024 12:09:36 by doxygen 1.12.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.