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/qbasicatomic.h>
39#include <QtCore/qjnienvironment.h>
40#include <QtCore/qjniobject.h>
41#include <QtCore/qprocess.h>
42#include <QtCore/qresource.h>
43#include <QtCore/qscopeguard.h>
44#include <QtCore/qthread.h>
45#include <QtCore/private/qandroiditemmodelproxy_p.h>
46#include <QtCore/private/qandroidmodelindexproxy_p.h>
47#include <QtGui/private/qguiapplication_p.h>
49#include <qpa/qwindowsysteminterface.h>
52using namespace Qt::StringLiterals;
56static jclass m_applicationClass =
nullptr;
75extern "C" typedef int (*
Main)(
int,
char **);
94Q_CONSTINIT
static QBasicAtomicInt startQtAndroidPluginCalled = Q_BASIC_ATOMIC_INITIALIZER(0);
96#if QT_CONFIG(accessibility)
97Q_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 JNIEnv *env = QJniEnvironment::getJniEnv();
175 auto activity = QtAndroidPrivate::activity();
176 if (activity.isValid())
177 return env->IsInstanceOf(activity.object(), m_qtActivityClass);
178 auto service = QtAndroidPrivate::service();
179 if (service.isValid())
180 return env->IsInstanceOf(QtAndroidPrivate::service().object(), m_qtServiceClass);
186#if QT_CONFIG(accessibility)
247 QJniObject::callStaticMethod<
void>(m_applicationClass,
248 "notifyNativePluginIntegrationReady",
260 jobject config = m_ARGB_8888_BitmapConfigValue;
261 if (img.format() == QImage::Format_RGB16)
262 config = m_RGB_565_BitmapConfigValue;
263 else if (img.format() != QImage::Format_RGBA8888_Premultiplied)
264 img =
std::move(img).convertToFormat(QImage::Format_RGBA8888_Premultiplied);
266 jobject bitmap = env->CallStaticObjectMethod(
267 m_bitmapClass, m_createBitmapMethodID, img.width(), img.height(), config);
271 AndroidBitmapInfo info;
272 if (AndroidBitmap_getInfo(env, bitmap, &info) < 0) {
273 env->DeleteLocalRef(bitmap);
278 if (AndroidBitmap_lockPixels(env, bitmap, &pixels) < 0) {
279 env->DeleteLocalRef(bitmap);
283 if (info.stride == uint(img.bytesPerLine())
284 && info.width == uint(img.width())
285 && info.height == uint(img.height())) {
286 memcpy(pixels, img.constBits(), info.stride * info.height);
288 uchar *bmpPtr =
static_cast<uchar *>(pixels);
289 const unsigned width = qMin(info.width, (uint)img.width());
290 const unsigned height = qMin(info.height, (uint)img.height());
291 for (
unsigned y = 0; y < height; y++, bmpPtr += info.stride)
292 memcpy(bmpPtr, img.constScanLine(y), width);
294 AndroidBitmap_unlockPixels(env, bitmap);
300 if (format != QImage::Format_RGBA8888
301 && format != QImage::Format_RGB16)
304 return env->CallStaticObjectMethod(m_bitmapClass,
305 m_createBitmapMethodID,
308 format == QImage::Format_RGB16
309 ? m_RGB_565_BitmapConfigValue
310 : m_ARGB_8888_BitmapConfigValue);
315 if (!bitmap || !m_bitmapDrawableClass || !m_resourcesObj)
318 return env->NewObject(m_bitmapDrawableClass,
319 m_bitmapDrawableConstructorMethodID,
346 QString manufacturer = QJniObject::getStaticObjectField(
"android/os/Build",
"MANUFACTURER",
"Ljava/lang/String;").toString();
347 QString model = QJniObject::getStaticObjectField(
"android/os/Build",
"MODEL",
"Ljava/lang/String;").toString();
349 return manufacturer + u' ' + model;
354 QJniObject::callStaticMethod<
void>(m_applicationClass,
356 "(Landroid/view/View;Z)V",
363 static bool block = qEnvironmentVariableIntValue(
"QT_BLOCK_EVENT_LOOPS_WHEN_SUSPENDED");
392 QJniEnvironment qEnv;
393 if (!qEnv.isValid()) {
394 qCritical() <<
"Failed to initialize the JNI Environment";
398 if (!initJavaReferences(qEnv))
411 qCritical() <<
"Failed to init Qt application cleanup semaphores";
424 JNIEnv* env =
nullptr;
425 JavaVMAttachArgs args;
426 args.version = JNI_VERSION_1_6;
427 args.name =
"QtMainThread";
429 JavaVM *vm = QJniEnvironment::javaVM();
431 vm->AttachCurrentThread(&env, &args);
434 const QStringList argsList = QProcess::splitCommand(QJniObject(paramsString).toString());
435 const int argc = argsList.size();
436 QVarLengthArray<
char *> argv(argc + 1);
437 QList<QByteArray> argvData;
438 argvData.reserve(argc);
439 for (
int i = 0; i < argc; ++i) {
440 argvData.append(argsList.at(i).toUtf8());
441 argv[i] = argvData.back().data();
443 argv[argc] =
nullptr;
446 QDir::setCurrent(QDir::homePath());
449 void *mainLibraryHnd =
nullptr;
453 mainLibraryHnd = dlopen(argv.first(), 0);
454 if (Q_UNLIKELY(!mainLibraryHnd)) {
455 qCritical() <<
"dlopen failed:" << dlerror();
460 qWarning(
"No main library was specified; searching entire process (this is slow!)");
464 if (Q_UNLIKELY(!
m_main)) {
465 qCritical() <<
"dlsym failed:" << dlerror() << Qt::endl
466 <<
"Could not find main method";
471 qRegisterMetaType<Qt::ScreenOrientation>(
"Qt::ScreenOrientation");
474 if (QFile{QStringLiteral(
"assets:/android_rcc_bundle.rcc")}.exists())
475 QResource::registerResource(QStringLiteral(
"assets:/android_rcc_bundle.rcc"));
477 startQtAndroidPluginCalled.fetchAndAddRelease(1);
479 const int ret =
m_main(argc, argv.data());
480 qInfo() <<
"main() returned" << ret;
482 if (mainLibraryHnd) {
483 int res = dlclose(mainLibraryHnd);
485 qWarning() <<
"dlclose failed:" << dlerror();
488 QNativeInterface::QAndroidApplication::runOnAndroidMainThread([]() {
489 QtNative::callStaticMethod(
"setStarted",
false);
491 if (QtAndroid::isQtApplication()) {
493 auto activity = QtAndroidPrivate::activity();
494 if (activity.isValid())
495 activity.callMethod(
"finish");
496 auto service = QtAndroidPrivate::service();
497 if (service.isValid())
498 service.callMethod(
"stopSelf");
501 QtNative::callStaticMethod(
"terminateQtNativeApplication");
510 if (!qEnvironmentVariableIsSet(
"QT_ANDROID_NO_EXIT_CALL"))
516 if (m_applicationClass) {
517 env->DeleteGlobalRef(m_applicationClass);
518 m_applicationClass =
nullptr;
521 env->DeleteGlobalRef(m_resourcesObj);
525 env->DeleteGlobalRef(m_bitmapClass);
529 env->DeleteGlobalRef(m_ARGB_8888_BitmapConfigValue);
533 env->DeleteGlobalRef(m_RGB_565_BitmapConfigValue);
537 env->DeleteGlobalRef(m_bitmapDrawableClass);
541 env->DeleteGlobalRef(m_assets);
545 env->DeleteGlobalRef(m_qtActivityClass);
549 env->DeleteGlobalRef(m_qtServiceClass);
559 if (QtAndroidPrivate::service().isValid() && QtAndroid::isQtApplication())
560 QtAndroidPrivate::waitForServiceSetup();
567 if (QAndroidEventDispatcherStopper::instance()->stopped()
568 || QtAndroidPrivate::service().isValid()) {
569 QAndroidEventDispatcherStopper::instance()->startAll();
570 QCoreApplication::quit();
571 QAndroidEventDispatcherStopper::instance()->goingToStop(
false);
574 if (startQtAndroidPluginCalled.loadAcquire())
575 sem_wait(&m_stopQtSemaphore);
577 sem_destroy(&m_stopQtSemaphore);
579 clearJavaReferences(env);
581 m_androidPlatformIntegration =
nullptr;
582 delete m_androidAssetsFileEngineHandler;
583 m_androidAssetsFileEngineHandler =
nullptr;
584 delete m_androidContentFileEngineHandler;
585 m_androidContentFileEngineHandler =
nullptr;
586 delete m_androidApkFileEngineHandler;
587 m_androidApkFileEngineHandler =
nullptr;
588 delete m_backendRegister;
589 m_backendRegister =
nullptr;
590 sem_post(&m_exitSemaphore);
593 QtNative::callStaticMethod<QtThread>(
"getQtThread").callMethod(
"exit");
597 jint availableWidth, jint availableHeight)
599 QMutexLocker lock(&m_platformMutex);
601 const QRect availableGeometry(0, 0, availableWidth, availableHeight);
602 if (m_androidPlatformIntegration)
603 m_androidPlatformIntegration->setAvailableGeometry(availableGeometry);
604 else if (QAndroidPlatformScreen::defaultAvailableGeometry().isNull())
605 QAndroidPlatformScreen::defaultAvailableGeometry() = availableGeometry;
607Q_DECLARE_JNI_NATIVE_METHOD(handleLayoutSizeChanged)
611 QMutexLocker lock(&m_platformMutex);
620 if (state == Qt::ApplicationActive)
621 QtAndroidPrivate::handleResume();
622 else if (state == Qt::ApplicationInactive)
623 QtAndroidPrivate::handlePause();
628 if (state <= Qt::ApplicationInactive) {
638 QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationState(state));
639 if (state == Qt::ApplicationSuspended)
643 QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationState(state));
650 QCoreApplication::postEvent(QCoreApplication::instance(),
new QEvent(QEvent::LocaleChange));
651 QCoreApplication::postEvent(QCoreApplication::instance(),
new QEvent(QEvent::LanguageChange));
658 static const Qt::ScreenOrientation orientations[] = {
659 Qt::PortraitOrientation,
660 Qt::LandscapeOrientation,
661 Qt::InvertedPortraitOrientation,
662 Qt::InvertedLandscapeOrientation
676 Qt::ScreenOrientation screenOrientation = orientations[(nativeOrientation - 1 + newRotation) % 4];
677 Qt::ScreenOrientation native = orientations[nativeOrientation - 1];
679 QAndroidPlatformIntegration::setScreenOrientation(screenOrientation, native);
680 QMutexLocker lock(&m_platformMutex);
686 QMetaObject::invokeMethod(screen,
"setOrientation", Qt::AutoConnection,
687 Q_ARG(Qt::ScreenOrientation, screenOrientation));
691Q_DECLARE_JNI_NATIVE_METHOD(handleOrientationChanged)
695 if (m_androidPlatformIntegration)
696 m_androidPlatformIntegration->setRefreshRate(refreshRate);
698Q_DECLARE_JNI_NATIVE_METHOD(handleRefreshRateChanged)
702 if (m_androidPlatformIntegration)
703 m_androidPlatformIntegration->handleScreenAdded(displayId);
705Q_DECLARE_JNI_NATIVE_METHOD(handleScreenAdded)
709 if (m_androidPlatformIntegration)
710 m_androidPlatformIntegration->handleScreenChanged(displayId);
712Q_DECLARE_JNI_NATIVE_METHOD(handleScreenChanged)
716 if (m_androidPlatformIntegration)
717 m_androidPlatformIntegration->handleScreenRemoved(displayId);
719Q_DECLARE_JNI_NATIVE_METHOD(handleScreenRemoved)
723 QAndroidPlatformIntegration::updateColorScheme(
724 (newUiMode == 1 ) ? Qt::ColorScheme::Dark : Qt::ColorScheme::Light);
726Q_DECLARE_JNI_NATIVE_METHOD(handleUiDarkModeChanged)
732Q_DECLARE_JNI_NATIVE_METHOD(handleScreenDensityChanged)
739 QtAndroidPrivate::handleActivityResult(requestCode, resultCode, data);
744 QtAndroidPrivate::handleNewIntent(env, data);
749 return QtAndroidPrivate::callOnBindListener(intent);
753 {
"initAndroidQpaPlugin",
"()Z", (
void *)initAndroidQpaPlugin },
754 {
"startQtNativeApplication",
"(Ljava/lang/String;)V", (
void *)startQtNativeApplication },
755 {
"terminateQtNativeApplication",
"()V", (
void *)terminateQtNativeApplication },
756 {
"waitForServiceSetup",
"()V", (
void *)waitForServiceSetup },
757 {
"updateApplicationState",
"(I)V", (
void *)updateApplicationState },
758 {
"onActivityResult",
"(IILandroid/content/Intent;)V", (
void *)onActivityResult },
759 {
"onNewIntent",
"(Landroid/content/Intent;)V", (
void *)onNewIntent },
760 {
"onBind",
"(Landroid/content/Intent;)Landroid/os/IBinder;", (
void *)onBind },
761 {
"updateLocale",
"()V", (
void *)updateLocale },
764#define FIND_AND_CHECK_CLASS(CLASS_NAME) clazz
765 = env->FindClass(CLASS_NAME); if
767 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_classErrorMsg, CLASS_NAME);
769}
771#define GET_AND_CHECK_METHOD(VAR, CLASS, METHOD_NAME, METHOD_SIGNATURE) VAR
772 = env->GetMethodID(CLASS, METHOD_NAME, METHOD_SIGNATURE); if
774 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, METHOD_NAME, METHOD_SIGNATURE);
776}
778#define GET_AND_CHECK_STATIC_METHOD(VAR, CLASS, METHOD_NAME, METHOD_SIGNATURE) VAR
779 = env->GetStaticMethodID(CLASS, METHOD_NAME, METHOD_SIGNATURE); if
781 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, METHOD_NAME, METHOD_SIGNATURE);
783}
785#define GET_AND_CHECK_FIELD(VAR, CLASS, FIELD_NAME, FIELD_SIGNATURE) VAR
786 = env->GetFieldID(CLASS, FIELD_NAME, FIELD_SIGNATURE); if
788 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, FIELD_NAME, FIELD_SIGNATURE);
790}
792#define GET_AND_CHECK_STATIC_FIELD(VAR, CLASS, FIELD_NAME, FIELD_SIGNATURE) VAR
793 = env->GetStaticFieldID(CLASS, FIELD_NAME, FIELD_SIGNATURE); if
795 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, FIELD_NAME, FIELD_SIGNATURE);
797}
803 bool success = env.registerNativeMethods(m_applicationClass,
805 success &= env.registerNativeMethods(
806 QtJniTypes::Traits<QtJniTypes::QtDisplayManager>::className(),
808 Q_JNI_NATIVE_METHOD(handleLayoutSizeChanged),
809 Q_JNI_NATIVE_METHOD(handleOrientationChanged),
810 Q_JNI_NATIVE_METHOD(handleRefreshRateChanged),
811 Q_JNI_NATIVE_METHOD(handleScreenAdded),
812 Q_JNI_NATIVE_METHOD(handleScreenChanged),
813 Q_JNI_NATIVE_METHOD(handleScreenRemoved),
814 Q_JNI_NATIVE_METHOD(handleUiDarkModeChanged),
815 Q_JNI_NATIVE_METHOD(handleScreenDensityChanged)
819 && QtAndroidInput::registerNatives(env)
820 && QtAndroidMenu::registerNatives(env)
821#if QT_CONFIG(accessibility)
822 && QtAndroidAccessibility::registerNatives(env)
824 && QtAndroidDialogHelpers::registerNatives(env)
825#if QT_CONFIG(clipboard)
826 && QAndroidPlatformClipboard::registerNatives(env)
828#if QT_CONFIG(draganddrop)
829 && QAndroidPlatformDrag::registerNatives(env)
831 && QAndroidPlatformWindow::registerNatives(env)
832 && QtAndroidWindowEmbedding::registerNatives(env)
833 && AndroidBackendRegister::registerNatives()
834 && QAndroidModelIndexProxy::registerNatives(env)
835 && QAndroidItemModelProxy::registerAbstractNatives(env)
836 && QAndroidItemModelProxy::registerProxyNatives(env);
843 if (m_applicationClass)
848 m_applicationClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
853 jobject contextObject = env->CallStaticObjectMethod(m_applicationClass, methodID);
854 if (!contextObject) {
856 contextObject = env->CallStaticObjectMethod(m_applicationClass, methodID);
859 if (!contextObject) {
860 __android_log_print(ANDROID_LOG_FATAL,
"Qt",
"Failed to get Activity or Service object");
863 const auto releaseContextObject = qScopeGuard([&env, contextObject]{
864 env->DeleteLocalRef(contextObject);
869 m_assets = env->NewGlobalRef(env->CallObjectMethod(contextObject, methodID));
873 m_resourcesObj = env->NewGlobalRef(env->CallObjectMethod(contextObject, methodID));
876 m_bitmapClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
878 "createBitmap",
"(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;");
882 m_ARGB_8888_BitmapConfigValue = env->NewGlobalRef(env->GetStaticObjectField(clazz, fieldId));
884 m_RGB_565_BitmapConfigValue = env->NewGlobalRef(env->GetStaticObjectField(clazz, fieldId));
887 m_bitmapDrawableClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
889 m_bitmapDrawableClass,
890 "<init>",
"(Landroid/content/res/Resources;Landroid/graphics/Bitmap;)V");
893 m_qtActivityClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
895 m_qtServiceClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
898 QThread::currentThread()->setObjectName(
"QtMainLoopThread");
900 QWindowSystemInterfacePrivate::TabletEvent::setPlatformSynthesizesMouse(
false);
907extern "C" Q_DECL_EXPORT jint JNICALL JNI_OnLoad(JavaVM *,
void *)
909 static bool initialized =
false;
911 return JNI_VERSION_1_6;
917 if (!env.isValid()) {
918 __android_log_print(ANDROID_LOG_FATAL,
"Qt",
"Failed to initialize the JNI Environment");
922 if (!initJavaReferences(env))
925 if (!registerNatives(env)) {
926 __android_log_print(ANDROID_LOG_FATAL,
"Qt",
"registerNatives failed");
930 __android_log_print(ANDROID_LOG_INFO,
"Qt",
"Qt platform plugin started");
931 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 const char m_staticFieldErrorMsg[]
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 * staticFieldErrorMsgFmt()
const char * methodErrorMsgFmt()
Q_DECLARE_JNI_CLASS(MotionEvent, "android/view/MotionEvent")