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
QtSurface.java
Go to the documentation of this file.
1// Copyright (C) 2014 BogDan Vatra <bogdan@kde.org>
2// Copyright (C) 2026 The Qt Company Ltd.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4
5package org.qtproject.qt.android;
6
7import android.annotation.SuppressLint;
8import android.content.Context;
9import android.content.res.TypedArray;
10import android.graphics.PixelFormat;
11import android.graphics.Rect;
12import android.opengl.EGL14;
13import android.opengl.EGLConfig;
14import android.opengl.EGLContext;
15import android.opengl.EGLDisplay;
16import android.opengl.EGLSurface;
17import android.opengl.GLES20;
18import android.os.Build;
19import android.util.Log;
20import android.view.Surface;
21import android.view.SurfaceControl;
22import android.view.SurfaceHolder;
23import android.view.SurfaceView;
24
25@SuppressLint("ViewConstructor")
26class QtSurface extends SurfaceView implements SurfaceHolder.Callback2
27{
28 private final int m_format;
29 private final QtSurfaceInterface m_surfaceCallback;
30 private boolean m_backgroundPrimed = false;
31 private boolean m_primeUnconsumed = false;
32 private SurfaceControl m_renderControl;
33 private Surface m_renderSurface;
34
35 QtSurface(Context context, QtSurfaceInterface surfaceCallback, boolean onTop, int imageDepth)
36 {
37 super(context);
38 setFocusable(false);
39 setFocusableInTouchMode(false);
40 setZOrderMediaOverlay(onTop);
41 m_surfaceCallback = surfaceCallback;
42 m_format = imageDepth == 16 ? PixelFormat.RGB_565 : PixelFormat.RGBA_8888;
43 SurfaceHolder holder = getHolder();
44 holder.setFormat(m_format);
45 holder.addCallback(this);
46 }
47
49 public void surfaceCreated(SurfaceHolder holder)
50 {
51 // A shared producer must be primed before Qt gets the Surface. With a
52 // separate render Surface, priming follows the callback so Qt's own GPU
53 // setup starts without waiting for it.
54 final Rect frame = holder.getSurfaceFrame();
55 final boolean canPrime = frame != null && frame.width() > 0 && frame.height() > 0;
56 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && canPrime)
57 m_backgroundPrimed = paintBackgroundColor(holder.getSurface());
58 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
59 // The holder forcibly disconnects its queue when this view disappears.
60 final SurfaceControl control = new SurfaceControl.Builder()
61 .setName("QtSurface")
62 .setParent(getSurfaceControl())
63 .setBufferSize(Math.max(1, getWidth()), Math.max(1, getHeight()))
64 .setFormat(m_format)
65 .build();
66 try {
67 initializeRenderSurface(control, new Surface(control));
68 } catch (RuntimeException | Error failure) {
69 try {
70 control.release();
71 } catch (RuntimeException | Error cleanupFailure) {
72 failure.addSuppressed(cleanupFailure);
73 }
74 throw failure;
75 }
76 }
77 if (m_surfaceCallback != null)
78 m_surfaceCallback.onSurfaceCreated(
79 m_renderSurface != null ? m_renderSurface : holder.getSurface());
80 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && canPrime)
81 m_backgroundPrimed = m_primeUnconsumed = paintBackgroundColor(holder.getSurface());
82 }
83
84 private void initializeRenderSurface(SurfaceControl control, Surface surface)
85 {
86 try (SurfaceControl.Transaction transaction = new SurfaceControl.Transaction()) {
87 transaction.setVisibility(control, true).apply();
88 } catch (RuntimeException | Error failure) {
89 try {
90 surface.release();
91 } catch (RuntimeException | Error cleanupFailure) {
92 failure.addSuppressed(cleanupFailure);
93 }
94 throw failure;
95 }
96 m_renderControl = control;
97 m_renderSurface = surface;
98 }
99
100 @Override
101 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
102 {
103 if (m_renderControl != null) {
104 try (SurfaceControl.Transaction transaction = new SurfaceControl.Transaction()) {
105 transaction.setBufferSize(m_renderControl, width, height).apply();
106 }
107 }
108 // Only an independent holder can be primed after Qt has its producer.
109 if (!m_backgroundPrimed && m_renderSurface != null && width > 0 && height > 0)
110 m_backgroundPrimed = m_primeUnconsumed = paintBackgroundColor(holder.getSurface());
111 }
112
113 @Override
114 public void surfaceRedrawNeeded(SurfaceHolder holder)
115 {
116 // Only reached through the default surfaceRedrawNeededAsync().
117 }
118
119 @Override
120 public void surfaceRedrawNeededAsync(SurfaceHolder holder, Runnable drawingFinished)
121 {
122 // SurfaceView's redraw synchronization still consumes a holder buffer.
123 if (m_renderSurface != null) {
124 if (m_primeUnconsumed)
125 m_primeUnconsumed = false;
126 else
127 paintBackgroundColor(holder.getSurface());
128 }
129 if (m_surfaceCallback != null)
130 m_surfaceCallback.onSurfaceRedrawNeeded(drawingFinished);
131 else
132 drawingFinished.run();
133 }
134
135 @Override
136 public void surfaceDestroyed(SurfaceHolder holder)
137 {
138 // The next Surface has fresh buffers, so it needs its own prime.
139 m_backgroundPrimed = m_primeUnconsumed = false;
140 final Surface surface = m_renderSurface;
141 final SurfaceControl control = m_renderControl;
142 m_renderSurface = null;
143 m_renderControl = null;
144 final Runnable released = () -> {
145 if (surface != null)
146 surface.release();
147 if (control != null)
148 control.release();
149 };
150 Throwable detachFailure = null;
151 try {
152 if (control != null) {
153 try (SurfaceControl.Transaction transaction = new SurfaceControl.Transaction()) {
154 transaction.reparent(control, null).apply();
155 }
156 }
157 } catch (RuntimeException | Error failure) {
158 detachFailure = failure;
159 throw failure;
160 } finally {
161 try {
162 if (m_surfaceCallback != null)
163 m_surfaceCallback.onSurfaceDestroyed(released);
164 else
165 released.run();
166 } catch (RuntimeException | Error failure) {
167 if (detachFailure == null)
168 throw failure;
169 detachFailure.addSuppressed(failure);
170 }
171 }
172 }
173
174 // Fill one buffer with colorBackground to avoid a black flash. lockCanvas()
175 // would leave a producer connected and break Qt's eglCreateWindowSurface().
176 private boolean paintBackgroundColor(Surface surface)
177 {
178 if (surface == null || !surface.isValid()) {
179 Log.w(QtNative.QtTAG, "Cannot prime an invalid background Surface");
180 return false;
181 }
182
183 final EGLDisplay display = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);
184 if (display == EGL14.EGL_NO_DISPLAY)
185 return backgroundEglFailure("get display");
186
187 final int[] version = new int[2];
188 if (!EGL14.eglInitialize(display, version, 0, version, 1))
189 return backgroundEglFailure("initialize display");
190
191 final EGLConfig[] configs = new EGLConfig[1];
192 final int[] matching = new int[1];
193 final int[] configAttribs = {
194 EGL14.EGL_SURFACE_TYPE, EGL14.EGL_WINDOW_BIT,
195 EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT,
196 EGL14.EGL_RED_SIZE, 8,
197 EGL14.EGL_GREEN_SIZE, 8,
198 EGL14.EGL_BLUE_SIZE, 8,
199 EGL14.EGL_ALPHA_SIZE, 8,
200 EGL14.EGL_NONE
201 };
202
203 if (!EGL14.eglChooseConfig(display, configAttribs, 0, configs, 0, 1, matching, 0))
204 return backgroundEglFailure("choose config");
205
206 if (matching[0] == 0) {
207 Log.w(QtNative.QtTAG, "No EGL config for the background Surface");
208 return false;
209 }
210
211 final int[] contextAttribs = { EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, EGL14.EGL_NONE };
212 final EGLContext context = EGL14.eglCreateContext(display, configs[0],
213 EGL14.EGL_NO_CONTEXT, contextAttribs, 0);
214 if (context == EGL14.EGL_NO_CONTEXT)
215 return backgroundEglFailure("create context");
216
217 final EGLSurface eglSurface = EGL14.eglCreateWindowSurface(display, configs[0],
218 surface, new int[] { EGL14.EGL_NONE }, 0);
219 if (eglSurface == EGL14.EGL_NO_SURFACE) {
220 backgroundEglFailure("create window surface");
221 if (!EGL14.eglDestroyContext(display, context))
222 backgroundEglFailure("destroy context");
223 return false;
224 }
225
226 // Embedded hosts may already have an EGL context current on this thread.
227 final EGLDisplay previousDisplay = EGL14.eglGetCurrentDisplay();
228 final EGLContext previousContext = EGL14.eglGetCurrentContext();
229 final EGLSurface previousDraw = EGL14.eglGetCurrentSurface(EGL14.EGL_DRAW);
230 final EGLSurface previousRead = EGL14.eglGetCurrentSurface(EGL14.EGL_READ);
231 boolean madeCurrent = false;
232 try {
233 madeCurrent = EGL14.eglMakeCurrent(display, eglSurface, eglSurface, context);
234 if (!madeCurrent) {
235 Log.w(QtNative.QtTAG, "Cannot bind the background EGL context: 0x"
236 + Integer.toHexString(EGL14.eglGetError()));
237 return false;
238 }
239 final int color = resolveBackgroundColor();
240 GLES20.glClearColor(
241 ((color >> 16) & 0xff) / 255f,
242 ((color >> 8) & 0xff) / 255f,
243 (color & 0xff) / 255f,
244 ((color >>> 24) & 0xff) / 255f);
245 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
246 if (!EGL14.eglSwapBuffers(display, eglSurface)) {
247 Log.w(QtNative.QtTAG, "Cannot post the background EGL buffer: 0x"
248 + Integer.toHexString(EGL14.eglGetError()));
249 return false;
250 }
251 return true;
252 } finally {
253 if (madeCurrent) {
254 final EGLDisplay restoreDisplay = previousDisplay.equals(EGL14.EGL_NO_DISPLAY)
255 ? display : previousDisplay;
256 if (!EGL14.eglMakeCurrent(restoreDisplay, previousDraw,
257 previousRead, previousContext)) {
258 Log.w(QtNative.QtTAG, "Cannot restore the UI thread EGL binding: 0x"
259 + Integer.toHexString(EGL14.eglGetError()));
260 if (!EGL14.eglMakeCurrent(display, EGL14.EGL_NO_SURFACE,
261 EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT)) {
262 Log.w(QtNative.QtTAG, "Cannot release the background EGL binding: 0x"
263 + Integer.toHexString(EGL14.eglGetError()));
264 }
265 }
266 }
267 if (!EGL14.eglDestroySurface(display, eglSurface)) {
268 Log.w(QtNative.QtTAG, "Cannot destroy the background EGL surface: 0x"
269 + Integer.toHexString(EGL14.eglGetError()));
270 }
271 if (!EGL14.eglDestroyContext(display, context)) {
272 Log.w(QtNative.QtTAG, "Cannot destroy the background EGL context: 0x"
273 + Integer.toHexString(EGL14.eglGetError()));
274 }
275 }
276 }
277
278 private static boolean backgroundEglFailure(String operation)
279 {
280 Log.w(QtNative.QtTAG, "Cannot " + operation + " for the background EGL buffer: 0x"
281 + Integer.toHexString(EGL14.eglGetError()));
282 return false;
283 }
284
285 private int resolveBackgroundColor()
286 {
287 TypedArray typedArray = getContext().getTheme().obtainStyledAttributes(
288 new int[] {
289 android.R.attr.windowSplashScreenBackground,
290 android.R.attr.colorBackground
291 });
292 try {
293 // Android 12+ has an API for splash, so prefer that.
294 final int splash = typedArray.getColor(0, 0);
295 if ((splash >>> 24) != 0)
296 return splash | 0xff000000;
297 return typedArray.getColor(1, 0xff000000) | 0xff000000;
298 } finally {
299 typedArray.recycle();
300 }
301 }
302}
int width
the width of the widget excluding any window frame
Definition qwidget.h:114
int height
the height of the widget excluding any window frame
Definition qwidget.h:115
QPainter Context
struct wl_display * display
Definition linuxdmabuf.h:47
Napi::TypedArray TypedArray
Definition qnapi_p.h:74
QVideoFrameFormat::PixelFormat PixelFormat
typedef EGLSurface(EGLAPIENTRYP PFNEGLCREATESTREAMPRODUCERSURFACEKHRPROC)(EGLDisplay dpy
typedef EGLDisplay(EGLAPIENTRYP PFNEGLGETPLATFORMDISPLAYEXTPROC)(EGLenum platform
GLfloat GLfloat f
[26]
GLuint color
[setDefaultFactory]
GLint GLsizei width
EGLint EGLint EGLint format
QFrame frame
[0]
QSplashScreen * splash