Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qeglfscursor.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
9
10#include <qpa/qwindowsysteminterface.h>
11#include <QtGui/QOpenGLContext>
12#include <QtGui/QOpenGLFunctions>
13#include <QtCore/QFile>
14#include <QtCore/QJsonDocument>
15#include <QtCore/QJsonArray>
16#include <QtCore/QJsonObject>
17
18#include <QtGui/private/qguiapplication_p.h>
19#include <QtOpenGL/private/qopenglvertexarrayobject_p.h>
20
21#ifndef GL_VERTEX_ARRAY_BINDING
22#define GL_VERTEX_ARRAY_BINDING 0x85B5
23#endif
24
26
27using namespace Qt::StringLiterals;
28
29QEglFSCursor::QEglFSCursor(QPlatformScreen *screen)
30 : m_visible(true),
31 m_screen(static_cast<QEglFSScreen *>(screen)),
32 m_activeScreen(nullptr),
33 m_deviceListener(nullptr),
34 m_updateRequested(false)
35{
36 QByteArray hideCursorVal = qgetenv("QT_QPA_EGLFS_HIDECURSOR");
37 if (!hideCursorVal.isEmpty())
38 m_visible = hideCursorVal.toInt() == 0;
39 if (!m_visible)
40 return;
41
42 int rotation = qEnvironmentVariableIntValue("QT_QPA_EGLFS_ROTATION");
43 if (rotation)
44 m_rotationMatrix.rotate(rotation, 0, 0, 1);
45
46 // Try to load the cursor atlas. If this fails, m_visible is set to false and
47 // paintOnScreen() and setCurrentCursor() become no-ops.
48 initCursorAtlas();
49
50 // initialize the cursor
51#ifndef QT_NO_CURSOR
52 QCursor cursor(Qt::ArrowCursor);
53 setCurrentCursor(&cursor);
54#endif
55
56 m_deviceListener = new QEglFSCursorDeviceListener(this);
57 connect(QGuiApplicationPrivate::inputDeviceManager(), &QInputDeviceManager::deviceListChanged,
58 m_deviceListener, &QEglFSCursorDeviceListener::onDeviceListChanged);
59 updateMouseStatus();
60}
61
62QEglFSCursor::~QEglFSCursor()
63{
64 resetResources();
65 delete m_deviceListener;
66}
67
68void QEglFSCursor::updateMouseStatus()
69{
70 m_visible = m_deviceListener->hasMouse();
71}
72
73bool QEglFSCursorDeviceListener::hasMouse() const
74{
75 return QGuiApplicationPrivate::inputDeviceManager()->deviceCount(QInputDeviceManager::DeviceTypePointer) > 0;
76}
77
78void QEglFSCursorDeviceListener::onDeviceListChanged(QInputDeviceManager::DeviceType type)
79{
80 if (type == QInputDeviceManager::DeviceTypePointer)
81 m_cursor->updateMouseStatus();
82}
83
84void QEglFSCursor::resetResources()
85{
86 m_cursor.customCursorPending = !m_cursor.customCursorImage.isNull();
87}
88
89void QEglFSCursor::createShaderPrograms()
90{
91 static const char *textureVertexProgram =
92 "attribute highp vec2 vertexCoordEntry;\n"
93 "attribute highp vec2 textureCoordEntry;\n"
94 "varying highp vec2 textureCoord;\n"
95 "uniform highp mat4 mat;\n"
96 "void main() {\n"
97 " textureCoord = textureCoordEntry;\n"
98 " gl_Position = mat * vec4(vertexCoordEntry, 1.0, 1.0);\n"
99 "}\n";
100
101 static const char *textureFragmentProgram =
102 "uniform sampler2D texture;\n"
103 "varying highp vec2 textureCoord;\n"
104 "void main() {\n"
105 " gl_FragColor = texture2D(texture, textureCoord).bgra;\n"
106 "}\n";
107
108 QEglFSCursorData &gfx = static_cast<QEglFSContext*>(QOpenGLContext::currentContext()->handle())->cursorData;
109 gfx.program.reset(new QOpenGLShaderProgram);
110 gfx.program->addCacheableShaderFromSourceCode(QOpenGLShader::Vertex, textureVertexProgram);
111 gfx.program->addCacheableShaderFromSourceCode(QOpenGLShader::Fragment, textureFragmentProgram);
112 gfx.program->bindAttributeLocation("vertexCoordEntry", 0);
113 gfx.program->bindAttributeLocation("textureCoordEntry", 1);
114 gfx.program->link();
115
116 gfx.textureEntry = gfx.program->uniformLocation("texture");
117 gfx.matEntry = gfx.program->uniformLocation("mat");
118}
119
120void QEglFSCursor::createCursorTexture(uint *texture, const QImage &image)
121{
122 Q_ASSERT(QOpenGLContext::currentContext());
123 QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions();
124 if (!*texture)
125 f->glGenTextures(1, texture);
126 f->glBindTexture(GL_TEXTURE_2D, *texture);
127 f->glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
128 f->glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
129 f->glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
130 f->glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
131
132 f->glTexImage2D(GL_TEXTURE_2D, 0 /* level */, GL_RGBA, image.width(), image.height(), 0 /* border */,
133 GL_RGBA, GL_UNSIGNED_BYTE, image.constBits());
134}
135
136void QEglFSCursor::initCursorAtlas()
137{
138 static QByteArray json = qgetenv("QT_QPA_EGLFS_CURSOR");
139 if (json.isEmpty())
140 json = ":/cursor.json";
141
142 QFile file(QString::fromUtf8(json));
143 if (!file.open(QFile::ReadOnly)) {
144 m_visible = false;
145 return;
146 }
147
148 QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
149 QJsonObject object = doc.object();
150
151 const QString atlas = object.value("image"_L1).toString();
152 const int cursorsPerRow = object.value("cursorsPerRow"_L1).toInt();
153 const QJsonArray hotSpots = object.value("hotSpots"_L1).toArray();
154
155 if (atlas.isEmpty() || cursorsPerRow <= 0 || cursorsPerRow > Qt::LastCursor + 1
156 || hotSpots.count() != Qt::LastCursor + 1)
157 {
158 qWarning("Invalid cursor atlas '%s', disabling the cursor. Expected a non-empty "
159 "'image', a 'cursorsPerRow' between 1 and %d, and %d 'hotSpots' entries.",
160 json.constData(), Qt::LastCursor + 1, Qt::LastCursor + 1);
161 m_visible = false;
162 return;
163 }
164
165 m_cursorAtlas.cursorsPerRow = cursorsPerRow;
166
167 for (int i = 0; i < hotSpots.count(); i++) {
168 QPoint hotSpot(hotSpots[i].toArray()[0].toDouble(), hotSpots[i].toArray()[1].toDouble());
169 m_cursorAtlas.hotSpots << hotSpot;
170 }
171
172 QImage image = QImage(atlas).convertToFormat(QImage::Format_ARGB32_Premultiplied);
173 if (image.isNull()) {
174 qWarning("Failed to load cursor atlas image '%s', disabling the cursor",
175 qPrintable(atlas));
176 m_visible = false;
177 return;
178 }
179
180 m_cursorAtlas.cursorWidth = image.width() / m_cursorAtlas.cursorsPerRow;
181 m_cursorAtlas.cursorHeight = image.height() / ((Qt::LastCursor + cursorsPerRow) / cursorsPerRow);
182 m_cursorAtlas.width = image.width();
183 m_cursorAtlas.height = image.height();
184 m_cursorAtlas.image = image;
185}
186
187#ifndef QT_NO_CURSOR
188void QEglFSCursor::changeCursor(QCursor *cursor, QWindow *window)
189{
190 Q_UNUSED(window);
191 const QRect oldCursorRect = cursorRect();
192 if (setCurrentCursor(cursor))
193 update(oldCursorRect | cursorRect(), false);
194}
195
196bool QEglFSCursor::setCurrentCursor(QCursor *cursor)
197{
198 if (!m_visible)
199 return false;
200
201 const Qt::CursorShape newShape = cursor ? cursor->shape() : Qt::ArrowCursor;
202 if (m_cursor.shape == newShape && newShape != Qt::BitmapCursor)
203 return false;
204
205 if (m_cursor.shape == Qt::BitmapCursor) {
206 m_cursor.customCursorImage = QImage();
207 m_cursor.customCursorPending = false;
208 }
209 m_cursor.shape = newShape;
210 if (newShape != Qt::BitmapCursor) { // standard cursor
211 const float ws = (float)m_cursorAtlas.cursorWidth / m_cursorAtlas.width,
212 hs = (float)m_cursorAtlas.cursorHeight / m_cursorAtlas.height;
213 m_cursor.textureRect = QRectF(ws * (m_cursor.shape % m_cursorAtlas.cursorsPerRow),
214 hs * (m_cursor.shape / m_cursorAtlas.cursorsPerRow),
215 ws, hs);
216 m_cursor.hotSpot = m_cursorAtlas.hotSpots[m_cursor.shape];
217 m_cursor.useCustomCursor = false;
218 m_cursor.size = QSize(m_cursorAtlas.cursorWidth, m_cursorAtlas.cursorHeight);
219 } else {
220 QImage image = cursor->pixmap().toImage();
221 m_cursor.textureRect = QRectF(0, 0, 1, 1);
222 m_cursor.hotSpot = cursor->hotSpot();
223 m_cursor.useCustomCursor = false; // will get updated in the next render()
224 m_cursor.size = image.size();
225 m_cursor.customCursorImage = image;
226 m_cursor.customCursorPending = true;
227 m_cursor.customCursorKey = m_cursor.customCursorImage.cacheKey();
228 }
229
230 return true;
231}
232#endif
233
235{
236public:
237 CursorUpdateEvent(const QPoint &pos, const QRect &rect, bool allScreens)
238 : QEvent(QEvent::Type(QEvent::User + 1)),
239 m_pos(pos),
240 m_rect(rect),
241 m_allScreens(allScreens)
242 { }
243 QPoint pos() const { return m_pos; }
244 QRegion rect() const { return m_rect; }
245 bool allScreens() const { return m_allScreens; }
246
247private:
248 QPoint m_pos;
249 QRect m_rect;
250 bool m_allScreens;
251};
252
253bool QEglFSCursor::event(QEvent *e)
254{
255 if (e->type() == QEvent::User + 1) {
256 CursorUpdateEvent *ev = static_cast<CursorUpdateEvent *>(e);
257 m_updateRequested = false;
258 if (!ev->allScreens()) {
259 QWindow *w = m_screen->topLevelAt(ev->pos()); // works for the entire virtual desktop, no need to loop
260 if (w) {
261 QWindowSystemInterface::handleExposeEvent(w, ev->rect());
262 QWindowSystemInterface::flushWindowSystemEvents(QEventLoop::ExcludeUserInputEvents);
263 }
264 } else {
265 const auto windows = qGuiApp->topLevelWindows();
266 for (QWindow *w : windows)
267 QWindowSystemInterface::handleExposeEvent(w, w->geometry());
268 QWindowSystemInterface::flushWindowSystemEvents(QEventLoop::ExcludeUserInputEvents);
269 }
270 return true;
271 }
272 return QPlatformCursor::event(e);
273}
274
275void QEglFSCursor::update(const QRect &rect, bool allScreens)
276{
277 if (!m_updateRequested) {
278 // Must not flush the window system events directly from here since we are likely to
279 // be a called directly from QGuiApplication's processMouseEvents. Flushing events
280 // could cause reentering by dispatching more queued mouse events.
281 m_updateRequested = true;
282 QCoreApplication::postEvent(this, new CursorUpdateEvent(m_cursor.pos, rect, allScreens));
283 }
284}
285
286QRect QEglFSCursor::cursorRect() const
287{
288 return QRect(m_cursor.pos - m_cursor.hotSpot, m_cursor.size);
289}
290
291QPoint QEglFSCursor::pos() const
292{
293 return m_cursor.pos;
294}
295
296void QEglFSCursor::setPos(const QPoint &pos)
297{
298 QGuiApplicationPrivate::inputDeviceManager()->setCursorPos(pos);
299 const QRect oldCursorRect = cursorRect();
300 m_cursor.pos = pos;
301 update(oldCursorRect | cursorRect(), false);
302 const auto siblings = m_screen->virtualSiblings();
303 for (QPlatformScreen *screen : siblings)
304 static_cast<QEglFSScreen *>(screen)->handleCursorMove(m_cursor.pos);
305}
306
307void QEglFSCursor::pointerEvent(const QMouseEvent &event)
308{
309 if (event.type() != QEvent::MouseMove)
310 return;
311 const QRect oldCursorRect = cursorRect();
312 m_cursor.pos = event.globalPosition().toPoint();
313 update(oldCursorRect | cursorRect(), false);
314 const auto siblings = m_screen->virtualSiblings();
315 for (QPlatformScreen *screen : siblings)
316 static_cast<QEglFSScreen *>(screen)->handleCursorMove(m_cursor.pos);
317}
318
319void QEglFSCursor::paintOnScreen()
320{
321 if (!m_visible)
322 return;
323
324 // cr must be a QRectF, otherwise cr.right() and bottom() would be off by
325 // one in the calculations below.
326 QRectF cr = cursorRect(); // hotspot included
327
328 // Support virtual desktop too. Backends with multi-screen support (e.g. all
329 // variants of KMS/DRM) will enable this by default. In this case all
330 // screens are siblings of each other. When not enabled, the sibling list
331 // only contains m_screen itself.
332 const auto siblings = m_screen->virtualSiblings();
333 for (QPlatformScreen *screen : siblings) {
334 if (screen->geometry().contains(cr.topLeft().toPoint() + m_cursor.hotSpot))
335 {
336 cr.translate(-screen->geometry().topLeft());
337 const QSize screenSize = screen->geometry().size();
338 const GLfloat x1 = 2 * (cr.left() / GLfloat(screenSize.width())) - 1;
339 const GLfloat x2 = 2 * (cr.right() / GLfloat(screenSize.width())) - 1;
340 const GLfloat y1 = 1 - (cr.top() / GLfloat(screenSize.height())) * 2;
341 const GLfloat y2 = 1 - (cr.bottom() / GLfloat(screenSize.height())) * 2;
342 QRectF r(QPointF(x1, y1), QPointF(x2, y2));
343
344 draw(r);
345
346 if (screen != m_activeScreen) {
347 m_activeScreen = screen;
348 // Do not want a leftover cursor on the screen the cursor just left.
349 update(cursorRect(), true);
350 }
351
352 break;
353 }
354 }
355}
356
357// In order to prevent breaking code doing custom OpenGL rendering while
358// expecting the state in the context unchanged, save and restore all the state
359// we touch. The exception is Qt Quick where the scenegraph is known to be able
360// to deal with the changes we make.
362{
363 StateSaver(QOpenGLFunctions* func) {
364 f = func;
365 vaoHelper = QOpenGLVertexArrayObjectHelper::vertexArrayObjectHelperForContext(QOpenGLContext::currentContext());
366
367 static bool windowsChecked = false;
368 static bool shouldSave = true;
369 if (!windowsChecked) {
370 windowsChecked = true;
371 QWindowList windows = QGuiApplication::allWindows();
372 if (!windows.isEmpty() && windows[0]->inherits("QQuickWindow"))
373 shouldSave = false;
374 }
375 saved = shouldSave;
376 if (!shouldSave)
377 return;
378
379 f->glGetIntegerv(GL_CURRENT_PROGRAM, &program);
380 f->glGetIntegerv(GL_TEXTURE_BINDING_2D, &texture);
381 f->glGetIntegerv(GL_ACTIVE_TEXTURE, &activeTexture);
382 f->glGetIntegerv(GL_FRONT_FACE, &frontFace);
383 cull = f->glIsEnabled(GL_CULL_FACE);
384 depthTest = f->glIsEnabled(GL_DEPTH_TEST);
385 blend = f->glIsEnabled(GL_BLEND);
386 f->glGetIntegerv(GL_BLEND_SRC_RGB, blendFunc);
387 f->glGetIntegerv(GL_BLEND_SRC_ALPHA, blendFunc + 1);
388 f->glGetIntegerv(GL_BLEND_DST_RGB, blendFunc + 2);
389 f->glGetIntegerv(GL_BLEND_DST_ALPHA, blendFunc + 3);
390 scissor = f->glIsEnabled(GL_SCISSOR_TEST);
391 stencil = f->glIsEnabled(GL_STENCIL_TEST);
392 f->glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &arrayBuf);
393 if (vaoHelper->isValid())
394 f->glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &vao);
395 else
396 vao = 0;
397 for (int i = 0; i < 2; ++i) {
398 f->glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &va[i].enabled);
399 f->glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_SIZE, &va[i].size);
400 f->glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_TYPE, &va[i].type);
401 f->glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &va[i].normalized);
402 f->glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &va[i].stride);
403 f->glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, &va[i].buffer);
404 f->glGetVertexAttribPointerv(i, GL_VERTEX_ATTRIB_ARRAY_POINTER, &va[i].pointer);
405 }
406 }
408 if (saved) {
409 f->glUseProgram(program);
410 f->glBindTexture(GL_TEXTURE_2D, texture);
411 f->glActiveTexture(activeTexture);
412 f->glFrontFace(frontFace);
413 if (cull)
414 f->glEnable(GL_CULL_FACE);
415 if (depthTest)
416 f->glEnable(GL_DEPTH_TEST);
417 if (!blend)
418 f->glDisable(GL_BLEND);
419 f->glBlendFuncSeparate(blendFunc[0], blendFunc[1], blendFunc[2], blendFunc[3]);
420 if (scissor)
421 f->glEnable(GL_SCISSOR_TEST);
422 if (stencil)
423 f->glEnable(GL_STENCIL_TEST);
424 f->glBindBuffer(GL_ARRAY_BUFFER, arrayBuf);
425 if (vaoHelper->isValid())
426 vaoHelper->glBindVertexArray(vao);
427 for (int i = 0; i < 2; ++i) {
428 if (va[i].enabled)
429 f->glEnableVertexAttribArray(i);
430 else
431 f->glDisableVertexAttribArray(i);
432 f->glBindBuffer(GL_ARRAY_BUFFER, va[i].buffer);
433 f->glVertexAttribPointer(i, va[i].size, va[i].type, va[i].normalized, va[i].stride, va[i].pointer);
434 }
435 }
436 }
439 bool saved;
444 bool cull;
446 bool blend;
453};
454
455void QEglFSCursor::draw(const QRectF &r)
456{
457 Q_ASSERT(QOpenGLContext::currentContext());
458 QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions();
459 StateSaver stateSaver(f);
460
461 QEglFSCursorData &gfx = static_cast<QEglFSContext*>(QOpenGLContext::currentContext()->handle())->cursorData;
462 if (!gfx.program) {
463 createShaderPrograms();
464
465 if (!gfx.atlasTexture) {
466 createCursorTexture(&gfx.atlasTexture, m_cursorAtlas.image);
467
468 if (m_cursor.shape != Qt::BitmapCursor)
469 m_cursor.useCustomCursor = false;
470 }
471 }
472
473 if (m_cursor.shape == Qt::BitmapCursor && (m_cursor.customCursorPending || m_cursor.customCursorKey != gfx.customCursorKey)) {
474 // upload the custom cursor
475 createCursorTexture(&gfx.customCursorTexture, m_cursor.customCursorImage);
476 m_cursor.useCustomCursor = true;
477 m_cursor.customCursorPending = false;
478 gfx.customCursorKey = m_cursor.customCursorKey;
479 }
480
481 GLuint cursorTexture = !m_cursor.useCustomCursor ? gfx.atlasTexture : gfx.customCursorTexture;
482 Q_ASSERT(cursorTexture);
483
484 gfx.program->bind();
485
486 const GLfloat x1 = r.left();
487 const GLfloat x2 = r.right();
488 const GLfloat y1 = r.top();
489 const GLfloat y2 = r.bottom();
490 const GLfloat cursorCoordinates[] = {
491 x1, y2,
492 x2, y2,
493 x1, y1,
494 x2, y1
495 };
496
497 const GLfloat s1 = m_cursor.textureRect.left();
498 const GLfloat s2 = m_cursor.textureRect.right();
499 const GLfloat t1 = m_cursor.textureRect.top();
500 const GLfloat t2 = m_cursor.textureRect.bottom();
501 const GLfloat textureCoordinates[] = {
502 s1, t2,
503 s2, t2,
504 s1, t1,
505 s2, t1
506 };
507
508 f->glActiveTexture(GL_TEXTURE0);
509 f->glBindTexture(GL_TEXTURE_2D, cursorTexture);
510
511 if (stateSaver.vaoHelper->isValid())
512 stateSaver.vaoHelper->glBindVertexArray(0);
513
514 f->glBindBuffer(GL_ARRAY_BUFFER, 0);
515
516 gfx.program->enableAttributeArray(0);
517 gfx.program->enableAttributeArray(1);
518 gfx.program->setAttributeArray(0, cursorCoordinates, 2);
519 gfx.program->setAttributeArray(1, textureCoordinates, 2);
520
521 gfx.program->setUniformValue(gfx.textureEntry, 0);
522 gfx.program->setUniformValue(gfx.matEntry, m_rotationMatrix);
523
524 f->glDisable(GL_CULL_FACE);
525 f->glFrontFace(GL_CCW);
526 f->glEnable(GL_BLEND);
527 f->glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
528 f->glDisable(GL_DEPTH_TEST); // disable depth testing to make sure cursor is always on top
529 f->glDisable(GL_SCISSOR_TEST);
530 f->glDisable(GL_STENCIL_TEST);
531
532 f->glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
533
534 gfx.program->disableAttributeArray(0);
535 gfx.program->disableAttributeArray(1);
536 gfx.program->release();
537}
538
539QT_END_NAMESPACE
540
541#include "moc_qeglfscursor_p.cpp"
CursorUpdateEvent(const QPoint &pos, const QRect &rect, bool allScreens)
QPoint pos() const
QRegion rect() const
bool allScreens() const
Combined button and popup list for selecting options.
#define GL_VERTEX_ARRAY_BINDING
GLvoid * pointer
StateSaver(QOpenGLFunctions *func)
QOpenGLFunctions * f
QOpenGLVertexArrayObjectHelper * vaoHelper
GLint activeTexture
GLint blendFunc[4]