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;
76extern "C" typedef int (*
Main)(
int,
char **);
95Q_CONSTINIT
static QBasicAtomicInt startQtAndroidPluginCalled = Q_BASIC_ATOMIC_INITIALIZER(0);
97#if QT_CONFIG(accessibility)
98Q_DECLARE_JNI_CLASS(QtAccessibilityInterface,
"org/qtproject/qt/android/QtAccessibilityInterface");
107 return &m_platformMutex;
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));
144 for (QWindow *w : qGuiApp->allWindows()) {
147 QAndroidPlatformWindow *window =
static_cast<QAndroidPlatformWindow *>(w->handle());
148 if (window->nativeViewId() == windowId)
161 return m_assetManager;
166 return m_applicationClass;
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);
187#if QT_CONFIG(accessibility)
260 QJniObject::callStaticMethod<
void>(m_applicationClass,
261 "notifyNativePluginIntegrationReady",
273 jobject config = m_ARGB_8888_BitmapConfigValue;
274 if (img.format() == QImage::Format_RGB16)
275 config = m_RGB_565_BitmapConfigValue;
276 else if (img.format() != QImage::Format_RGBA8888_Premultiplied)
277 img =
std::move(img).convertToFormat(QImage::Format_RGBA8888_Premultiplied);
279 jobject bitmap = env->CallStaticObjectMethod(
280 m_bitmapClass, m_createBitmapMethodID, img.width(), img.height(), config);
284 AndroidBitmapInfo info;
285 if (AndroidBitmap_getInfo(env, bitmap, &info) < 0) {
286 env->DeleteLocalRef(bitmap);
291 if (AndroidBitmap_lockPixels(env, bitmap, &pixels) < 0) {
292 env->DeleteLocalRef(bitmap);
296 if (info.stride == uint(img.bytesPerLine())
297 && info.width == uint(img.width())
298 && info.height == uint(img.height())) {
299 memcpy(pixels, img.constBits(), info.stride * info.height);
301 uchar *bmpPtr =
static_cast<uchar *>(pixels);
302 const unsigned width = qMin(info.width, (uint)img.width());
303 const unsigned height = qMin(info.height, (uint)img.height());
304 for (
unsigned y = 0; y < height; y++, bmpPtr += info.stride)
305 memcpy(bmpPtr, img.constScanLine(y), width);
307 AndroidBitmap_unlockPixels(env, bitmap);
313 if (format != QImage::Format_RGBA8888
314 && format != QImage::Format_RGB16)
317 return env->CallStaticObjectMethod(m_bitmapClass,
318 m_createBitmapMethodID,
321 format == QImage::Format_RGB16
322 ? m_RGB_565_BitmapConfigValue
323 : m_ARGB_8888_BitmapConfigValue);
328 if (!bitmap || !m_bitmapDrawableClass || !m_resourcesObj)
331 return env->NewObject(m_bitmapDrawableClass,
332 m_bitmapDrawableConstructorMethodID,
359 QString manufacturer = QJniObject::getStaticObjectField(
"android/os/Build",
"MANUFACTURER",
"Ljava/lang/String;").toString();
360 QString model = QJniObject::getStaticObjectField(
"android/os/Build",
"MODEL",
"Ljava/lang/String;").toString();
362 return manufacturer + u' ' + model;
367 QJniObject::callStaticMethod<
void>(m_applicationClass,
369 "(Landroid/view/View;Z)V",
376 static bool block = qEnvironmentVariableIntValue(
"QT_BLOCK_EVENT_LOOPS_WHEN_SUSPENDED");
405 QJniEnvironment qEnv;
406 if (!qEnv.isValid()) {
407 qCritical() <<
"Failed to initialize the JNI Environment";
411 if (!initJavaReferences(qEnv))
424 qCritical() <<
"Failed to init Qt application cleanup semaphores";
437 JNIEnv* env =
nullptr;
438 JavaVMAttachArgs args;
439 args.version = JNI_VERSION_1_6;
440 args.name =
"QtMainThread";
442 JavaVM *vm = QJniEnvironment::javaVM();
444 vm->AttachCurrentThread(&env, &args);
447 const QStringList argsList = QProcess::splitCommand(QJniObject(paramsString).toString());
448 const int argc = argsList.size();
449 QVarLengthArray<
char *> argv(argc + 1);
450 QList<QByteArray> argvData;
451 argvData.reserve(argc);
452 for (
int i = 0; i < argc; ++i) {
453 argvData.append(argsList.at(i).toUtf8());
454 argv[i] = argvData.back().data();
456 argv[argc] =
nullptr;
459 QDir::setCurrent(QDir::homePath());
462 void *mainLibraryHnd =
nullptr;
466 mainLibraryHnd = dlopen(argv.first(), 0);
467 if (Q_UNLIKELY(!mainLibraryHnd)) {
468 qCritical() <<
"dlopen failed:" << dlerror();
473 qWarning(
"No main library was specified; searching entire process (this is slow!)");
477 if (Q_UNLIKELY(!
m_main)) {
478 qCritical() <<
"dlsym failed:" << dlerror() << Qt::endl
479 <<
"Could not find main method";
484 qRegisterMetaType<Qt::ScreenOrientation>(
"Qt::ScreenOrientation");
487 if (QFile{QStringLiteral(
"assets:/android_rcc_bundle.rcc")}.exists())
488 QResource::registerResource(QStringLiteral(
"assets:/android_rcc_bundle.rcc"));
490 startQtAndroidPluginCalled.fetchAndAddRelease(1);
492 const int ret =
m_main(argc, argv.data());
493 qInfo() <<
"main() returned" << ret;
495 if (mainLibraryHnd) {
496 int res = dlclose(mainLibraryHnd);
498 qWarning() <<
"dlclose failed:" << dlerror();
501 QNativeInterface::QAndroidApplication::runOnAndroidMainThread([]() {
502 QtNative::callStaticMethod(
"setStarted",
false);
504 if (QtAndroid::isQtApplication()) {
506 auto activity = QtAndroidPrivate::activity();
507 if (activity.isValid())
508 activity.callMethod(
"finish");
509 auto service = QtAndroidPrivate::service();
510 if (service.isValid())
511 service.callMethod(
"stopSelf");
514 QtNative::callStaticMethod(
"terminateQtNativeApplication");
523 if (!qEnvironmentVariableIsSet(
"QT_ANDROID_NO_EXIT_CALL"))
529 if (m_applicationClass) {
530 env->DeleteGlobalRef(m_applicationClass);
531 m_applicationClass =
nullptr;
534 env->DeleteGlobalRef(m_resourcesObj);
538 env->DeleteGlobalRef(m_bitmapClass);
542 env->DeleteGlobalRef(m_ARGB_8888_BitmapConfigValue);
546 env->DeleteGlobalRef(m_RGB_565_BitmapConfigValue);
550 env->DeleteGlobalRef(m_bitmapDrawableClass);
554 env->DeleteGlobalRef(m_assets);
558 env->DeleteGlobalRef(m_qtActivityClass);
562 env->DeleteGlobalRef(m_qtServiceClass);
572 if (QtAndroidPrivate::service().isValid() && QtAndroid::isQtApplication())
573 QtAndroidPrivate::waitForServiceSetup();
580 if (QAndroidEventDispatcherStopper::instance()->stopped()
581 || QtAndroidPrivate::service().isValid()) {
582 QAndroidEventDispatcherStopper::instance()->startAll();
583 QCoreApplication::quit();
584 QAndroidEventDispatcherStopper::instance()->goingToStop(
false);
587 if (startQtAndroidPluginCalled.loadAcquire())
588 sem_wait(&m_stopQtSemaphore);
590 sem_destroy(&m_stopQtSemaphore);
592 clearJavaReferences(env);
594 m_androidPlatformIntegration =
nullptr;
595 delete m_androidAssetsFileEngineHandler;
596 m_androidAssetsFileEngineHandler =
nullptr;
597 delete m_androidContentFileEngineHandler;
598 m_androidContentFileEngineHandler =
nullptr;
599 delete m_androidApkFileEngineHandler;
600 m_androidApkFileEngineHandler =
nullptr;
601 delete m_backendRegister;
602 m_backendRegister =
nullptr;
603 sem_post(&m_exitSemaphore);
606 QtNative::callStaticMethod<QtThread>(
"getQtThread").callMethod(
"exit");
610 jint availableWidth, jint availableHeight)
612 QMutexLocker lock(&m_platformMutex);
614 const QRect availableGeometry(0, 0, availableWidth, availableHeight);
615 if (m_androidPlatformIntegration)
616 m_androidPlatformIntegration->setAvailableGeometry(availableGeometry);
618 QAndroidPlatformScreen::defaultAvailableGeometry() = availableGeometry;
620Q_DECLARE_JNI_NATIVE_METHOD(handleLayoutSizeChanged)
624 QMutexLocker lock(&m_platformMutex);
633 if (state == Qt::ApplicationActive)
634 QtAndroidPrivate::handleResume();
635 else if (state == Qt::ApplicationInactive)
636 QtAndroidPrivate::handlePause();
641 if (state <= Qt::ApplicationInactive) {
651 QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationState(state));
652 if (state == Qt::ApplicationSuspended)
656 QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationState(state));
663#ifndef QT_NO_SYSTEMLOCALE
665 { QSystemLocale dummy; }
667 QCoreApplication::postEvent(QCoreApplication::instance(),
new QEvent(QEvent::LocaleChange));
668 QCoreApplication::postEvent(QCoreApplication::instance(),
new QEvent(QEvent::LanguageChange));
675 static const Qt::ScreenOrientation orientations[] = {
676 Qt::PortraitOrientation,
677 Qt::LandscapeOrientation,
678 Qt::InvertedPortraitOrientation,
679 Qt::InvertedLandscapeOrientation
693 Qt::ScreenOrientation screenOrientation = orientations[(nativeOrientation - 1 + newRotation) % 4];
694 Qt::ScreenOrientation native = orientations[nativeOrientation - 1];
696 QAndroidPlatformIntegration::setScreenOrientation(screenOrientation, native);
697 QMutexLocker lock(&m_platformMutex);
703 QMetaObject::invokeMethod(screen,
"setOrientation", Qt::AutoConnection,
704 Q_ARG(Qt::ScreenOrientation, screenOrientation));
708Q_DECLARE_JNI_NATIVE_METHOD(handleOrientationChanged)
712 if (m_androidPlatformIntegration)
713 m_androidPlatformIntegration->setRefreshRate(refreshRate);
715Q_DECLARE_JNI_NATIVE_METHOD(handleRefreshRateChanged)
719 if (m_androidPlatformIntegration)
720 m_androidPlatformIntegration->handleScreenAdded(displayId);
722Q_DECLARE_JNI_NATIVE_METHOD(handleScreenAdded)
726 if (m_androidPlatformIntegration)
727 m_androidPlatformIntegration->handleScreenChanged(displayId);
729Q_DECLARE_JNI_NATIVE_METHOD(handleScreenChanged)
733 if (m_androidPlatformIntegration)
734 m_androidPlatformIntegration->handleScreenRemoved(displayId);
736Q_DECLARE_JNI_NATIVE_METHOD(handleScreenRemoved)
740 QAndroidPlatformIntegration::updateColorScheme(
741 (newUiMode == 1 ) ? Qt::ColorScheme::Dark : Qt::ColorScheme::Light);
743Q_DECLARE_JNI_NATIVE_METHOD(handleUiDarkModeChanged)
749Q_DECLARE_JNI_NATIVE_METHOD(handleScreenDensityChanged)
756 QtAndroidPrivate::handleActivityResult(requestCode, resultCode, data);
761 QtAndroidPrivate::handleNewIntent(env, data);
766 return QtAndroidPrivate::callOnBindListener(intent);
770 {
"initAndroidQpaPlugin",
"()Z", (
void *)initAndroidQpaPlugin },
771 {
"startQtNativeApplication",
"(Ljava/lang/String;)V", (
void *)startQtNativeApplication },
772 {
"terminateQtNativeApplication",
"()V", (
void *)terminateQtNativeApplication },
773 {
"waitForServiceSetup",
"()V", (
void *)waitForServiceSetup },
774 {
"updateApplicationState",
"(I)V", (
void *)updateApplicationState },
775 {
"onActivityResult",
"(IILandroid/content/Intent;)V", (
void *)onActivityResult },
776 {
"onNewIntent",
"(Landroid/content/Intent;)V", (
void *)onNewIntent },
777 {
"onBind",
"(Landroid/content/Intent;)Landroid/os/IBinder;", (
void *)onBind },
778 {
"updateLocale",
"()V", (
void *)updateLocale },
781#define FIND_AND_CHECK_CLASS(CLASS_NAME) clazz
782 = env->FindClass(CLASS_NAME); if
784 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_classErrorMsg, CLASS_NAME);
786}
788#define GET_AND_CHECK_METHOD(VAR, CLASS, METHOD_NAME, METHOD_SIGNATURE) VAR
789 = env->GetMethodID(CLASS, METHOD_NAME, METHOD_SIGNATURE); if
791 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, METHOD_NAME, METHOD_SIGNATURE);
793}
795#define GET_AND_CHECK_STATIC_METHOD(VAR, CLASS, METHOD_NAME, METHOD_SIGNATURE) VAR
796 = env->GetStaticMethodID(CLASS, METHOD_NAME, METHOD_SIGNATURE); if
798 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, METHOD_NAME, METHOD_SIGNATURE);
800}
802#define GET_AND_CHECK_FIELD(VAR, CLASS, FIELD_NAME, FIELD_SIGNATURE) VAR
803 = env->GetFieldID(CLASS, FIELD_NAME, FIELD_SIGNATURE); if
805 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, FIELD_NAME, FIELD_SIGNATURE);
807}
809#define GET_AND_CHECK_STATIC_FIELD(VAR, CLASS, FIELD_NAME, FIELD_SIGNATURE) VAR
810 = env->GetStaticFieldID(CLASS, FIELD_NAME, FIELD_SIGNATURE); if
812 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, FIELD_NAME, FIELD_SIGNATURE);
814}
820 bool success = env.registerNativeMethods(m_applicationClass,
822 success &= env.registerNativeMethods(
823 QtJniTypes::Traits<QtJniTypes::QtDisplayManager>::className(),
825 Q_JNI_NATIVE_METHOD(handleLayoutSizeChanged),
826 Q_JNI_NATIVE_METHOD(handleOrientationChanged),
827 Q_JNI_NATIVE_METHOD(handleRefreshRateChanged),
828 Q_JNI_NATIVE_METHOD(handleScreenAdded),
829 Q_JNI_NATIVE_METHOD(handleScreenChanged),
830 Q_JNI_NATIVE_METHOD(handleScreenRemoved),
831 Q_JNI_NATIVE_METHOD(handleUiDarkModeChanged),
832 Q_JNI_NATIVE_METHOD(handleScreenDensityChanged)
836 && QtAndroidInput::registerNatives(env)
837 && QtAndroidMenu::registerNatives(env)
838#if QT_CONFIG(accessibility)
839 && QtAndroidAccessibility::registerNatives(env)
841 && QtAndroidDialogHelpers::registerNatives(env)
842#if QT_CONFIG(clipboard)
843 && QAndroidPlatformClipboard::registerNatives(env)
845#if QT_CONFIG(draganddrop)
846 && QAndroidPlatformDrag::registerNatives(env)
848 && QAndroidPlatformWindow::registerNatives(env)
849 && QtAndroidWindowEmbedding::registerNatives(env)
850 && AndroidBackendRegister::registerNatives()
851 && QAndroidModelIndexProxy::registerNatives(env)
852 && QAndroidItemModelProxy::registerAbstractNatives(env)
853 && QAndroidItemModelProxy::registerProxyNatives(env);
860 if (m_applicationClass)
865 m_applicationClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
870 jobject contextObject = env->CallStaticObjectMethod(m_applicationClass, methodID);
871 if (!contextObject) {
873 contextObject = env->CallStaticObjectMethod(m_applicationClass, methodID);
876 if (!contextObject) {
877 __android_log_print(ANDROID_LOG_FATAL,
"Qt",
"Failed to get Activity or Service object");
880 const auto releaseContextObject = qScopeGuard([&env, contextObject]{
881 env->DeleteLocalRef(contextObject);
886 m_assets = env->NewGlobalRef(env->CallObjectMethod(contextObject, methodID));
890 m_resourcesObj = env->NewGlobalRef(env->CallObjectMethod(contextObject, methodID));
893 m_bitmapClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
895 "createBitmap",
"(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;");
899 m_ARGB_8888_BitmapConfigValue = env->NewGlobalRef(env->GetStaticObjectField(clazz, fieldId));
901 m_RGB_565_BitmapConfigValue = env->NewGlobalRef(env->GetStaticObjectField(clazz, fieldId));
904 m_bitmapDrawableClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
906 m_bitmapDrawableClass,
907 "<init>",
"(Landroid/content/res/Resources;Landroid/graphics/Bitmap;)V");
910 m_qtActivityClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
912 m_qtServiceClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
915 QThread::currentThread()->setObjectName(
"QtMainLoopThread");
917 QWindowSystemInterfacePrivate::TabletEvent::setPlatformSynthesizesMouse(
false);
924extern "C" Q_DECL_EXPORT jint JNICALL JNI_OnLoad(JavaVM *,
void *)
926 static bool initialized =
false;
928 return JNI_VERSION_1_6;
934 if (!env.isValid()) {
935 __android_log_print(ANDROID_LOG_FATAL,
"Qt",
"Failed to initialize the JNI Environment");
939 if (!initJavaReferences(env))
942 if (!registerNatives(env)) {
943 __android_log_print(ANDROID_LOG_FATAL,
"Qt",
"registerNatives failed");
947 __android_log_print(ANDROID_LOG_INFO,
"Qt",
"Qt platform plugin started");
948 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")