xref: /aosp_15_r20/external/angle/util/android/AndroidWindow.cpp (revision 8975f5c5ed3d1c378011245431ada316dfb6f244)
1 //
2 // Copyright 2016 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6 
7 // AndroidWindow.cpp: Implementation of OSWindow for Android
8 
9 #include "util/android/AndroidWindow.h"
10 
11 #include <pthread.h>
12 #include <filesystem>
13 #include <iostream>
14 
15 #include "common/debug.h"
16 #include "util/android/third_party/android_native_app_glue.h"
17 
18 namespace
19 {
20 struct android_app *sApp = nullptr;
21 pthread_mutex_t sInitWindowMutex;
22 pthread_cond_t sInitWindowCond;
23 bool sInitWindowDone = false;
24 JNIEnv *gJni         = nullptr;
25 
26 // SCREEN_ORIENTATION_LANDSCAPE and SCREEN_ORIENTATION_PORTRAIT are
27 // available from Android API level 1
28 // https://developer.android.com/reference/android/app/Activity#setRequestedOrientation(int)
29 const int kScreenOrientationLandscape = 0;
30 const int kScreenOrientationPortrait  = 1;
31 
GetJniEnv()32 JNIEnv *GetJniEnv()
33 {
34     if (gJni)
35         return gJni;
36 
37     sApp->activity->vm->AttachCurrentThread(&gJni, NULL);
38     return gJni;
39 }
40 
SetScreenOrientation(struct android_app * app,int orientation)41 int SetScreenOrientation(struct android_app *app, int orientation)
42 {
43     // Use reverse JNI to call the Java entry point that rotates the
44     // display to respect width and height
45     JNIEnv *jni = GetJniEnv();
46     if (!jni)
47     {
48         std::cerr << "Failed to get JNI env for screen rotation";
49         return JNI_ERR;
50     }
51 
52     jclass clazz       = jni->GetObjectClass(app->activity->clazz);
53     jmethodID methodID = jni->GetMethodID(clazz, "setRequestedOrientation", "(I)V");
54     jni->CallVoidMethod(app->activity->clazz, methodID, orientation);
55 
56     return 0;
57 }
58 }  // namespace
59 
AndroidWindow()60 AndroidWindow::AndroidWindow() {}
61 
~AndroidWindow()62 AndroidWindow::~AndroidWindow() {}
63 
initializeImpl(const std::string & name,int width,int height)64 bool AndroidWindow::initializeImpl(const std::string &name, int width, int height)
65 {
66     return resize(width, height);
67 }
destroy()68 void AndroidWindow::destroy() {}
69 
disableErrorMessageDialog()70 void AndroidWindow::disableErrorMessageDialog() {}
71 
resetNativeWindow()72 void AndroidWindow::resetNativeWindow() {}
73 
getNativeWindow() const74 EGLNativeWindowType AndroidWindow::getNativeWindow() const
75 {
76     // Return the entire Activity Surface for now
77     // sApp->window is valid only after sInitWindowDone, which is true after initializeImpl()
78     return sApp->window;
79 }
80 
getNativeDisplay() const81 EGLNativeDisplayType AndroidWindow::getNativeDisplay() const
82 {
83     return EGL_DEFAULT_DISPLAY;
84 }
85 
messageLoop()86 void AndroidWindow::messageLoop()
87 {
88     // TODO: accumulate events in the real message loop of android_main,
89     // and process them here
90 }
91 
setMousePosition(int x,int y)92 void AndroidWindow::setMousePosition(int x, int y)
93 {
94     UNIMPLEMENTED();
95 }
96 
setOrientation(int width,int height)97 bool AndroidWindow::setOrientation(int width, int height)
98 {
99     // Set tests to run in correct orientation
100     int32_t err = SetScreenOrientation(
101         sApp, (width > height) ? kScreenOrientationLandscape : kScreenOrientationPortrait);
102 
103     return err == 0;
104 }
setPosition(int x,int y)105 bool AndroidWindow::setPosition(int x, int y)
106 {
107     UNIMPLEMENTED();
108     return false;
109 }
110 
resize(int width,int height)111 bool AndroidWindow::resize(int width, int height)
112 {
113     mWidth  = width;
114     mHeight = height;
115 
116     // sApp->window used below is valid only after Activity Surface is created
117     pthread_mutex_lock(&sInitWindowMutex);
118     while (!sInitWindowDone)
119     {
120         pthread_cond_wait(&sInitWindowCond, &sInitWindowMutex);
121     }
122     pthread_mutex_unlock(&sInitWindowMutex);
123 
124     if (sApp->window == nullptr)
125     {
126         // Note: logging isn't initalized yet but this message shows up in logcat.
127         FATAL() << "Window is NULL (is screen locked? e.g. SplashScreen in logcat)";
128     }
129 
130     // TODO: figure out a way to set the format as well,
131     // which is available only after EGLWindow initialization
132     int32_t err = ANativeWindow_setBuffersGeometry(sApp->window, mWidth, mHeight, 0);
133     return err == 0;
134 }
135 
setVisible(bool isVisible)136 void AndroidWindow::setVisible(bool isVisible) {}
137 
signalTestEvent()138 void AndroidWindow::signalTestEvent()
139 {
140     UNIMPLEMENTED();
141 }
142 
onAppCmd(struct android_app * app,int32_t cmd)143 static void onAppCmd(struct android_app *app, int32_t cmd)
144 {
145     switch (cmd)
146     {
147         case APP_CMD_INIT_WINDOW:
148             pthread_mutex_lock(&sInitWindowMutex);
149             sInitWindowDone = true;
150             pthread_cond_broadcast(&sInitWindowCond);
151             pthread_mutex_unlock(&sInitWindowMutex);
152             break;
153         case APP_CMD_DESTROY:
154             if (gJni)
155             {
156                 sApp->activity->vm->DetachCurrentThread();
157             }
158             gJni = nullptr;
159             break;
160 
161             // TODO: process other commands and pass them to AndroidWindow for handling
162             // TODO: figure out how to handle APP_CMD_PAUSE,
163             // which should immediately halt all the rendering,
164             // since Activity Surface is no longer available.
165             // Currently tests crash when paused, for example, due to device changing orientation
166     }
167 }
168 
onInputEvent(struct android_app * app,AInputEvent * event)169 static int32_t onInputEvent(struct android_app *app, AInputEvent *event)
170 {
171     // TODO: Handle input events
172     return 0;  // 0 == not handled
173 }
174 
validPollResult(int result)175 static bool validPollResult(int result)
176 {
177     return result >= 0 || result == ALOOPER_POLL_CALLBACK;
178 }
179 
android_main(struct android_app * app)180 void android_main(struct android_app *app)
181 {
182     int events;
183     struct android_poll_source *source;
184 
185     sApp = app;
186     pthread_mutex_init(&sInitWindowMutex, nullptr);
187     pthread_cond_init(&sInitWindowCond, nullptr);
188 
189     // Event handlers, invoked from source->process()
190     app->onAppCmd     = onAppCmd;
191     app->onInputEvent = onInputEvent;
192 
193     // Message loop, polling for events indefinitely (due to -1 timeout)
194     // Must be here in order to handle APP_CMD_INIT_WINDOW event,
195     // which occurs after AndroidWindow::initializeImpl(), but before AndroidWindow::messageLoop
196     while (
197         validPollResult(ALooper_pollOnce(-1, nullptr, &events, reinterpret_cast<void **>(&source))))
198     {
199         if (source != nullptr)
200         {
201             source->process(app, source);
202         }
203     }
204 }
205 
GetApplicationDirectory()206 std::string AndroidWindow::GetApplicationDirectory()
207 {
208     // Use reverse JNI.
209     JNIEnv *jni = GetJniEnv();
210     if (!jni)
211     {
212         std::cerr << "GetApplicationDirectory:: Failed to get JNI env";
213         return "";
214     }
215 
216     // Get the ANativeActivity class
217     jclass nativeActivityClass = jni->GetObjectClass(sApp->activity->clazz);
218     if (!nativeActivityClass)
219     {
220         std::cerr << "GetApplicationDirectory: Failed to get ANativeActivity class";
221         return "";
222     }
223 
224     // Get the getApplicationContext() method ID
225     jmethodID getApplicationContextMethod = jni->GetMethodID(
226         nativeActivityClass, "getApplicationContext", "()Landroid/content/Context;");
227     if (!getApplicationContextMethod)
228     {
229         std::cerr << "GetApplicationDirectory: Failed to find getApplicationContext method";
230         return "";
231     }
232 
233     // Call getApplicationContext() to get the Context object
234     jobject context = jni->CallObjectMethod(sApp->activity->clazz, getApplicationContextMethod);
235     if (!context)
236     {
237         std::cerr << "GetApplicationDirectory: Failed to get Context object";
238         return "";
239     }
240 
241     // Get the Context class
242     jclass contextClass = jni->GetObjectClass(context);
243     if (!contextClass)
244     {
245         std::cerr << "GetApplicationDirectory: Failed to get Context class";
246         return "";
247     }
248 
249     // Get the getFilesDir() method ID
250     jmethodID getFilesDirMethod = jni->GetMethodID(contextClass, "getFilesDir", "()Ljava/io/File;");
251     if (!getFilesDirMethod)
252     {
253         std::cerr << "GetApplicationDirectory: Failed to find getFilesDir method";
254         return "";
255     }
256 
257     // Call getFilesDir() to get the File object
258     jobject fileObject = jni->CallObjectMethod(context, getFilesDirMethod);
259     if (!fileObject)
260     {
261         std::cerr << "GetApplicationDirectory: Failed to get File object";
262         return "";
263     }
264 
265     // Get the File class
266     jclass fileClass = jni->GetObjectClass(fileObject);
267     if (!fileClass)
268     {
269         std::cerr << "GetApplicationDirectory: Failed to get File class";
270         return "";
271     }
272 
273     // Get the getAbsolutePath() method ID
274     jmethodID getAbsolutePathMethod =
275         jni->GetMethodID(fileClass, "getAbsolutePath", "()Ljava/lang/String;");
276     if (!getAbsolutePathMethod)
277     {
278         std::cerr << "GetApplicationDirectory: Failed to find getAbsolutePath method";
279         return "";
280     }
281 
282     // Call getAbsolutePath() to get the path as a jstring
283     jstring pathString = (jstring)jni->CallObjectMethod(fileObject, getAbsolutePathMethod);
284     if (!pathString)
285     {
286         std::cerr << "GetApplicationDirectory: Failed to get path string";
287         return "";
288     }
289 
290     // Convert the jstring to a std::string
291     const char *pathChars = jni->GetStringUTFChars(pathString, nullptr);
292     std::string filesDirPath(pathChars);
293     jni->ReleaseStringUTFChars(pathString, pathChars);
294 
295     // Return the base directory, stripping "files" essentially
296     std::filesystem::path fullPath(filesDirPath);
297     return fullPath.parent_path();
298 }
299 
300 // static
GetExternalStorageDirectory()301 std::string AndroidWindow::GetExternalStorageDirectory()
302 {
303     // Use reverse JNI.
304     JNIEnv *jni = GetJniEnv();
305     if (!jni)
306     {
307         std::cerr << "GetExternalStorageDirectory:: Failed to get JNI env";
308         return "";
309     }
310 
311     jclass classEnvironment = jni->FindClass("android/os/Environment");
312     if (classEnvironment == 0)
313     {
314         std::cerr << "GetExternalStorageDirectory: Failed to find Environment";
315         return "";
316     }
317 
318     // public static File getExternalStorageDirectory ()
319     jmethodID methodIDgetExternalStorageDirectory =
320         jni->GetStaticMethodID(classEnvironment, "getExternalStorageDirectory", "()Ljava/io/File;");
321     if (methodIDgetExternalStorageDirectory == 0)
322     {
323         std::cerr << "GetExternalStorageDirectory: Failed to get static method";
324         return "";
325     }
326 
327     jobject objectFile =
328         jni->CallStaticObjectMethod(classEnvironment, methodIDgetExternalStorageDirectory);
329     jthrowable exception = jni->ExceptionOccurred();
330     if (exception != 0)
331     {
332         jni->ExceptionDescribe();
333         jni->ExceptionClear();
334         std::cerr << "GetExternalStorageDirectory: Failed because of exception";
335         return "";
336     }
337 
338     // Call method on File object to retrieve String object.
339     jclass classFile = jni->GetObjectClass(objectFile);
340     if (classEnvironment == 0)
341     {
342         std::cerr << "GetExternalStorageDirectory: Failed to find object class";
343         return "";
344     }
345 
346     jmethodID methodIDgetAbsolutePath =
347         jni->GetMethodID(classFile, "getAbsolutePath", "()Ljava/lang/String;");
348     if (methodIDgetAbsolutePath == 0)
349     {
350         std::cerr << "GetExternalStorageDirectory: Failed to get method ID";
351         return "";
352     }
353 
354     jstring stringPath =
355         static_cast<jstring>(jni->CallObjectMethod(objectFile, methodIDgetAbsolutePath));
356 
357     // TODO(jmadill): Find how to pass the root test directory to ANGLE. http://crbug.com/1097957
358 
359     // // https://stackoverflow.com/questions/12841240/android-pass-parameter-to-native-activity
360     // jclass clazz = jni->GetObjectClass(sApp->activity->clazz);
361     // if (clazz == 0)
362     // {
363     //     std::cerr << "GetExternalStorageDirectory: Bad activity";
364     //     return "";
365     // }
366 
367     // jmethodID giid = jni->GetMethodID(clazz, "getIntent", "()Landroid/content/Intent;");
368     // if (giid == 0)
369     // {
370     //     std::cerr << "GetExternalStorageDirectory: Could not find getIntent";
371     //     return "";
372     // }
373 
374     // jobject intent = jni->CallObjectMethod(sApp->activity->clazz, giid);
375     // if (intent == 0)
376     // {
377     //     std::cerr << "GetExternalStorageDirectory: Error calling getIntent";
378     //     return "";
379     // }
380 
381     // jclass icl = jni->GetObjectClass(intent);
382     // if (icl == 0)
383     // {
384     //     std::cerr << "GetExternalStorageDirectory: Error getting getIntent class";
385     //     return "";
386     // }
387 
388     // jmethodID gseid =
389     //     jni->GetMethodID(icl, "getStringExtra", "(Ljava/lang/String;)Ljava/lang/String;");
390     // if (gseid == 0)
391     // {
392     //     std::cerr << "GetExternalStorageDirectory: Could not find getStringExtra";
393     //     return "";
394     // }
395 
396     // jstring stringPath = static_cast<jstring>(jni->CallObjectMethod(
397     //     intent, gseid, jni->NewStringUTF("org.chromium.base.test.util.UrlUtils.RootDirectory")));
398     // if (stringPath != 0)
399     // {
400     //     const char *path = jni->GetStringUTFChars(stringPath, nullptr);
401     //     return std::string(path) + "/chromium_tests_root";
402     // }
403 
404     // jclass environment = jni->FindClass("org/chromium/base/test/util/UrlUtils");
405     // if (environment == 0)
406     // {
407     //     std::cerr << "GetExternalStorageDirectory: Failed to find Environment";
408     //     return "";
409     // }
410 
411     // jmethodID getDir =
412     //     jni->GetStaticMethodID(environment, "getIsolatedTestRoot", "()Ljava/lang/String;");
413     // if (getDir == 0)
414     // {
415     //     std::cerr << "GetExternalStorageDirectory: Failed to get static method";
416     //     return "";
417     // }
418 
419     // stringPath = static_cast<jstring>(jni->CallStaticObjectMethod(environment, getDir));
420 
421     exception = jni->ExceptionOccurred();
422     if (exception != 0)
423     {
424         jni->ExceptionDescribe();
425         jni->ExceptionClear();
426         std::cerr << "GetExternalStorageDirectory: Failed because of exception";
427         return "";
428     }
429 
430     const char *path = jni->GetStringUTFChars(stringPath, nullptr);
431     return std::string(path) + "/chromium_tests_root";
432 }
433 
434 // static
New()435 OSWindow *OSWindow::New()
436 {
437     // There should be only one live instance of AndroidWindow at a time,
438     // as there is only one Activity Surface behind it.
439     // Creating a new AndroidWindow each time works for ANGLETest,
440     // as it destroys an old window before creating a new one.
441     // TODO: use GLSurfaceView to support multiple windows
442     return new AndroidWindow();
443 }
444