21#if QT_CONFIG(clipboard)
22#include "qandroidplatformclipboard.h"
24#if QT_CONFIG(draganddrop)
25#include "qandroidplatformdrag.h"
27#if QT_CONFIG(accessibility)
28#include "androidjniaccessibility.h"
33#include <android/api-level.h>
34#include <android/asset_manager_jni.h>
35#include <android/bitmap.h>
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>
50#include <qpa/qwindowsysteminterface.h>
53using namespace Qt::StringLiterals;
57static jclass m_applicationClass =
nullptr;
73extern "C" typedef int (*
Main)(
int,
char **);
92Q_CONSTINIT
static QBasicAtomicInt startQtAndroidPluginCalled = Q_BASIC_ATOMIC_INITIALIZER(0);
94#if QT_CONFIG(accessibility)
95Q_DECLARE_JNI_CLASS(QtAccessibilityInterface,
"org/qtproject/qt/android/QtAccessibilityInterface");
106 return &m_platformMutex;
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));
143 for (QWindow *w : qGuiApp->allWindows()) {
146 QAndroidPlatformWindow *window =
static_cast<QAndroidPlatformWindow *>(w->handle());
147 if (window->nativeViewId() == windowId)
160 return m_assetManager;
165 return m_applicationClass;
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>();
186#if QT_CONFIG(accessibility)
259 QJniObject::callStaticMethod<
void>(m_applicationClass,
260 "notifyNativePluginIntegrationReady",
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);
278 jobject bitmap = env->CallStaticObjectMethod(
279 m_bitmapClass, m_createBitmapMethodID, img.width(), img.height(), config);
283 AndroidBitmapInfo info;
284 if (AndroidBitmap_getInfo(env, bitmap, &info) < 0) {
285 env->DeleteLocalRef(bitmap);
290 if (AndroidBitmap_lockPixels(env, bitmap, &pixels) < 0) {
291 env->DeleteLocalRef(bitmap);
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);
300 uchar *bmpPtr =
static_cast<uchar *>(pixels);
301 const unsigned width = qMin(info.width, (uint)img.width());
302 const unsigned height = qMin(info.height, (uint)img.height());
303 for (
unsigned y = 0; y < height; y++, bmpPtr += info.stride)
304 memcpy(bmpPtr, img.constScanLine(y), width);
306 AndroidBitmap_unlockPixels(env, bitmap);
312 if (format != QImage::Format_RGBA8888
313 && format != QImage::Format_RGB16)
316 return env->CallStaticObjectMethod(m_bitmapClass,
317 m_createBitmapMethodID,
320 format == QImage::Format_RGB16
321 ? m_RGB_565_BitmapConfigValue
322 : m_ARGB_8888_BitmapConfigValue);
327 if (!bitmap || !m_bitmapDrawableClass || !m_resourcesObj)
330 return env->NewObject(m_bitmapDrawableClass,
331 m_bitmapDrawableConstructorMethodID,
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();
361 return manufacturer + u' ' + model;
366 QJniObject::callStaticMethod<
void>(m_applicationClass,
368 "(Landroid/view/View;Z)V",
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;
410 QJniEnvironment qEnv;
411 if (!qEnv.isValid()) {
412 qCritical() <<
"Failed to initialize the JNI Environment";
416 if (!initJavaReferences(qEnv))
429 qCritical() <<
"Failed to init Qt application cleanup semaphores";
442 JNIEnv* env =
nullptr;
443 JavaVMAttachArgs args;
444 args.version = JNI_VERSION_1_6;
445 args.name =
"QtMainThread";
447 JavaVM *vm = QJniEnvironment::javaVM();
449 vm->AttachCurrentThread(&env, &args);
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();
461 argv[argc] =
nullptr;
464 QDir::setCurrent(QDir::homePath());
467 void *mainLibraryHnd =
nullptr;
471 mainLibraryHnd = dlopen(argv.first(), 0);
472 if (Q_UNLIKELY(!mainLibraryHnd)) {
473 qCritical() <<
"dlopen failed:" << dlerror();
478 qWarning(
"No main library was specified; searching entire process (this is slow!)");
482 if (Q_UNLIKELY(!
m_main)) {
483 qCritical() <<
"dlsym failed:" << dlerror() << Qt::endl
484 <<
"Could not find main method";
489 qRegisterMetaType<Qt::ScreenOrientation>(
"Qt::ScreenOrientation");
492 if (QFile{QStringLiteral(
"assets:/android_rcc_bundle.rcc")}.exists())
493 QResource::registerResource(QStringLiteral(
"assets:/android_rcc_bundle.rcc"));
495 startQtAndroidPluginCalled.fetchAndAddRelease(1);
497 const int ret =
m_main(argc, argv.data());
498 qInfo() <<
"main() returned" << ret;
500 if (mainLibraryHnd) {
501 int res = dlclose(mainLibraryHnd);
503 qWarning() <<
"dlclose failed:" << dlerror();
506 QNativeInterface::QAndroidApplication::runOnAndroidMainThread([]() {
507 QtNative::callStaticMethod(
"setStarted",
false);
509 if (QtAndroid::isQtApplication()) {
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");
519 QtNative::callStaticMethod(
"terminateQtNativeApplication");
528 if (!qEnvironmentVariableIsSet(
"QT_ANDROID_NO_EXIT_CALL"))
534 if (m_applicationClass) {
535 env->DeleteGlobalRef(m_applicationClass);
536 m_applicationClass =
nullptr;
539 env->DeleteGlobalRef(m_resourcesObj);
543 env->DeleteGlobalRef(m_bitmapClass);
547 env->DeleteGlobalRef(m_ARGB_8888_BitmapConfigValue);
551 env->DeleteGlobalRef(m_RGB_565_BitmapConfigValue);
555 env->DeleteGlobalRef(m_bitmapDrawableClass);
559 env->DeleteGlobalRef(m_assets);
569 if (QtAndroidPrivate::service().isValid() && QtAndroid::isQtApplication())
570 QtAndroidPrivate::waitForServiceSetup();
576 QAndroidEventDispatcherStopper::instance()->startAll();
577 QAndroidEventDispatcherStopper::instance()->goingToStop(
false);
581 if (QCoreApplication *app = QCoreApplication::instance()) {
582 QMetaObject::invokeMethod(app, [] {
583 QCoreApplication::quit();
584 QCoreApplication::exit(0);
585 }, Qt::QueuedConnection);
588 if (startQtAndroidPluginCalled.loadAcquire())
589 sem_wait(&m_stopQtSemaphore);
591 sem_destroy(&m_stopQtSemaphore);
593 clearJavaReferences(env);
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);
607 QtNative::callStaticMethod<QtThread>(
"getQtThread").callMethod(
"exit");
611 jint availableWidth, jint availableHeight)
613 QMutexLocker lock(&m_platformMutex);
615 const QRect availableGeometry(0, 0, availableWidth, availableHeight);
616 if (m_androidPlatformIntegration)
617 m_androidPlatformIntegration->setAvailableGeometry(availableGeometry);
619 QAndroidPlatformScreen::defaultAvailableGeometry() = availableGeometry;
621Q_DECLARE_JNI_NATIVE_METHOD(handleLayoutSizeChanged)
625 QMutexLocker lock(&m_platformMutex);
634 if (state == Qt::ApplicationActive)
635 QtAndroidPrivate::handleResume();
636 else if (state == Qt::ApplicationInactive)
637 QtAndroidPrivate::handlePause();
642 if (state != Qt::ApplicationActive) {
652 QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationState(state));
653 if (state == Qt::ApplicationSuspended)
657 QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationState(state));
664#ifndef QT_NO_SYSTEMLOCALE
666 { QSystemLocale dummy; }
668 QCoreApplication::postEvent(QCoreApplication::instance(),
new QEvent(QEvent::LocaleChange));
669 QCoreApplication::postEvent(QCoreApplication::instance(),
new QEvent(QEvent::LanguageChange));
676 static const Qt::ScreenOrientation orientations[] = {
677 Qt::PortraitOrientation,
678 Qt::LandscapeOrientation,
679 Qt::InvertedPortraitOrientation,
680 Qt::InvertedLandscapeOrientation
694 Qt::ScreenOrientation screenOrientation = orientations[(nativeOrientation - 1 + newRotation) % 4];
695 Qt::ScreenOrientation native = orientations[nativeOrientation - 1];
697 QAndroidPlatformIntegration::setScreenOrientation(screenOrientation, native);
698 QMutexLocker lock(&m_platformMutex);
704 QMetaObject::invokeMethod(screen,
"setOrientation", Qt::AutoConnection,
705 Q_ARG(Qt::ScreenOrientation, screenOrientation));
709Q_DECLARE_JNI_NATIVE_METHOD(handleOrientationChanged)
713 if (m_androidPlatformIntegration)
714 m_androidPlatformIntegration->setRefreshRate(refreshRate);
716Q_DECLARE_JNI_NATIVE_METHOD(handleRefreshRateChanged)
720 if (m_androidPlatformIntegration)
721 m_androidPlatformIntegration->handleScreenAdded(displayId);
723Q_DECLARE_JNI_NATIVE_METHOD(handleScreenAdded)
727 if (m_androidPlatformIntegration)
728 m_androidPlatformIntegration->handleScreenChanged(displayId);
730Q_DECLARE_JNI_NATIVE_METHOD(handleScreenChanged)
734 if (m_androidPlatformIntegration)
735 m_androidPlatformIntegration->handleScreenRemoved(displayId);
737Q_DECLARE_JNI_NATIVE_METHOD(handleScreenRemoved)
741 QAndroidPlatformIntegration::updateColorScheme(
742 (newUiMode == 1 ) ? Qt::ColorScheme::Dark : Qt::ColorScheme::Light);
744Q_DECLARE_JNI_NATIVE_METHOD(handleUiDarkModeChanged)
750Q_DECLARE_JNI_NATIVE_METHOD(handleScreenDensityChanged)
757 QtAndroidPrivate::handleActivityResult(requestCode, resultCode, data);
762 QtAndroidPrivate::handleNewIntent(env, data);
767 return QtAndroidPrivate::callOnBindListener(intent);
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 },
782#define FIND_AND_CHECK_CLASS(CLASS_NAME) clazz
783 = env->FindClass(CLASS_NAME); if
785 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_classErrorMsg, CLASS_NAME);
787}
789#define GET_AND_CHECK_METHOD(VAR, CLASS, METHOD_NAME, METHOD_SIGNATURE) VAR
790 = env->GetMethodID(CLASS, METHOD_NAME, METHOD_SIGNATURE); if
792 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, METHOD_NAME, METHOD_SIGNATURE);
794}
796#define GET_AND_CHECK_STATIC_METHOD(VAR, CLASS, METHOD_NAME, METHOD_SIGNATURE) VAR
797 = env->GetStaticMethodID(CLASS, METHOD_NAME, METHOD_SIGNATURE); if
799 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, METHOD_NAME, METHOD_SIGNATURE);
801}
803#define GET_AND_CHECK_FIELD(VAR, CLASS, FIELD_NAME, FIELD_SIGNATURE) VAR
804 = env->GetFieldID(CLASS, FIELD_NAME, FIELD_SIGNATURE); if
806 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, FIELD_NAME, FIELD_SIGNATURE);
808}
810#define GET_AND_CHECK_STATIC_FIELD(VAR, CLASS, FIELD_NAME, FIELD_SIGNATURE) VAR
811 = env->GetStaticFieldID(CLASS, FIELD_NAME, FIELD_SIGNATURE); if
813 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, FIELD_NAME, FIELD_SIGNATURE);
815}
821 bool success = env.registerNativeMethods(m_applicationClass,
823 success &= env.registerNativeMethods(
824 QtJniTypes::Traits<QtJniTypes::QtDisplayManager>::className(),
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)
837 && QtAndroidInput::registerNatives(env)
838 && QtAndroidMenu::registerNatives(env)
839#if QT_CONFIG(accessibility)
840 && QtAndroidAccessibility::registerNatives(env)
842 && QtAndroidDialogHelpers::registerNatives(env)
843#if QT_CONFIG(clipboard)
844 && QAndroidPlatformClipboard::registerNatives(env)
846#if QT_CONFIG(draganddrop)
847 && QAndroidPlatformDrag::registerNatives(env)
849 && QAndroidPlatformWindow::registerNatives(env)
850 && QtAndroidWindowEmbedding::registerNatives(env)
851 && AndroidBackendRegister::registerNatives()
852 && QAndroidModelIndexProxy::registerNatives(env)
853 && QAndroidItemModelProxy::registerAbstractNatives(env)
854 && QAndroidItemModelProxy::registerProxyNatives(env);
861 if (m_applicationClass)
866 m_applicationClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
871 jobject contextObject = env->CallStaticObjectMethod(m_applicationClass, methodID);
872 if (!contextObject) {
874 contextObject = env->CallStaticObjectMethod(m_applicationClass, methodID);
877 if (!contextObject) {
878 __android_log_print(ANDROID_LOG_FATAL,
"Qt",
"Failed to get Activity or Service object");
881 const auto releaseContextObject = qScopeGuard([&env, contextObject]{
882 env->DeleteLocalRef(contextObject);
887 m_assets = env->NewGlobalRef(env->CallObjectMethod(contextObject, methodID));
891 m_resourcesObj = env->NewGlobalRef(env->CallObjectMethod(contextObject, methodID));
894 m_bitmapClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
896 "createBitmap",
"(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;");
900 m_ARGB_8888_BitmapConfigValue = env->NewGlobalRef(env->GetStaticObjectField(clazz, fieldId));
902 m_RGB_565_BitmapConfigValue = env->NewGlobalRef(env->GetStaticObjectField(clazz, fieldId));
907 m_bitmapDrawableClass,
908 "<init>",
"(Landroid/content/res/Resources;Landroid/graphics/Bitmap;)V");
911 QThread::currentThread()->setObjectName(
"QtMainLoopThread");
913 QWindowSystemInterfacePrivate::TabletEvent::setPlatformSynthesizesMouse(
false);
920extern "C" Q_DECL_EXPORT jint JNICALL JNI_OnLoad(JavaVM *,
void *)
922 static bool initialized =
false;
924 return JNI_VERSION_1_6;
930 if (!env.isValid()) {
931 __android_log_print(ANDROID_LOG_FATAL,
"Qt",
"Failed to initialize the JNI Environment");
935 if (!initJavaReferences(env))
938 if (!registerNatives(env)) {
939 __android_log_print(ANDROID_LOG_FATAL,
"Qt",
"registerNatives failed");
943 __android_log_print(ANDROID_LOG_INFO,
"Qt",
"Qt platform plugin started");
944 return JNI_VERSION_1_6;
#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 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 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()
void goingToStop(bool stop)
\inmodule QtCore\reentrant
const char * classErrorMsgFmt()
void setViewVisibility(jobject view, bool visible)
void setAndroidPlatformIntegration(QAndroidPlatformIntegration *androidPlatformIntegration)
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()
bool blockEventLoopsWhenSuspended()
QWindow * windowFromId(int windowId)
jclass applicationClass()
void notifyNativePluginIntegrationReady(bool ready)
AAssetManager * assetManager()
const char * staticFieldErrorMsgFmt()
const char * methodErrorMsgFmt()