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