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");
384 JNIEnv* env =
nullptr;
385 JavaVMAttachArgs args;
386 args.version = JNI_VERSION_1_6;
387 args.name =
"QtMainThread";
389 JavaVM *vm = QJniEnvironment::javaVM();
391 vm->AttachCurrentThread(&env, &args);
400 QJniEnvironment qEnv;
401 if (!qEnv.isValid()) {
402 qCritical() <<
"Failed to initialize the JNI Environment";
405 if (!initJavaReferences(qEnv))
411 const QStringList argsList = QProcess::splitCommand(QJniObject(paramsString).toString());
412 const int argc = argsList.size();
413 QVarLengthArray<
char *> argv(argc + 1);
414 QList<QByteArray> argvData;
415 argvData.reserve(argc);
416 for (
int i = 0; i < argc; ++i) {
417 argvData.append(argsList.at(i).toUtf8());
418 argv[i] = argvData.back().data();
420 argv[argc] =
nullptr;
423 QDir::setCurrent(QDir::homePath());
426 void *mainLibraryHnd =
nullptr;
430 mainLibraryHnd = dlopen(argv.first(), 0);
431 if (Q_UNLIKELY(!mainLibraryHnd)) {
432 qCritical() <<
"dlopen failed:" << dlerror();
437 qWarning(
"No main library was specified; searching entire process (this is slow!)");
441 if (Q_UNLIKELY(!
m_main)) {
442 qCritical() <<
"dlsym failed:" << dlerror() << Qt::endl
443 <<
"Could not find main method";
448 qCritical() <<
"Failed to init Qt application cleanup semaphores";
453 qRegisterMetaType<Qt::ScreenOrientation>(
"Qt::ScreenOrientation");
456 if (QFile{QStringLiteral(
"assets:/android_rcc_bundle.rcc")}.exists())
457 QResource::registerResource(QStringLiteral(
"assets:/android_rcc_bundle.rcc"));
459 startQtAndroidPluginCalled.fetchAndAddRelease(1);
461 QtNative::callStaticMethod(
"setStarted",
true);
465 if (QtAndroidPrivate::service().isValid() && QtAndroid::isQtApplication())
466 QtAndroidPrivate::waitForServiceSetup();
468 const int ret = m_main(argc, argv.data());
469 qInfo() <<
"main() returned" << ret;
471 if (mainLibraryHnd) {
472 int res = dlclose(mainLibraryHnd);
474 qWarning() <<
"dlclose failed:" << dlerror();
477 QNativeInterface::QAndroidApplication::runOnAndroidMainThread([]() {
478 QtNative::callStaticMethod(
"setStarted",
false);
480 if (QtAndroid::isQtApplication()) {
482 auto activity = QtAndroidPrivate::activity();
483 if (activity.isValid())
484 activity.callMethod(
"finish");
485 auto service = QtAndroidPrivate::service();
486 if (service.isValid())
487 service.callMethod(
"stopSelf");
490 QtNative::callStaticMethod(
"terminateQtNativeApplication");
499 if (!qEnvironmentVariableIsSet(
"QT_ANDROID_NO_EXIT_CALL"))
505 if (m_applicationClass) {
506 env->DeleteGlobalRef(m_applicationClass);
507 m_applicationClass =
nullptr;
510 env->DeleteGlobalRef(m_resourcesObj);
514 env->DeleteGlobalRef(m_bitmapClass);
518 env->DeleteGlobalRef(m_ARGB_8888_BitmapConfigValue);
522 env->DeleteGlobalRef(m_RGB_565_BitmapConfigValue);
526 env->DeleteGlobalRef(m_bitmapDrawableClass);
530 env->DeleteGlobalRef(m_assets);
534 env->DeleteGlobalRef(m_qtActivityClass);
538 env->DeleteGlobalRef(m_qtServiceClass);
547 if (QAndroidEventDispatcherStopper::instance()->stopped()
548 || QtAndroidPrivate::service().isValid()) {
549 QAndroidEventDispatcherStopper::instance()->startAll();
550 QCoreApplication::quit();
551 QAndroidEventDispatcherStopper::instance()->goingToStop(
false);
554 if (startQtAndroidPluginCalled.loadAcquire())
555 sem_wait(&m_stopQtSemaphore);
557 sem_destroy(&m_stopQtSemaphore);
559 clearJavaReferences(env);
561 m_androidPlatformIntegration =
nullptr;
562 delete m_androidAssetsFileEngineHandler;
563 m_androidAssetsFileEngineHandler =
nullptr;
564 delete m_androidContentFileEngineHandler;
565 m_androidContentFileEngineHandler =
nullptr;
566 delete m_androidApkFileEngineHandler;
567 m_androidApkFileEngineHandler =
nullptr;
568 delete m_backendRegister;
569 m_backendRegister =
nullptr;
570 sem_post(&m_exitSemaphore);
573 QtNative::callStaticMethod<QtThread>(
"getQtThread").callMethod(
"exit");
577 jint availableWidth, jint availableHeight)
579 QMutexLocker lock(&m_platformMutex);
581 const QRect availableGeometry(0, 0, availableWidth, availableHeight);
582 if (m_androidPlatformIntegration)
583 m_androidPlatformIntegration->setAvailableGeometry(availableGeometry);
584 else if (QAndroidPlatformScreen::defaultAvailableGeometry().isNull())
585 QAndroidPlatformScreen::defaultAvailableGeometry() = availableGeometry;
587Q_DECLARE_JNI_NATIVE_METHOD(handleLayoutSizeChanged)
591 QMutexLocker lock(&m_platformMutex);
600 if (state == Qt::ApplicationActive)
601 QtAndroidPrivate::handleResume();
602 else if (state == Qt::ApplicationInactive)
603 QtAndroidPrivate::handlePause();
608 if (state <= Qt::ApplicationInactive) {
618 QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationState(state));
619 if (state == Qt::ApplicationSuspended)
623 QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationState(state));
630 QCoreApplication::postEvent(QCoreApplication::instance(),
new QEvent(QEvent::LocaleChange));
631 QCoreApplication::postEvent(QCoreApplication::instance(),
new QEvent(QEvent::LanguageChange));
638 static const Qt::ScreenOrientation orientations[] = {
639 Qt::PortraitOrientation,
640 Qt::LandscapeOrientation,
641 Qt::InvertedPortraitOrientation,
642 Qt::InvertedLandscapeOrientation
656 Qt::ScreenOrientation screenOrientation = orientations[(nativeOrientation - 1 + newRotation) % 4];
657 Qt::ScreenOrientation native = orientations[nativeOrientation - 1];
659 QAndroidPlatformIntegration::setScreenOrientation(screenOrientation, native);
660 QMutexLocker lock(&m_platformMutex);
666 QMetaObject::invokeMethod(screen,
"setOrientation", Qt::AutoConnection,
667 Q_ARG(Qt::ScreenOrientation, screenOrientation));
671Q_DECLARE_JNI_NATIVE_METHOD(handleOrientationChanged)
675 if (m_androidPlatformIntegration)
676 m_androidPlatformIntegration->setRefreshRate(refreshRate);
678Q_DECLARE_JNI_NATIVE_METHOD(handleRefreshRateChanged)
682 if (m_androidPlatformIntegration)
683 m_androidPlatformIntegration->handleScreenAdded(displayId);
685Q_DECLARE_JNI_NATIVE_METHOD(handleScreenAdded)
689 if (m_androidPlatformIntegration)
690 m_androidPlatformIntegration->handleScreenChanged(displayId);
692Q_DECLARE_JNI_NATIVE_METHOD(handleScreenChanged)
696 if (m_androidPlatformIntegration)
697 m_androidPlatformIntegration->handleScreenRemoved(displayId);
699Q_DECLARE_JNI_NATIVE_METHOD(handleScreenRemoved)
703 QAndroidPlatformIntegration::updateColorScheme(
704 (newUiMode == 1 ) ? Qt::ColorScheme::Dark : Qt::ColorScheme::Light);
706Q_DECLARE_JNI_NATIVE_METHOD(handleUiDarkModeChanged)
712Q_DECLARE_JNI_NATIVE_METHOD(handleScreenDensityChanged)
719 QtAndroidPrivate::handleActivityResult(requestCode, resultCode, data);
724 QtAndroidPrivate::handleNewIntent(env, data);
729 return QtAndroidPrivate::callOnBindListener(intent);
733 {
"startQtNativeApplication",
"(Ljava/lang/String;)V", (
void *)startQtNativeApplication },
734 {
"terminateQtNativeApplication",
"()V", (
void *)terminateQtNativeApplication },
735 {
"updateApplicationState",
"(I)V", (
void *)updateApplicationState },
736 {
"onActivityResult",
"(IILandroid/content/Intent;)V", (
void *)onActivityResult },
737 {
"onNewIntent",
"(Landroid/content/Intent;)V", (
void *)onNewIntent },
738 {
"onBind",
"(Landroid/content/Intent;)Landroid/os/IBinder;", (
void *)onBind },
739 {
"updateLocale",
"()V", (
void *)updateLocale },
742#define FIND_AND_CHECK_CLASS(CLASS_NAME) clazz
743 = env->FindClass(CLASS_NAME); if
745 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_classErrorMsg, CLASS_NAME);
747}
749#define GET_AND_CHECK_METHOD(VAR, CLASS, METHOD_NAME, METHOD_SIGNATURE) VAR
750 = env->GetMethodID(CLASS, METHOD_NAME, METHOD_SIGNATURE); if
752 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, METHOD_NAME, METHOD_SIGNATURE);
754}
756#define GET_AND_CHECK_STATIC_METHOD(VAR, CLASS, METHOD_NAME, METHOD_SIGNATURE) VAR
757 = env->GetStaticMethodID(CLASS, METHOD_NAME, METHOD_SIGNATURE); if
759 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, METHOD_NAME, METHOD_SIGNATURE);
761}
763#define GET_AND_CHECK_FIELD(VAR, CLASS, FIELD_NAME, FIELD_SIGNATURE) VAR
764 = env->GetFieldID(CLASS, FIELD_NAME, FIELD_SIGNATURE); if
766 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, FIELD_NAME, FIELD_SIGNATURE);
768}
770#define GET_AND_CHECK_STATIC_FIELD(VAR, CLASS, FIELD_NAME, FIELD_SIGNATURE) VAR
771 = env->GetStaticFieldID(CLASS, FIELD_NAME, FIELD_SIGNATURE); if
773 __android_log_print(ANDROID_LOG_FATAL, m_qtTag, m_methodErrorMsg, FIELD_NAME, FIELD_SIGNATURE);
775}
781 bool success = env.registerNativeMethods(m_applicationClass,
782 methods,
sizeof(methods) /
sizeof(methods[0]));
783 success &= env.registerNativeMethods(
784 QtJniTypes::Traits<QtJniTypes::QtDisplayManager>::className(),
786 Q_JNI_NATIVE_METHOD(handleLayoutSizeChanged),
787 Q_JNI_NATIVE_METHOD(handleOrientationChanged),
788 Q_JNI_NATIVE_METHOD(handleRefreshRateChanged),
789 Q_JNI_NATIVE_METHOD(handleScreenAdded),
790 Q_JNI_NATIVE_METHOD(handleScreenChanged),
791 Q_JNI_NATIVE_METHOD(handleScreenRemoved),
792 Q_JNI_NATIVE_METHOD(handleUiDarkModeChanged),
793 Q_JNI_NATIVE_METHOD(handleScreenDensityChanged)
797 && QtAndroidInput::registerNatives(env)
798 && QtAndroidMenu::registerNatives(env)
799#if QT_CONFIG(accessibility)
800 && QtAndroidAccessibility::registerNatives(env)
802 && QtAndroidDialogHelpers::registerNatives(env)
803#if QT_CONFIG(clipboard)
804 && QAndroidPlatformClipboard::registerNatives(env)
806 && QAndroidPlatformWindow::registerNatives(env)
807 && QtAndroidWindowEmbedding::registerNatives(env)
808 && AndroidBackendRegister::registerNatives()
809 && QAndroidModelIndexProxy::registerNatives(env)
810 && QAndroidItemModelProxy::registerAbstractNatives(env)
811 && QAndroidItemModelProxy::registerProxyNatives(env);
818 if (m_applicationClass)
823 m_applicationClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
828 jobject contextObject = env->CallStaticObjectMethod(m_applicationClass, methodID);
829 if (!contextObject) {
831 contextObject = env->CallStaticObjectMethod(m_applicationClass, methodID);
834 if (!contextObject) {
835 __android_log_print(ANDROID_LOG_FATAL,
"Qt",
"Failed to get Activity or Service object");
838 const auto releaseContextObject = qScopeGuard([&env, contextObject]{
839 env->DeleteLocalRef(contextObject);
844 m_assets = env->NewGlobalRef(env->CallObjectMethod(contextObject, methodID));
848 m_resourcesObj = env->NewGlobalRef(env->CallObjectMethod(contextObject, methodID));
851 m_bitmapClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
853 "createBitmap",
"(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;");
857 m_ARGB_8888_BitmapConfigValue = env->NewGlobalRef(env->GetStaticObjectField(clazz, fieldId));
859 m_RGB_565_BitmapConfigValue = env->NewGlobalRef(env->GetStaticObjectField(clazz, fieldId));
862 m_bitmapDrawableClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
864 m_bitmapDrawableClass,
865 "<init>",
"(Landroid/content/res/Resources;Landroid/graphics/Bitmap;)V");
868 m_qtActivityClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
870 m_qtServiceClass =
static_cast<jclass>(env->NewGlobalRef(clazz));
873 QThread::currentThread()->setObjectName(
"QtMainLoopThread");
875 QWindowSystemInterfacePrivate::TabletEvent::setPlatformSynthesizesMouse(
false);
882Q_DECL_EXPORT jint JNICALL JNI_OnLoad(JavaVM *,
void *)
884 static bool initialized =
false;
886 return JNI_VERSION_1_6;
892 if (!env.isValid()) {
893 __android_log_print(ANDROID_LOG_FATAL,
"Qt",
"Failed to initialize the JNI Environment");
897 if (!initJavaReferences(env))
900 if (!registerNatives(env)) {
901 __android_log_print(ANDROID_LOG_FATAL,
"Qt",
"registerNatives failed");
905 __android_log_print(ANDROID_LOG_INFO,
"Qt",
"Qt platform plugin started");
906 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 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)
static void initializeBackends()
#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 bool initCleanupHandshakeSemaphores()
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 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")