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