20#if QT_CONFIG(clipboard)
21#include "qandroidplatformclipboard.h"
23#if QT_CONFIG(accessibility)
24#include "androidjniaccessibility.h"
29#include <android/api-level.h>
30#include <android/asset_manager_jni.h>
31#include <android/bitmap.h>
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>
46#include <qpa/qwindowsysteminterface.h>
49using namespace Qt::StringLiterals;
53static jclass m_applicationClass =
nullptr;
72extern "C" typedef int (*
Main)(
int,
char **);
90Q_CONSTINIT
static QBasicAtomicInt startQtAndroidPluginCalled = Q_BASIC_ATOMIC_INITIALIZER(0);
92#if QT_CONFIG(accessibility)
93Q_DECLARE_JNI_CLASS(QtAccessibilityInterface,
"org/qtproject/qt/android/QtAccessibilityInterface");
102 return &m_platformMutex;
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));
139 for (QWindow *w : qGuiApp->allWindows()) {
142 QAndroidPlatformWindow *window =
static_cast<QAndroidPlatformWindow *>(w->handle());
143 if (window->nativeViewId() == windowId)
156 return m_assetManager;
161 return m_applicationClass;
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);
182#if QT_CONFIG(accessibility)
234 QJniObject::callStaticMethod<
void>(m_applicationClass,
235 "notifyNativePluginIntegrationReady",
244 if (img.format() != QImage::Format_RGBA8888 && img.format() != QImage::Format_RGB16)
245 img = std::move(img).convertToFormat(QImage::Format_RGBA8888);
247 jobject bitmap = env->CallStaticObjectMethod(m_bitmapClass,
248 m_createBitmapMethodID,
251 img.format() == QImage::Format_RGBA8888
252 ? m_ARGB_8888_BitmapConfigValue
253 : m_RGB_565_BitmapConfigValue);
257 AndroidBitmapInfo info;
258 if (AndroidBitmap_getInfo(env, bitmap, &info) < 0) {
259 env->DeleteLocalRef(bitmap);
264 if (AndroidBitmap_lockPixels(env, bitmap, &pixels) < 0) {
265 env->DeleteLocalRef(bitmap);
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);
274 uchar *bmpPtr =
static_cast<uchar *>(pixels);
275 const unsigned width = qMin(info.width, (uint)img.width());
276 const unsigned height = qMin(info.height, (uint)img.height());
277 for (
unsigned y = 0; y < height; y++, bmpPtr += info.stride)
278 memcpy(bmpPtr, img.constScanLine(y), width);
280 AndroidBitmap_unlockPixels(env, bitmap);
286 if (format != QImage::Format_RGBA8888
287 && format != QImage::Format_RGB16)
290 return env->CallStaticObjectMethod(m_bitmapClass,
291 m_createBitmapMethodID,
294 format == QImage::Format_RGB16
295 ? m_RGB_565_BitmapConfigValue
296 : m_ARGB_8888_BitmapConfigValue);
301 if (!bitmap || !m_bitmapDrawableClass || !m_resourcesObj)
304 return env->NewObject(m_bitmapDrawableClass,
305 m_bitmapDrawableConstructorMethodID,
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();
330 return manufacturer + u' ' + model;
335 QJniObject::callStaticMethod<
void>(m_applicationClass,
337 "(Landroid/view/View;Z)V",
344 static bool block = qEnvironmentVariableIntValue(
"QT_BLOCK_EVENT_LOOPS_WHEN_SUSPENDED");
373 QJniEnvironment qEnv;
374 if (!qEnv.isValid()) {
375 qCritical() <<
"Failed to initialize the JNI Environment";
379 if (!initJavaReferences(qEnv))
392 qCritical() <<
"Failed to init Qt application cleanup semaphores";
405 JNIEnv* env =
nullptr;
406 JavaVMAttachArgs args;
407 args.version = JNI_VERSION_1_6;
408 args.name =
"QtMainThread";
410 JavaVM *vm = QJniEnvironment::javaVM();
412 vm->AttachCurrentThread(&env, &args);
415 const QStringList argsList = QProcess::splitCommand(QJniObject(paramsString).toString());
416 const int argc = argsList.size();
417 QVarLengthArray<
char *> argv(argc + 1);
418 QList<QByteArray> argvData;
419 argvData.reserve(argc);
420 for (
int i = 0; i < argc; ++i) {
421 argvData.append(argsList.at(i).toUtf8());
422 argv[i] = argvData.back().data();
424 argv[argc] =
nullptr;
427 QDir::setCurrent(QDir::homePath());
430 void *mainLibraryHnd =
nullptr;
434 mainLibraryHnd = dlopen(argv.first(), 0);
435 if (Q_UNLIKELY(!mainLibraryHnd)) {
436 qCritical() <<
"dlopen failed:" << dlerror();
441 qWarning(
"No main library was specified; searching entire process (this is slow!)");
445 if (Q_UNLIKELY(!
m_main)) {
446 qCritical() <<
"dlsym failed:" << dlerror() << Qt::endl
447 <<
"Could not find main method";
452 qRegisterMetaType<Qt::ScreenOrientation>(
"Qt::ScreenOrientation");
455 if (QFile{QStringLiteral(
"assets:/android_rcc_bundle.rcc")}.exists())
456 QResource::registerResource(QStringLiteral(
"assets:/android_rcc_bundle.rcc"));
458 startQtAndroidPluginCalled.fetchAndAddRelease(1);
460 const int ret = m_main(argc, argv.data());
461 qInfo() <<
"main() returned" << ret;
463 if (mainLibraryHnd) {
464 int res = dlclose(mainLibraryHnd);
466 qWarning() <<
"dlclose failed:" << dlerror();
469 QNativeInterface::QAndroidApplication::runOnAndroidMainThread([]() {
470 QtNative::callStaticMethod(
"setStarted",
false);
472 if (QtAndroid::isQtApplication()) {
474 auto activity = QtAndroidPrivate::activity();
475 if (activity.isValid())
476 activity.callMethod(
"finish");
477 auto service = QtAndroidPrivate::service();
478 if (service.isValid())
479 service.callMethod(
"stopSelf");
482 QtNative::callStaticMethod(
"terminateQtNativeApplication");
491 if (!qEnvironmentVariableIsSet(
"QT_ANDROID_NO_EXIT_CALL"))
497 if (m_applicationClass) {
498 env->DeleteGlobalRef(m_applicationClass);
499 m_applicationClass =
nullptr;
502 env->DeleteGlobalRef(m_resourcesObj);
506 env->DeleteGlobalRef(m_bitmapClass);
510 env->DeleteGlobalRef(m_ARGB_8888_BitmapConfigValue);
514 env->DeleteGlobalRef(m_RGB_565_BitmapConfigValue);
518 env->DeleteGlobalRef(m_bitmapDrawableClass);
522 env->DeleteGlobalRef(m_assets);
526 env->DeleteGlobalRef(m_qtActivityClass);
530 env->DeleteGlobalRef(m_qtServiceClass);
540 if (QtAndroidPrivate::service().isValid() && QtAndroid::isQtApplication())
541 QtAndroidPrivate::waitForServiceSetup();
548 if (QAndroidEventDispatcherStopper::instance()->stopped()
549 || QtAndroidPrivate::service().isValid()) {
550 QAndroidEventDispatcherStopper::instance()->startAll();
551 QCoreApplication::quit();
552 QAndroidEventDispatcherStopper::instance()->goingToStop(
false);
555 if (startQtAndroidPluginCalled.loadAcquire())
556 sem_wait(&m_stopQtSemaphore);
558 sem_destroy(&m_stopQtSemaphore);
560 clearJavaReferences(env);
562 m_androidPlatformIntegration =
nullptr;
563 delete m_androidAssetsFileEngineHandler;
564 m_androidAssetsFileEngineHandler =
nullptr;
565 delete m_androidContentFileEngineHandler;
566 m_androidContentFileEngineHandler =
nullptr;
567 delete m_androidApkFileEngineHandler;
568 m_androidApkFileEngineHandler =
nullptr;
569 delete m_backendRegister;
570 m_backendRegister =
nullptr;
571 sem_post(&m_exitSemaphore);
574 QtNative::callStaticMethod<QtThread>(
"getQtThread").callMethod(
"exit");
578 jint availableWidth, jint availableHeight)
580 QMutexLocker lock(&m_platformMutex);
582 const QRect availableGeometry(0, 0, availableWidth, availableHeight);
583 if (m_androidPlatformIntegration)
584 m_androidPlatformIntegration->setAvailableGeometry(availableGeometry);
585 else if (QAndroidPlatformScreen::defaultAvailableGeometry().isNull())
586 QAndroidPlatformScreen::defaultAvailableGeometry() = availableGeometry;
588Q_DECLARE_JNI_NATIVE_METHOD(handleLayoutSizeChanged)
592 QMutexLocker lock(&m_platformMutex);
601 if (state == Qt::ApplicationActive)
602 QtAndroidPrivate::handleResume();
603 else if (state == Qt::ApplicationInactive)
604 QtAndroidPrivate::handlePause();
609 if (state <= Qt::ApplicationInactive) {
619 QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationState(state));
620 if (state == Qt::ApplicationSuspended)
624 QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationState(state));
631 QCoreApplication::postEvent(QCoreApplication::instance(),
new QEvent(QEvent::LocaleChange));
632 QCoreApplication::postEvent(QCoreApplication::instance(),
new QEvent(QEvent::LanguageChange));
639 static const Qt::ScreenOrientation orientations[] = {
640 Qt::PortraitOrientation,
641 Qt::LandscapeOrientation,
642 Qt::InvertedPortraitOrientation,
643 Qt::InvertedLandscapeOrientation
657 Qt::ScreenOrientation screenOrientation = orientations[(nativeOrientation - 1 + newRotation) % 4];
658 Qt::ScreenOrientation native = orientations[nativeOrientation - 1];
660 QAndroidPlatformIntegration::setScreenOrientation(screenOrientation, native);
661 QMutexLocker lock(&m_platformMutex);
667 QMetaObject::invokeMethod(screen,
"setOrientation", Qt::AutoConnection,
668 Q_ARG(Qt::ScreenOrientation, screenOrientation));
672Q_DECLARE_JNI_NATIVE_METHOD(handleOrientationChanged)
676 if (m_androidPlatformIntegration)
677 m_androidPlatformIntegration->setRefreshRate(refreshRate);
679Q_DECLARE_JNI_NATIVE_METHOD(handleRefreshRateChanged)
683 if (m_androidPlatformIntegration)
684 m_androidPlatformIntegration->handleScreenAdded(displayId);
686Q_DECLARE_JNI_NATIVE_METHOD(handleScreenAdded)
690 if (m_androidPlatformIntegration)
691 m_androidPlatformIntegration->handleScreenChanged(displayId);
693Q_DECLARE_JNI_NATIVE_METHOD(handleScreenChanged)
697 if (m_androidPlatformIntegration)
698 m_androidPlatformIntegration->handleScreenRemoved(displayId);
700Q_DECLARE_JNI_NATIVE_METHOD(handleScreenRemoved)
704 QAndroidPlatformIntegration::updateColorScheme(
705 (newUiMode == 1 ) ? Qt::ColorScheme::Dark : Qt::ColorScheme::Light);
707Q_DECLARE_JNI_NATIVE_METHOD(handleUiDarkModeChanged)
713Q_DECLARE_JNI_NATIVE_METHOD(handleScreenDensityChanged)
720 QtAndroidPrivate::handleActivityResult(requestCode, resultCode, data);
725 QtAndroidPrivate::handleNewIntent(env, data);
730 return QtAndroidPrivate::callOnBindListener(intent);
734 {
"initAndroidQpaPlugin",
"()Z", (
void *)initAndroidQpaPlugin },
735 {
"startQtNativeApplication",
"(Ljava/lang/String;)V", (
void *)startQtNativeApplication },
736 {
"terminateQtNativeApplication",
"()V", (
void *)terminateQtNativeApplication },
737 {
"waitForServiceSetup",
"()V", (
void *)waitForServiceSetup },
738 {
"updateApplicationState",
"(I)V", (
void *)updateApplicationState },
739 {
"onActivityResult",
"(IILandroid/content/Intent;)V", (
void *)onActivityResult },
740 {
"onNewIntent",
"(Landroid/content/Intent;)V", (
void *)onNewIntent },
741 {
"onBind",
"(Landroid/content/Intent;)Landroid/os/IBinder;", (
void *)onBind },
742 {
"updateLocale",
"()V", (
void *)updateLocale },
745#define FIND_AND_CHECK_CLASS(CLASS_NAME) clazz
746 = env->FindClass(CLASS_NAME); if
748 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_classErrorMsg, CLASS_NAME);
750}
752#define GET_AND_CHECK_METHOD(VAR, CLASS, METHOD_NAME, METHOD_SIGNATURE) VAR
753 = env->GetMethodID(CLASS, METHOD_NAME, METHOD_SIGNATURE); if
755 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, METHOD_NAME, METHOD_SIGNATURE);
757}
759#define GET_AND_CHECK_STATIC_METHOD(VAR, CLASS, METHOD_NAME, METHOD_SIGNATURE) VAR
760 = env->GetStaticMethodID(CLASS, METHOD_NAME, METHOD_SIGNATURE); if
762 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, METHOD_NAME, METHOD_SIGNATURE);
764}
766#define GET_AND_CHECK_FIELD(VAR, CLASS, FIELD_NAME, FIELD_SIGNATURE) VAR
767 = env->GetFieldID(CLASS, FIELD_NAME, FIELD_SIGNATURE); if
769 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, FIELD_NAME, FIELD_SIGNATURE);
771}
773#define GET_AND_CHECK_STATIC_FIELD(VAR, CLASS, FIELD_NAME, FIELD_SIGNATURE) VAR
774 = env->GetStaticFieldID(CLASS, FIELD_NAME, FIELD_SIGNATURE); if
776 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, FIELD_NAME, FIELD_SIGNATURE);
778}
784 bool success = env.registerNativeMethods(m_applicationClass,
785 methods,
sizeof(methods) /
sizeof(methods[0]));
786 success &= env.registerNativeMethods(
787 QtJniTypes::Traits<QtJniTypes::QtDisplayManager>::className(),
789 Q_JNI_NATIVE_METHOD(handleLayoutSizeChanged),
790 Q_JNI_NATIVE_METHOD(handleOrientationChanged),
791 Q_JNI_NATIVE_METHOD(handleRefreshRateChanged),
792 Q_JNI_NATIVE_METHOD(handleScreenAdded),
793 Q_JNI_NATIVE_METHOD(handleScreenChanged),
794 Q_JNI_NATIVE_METHOD(handleScreenRemoved),
795 Q_JNI_NATIVE_METHOD(handleUiDarkModeChanged),
796 Q_JNI_NATIVE_METHOD(handleScreenDensityChanged)
800 && QtAndroidInput::registerNatives(env)
801 && QtAndroidMenu::registerNatives(env)
802#if QT_CONFIG(accessibility)
803 && QtAndroidAccessibility::registerNatives(env)
805 && QtAndroidDialogHelpers::registerNatives(env)
806#if QT_CONFIG(clipboard)
807 && QAndroidPlatformClipboard::registerNatives(env)
809 && QAndroidPlatformWindow::registerNatives(env)
810 && QtAndroidWindowEmbedding::registerNatives(env)
811 && AndroidBackendRegister::registerNatives()
812 && QAndroidModelIndexProxy::registerNatives(env)
813 && QAndroidItemModelProxy::registerAbstractNatives(env)
814 && QAndroidItemModelProxy::registerProxyNatives(env);
821 if (m_applicationClass)
826 m_applicationClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
831 jobject contextObject = env->CallStaticObjectMethod(m_applicationClass, methodID);
832 if (!contextObject) {
834 contextObject = env->CallStaticObjectMethod(m_applicationClass, methodID);
837 if (!contextObject) {
838 __android_log_print(ANDROID_LOG_FATAL,
"Qt",
"Failed to get Activity or Service object");
841 const auto releaseContextObject = qScopeGuard([&env, contextObject]{
842 env->DeleteLocalRef(contextObject);
847 m_assets = env->NewGlobalRef(env->CallObjectMethod(contextObject, methodID));
851 m_resourcesObj = env->NewGlobalRef(env->CallObjectMethod(contextObject, methodID));
854 m_bitmapClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
856 "createBitmap",
"(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;");
860 m_ARGB_8888_BitmapConfigValue = env->NewGlobalRef(env->GetStaticObjectField(clazz, fieldId));
862 m_RGB_565_BitmapConfigValue = env->NewGlobalRef(env->GetStaticObjectField(clazz, fieldId));
865 m_bitmapDrawableClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
867 m_bitmapDrawableClass,
868 "<init>",
"(Landroid/content/res/Resources;Landroid/graphics/Bitmap;)V");
871 m_qtActivityClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
873 m_qtServiceClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
876 QThread::currentThread()->setObjectName(
"QtMainLoopThread");
878 QWindowSystemInterfacePrivate::TabletEvent::setPlatformSynthesizesMouse(
false);
885Q_DECL_EXPORT jint JNICALL JNI_OnLoad(JavaVM *,
void *)
887 static bool initialized =
false;
889 return JNI_VERSION_1_6;
895 if (!env.isValid()) {
896 __android_log_print(ANDROID_LOG_FATAL,
"Qt",
"Failed to initialize the JNI Environment");
900 if (!initJavaReferences(env))
903 if (!registerNatives(env)) {
904 __android_log_print(ANDROID_LOG_FATAL,
"Qt",
"registerNatives failed");
908 __android_log_print(ANDROID_LOG_INFO,
"Qt",
"Qt platform plugin started");
909 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 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 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 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()
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 * methodErrorMsgFmt()
Q_DECLARE_JNI_CLASS(MotionEvent, "android/view/MotionEvent")