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
androidjnimain.cpp
Go to the documentation of this file.
1// Copyright (C) 2014 BogDan Vatra <bogdan@kde.org>
2// Copyright (C) 2022 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
5#include <dlfcn.h>
6#include <pthread.h>
7#include <qplugin.h>
8#include <semaphore.h>
9
13#include "androidjnimain.h"
14#include "androidjnimenu.h"
20#if QT_CONFIG(clipboard)
21#include "qandroidplatformclipboard.h"
22#endif
23#if QT_CONFIG(accessibility)
24#include "androidjniaccessibility.h"
25#endif
28
29#include <android/api-level.h>
30#include <android/asset_manager_jni.h>
31#include <android/bitmap.h>
32
33#include <QtCore/private/qjnihelpers_p.h>
34#include <QtCore/qbasicatomic.h>
35#include <QtCore/qjnienvironment.h>
36#include <QtCore/qjniobject.h>
37#include <QtCore/qprocess.h>
38#include <QtCore/qresource.h>
39#include <QtCore/qscopeguard.h>
40#include <QtCore/qthread.h>
41#include <QtCore/private/qandroiditemmodelproxy_p.h>
42#include <QtCore/private/qandroidmodelindexproxy_p.h>
43#include <QtGui/private/qguiapplication_p.h>
44#include <QtGui/private/qhighdpiscaling_p.h>
45
46#include <qpa/qwindowsysteminterface.h>
47
48
49using namespace Qt::StringLiterals;
50
51QT_BEGIN_NAMESPACE
52
53static jclass m_applicationClass = nullptr;
54static AAssetManager *m_assetManager = nullptr;
55static jobject m_assets = nullptr;
56static jobject m_resourcesObj = nullptr;
57
58static jclass m_qtActivityClass = nullptr;
59static jclass m_qtServiceClass = nullptr;
60
62static QBasicMutex m_platformMutex;
63
64static jclass m_bitmapClass = nullptr;
68
71
72extern "C" typedef int (*Main)(int, char **); //use the standard main method to start the application
73static Main m_main = nullptr;
75
77
78static double m_density = 1.0;
79
83
85
86static const char m_qtTag[] = "Qt";
87static const char m_classErrorMsg[] = "Can't find class \"%s\"";
88static const char m_methodErrorMsg[] = "Can't find method \"%s%s\"";
89
90Q_CONSTINIT static QBasicAtomicInt startQtAndroidPluginCalled = Q_BASIC_ATOMIC_INITIALIZER(0);
91
92#if QT_CONFIG(accessibility)
93Q_DECLARE_JNI_CLASS(QtAccessibilityInterface, "org/qtproject/qt/android/QtAccessibilityInterface");
94#endif
95
96Q_DECLARE_JNI_CLASS(QtThread, "org/qtproject/qt/android/QtThread");
97
98namespace QtAndroid
99{
101 {
102 return &m_platformMutex;
103 }
104
106 {
107 m_androidPlatformIntegration = androidPlatformIntegration;
109
110 // flush the pending state if necessary.
112 if (m_pendingApplicationState == Qt::ApplicationActive)
113 QtAndroidPrivate::handleResume();
114 else if (m_pendingApplicationState == Qt::ApplicationInactive)
115 QtAndroidPrivate::handlePause();
116 QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationState(m_pendingApplicationState));
117 }
118
120 }
121
126
127 QWindow *topLevelWindowAt(const QPoint &globalPos)
128 {
131 : 0;
132 }
133
134 QWindow *windowFromId(int windowId)
135 {
136 if (!qGuiApp)
137 return nullptr;
138
139 for (QWindow *w : qGuiApp->allWindows()) {
140 if (!w->handle())
141 continue;
142 QAndroidPlatformWindow *window = static_cast<QAndroidPlatformWindow *>(w->handle());
143 if (window->nativeViewId() == windowId)
144 return w;
145 }
146 return nullptr;
147 }
148
150 {
151 return m_density;
152 }
153
155 {
156 return m_assetManager;
157 }
158
160 {
161 return m_applicationClass;
162 }
163
165 {
166 // Returns true if the app is a Qt app, i.e. Qt controls the whole app and
167 // the Activity/Service is created by Qt. Returns false if instead Qt is
168 // embedded into a native Android app, where the Activity/Service is created
169 // by the user, outside of Qt, and Qt content is added as a view.
170 JNIEnv *env = QJniEnvironment::getJniEnv();
171 auto activity = QtAndroidPrivate::activity();
172 if (activity.isValid())
173 return env->IsInstanceOf(activity.object(), m_qtActivityClass);
174 auto service = QtAndroidPrivate::service();
175 if (service.isValid())
176 return env->IsInstanceOf(QtAndroidPrivate::service().object(), m_qtServiceClass);
177 // return true as default as Qt application is our default use case.
178 // famous last words: we should not end up here
179 return true;
180 }
181
182#if QT_CONFIG(accessibility)
184 {
186 "notifyLocationChange", accessibilityObjectId);
187 }
188
190 {
192 "notifyObjectHide", accessibilityObjectId, parentObjectId);
193 }
194
196 {
198 "notifyObjectShow", parentObjectId);
199 }
200
202 {
204 "notifyObjectFocus", accessibilityObjectId);
205 }
206
208 {
210 "notifyValueChanged", accessibilityObjectId, value);
211 }
212
214 {
216 "notifyDescriptionOrNameChanged", accessibilityObjectId, value);
217 }
218
220 {
222 "notifyScrolledEvent", accessibilityObjectId);
223 }
224
226 {
228 "notifyAnnouncementEvent", accessibilityObjectId, message);
229 }
230#endif //QT_CONFIG(accessibility)
231
233 {
234 QJniObject::callStaticMethod<void>(m_applicationClass,
235 "notifyNativePluginIntegrationReady",
236 ready);
237 }
238
239 jobject createBitmap(QImage img, JNIEnv *env)
240 {
241 if (!m_bitmapClass)
242 return 0;
243
244 if (img.format() != QImage::Format_RGBA8888 && img.format() != QImage::Format_RGB16)
245 img = std::move(img).convertToFormat(QImage::Format_RGBA8888);
246
247 jobject bitmap = env->CallStaticObjectMethod(m_bitmapClass,
248 m_createBitmapMethodID,
249 img.width(),
250 img.height(),
251 img.format() == QImage::Format_RGBA8888
252 ? m_ARGB_8888_BitmapConfigValue
253 : m_RGB_565_BitmapConfigValue);
254 if (!bitmap)
255 return 0;
256
257 AndroidBitmapInfo info;
258 if (AndroidBitmap_getInfo(env, bitmap, &info) < 0) {
259 env->DeleteLocalRef(bitmap);
260 return 0;
261 }
262
263 void *pixels;
264 if (AndroidBitmap_lockPixels(env, bitmap, &pixels) < 0) {
265 env->DeleteLocalRef(bitmap);
266 return 0;
267 }
268
269 if (info.stride == uint(img.bytesPerLine())
270 && info.width == uint(img.width())
271 && info.height == uint(img.height())) {
272 memcpy(pixels, img.constBits(), info.stride * info.height);
273 } else {
274 uchar *bmpPtr = static_cast<uchar *>(pixels);
275 const unsigned width = qMin(info.width, (uint)img.width()); //should be the same
276 const unsigned height = qMin(info.height, (uint)img.height()); //should be the same
277 for (unsigned y = 0; y < height; y++, bmpPtr += info.stride)
278 memcpy(bmpPtr, img.constScanLine(y), width);
279 }
280 AndroidBitmap_unlockPixels(env, bitmap);
281 return bitmap;
282 }
283
284 jobject createBitmap(int width, int height, QImage::Format format, JNIEnv *env)
285 {
286 if (format != QImage::Format_RGBA8888
287 && format != QImage::Format_RGB16)
288 return 0;
289
290 return env->CallStaticObjectMethod(m_bitmapClass,
291 m_createBitmapMethodID,
292 width,
293 height,
294 format == QImage::Format_RGB16
295 ? m_RGB_565_BitmapConfigValue
296 : m_ARGB_8888_BitmapConfigValue);
297 }
298
299 jobject createBitmapDrawable(jobject bitmap, JNIEnv *env)
300 {
301 if (!bitmap || !m_bitmapDrawableClass || !m_resourcesObj)
302 return 0;
303
304 return env->NewObject(m_bitmapDrawableClass,
305 m_bitmapDrawableConstructorMethodID,
306 m_resourcesObj,
307 bitmap);
308 }
309
310 const char *classErrorMsgFmt()
311 {
312 return m_classErrorMsg;
313 }
314
315 const char *methodErrorMsgFmt()
316 {
317 return m_methodErrorMsg;
318 }
319
320 const char *qtTagText()
321 {
322 return m_qtTag;
323 }
324
325 QString deviceName()
326 {
327 QString manufacturer = QJniObject::getStaticObjectField("android/os/Build", "MANUFACTURER", "Ljava/lang/String;").toString();
328 QString model = QJniObject::getStaticObjectField("android/os/Build", "MODEL", "Ljava/lang/String;").toString();
329
330 return manufacturer + u' ' + model;
331 }
332
333 void setViewVisibility(jobject view, bool visible)
334 {
335 QJniObject::callStaticMethod<void>(m_applicationClass,
336 "setViewVisibility",
337 "(Landroid/view/View;Z)V",
338 view,
339 visible);
340 }
341
343 {
344 static bool block = qEnvironmentVariableIntValue("QT_BLOCK_EVENT_LOOPS_WHEN_SUSPENDED");
345 return block;
346 }
347
349 {
350 return m_assets;
351 }
352
357
358} // namespace QtAndroid
359
360static bool initJavaReferences(QJniEnvironment &env);
361
371
373{
374 return sem_init(&m_exitSemaphore, 0, 0) != -1
375 && sem_init(&m_stopQtSemaphore, 0, 0) != -1;
376}
377
378static void startQtNativeApplication(JNIEnv *jenv, jobject object, jstring paramsString)
379{
380 Q_UNUSED(jenv)
381 Q_UNUSED(object)
382
383 {
384 JNIEnv* env = nullptr;
385 JavaVMAttachArgs args;
386 args.version = JNI_VERSION_1_6;
387 args.name = "QtMainThread";
388 args.group = NULL;
389 JavaVM *vm = QJniEnvironment::javaVM();
390 if (vm)
391 vm->AttachCurrentThread(&env, &args);
392 }
393
394 // Init all the Java refs, if they haven't already been initialized. They get initialized
395 // when the library is loaded, but in case Qt is terminated, they are cleared, and in case
396 // Qt is then started again JNI_OnLoad will not be called again, since the library is already
397 // loaded - in that case we need to init again here, hence the check.
398 // TODO QTBUG-130614 QtCore also inits some Java references in qjnihelpers - we probably
399 // want to reset those, too.
400 QJniEnvironment qEnv;
401 if (!qEnv.isValid()) {
402 qCritical() << "Failed to initialize the JNI Environment";
403 return;
404 }
405 if (!initJavaReferences(qEnv))
406 return;
407
410
411 const QStringList argsList = QProcess::splitCommand(QJniObject(paramsString).toString());
412 const int argc = argsList.size();
413 QVarLengthArray<char *> argv(argc + 1);
414 QList<QByteArray> argvData;
415 argvData.reserve(argc);
416 for (int i = 0; i < argc; ++i) {
417 argvData.append(argsList.at(i).toUtf8());
418 argv[i] = argvData.back().data();
419 }
420 argv[argc] = nullptr;
421
422 // Go home
423 QDir::setCurrent(QDir::homePath());
424
425 // look for main()
426 void *mainLibraryHnd = nullptr;
427 if (argc) {
428 // Obtain a handle to the main library (the library that contains the main() function).
429 // This library should already be loaded, and calling dlopen() will just return a reference to it.
430 mainLibraryHnd = dlopen(argv.first(), 0);
431 if (Q_UNLIKELY(!mainLibraryHnd)) {
432 qCritical() << "dlopen failed:" << dlerror();
433 return;
434 }
435 m_main = (Main)dlsym(mainLibraryHnd, "main");
436 } else {
437 qWarning("No main library was specified; searching entire process (this is slow!)");
438 m_main = (Main)dlsym(RTLD_DEFAULT, "main");
439 }
440
441 if (Q_UNLIKELY(!m_main)) {
442 qCritical() << "dlsym failed:" << dlerror() << Qt::endl
443 << "Could not find main method";
444 return;
445 }
446
448 qCritical() << "Failed to init Qt application cleanup semaphores";
449 return;
450 }
451
452 // Register type for invokeMethod() calls.
453 qRegisterMetaType<Qt::ScreenOrientation>("Qt::ScreenOrientation");
454
455 // Register resources if they are available
456 if (QFile{QStringLiteral("assets:/android_rcc_bundle.rcc")}.exists())
457 QResource::registerResource(QStringLiteral("assets:/android_rcc_bundle.rcc"));
458
459 startQtAndroidPluginCalled.fetchAndAddRelease(1);
460
461 QtNative::callStaticMethod("setStarted", true);
462
463 // The service must wait until the QCoreApplication starts,
464 // otherwise onBind will be called too early.
465 if (QtAndroidPrivate::service().isValid() && QtAndroid::isQtApplication())
466 QtAndroidPrivate::waitForServiceSetup();
467
468 const int ret = m_main(argc, argv.data());
469 qInfo() << "main() returned" << ret;
470
471 if (mainLibraryHnd) {
472 int res = dlclose(mainLibraryHnd);
473 if (res < 0)
474 qWarning() << "dlclose failed:" << dlerror();
475 }
476
477 QNativeInterface::QAndroidApplication::runOnAndroidMainThread([]() {
478 QtNative::callStaticMethod("setStarted", false);
479
480 if (QtAndroid::isQtApplication()) {
481 // Now, that the Qt application has exited, tear down the Activity and Service
482 auto activity = QtAndroidPrivate::activity();
483 if (activity.isValid())
484 activity.callMethod("finish");
485 auto service = QtAndroidPrivate::service();
486 if (service.isValid())
487 service.callMethod("stopSelf");
488 } else {
489 // For the embedded case, we only need to terminate Qt
490 QtNative::callStaticMethod("terminateQtNativeApplication");
491 }
492 });
493
494 sem_post(&m_stopQtSemaphore);
495 sem_wait(&m_exitSemaphore);
496 sem_destroy(&m_exitSemaphore);
497
498 // We must call exit() to ensure that all global objects will be destructed
499 if (!qEnvironmentVariableIsSet("QT_ANDROID_NO_EXIT_CALL"))
500 exit(ret);
501}
502
503static void clearJavaReferences(JNIEnv *env)
504{
505 if (m_applicationClass) {
506 env->DeleteGlobalRef(m_applicationClass);
507 m_applicationClass = nullptr;
508 }
509 if (m_resourcesObj) {
510 env->DeleteGlobalRef(m_resourcesObj);
511 m_resourcesObj = nullptr;
512 }
513 if (m_bitmapClass) {
514 env->DeleteGlobalRef(m_bitmapClass);
515 m_bitmapClass = nullptr;
516 }
518 env->DeleteGlobalRef(m_ARGB_8888_BitmapConfigValue);
520 }
522 env->DeleteGlobalRef(m_RGB_565_BitmapConfigValue);
524 }
526 env->DeleteGlobalRef(m_bitmapDrawableClass);
527 m_bitmapDrawableClass = nullptr;
528 }
529 if (m_assets) {
530 env->DeleteGlobalRef(m_assets);
531 m_assets = nullptr;
532 }
533 if (m_qtActivityClass) {
534 env->DeleteGlobalRef(m_qtActivityClass);
535 m_qtActivityClass = nullptr;
536 }
537 if (m_qtServiceClass) {
538 env->DeleteGlobalRef(m_qtServiceClass);
539 m_qtServiceClass = nullptr;
540 }
541}
542
543static void terminateQtNativeApplication(JNIEnv *env, jclass /*clazz*/)
544{
545 // QAndroidEventDispatcherStopper is stopped when the user uses the task manager
546 // to kill the application. Also, in case of a service ensure to call quit().
547 if (QAndroidEventDispatcherStopper::instance()->stopped()
548 || QtAndroidPrivate::service().isValid()) {
549 QAndroidEventDispatcherStopper::instance()->startAll();
550 QCoreApplication::quit();
551 QAndroidEventDispatcherStopper::instance()->goingToStop(false);
552 }
553
554 if (startQtAndroidPluginCalled.loadAcquire())
555 sem_wait(&m_stopQtSemaphore);
556
557 sem_destroy(&m_stopQtSemaphore);
558
559 clearJavaReferences(env);
560
561 m_androidPlatformIntegration = nullptr;
562 delete m_androidAssetsFileEngineHandler;
563 m_androidAssetsFileEngineHandler = nullptr;
564 delete m_androidContentFileEngineHandler;
565 m_androidContentFileEngineHandler = nullptr;
566 delete m_androidApkFileEngineHandler;
567 m_androidApkFileEngineHandler = nullptr;
568 delete m_backendRegister;
569 m_backendRegister = nullptr;
570 sem_post(&m_exitSemaphore);
571
572 // Terminate the QtThread
573 QtNative::callStaticMethod<QtThread>("getQtThread").callMethod("exit");
574}
575
576static void handleLayoutSizeChanged(JNIEnv * /*env*/, jclass /*clazz*/,
577 jint availableWidth, jint availableHeight)
578{
579 QMutexLocker lock(&m_platformMutex);
580 // available geometry always starts from top left
581 const QRect availableGeometry(0, 0, availableWidth, availableHeight);
582 if (m_androidPlatformIntegration)
583 m_androidPlatformIntegration->setAvailableGeometry(availableGeometry);
584 else if (QAndroidPlatformScreen::defaultAvailableGeometry().isNull())
585 QAndroidPlatformScreen::defaultAvailableGeometry() = availableGeometry;
586}
587Q_DECLARE_JNI_NATIVE_METHOD(handleLayoutSizeChanged)
588
589static void updateApplicationState(JNIEnv */*env*/, jobject /*thiz*/, jint state)
590{
591 QMutexLocker lock(&m_platformMutex);
594 return;
595 }
596
597 // We're about to call user code from the Android thread, since we don't know
598 //the side effects we'll unlock first!
599 lock.unlock();
600 if (state == Qt::ApplicationActive)
601 QtAndroidPrivate::handleResume();
602 else if (state == Qt::ApplicationInactive)
603 QtAndroidPrivate::handlePause();
604 lock.relock();
606 return;
607
608 if (state <= Qt::ApplicationInactive) {
609 // NOTE: sometimes we will receive two consecutive suspended notifications,
610 // In the second suspended notification, QWindowSystemInterface::flushWindowSystemEvents()
611 // will deadlock since the dispatcher has been stopped in the first suspended notification.
612 // To avoid the deadlock we simply return if we found the event dispatcher has been stopped.
614 return;
615
616 // Don't send timers and sockets events anymore if we are going to hide all windows
618 QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationState(state));
619 if (state == Qt::ApplicationSuspended)
621 } else {
623 QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationState(state));
625 }
626}
627
628static void updateLocale(JNIEnv */*env*/, jobject /*thiz*/)
629{
630 QCoreApplication::postEvent(QCoreApplication::instance(), new QEvent(QEvent::LocaleChange));
631 QCoreApplication::postEvent(QCoreApplication::instance(), new QEvent(QEvent::LanguageChange));
632}
633
634static void handleOrientationChanged(JNIEnv */*env*/, jobject /*thiz*/, jint newRotation, jint nativeOrientation)
635{
636 // Array of orientations rotated in 90 degree increments, counterclockwise
637 // (same direction as Android measures angles)
638 static const Qt::ScreenOrientation orientations[] = {
639 Qt::PortraitOrientation,
640 Qt::LandscapeOrientation,
641 Qt::InvertedPortraitOrientation,
642 Qt::InvertedLandscapeOrientation
643 };
644
645 // The Android API defines the following constants:
646 // ROTATION_0 : 0
647 // ROTATION_90 : 1
648 // ROTATION_180 : 2
649 // ROTATION_270 : 3
650 // ORIENTATION_PORTRAIT : 1
651 // ORIENTATION_LANDSCAPE : 2
652
653 // and newRotation is how much the current orientation is rotated relative to nativeOrientation
654
655 // which means that we can be really clever here :)
656 Qt::ScreenOrientation screenOrientation = orientations[(nativeOrientation - 1 + newRotation) % 4];
657 Qt::ScreenOrientation native = orientations[nativeOrientation - 1];
658
659 QAndroidPlatformIntegration::setScreenOrientation(screenOrientation, native);
660 QMutexLocker lock(&m_platformMutex);
663 // Use invokeMethod to keep the certain order of the "geometry change"
664 // and "orientation change" event handling.
665 if (screen) {
666 QMetaObject::invokeMethod(screen, "setOrientation", Qt::AutoConnection,
667 Q_ARG(Qt::ScreenOrientation, screenOrientation));
668 }
669 }
670}
671Q_DECLARE_JNI_NATIVE_METHOD(handleOrientationChanged)
672
673static void handleRefreshRateChanged(JNIEnv */*env*/, jclass /*cls*/, jfloat refreshRate)
674{
675 if (m_androidPlatformIntegration)
676 m_androidPlatformIntegration->setRefreshRate(refreshRate);
677}
678Q_DECLARE_JNI_NATIVE_METHOD(handleRefreshRateChanged)
679
680static void handleScreenAdded(JNIEnv */*env*/, jclass /*cls*/, jint displayId)
681{
682 if (m_androidPlatformIntegration)
683 m_androidPlatformIntegration->handleScreenAdded(displayId);
684}
685Q_DECLARE_JNI_NATIVE_METHOD(handleScreenAdded)
686
687static void handleScreenChanged(JNIEnv */*env*/, jclass /*cls*/, jint displayId)
688{
689 if (m_androidPlatformIntegration)
690 m_androidPlatformIntegration->handleScreenChanged(displayId);
691}
692Q_DECLARE_JNI_NATIVE_METHOD(handleScreenChanged)
693
694static void handleScreenRemoved(JNIEnv */*env*/, jclass /*cls*/, jint displayId)
695{
696 if (m_androidPlatformIntegration)
697 m_androidPlatformIntegration->handleScreenRemoved(displayId);
698}
699Q_DECLARE_JNI_NATIVE_METHOD(handleScreenRemoved)
700
701static void handleUiDarkModeChanged(JNIEnv */*env*/, jobject /*thiz*/, jint newUiMode)
702{
703 QAndroidPlatformIntegration::updateColorScheme(
704 (newUiMode == 1 ) ? Qt::ColorScheme::Dark : Qt::ColorScheme::Light);
705}
706Q_DECLARE_JNI_NATIVE_METHOD(handleUiDarkModeChanged)
707
708static void handleScreenDensityChanged(JNIEnv */*env*/, jclass /*cls*/, jdouble density)
709{
710 m_density = density;
711}
712Q_DECLARE_JNI_NATIVE_METHOD(handleScreenDensityChanged)
713
714static void onActivityResult(JNIEnv */*env*/, jclass /*cls*/,
715 jint requestCode,
716 jint resultCode,
717 jobject data)
718{
719 QtAndroidPrivate::handleActivityResult(requestCode, resultCode, data);
720}
721
722static void onNewIntent(JNIEnv *env, jclass /*cls*/, jobject data)
723{
724 QtAndroidPrivate::handleNewIntent(env, data);
725}
726
727static jobject onBind(JNIEnv */*env*/, jclass /*cls*/, jobject intent)
728{
729 return QtAndroidPrivate::callOnBindListener(intent);
730}
731
733 { "startQtNativeApplication", "(Ljava/lang/String;)V", (void *)startQtNativeApplication },
734 { "terminateQtNativeApplication", "()V", (void *)terminateQtNativeApplication },
735 { "updateApplicationState", "(I)V", (void *)updateApplicationState },
736 { "onActivityResult", "(IILandroid/content/Intent;)V", (void *)onActivityResult },
737 { "onNewIntent", "(Landroid/content/Intent;)V", (void *)onNewIntent },
738 { "onBind", "(Landroid/content/Intent;)Landroid/os/IBinder;", (void *)onBind },
739 { "updateLocale", "()V", (void *)updateLocale },
740};
741
742#define FIND_AND_CHECK_CLASS(CLASS_NAME) clazz
743 = env->FindClass(CLASS_NAME); if
744 (!clazz) {
745 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_classErrorMsg, CLASS_NAME);
746 return false; \
747}
748
749#define GET_AND_CHECK_METHOD(VAR, CLASS, METHOD_NAME, METHOD_SIGNATURE) VAR
750 = env->GetMethodID(CLASS, METHOD_NAME, METHOD_SIGNATURE); if
751 (!VAR) {
752 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, METHOD_NAME, METHOD_SIGNATURE);
753 return false; \
754}
755
756#define GET_AND_CHECK_STATIC_METHOD(VAR, CLASS, METHOD_NAME, METHOD_SIGNATURE) VAR
757 = env->GetStaticMethodID(CLASS, METHOD_NAME, METHOD_SIGNATURE); if
758 (!VAR) {
759 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, METHOD_NAME, METHOD_SIGNATURE);
760 return false; \
761}
762
763#define GET_AND_CHECK_FIELD(VAR, CLASS, FIELD_NAME, FIELD_SIGNATURE) VAR
764 = env->GetFieldID(CLASS, FIELD_NAME, FIELD_SIGNATURE); if
765 (!VAR) {
766 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, FIELD_NAME, FIELD_SIGNATURE);
767 return false; \
768}
769
770#define GET_AND_CHECK_STATIC_FIELD(VAR, CLASS, FIELD_NAME, FIELD_SIGNATURE) VAR
771 = env->GetStaticFieldID(CLASS, FIELD_NAME, FIELD_SIGNATURE); if
772 (!VAR) {
773 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, FIELD_NAME, FIELD_SIGNATURE);
774 return false; \
775}
776
777Q_DECLARE_JNI_CLASS(QtDisplayManager, "org/qtproject/qt/android/QtDisplayManager")
778
779static bool registerNatives(QJniEnvironment &env)
780{
781 bool success = env.registerNativeMethods(m_applicationClass,
782 methods, sizeof(methods) / sizeof(methods[0]));
783 success &= env.registerNativeMethods(
784 QtJniTypes::Traits<QtJniTypes::QtDisplayManager>::className(),
785 {
786 Q_JNI_NATIVE_METHOD(handleLayoutSizeChanged),
787 Q_JNI_NATIVE_METHOD(handleOrientationChanged),
788 Q_JNI_NATIVE_METHOD(handleRefreshRateChanged),
789 Q_JNI_NATIVE_METHOD(handleScreenAdded),
790 Q_JNI_NATIVE_METHOD(handleScreenChanged),
791 Q_JNI_NATIVE_METHOD(handleScreenRemoved),
792 Q_JNI_NATIVE_METHOD(handleUiDarkModeChanged),
793 Q_JNI_NATIVE_METHOD(handleScreenDensityChanged)
794 });
795
796 success = success
797 && QtAndroidInput::registerNatives(env)
798 && QtAndroidMenu::registerNatives(env)
799#if QT_CONFIG(accessibility)
800 && QtAndroidAccessibility::registerNatives(env)
801#endif
802 && QtAndroidDialogHelpers::registerNatives(env)
803#if QT_CONFIG(clipboard)
804 && QAndroidPlatformClipboard::registerNatives(env)
805#endif
806 && QAndroidPlatformWindow::registerNatives(env)
807 && QtAndroidWindowEmbedding::registerNatives(env)
808 && AndroidBackendRegister::registerNatives()
809 && QAndroidModelIndexProxy::registerNatives(env)
810 && QAndroidItemModelProxy::registerAbstractNatives(env)
811 && QAndroidItemModelProxy::registerProxyNatives(env);
812
813 return success;
814}
815
816static bool initJavaReferences(QJniEnvironment &env)
817{
818 if (m_applicationClass)
819 return true;
820
821 jclass clazz;
822 FIND_AND_CHECK_CLASS("org/qtproject/qt/android/QtNative");
823 m_applicationClass = static_cast<jclass>(env->NewGlobalRef(clazz));
824
825 jmethodID methodID;
826 GET_AND_CHECK_STATIC_METHOD(methodID, m_applicationClass, "activity", "()Landroid/app/Activity;");
827
828 jobject contextObject = env->CallStaticObjectMethod(m_applicationClass, methodID);
829 if (!contextObject) {
830 GET_AND_CHECK_STATIC_METHOD(methodID, m_applicationClass, "service", "()Landroid/app/Service;");
831 contextObject = env->CallStaticObjectMethod(m_applicationClass, methodID);
832 }
833
834 if (!contextObject) {
835 __android_log_print(ANDROID_LOG_FATAL,"Qt", "Failed to get Activity or Service object");
836 return false;
837 }
838 const auto releaseContextObject = qScopeGuard([&env, contextObject]{
839 env->DeleteLocalRef(contextObject);
840 });
841
842 FIND_AND_CHECK_CLASS("android/content/ContextWrapper");
843 GET_AND_CHECK_METHOD(methodID, clazz, "getAssets", "()Landroid/content/res/AssetManager;");
844 m_assets = env->NewGlobalRef(env->CallObjectMethod(contextObject, methodID));
845 m_assetManager = AAssetManager_fromJava(env.jniEnv(), m_assets);
846
847 GET_AND_CHECK_METHOD(methodID, clazz, "getResources", "()Landroid/content/res/Resources;");
848 m_resourcesObj = env->NewGlobalRef(env->CallObjectMethod(contextObject, methodID));
849
850 FIND_AND_CHECK_CLASS("android/graphics/Bitmap");
851 m_bitmapClass = static_cast<jclass>(env->NewGlobalRef(clazz));
852 GET_AND_CHECK_STATIC_METHOD(m_createBitmapMethodID, m_bitmapClass,
853 "createBitmap", "(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;");
854 FIND_AND_CHECK_CLASS("android/graphics/Bitmap$Config");
855 jfieldID fieldId;
856 GET_AND_CHECK_STATIC_FIELD(fieldId, clazz, "ARGB_8888", "Landroid/graphics/Bitmap$Config;");
857 m_ARGB_8888_BitmapConfigValue = env->NewGlobalRef(env->GetStaticObjectField(clazz, fieldId));
858 GET_AND_CHECK_STATIC_FIELD(fieldId, clazz, "RGB_565", "Landroid/graphics/Bitmap$Config;");
859 m_RGB_565_BitmapConfigValue = env->NewGlobalRef(env->GetStaticObjectField(clazz, fieldId));
860
861 FIND_AND_CHECK_CLASS("android/graphics/drawable/BitmapDrawable");
862 m_bitmapDrawableClass = static_cast<jclass>(env->NewGlobalRef(clazz));
863 GET_AND_CHECK_METHOD(m_bitmapDrawableConstructorMethodID,
864 m_bitmapDrawableClass,
865 "<init>", "(Landroid/content/res/Resources;Landroid/graphics/Bitmap;)V");
866
867 FIND_AND_CHECK_CLASS("org/qtproject/qt/android/QtActivityBase");
868 m_qtActivityClass = static_cast<jclass>(env->NewGlobalRef(clazz));
869 FIND_AND_CHECK_CLASS("org/qtproject/qt/android/QtServiceBase");
870 m_qtServiceClass = static_cast<jclass>(env->NewGlobalRef(clazz));
871
872 // The current thread will be the Qt thread, name it accordingly
873 QThread::currentThread()->setObjectName("QtMainLoopThread");
874
875 QWindowSystemInterfacePrivate::TabletEvent::setPlatformSynthesizesMouse(false);
876
877 return true;
878}
879
880QT_END_NAMESPACE
881
882Q_DECL_EXPORT jint JNICALL JNI_OnLoad(JavaVM */*vm*/, void */*reserved*/)
883{
884 static bool initialized = false;
885 if (initialized)
886 return JNI_VERSION_1_6;
887 initialized = true;
888
889 QT_USE_NAMESPACE
890
891 QJniEnvironment env;
892 if (!env.isValid()) {
893 __android_log_print(ANDROID_LOG_FATAL, "Qt", "Failed to initialize the JNI Environment");
894 return JNI_ERR;
895 }
896
897 if (!initJavaReferences(env))
898 return JNI_ERR;
899
900 if (!registerNatives(env)) {
901 __android_log_print(ANDROID_LOG_FATAL, "Qt", "registerNatives failed");
902 return JNI_ERR;
903 }
904
905 __android_log_print(ANDROID_LOG_INFO, "Qt", "Qt platform plugin started");
906 return JNI_VERSION_1_6;
907}
#define GET_AND_CHECK_STATIC_METHOD(VAR, CLASS, METHOD_NAME, METHOD_SIGNATURE)
static bool initJavaReferences(QJniEnvironment &env)
static const char m_qtTag[]
static sem_t m_exitSemaphore
#define GET_AND_CHECK_STATIC_FIELD(VAR, CLASS, FIELD_NAME, FIELD_SIGNATURE)
static jclass m_qtActivityClass
static AndroidAssetsFileEngineHandler * m_androidAssetsFileEngineHandler
static jclass m_bitmapClass
static void terminateQtNativeApplication(JNIEnv *env, jclass)
static jclass m_bitmapDrawableClass
static Main m_main
static void handleLayoutSizeChanged(JNIEnv *, jclass, jint availableWidth, jint availableHeight)
static jobject m_resourcesObj
static jmethodID m_bitmapDrawableConstructorMethodID
static void handleScreenChanged(JNIEnv *, jclass, jint displayId)
static QAndroidPlatformIntegration * m_androidPlatformIntegration
static AndroidContentFileEngineHandler * m_androidContentFileEngineHandler
static bool registerNatives(QJniEnvironment &env)
static JNINativeMethod methods[]
static AndroidBackendRegister * m_backendRegister
static void onNewIntent(JNIEnv *env, jclass, jobject data)
static void initializeBackends()
#define FIND_AND_CHECK_CLASS(CLASS_NAME)
#define GET_AND_CHECK_METHOD(VAR, CLASS, METHOD_NAME, METHOD_SIGNATURE)
static double m_density
static jobject m_assets
static void handleUiDarkModeChanged(JNIEnv *, jobject, jint newUiMode)
static int m_pendingApplicationState
static void handleRefreshRateChanged(JNIEnv *, jclass, jfloat refreshRate)
static QBasicMutex m_platformMutex
static void updateApplicationState(JNIEnv *, jobject, jint state)
static bool initCleanupHandshakeSemaphores()
static void clearJavaReferences(JNIEnv *env)
int(* Main)(int, char **)
static void handleOrientationChanged(JNIEnv *, jobject, jint newRotation, jint nativeOrientation)
static void startQtNativeApplication(JNIEnv *jenv, jobject object, jstring paramsString)
static const char m_methodErrorMsg[]
static void handleScreenRemoved(JNIEnv *, jclass, jint displayId)
static void updateLocale(JNIEnv *, jobject)
static jobject m_RGB_565_BitmapConfigValue
static const char m_classErrorMsg[]
static jobject m_ARGB_8888_BitmapConfigValue
static sem_t m_stopQtSemaphore
static jclass m_qtServiceClass
static AAssetManager * m_assetManager
static jmethodID m_createBitmapMethodID
static jobject onBind(JNIEnv *, jclass, jobject intent)
static void onActivityResult(JNIEnv *, jclass, jint requestCode, jint resultCode, jobject data)
static void handleScreenDensityChanged(JNIEnv *, jclass, jdouble density)
static QAndroidApkFileEngineHandler * m_androidApkFileEngineHandler
static void handleScreenAdded(JNIEnv *, jclass, jint displayId)
static QAndroidEventDispatcherStopper * instance()
QWindow * topLevelAt(const QPoint &p) const override
Return the given top level window for a given position.
\inmodule QtCore\reentrant
Definition qpoint.h:29
const char * classErrorMsgFmt()
void setViewVisibility(jobject view, bool visible)
void setAndroidPlatformIntegration(QAndroidPlatformIntegration *androidPlatformIntegration)
const char * qtTagText()
jobject assets()
QBasicMutex * platformInterfaceMutex()
jobject createBitmap(int width, int height, QImage::Format format, JNIEnv *env)
jobject createBitmapDrawable(jobject bitmap, JNIEnv *env=nullptr)
QWindow * topLevelWindowAt(const QPoint &globalPos)
QAndroidPlatformIntegration * androidPlatformIntegration()
jobject createBitmap(QImage img, JNIEnv *env=nullptr)
AndroidBackendRegister * backendRegister()
QString deviceName()
bool blockEventLoopsWhenSuspended()
double pixelDensity()
QWindow * windowFromId(int windowId)
jclass applicationClass()
void notifyNativePluginIntegrationReady(bool ready)
AAssetManager * assetManager()
bool isQtApplication()
const char * methodErrorMsgFmt()
Q_DECLARE_JNI_CLASS(MotionEvent, "android/view/MotionEvent")