Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qohosjsmain.cpp
Go to the documentation of this file.
1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#include "qohosjsmain.h"
5
6#include <qplugin.h>
7#include <dlfcn.h>
8#include <node_api.h>
9#include <napi/native_api.h>
10#include <hilog/log.h>
11#include <pthread.h>
12#include <qos/qos.h>
13#include <QtCore/qbytearray.h>
14#include <QtCore/qdebug.h>
15#include <QtCore/qglobal.h>
16#include <QtCore/qjsonarray.h>
17#include <QtCore/qjsondocument.h>
18#include <QtCore/qjsonobject.h>
19#include <QtCore/qmap.h>
20#include <QtCore/qwaitcondition.h>
21#include <QtCore/qdir.h>
22#include <QtCore/private/qcore_unix_p.h>
23#include <QtCore/qvariant.h>
24#include <QtCore/private/qnapi_p.h>
25#include <QtCore/private/qohosabilitylaunchparamstore_p.h>
26#include <QtCore/private/qohosappcontext_p.h>
27#include <QtCore/private/qohoscommon_p.h>
28#include <QtCore/private/qohospermissionshelper_p.h>
29#include <QtCore/private/qcoreapplication_p.h>
32#include <algorithm>
33#include <cerrno>
34#include <chrono>
35#include <cstdio>
36#include <cstring>
37#include <limits>
38#include <qohossinglethreadexecutor.h>
39#include <qpa/qwindowsysteminterface.h>
40#include <map>
41#include <qohosapppermissions_p.h>
42#include <qohosdeviceinfo_p.h>
43#include <qohospermissionshelperimpl.h>
44#include <qohosplugincore.h>
45#include <qohosqpaenums.h>
46#include <signal.h>
47#include <string>
48#include <sys/resource.h>
49#include <type_traits>
50#include <cstdlib>
51#include <optional>
52#include <unordered_map>
53#include <vector>
54
55#include "qarkui/qxcomponentregistry.h"
58#include "qohosjsutils.h"
63#include "qohosutils.h"
64#include "qohoswatchdog.h"
67#include "render/qxcomponent.h"
68
70
71using namespace std::chrono_literals;
72
74
76struct {
77 std::optional<std::uint64_t> lastRequestedInJsThread;
78 std::optional<std::uint64_t> activeInQtThread;
79} s_hotStartIteration;
81extern "C" typedef int (*Main)(int, char **); //use the standard main method to start the application
82
84
86static std::string s_appSharedLibName;
88static int s_appExitCode = 0;
89static std::string s_exitCodeFilePath;
90
91static bool s_hotStartEnabled = false;
92
93namespace QtOhos {
94
95namespace {
96
97constexpr const char *enableHotStartEnvVariableName = "IO__QT__OHOS__ENABLE_HOT_START";
98
99constexpr const char *forceLoadJsModulesEnvVariableName = "IO__QT__OHOS__FORCE_LOAD_JS_MODULES";
100
101constexpr const char *qtMainThreadStackSizeEnvVariableName = "IO__QT__OHOS__QT_MAIN_THREAD_STACK_SIZE";
102
103constexpr std::size_t defaultQtThreadStackSize = 8 * 1024 * 1024;
104
105constexpr auto minSupportedOhosSdkApiVersion = 26;
107
108std::atomic<bool> experimentalEnableGlBackinStore{false};
109std::atomic<bool> debugUseBasicStyleAndTheme{false};
110std::atomic<bool> debugDrawQtRasterBackingStoreFlushedRegion{false};
111std::atomic<bool> vsyncOnSoftwareBackingStoreEnabled{true};
112std::atomic<bool> enableNativeNodeApiKeyEvents{true};
113std::atomic<bool> enableNativeNodeApiMouseEvents{true};
114bool emulatorQuirkWorkaroundsEnabled = false;
115QtRunMode currentQtRunMode = QtRunMode::Normal;
116
117const auto callerPidWantArgName = "ohos.aafwk.param.callerPid";
118const auto qtAppProcessIdWantArgName = "io.qt.appProcessId";
119
120const char *mapQtRunModeToString(QtRunMode qtRunMode)
121{
122 switch (qtRunMode) {
124 return "Normal";
126 return "NoUiChildProcess";
127 }
128
129 qOhosReportFatalErrorAndAbort(
130 "%s: got unknown QtRunMode value: %d",
131 Q_FUNC_INFO, static_cast<int>(qtRunMode));
132}
133
134struct QtAppStartConfig
135{
136 std::string appLibraryPath;
137 bool watchdogEnabled = true;
138};
139
140class AppContextDirs
141{
142public:
143 static AppContextDirs mapFromNapiObject(QNapi::Object appContextObj);
144 static AppContextDirs mapFromQOhosAppContextProperties(const QMap<QOhosAppContext::Type, QString> &props);
145
146 QMap<QOhosAppContext::Type, QString> mapToQOhosAppContextProperties() const;
147 QJsonObject mapToQJsonObject() const;
148
149 std::string bundleCodeDir;
150 std::string cacheDir;
151 std::string filesDir;
152 std::string preferencesDir;
153 std::string tempDir;
154 std::string databaseDir;
155 std::string distributedFilesDir;
156 std::string resourceDir;
157
158private:
159 static const std::pair<const char *, std::string AppContextDirs::*> propsNames[];
160 static const std::pair<QOhosAppContext::Type, std::string AppContextDirs::*> qOhosAppContextPropsMap[];
161};
162
163const std::pair<const char *, std::string AppContextDirs::*> AppContextDirs::propsNames[] = {
164 {"bundleCodeDir", &AppContextDirs::bundleCodeDir},
165 {"cacheDir", &AppContextDirs::cacheDir},
166 {"filesDir", &AppContextDirs::filesDir},
167 {"preferencesDir", &AppContextDirs::preferencesDir},
168 {"tempDir", &AppContextDirs::tempDir},
169 {"databaseDir", &AppContextDirs::databaseDir},
170 {"distributedFilesDir", &AppContextDirs::distributedFilesDir},
171 {"resourceDir", &AppContextDirs::resourceDir},
172};
173
174const std::pair<QOhosAppContext::Type, std::string AppContextDirs::*> AppContextDirs::qOhosAppContextPropsMap[] = {
175 {QOhosAppContext::Type::bundleCodeDir, &AppContextDirs::bundleCodeDir},
176 {QOhosAppContext::Type::cacheDir, &AppContextDirs::cacheDir},
177 {QOhosAppContext::Type::filesDir, &AppContextDirs::filesDir},
178 {QOhosAppContext::Type::preferencesDir, &AppContextDirs::preferencesDir},
179 {QOhosAppContext::Type::tempDir, &AppContextDirs::tempDir},
180 {QOhosAppContext::Type::databaseDir, &AppContextDirs::databaseDir},
181 {QOhosAppContext::Type::distributedFilesDir, &AppContextDirs::distributedFilesDir},
182 {QOhosAppContext::Type::resourceDir, &AppContextDirs::resourceDir},
183};
184
185AppContextDirs AppContextDirs::mapFromNapiObject(QNapi::Object appContextObj)
186{
187 AppContextDirs appContextDirs;
188 for (const auto &propEntry : propsNames)
189 appContextDirs.*propEntry.second = appContextObj.get<QNapi::String>(propEntry.first);
190
191 return appContextDirs;
192}
193
194AppContextDirs AppContextDirs::mapFromQOhosAppContextProperties(
195 const QMap<QOhosAppContext::Type, QString> &props)
196{
197 AppContextDirs appContextDirs;
198 for (const auto &propEntry : qOhosAppContextPropsMap)
199 appContextDirs.*propEntry.second = props[propEntry.first].toStdString();
200 return appContextDirs;
201}
202
203QMap<QOhosAppContext::Type, QString> AppContextDirs::mapToQOhosAppContextProperties() const
204{
205 QMap<QOhosAppContext::Type, QString> qOhosAppContextProps;
206 for (const auto &propEntry : qOhosAppContextPropsMap)
207 qOhosAppContextProps[propEntry.first] = QString::fromStdString(this->*propEntry.second);
208 return qOhosAppContextProps;
209}
210
211QJsonObject AppContextDirs::mapToQJsonObject() const
212{
213 QJsonObject json;
214 for (const auto &propEntry : propsNames)
215 json[QString::fromUtf8(propEntry.first)] = QString::fromStdString(this->*propEntry.second);
216 return json;
217}
218
219std::vector<std::string> splitString(const std::string &inputStr, char separator)
220{
221 constexpr auto separatorSize = 1;
222
223 std::vector<std::string> result;
224 std::size_t currentPos = 0;
225 while (currentPos < inputStr.size()) {
226 auto separatorPos = inputStr.find(separator, currentPos);
227 result.push_back(inputStr.substr(currentPos, separatorPos));
228 currentPos = separatorPos != std::string::npos
229 ? separatorPos + separatorSize
230 : inputStr.size();
231 }
232
233 return result;
234}
235
236std::pair<QOhosConsumer<bool>, std::function<void()>> makeConditionFlagMTAccessors(
237 std::string conditionName)
238{
239 struct Context
240 {
241 std::string conditionName;
242 std::mutex conditionMutex;
243 std::condition_variable conditionCv;
244 bool condition = false;
245 };
246
247 auto context = std::make_shared<Context>();
248 context->conditionName = std::move(conditionName);
249
250 return {
251 [context](bool condition) {
252 qOhosPrintfDebug(
253 "%s: setting condition '%s' to %s",
254 Q_FUNC_INFO, context->conditionName.c_str(), mapBoolToTrueFalseStr(condition));
255 {
256 std::lock_guard<std::mutex> conditionLock(context->conditionMutex);
257 if (condition != context->condition) {
258 context->condition = condition;
259 context->conditionCv.notify_all();
260 }
261 }
262 },
263 [context]() {
264 qOhosPrintfDebug("%s: waiting for condition '%s'", Q_FUNC_INFO, context->conditionName.c_str());
265 {
266 std::unique_lock<std::mutex> conditionLock(context->conditionMutex);
267 context->conditionCv.wait(
268 conditionLock,
269 [&]() {
270 return context->condition;
271 });
272 }
273 qOhosPrintfDebug("%s: condition '%s' met", Q_FUNC_INFO, context->conditionName.c_str());
274 },
275 };
276}
277
278template<typename FuncResult, typename ...FuncArgs, typename FuncFactory>
279auto makeLazyInitFunc(FuncFactory funcFactory) -> std::function<FuncResult(FuncArgs...)>
280{
281 using Func = std::function<FuncResult(FuncArgs...)>;
282 return [func = Func(), factory = QOhosSupplier<Func>(std::move(funcFactory))](FuncArgs ...args) mutable {
283 if (!func)
284 func = std::exchange(factory, nullptr)();
285 return func(std::forward<FuncArgs>(args)...);
286 };
287}
288
289std::function<int(std::vector<std::string>)> openLibraryWithMainFunctionOrFail(const std::string &libraryPath)
290{
291 void *mainLibraryHnd = dlopen(libraryPath.c_str(), RTLD_LAZY);
292 if (Q_UNLIKELY(!mainLibraryHnd)) {
293 qOhosReportFatalErrorAndAbort(
294 "%s: dlopen() failed to open library '%s': %s",
295 Q_FUNC_INFO, libraryPath.c_str(), dlerror());
296 }
297
298 auto *mainFunc = reinterpret_cast<Main>(dlsym(mainLibraryHnd, "main"));
299 if (Q_UNLIKELY(!mainFunc)) {
300 qOhosReportFatalErrorAndAbort(
301 "%s: dlsym() failed to find 'main' symbol in library '%s': %s",
302 Q_FUNC_INFO, libraryPath.c_str(), dlerror());
303 }
304
305 qOhosPrintfDebug("%s: opened library '%s' with main function", Q_FUNC_INFO, libraryPath.c_str());
306
307 return [libraryPath, mainFunc](std::vector<std::string> mainArgs) {
308 auto mainArgsPointers = std::vector<char *>();
309 for (auto &arg : mainArgs)
310 mainArgsPointers.push_back(&arg[0]);
311 mainArgsPointers.push_back(nullptr);
312
313 int argc = mainArgs.size();
314 char **argv = &mainArgsPointers[0];
315
316 qOhosPrintfDebug(
317 "%s: calling 'main' function in library '%s' (argc=%d)",
318 Q_FUNC_INFO, libraryPath.c_str(), argc);
319
320 for (int i = 0; i < argc; ++i)
321 qOhosPrintfDebug("%s: 'main' function argv[%d]='%s'", Q_FUNC_INFO, i, argv[i]);
322
323 int mainResult = mainFunc(argc, argv);
324
325 qOhosPrintfDebug(
326 "%s: 'main' function in library '%s' returned %d",
327 Q_FUNC_INFO, libraryPath.c_str(), mainResult);
328
329 return mainResult;
330 };
331}
332
333void redirectStandardDescriptorsToFile(const std::string &redirectedStdoutPath)
334{
335 int openResult = qt_safe_open(redirectedStdoutPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
336 auto openErrno = errno;
337 if (openResult < 0) {
338 // Non-fatal: the test still needs to write its exit code.
339 qOhosPrintfWarning("%s: error opening file '%s' for redirected stdout: %s",
340 Q_FUNC_INFO, redirectedStdoutPath.c_str(), std::strerror(openErrno));
341 return;
342 }
343
344 ::fflush(stdout);
345
346 if (qt_safe_dup2(openResult, STDOUT_FILENO) < 0) {
347 auto dup2Errno = errno;
348 qOhosPrintfWarning("%s: dup2() failed on redirecting stdout to '%s': %s",
349 Q_FUNC_INFO, redirectedStdoutPath.c_str(), std::strerror(dup2Errno));
350 }
351
352 qt_safe_close(openResult);
353}
354
355QOhosConsumer<std::vector<std::string>> makeAppMainFuncLauncher(
356 const QtAppStartConfig &appStartConfig, QOhosConsumer<int> funcExitHandler)
357{
358 auto appLibraryMainFunc = makeLazyInitFunc<int, std::vector<std::string>>(
359 [appLibraryPath = appStartConfig.appLibraryPath]() {
360 return openLibraryWithMainFunctionOrFail(appLibraryPath);
361 });
362
363 return [appLibraryMainFunc = std::move(appLibraryMainFunc), funcExitHandler = std::move(funcExitHandler), appStartConfig](std::vector<std::string> appArgs) {
364 auto __dbg = make_QCScopedDebugJS("startApplicationMainFunction");
365 std::vector<std::string> mainArgs;
366 mainArgs.push_back(appStartConfig.appLibraryPath);
367 mainArgs.insert(mainArgs.end(), appArgs.begin(), appArgs.end());
368
369 auto qtWatchdog =
370 appStartConfig.watchdogEnabled
372 : std::shared_ptr<void>();
373
374 int exitCode = appLibraryMainFunc(std::move(mainArgs));
375
376 funcExitHandler(exitCode);
377 };
378}
379
380std::optional<std::vector<std::string>> tryMapJsonArrayToStrings(const std::string &inputJson)
381{
382 auto doc = QJsonDocument::fromJson(QByteArray::fromStdString(inputJson));
383 if (doc.isNull()) {
384 qOhosPrintfWarning("%s: input is not valid JSON string", Q_FUNC_INFO);
385 return std::nullopt;
386 }
387 if (!doc.isArray()) {
388 qOhosPrintfWarning("%s: input JSON does not contain an array", Q_FUNC_INFO);
389 return std::nullopt;
390 }
391
392 const auto inputArray = doc.array();
393
394 std::vector<std::string> result;
395 for (const auto &elem : inputArray) {
396 if (!elem.isString()) {
397 qOhosPrintfWarning("%s: input array's element is not a string", Q_FUNC_INFO);
398 return std::nullopt;
399 }
400 result.push_back(elem.toString().toStdString());
401 }
402
403 return result;
404}
405
406std::optional<std::vector<std::pair<std::string, std::string>>>
407tryMapJsonObjectToStringPairs(const std::string &inputJson)
408{
409 auto doc = QJsonDocument::fromJson(QByteArray::fromStdString(inputJson));
410 if (doc.isNull()) {
411 qOhosPrintfWarning("%s: input is not valid JSON string", Q_FUNC_INFO);
412 return std::nullopt;
413 }
414 if (!doc.isObject()) {
415 qOhosPrintfWarning("%s: input JSON does not contain an object", Q_FUNC_INFO);
416 return std::nullopt;
417 }
418
419 const auto inputObject = doc.object();
420
421 std::vector<std::pair<std::string, std::string>> result;
422 for (auto it = inputObject.constBegin(); it != inputObject.constEnd(); ++it) {
423 if (!it->isString()) {
424 qOhosPrintfWarning("%s: input object's value is not a string", Q_FUNC_INFO);
425 return std::nullopt;
426 }
427 result.emplace_back(it.key().toStdString(), it->toString().toStdString());
428 }
429
430 return result;
431}
432
433template<typename T>
434std::enable_if_t<std::is_base_of<QNapi::Value, T>::value, T>
435getWantParamOrEmptyIfNotPresent(QNapi::Object want, const std::string &paramName)
436{
437 return QNapi::getOptionalPropOrEmpty<T>(
438 QNapi::getOptionalPropOrEmpty<QNapi::Object>(want, "parameters"),
439 paramName, "parameters of Want");
440}
441
442std::vector<std::string> getQtAppArgsFromWant(QNapi::Object want)
443{
444 using namespace std::string_literals;
445
446 const auto *qtObsoleteUseUriAsArgPropName = "io.qt.useUriAsArg";
447 const auto *qtAppArgsPropName = "io.qt.appArgs";
448 const auto *qtAppArgsJsonPropName = "io.qt.appArgsJson";
449
450 Napi::HandleScope getArgsScope(want.Env());
451
452 std::vector<std::string> result;
453
454 auto optWantParams = QNapi::getOptionalPropOrEmpty<QNapi::Object>(want, "parameters");
455 if (!optWantParams.IsEmpty() && optWantParams.Has(qtObsoleteUseUriAsArgPropName)) {
456 qOhosPrintfWarning(
457 "Qt: Want parameter '%s' is obsolete and is ignored. The ability launch URI is no "
458 "longer passed as an application argument.",
459 qtObsoleteUseUriAsArgPropName);
460 }
461
462 auto optQtAppArgs = getWantParamOrEmptyIfNotPresent<QNapi::Array>(want, qtAppArgsPropName);
463 auto optQtAppArgsJson = getWantParamOrEmptyIfNotPresent<QNapi::String>(want, qtAppArgsJsonPropName);
464
465 if (!optQtAppArgs.IsEmpty()) {
466 if (!QNapi::arrayElementTypesMatch<QNapi::String>(optQtAppArgs)) {
467 throw QNapi::makeLoggedException(
468 want.Env(), "Want parameter '"s + qtAppArgsPropName + "' is not an array of strings"s);
469 }
470
471 auto qtAppArgsStrings = QNapi::getArrayElements<std::vector<std::string>, QNapi::String>(optQtAppArgs);
472 result.insert(result.end(), qtAppArgsStrings.begin(), qtAppArgsStrings.end());
473 } else if (!optQtAppArgsJson.IsEmpty()) {
474 auto optQtAppArgsJsonStrings = tryMapJsonArrayToStrings(optQtAppArgsJson);
475 if (!optQtAppArgsJsonStrings) {
476 throw QNapi::makeLoggedException(
477 want.Env(), "Want parameter '"s + qtAppArgsJsonPropName + "' is invalid"s);
478 }
479 result.insert(result.end(), optQtAppArgsJsonStrings->begin(), optQtAppArgsJsonStrings->end());
480 }
481
482 return result;
483}
484
485void requestAppPermissionsInBackground(JsState &jsState, const std::vector<std::string> &permissionsNames)
486{
487 for (const auto &permissionName : permissionsNames) {
488 qOhosPrintfInfo(
489 "Qt: automatically requesting application permission: '%s'",
490 permissionName.c_str());
491
492 QOhosAppPermissions::requestAppPermissionFromUser(
493 jsState, permissionName,
494 [permissionName](QOhosJsState &, bool permissionGranted) {
495 if (permissionGranted) {
496 qOhosPrintfInfo(
497 "Qt: automatically requested application permission granted: '%s'",
498 permissionName.c_str());
499 } else {
500 qOhosPrintfWarning(
501 "Qt: automatically requested application permission rejected: '%s'",
502 permissionName.c_str());
503 }
504 });
505 }
506}
507
508struct AppProcessLaunchOptions
509{
510 QNapi::Boolean useDefaultUiAbilityInstanceInQt;
511 QNapi::String appSharedLibNameOverride;
512 QNapi::Boolean experimentalGlBackingStore;
513 QNapi::Boolean debugDrawQtRasterBackingStoreFlushedRegion;
514 QNapi::Boolean debugUseBasicStyleAndTheme;
515 QNapi::Boolean enableVsyncOnSoftwareBackingStore;
516 QNapi::Boolean watchdogEnabled;
517 QNapi::String redirectStdoutToFile;
518 QNapi::String exitCodeFile;
519 QNapi::String autoRequestPermissions;
520 QNapi::Boolean enableNativeNodeApiKeyEvents;
521 QNapi::Boolean enableNativeNodeApiMouseEvents;
522 QNapi::String envVarsJson;
523 QNapi::Boolean enableEmulatorQuirkWorkarounds;
524};
525
526AppProcessLaunchOptions getProcessLaunchOptionsFromWant(QNapi::Object launchWant)
527{
528 auto assignWantParamIfPresent = [&](auto &outputValue, const char *paramName) {
529 using Param = std::remove_reference_t<decltype(outputValue)>;
530 outputValue = getWantParamOrEmptyIfNotPresent<Param>(launchWant, paramName);
531 };
532
533 AppProcessLaunchOptions launchOpts;
534
535 assignWantParamIfPresent(
536 launchOpts.useDefaultUiAbilityInstanceInQt,
537 "io.qt.useDefaultUiAbilityInstanceInQt");
538 assignWantParamIfPresent(
539 launchOpts.appSharedLibNameOverride,
540 "io.qt.appSharedLibNameOverride");
541 assignWantParamIfPresent(
542 launchOpts.experimentalGlBackingStore,
543 "io.qt.experimental.enableGlBackingStore");
544 assignWantParamIfPresent(
545 launchOpts.debugDrawQtRasterBackingStoreFlushedRegion,
546 "io.qt.debug.drawQtRasterBackingStoreFlushedRegion");
547 assignWantParamIfPresent(
548 launchOpts.debugUseBasicStyleAndTheme,
549 "io.qt.debug.useBasicStyleAndTheme");
550 assignWantParamIfPresent(
551 launchOpts.enableVsyncOnSoftwareBackingStore,
552 "io.qt.experimental.enableVsyncOnSoftwareBackingStore");
553 assignWantParamIfPresent(
554 launchOpts.watchdogEnabled,
555 "io.qt.watchdogEnabled");
556 assignWantParamIfPresent(
557 launchOpts.redirectStdoutToFile,
558 "io.qt.debug.redirectedStdoutPath");
559 assignWantParamIfPresent(
560 launchOpts.exitCodeFile,
561 "io.qt.debug.exitCodePath");
562 assignWantParamIfPresent(
563 launchOpts.autoRequestPermissions,
564 "io.qt.debug.autoRequestPermissions");
565 assignWantParamIfPresent(
566 launchOpts.enableNativeNodeApiKeyEvents,
567 "io.qt.experimental.enableNativeNodeApiKeyEvents");
568 assignWantParamIfPresent(
569 launchOpts.enableNativeNodeApiMouseEvents,
570 "io.qt.experimental.enableNativeNodeApiMouseEvents");
571 assignWantParamIfPresent(
572 launchOpts.envVarsJson,
573 "io.qt.envVarsJson");
574 assignWantParamIfPresent(
575 launchOpts.enableEmulatorQuirkWorkarounds,
576 "io.qt.debug.enableEmulatorQuirkWorkarounds");
577
578 return launchOpts;
579}
580
581void setGlobalFlagsFromAppProcessLaunchOptions(const AppProcessLaunchOptions &launchOpts)
582{
583 if (!launchOpts.useDefaultUiAbilityInstanceInQt.IsEmpty())
584 s_autoStartedAbilityInstanceWaitingForQtWindow = launchOpts.useDefaultUiAbilityInstanceInQt.Value();
585
586 if (!launchOpts.experimentalGlBackingStore.IsEmpty())
587 experimentalEnableGlBackinStore = launchOpts.experimentalGlBackingStore.Value();
588
589 if (!launchOpts.debugUseBasicStyleAndTheme.IsEmpty())
590 debugUseBasicStyleAndTheme = launchOpts.debugUseBasicStyleAndTheme.Value();
591
592 if (!launchOpts.enableVsyncOnSoftwareBackingStore.IsEmpty())
593 vsyncOnSoftwareBackingStoreEnabled = launchOpts.enableVsyncOnSoftwareBackingStore.Value();
594
595 debugDrawQtRasterBackingStoreFlushedRegion =
596 launchOpts.debugDrawQtRasterBackingStoreFlushedRegion.IsEmpty()
597 ? false
598 : launchOpts.debugDrawQtRasterBackingStoreFlushedRegion.Value();
599
600 if (!launchOpts.enableNativeNodeApiKeyEvents.IsEmpty())
601 enableNativeNodeApiKeyEvents = launchOpts.enableNativeNodeApiKeyEvents.Value();
602
603 if (!launchOpts.enableNativeNodeApiMouseEvents.IsEmpty())
604 enableNativeNodeApiMouseEvents = launchOpts.enableNativeNodeApiMouseEvents.Value();
605
606 if (!launchOpts.enableEmulatorQuirkWorkarounds.IsEmpty())
607 emulatorQuirkWorkaroundsEnabled = launchOpts.enableEmulatorQuirkWorkarounds.Value();
608
609 if (!launchOpts.envVarsJson.IsEmpty()) {
610 auto optEnvVars = tryMapJsonObjectToStringPairs(launchOpts.envVarsJson.Utf8Value());
611 if (optEnvVars) {
612 for (const auto &[name, value] : *optEnvVars)
613 qputenv(name.c_str(), QByteArray::fromStdString(value));
614 }
615 }
616}
617
618void terminateAllAbilityInstances(JsState &jsState, const char *logContext)
619{
620 QAbilityInstancesManager::instance(jsState).visitEachQAbilityPeer(
621 [&](auto qAbilityPeer) {
622 qOhosPrintfInfo(
623 "Qt: terminating QAbility with instanceId='%s'",
624 qAbilityPeer->instanceId().c_str());
625 auto optQUiAbilityPeer = QUiAbilityPeer::tryCastFromQAbilityPeerOrNull(qAbilityPeer);
626 if (optQUiAbilityPeer)
627 JsWindowsTracker::tagWindowAsClosing(optQUiAbilityPeer->window(), logContext);
628 qAbilityPeer->qAbility().eval("context.terminateSelf()");
629 });
630}
631
632std::optional<std::size_t> tryGetMaxStackSizeHardLimit()
633{
634 struct ::rlimit limit;
635 if (::getrlimit(RLIMIT_STACK, &limit) != 0) {
636 auto getrlimitErrno = errno;
637 qOhosPrintfWarning(
638 "%s: error reading stack size hard limit (assuming no limit): %s",
639 Q_FUNC_INFO, std::strerror(getrlimitErrno));
640 return std::nullopt;
641 }
642
643 return limit.rlim_max != RLIM_INFINITY
644 ? std::optional<std::size_t>(limit.rlim_max)
645 : std::nullopt;
646}
647
648std::optional<std::size_t> tryGetQtThreadStackSizeFromEnv()
649{
650 int stackSizeFromEnv = qEnvironmentVariableIntValue(qtMainThreadStackSizeEnvVariableName);
651 return stackSizeFromEnv > 0
652 ? std::optional(static_cast<std::size_t>(stackSizeFromEnv))
653 : std::nullopt;
654}
655
656std::size_t getPreferredStackSizeForQtThread()
657{
658 constexpr std::size_t qtRequiredMinStackSize = 40960;
659 std::size_t pthreadStackMin = PTHREAD_STACK_MIN;
660 auto minStackSize = std::max({qtRequiredMinStackSize, pthreadStackMin});
661 auto maxStackSize = tryGetMaxStackSizeHardLimit().value_or(std::numeric_limits<std::size_t>::max());
662
663 auto optRequestedStackSize = tryGetQtThreadStackSizeFromEnv();
664
665 if (optRequestedStackSize.has_value()) {
666 auto requestedStackSize = optRequestedStackSize.value();
667 if (requestedStackSize < minStackSize) {
668 qOhosPrintfWarning(
669 "%s: requested stack size (%zu) is below minimum (pthread min: %zu, Qt min: %zu), increasing",
670 Q_FUNC_INFO, requestedStackSize, pthreadStackMin, qtRequiredMinStackSize);
671 }
672 if (requestedStackSize > maxStackSize) {
673 qOhosPrintfWarning(
674 "%s: requested stack size (%zu) is above maximum (hard limit: %zu), decreasing",
675 Q_FUNC_INFO, requestedStackSize, maxStackSize);
676 }
677 }
678
679 auto preferredStackSize = qBound(
680 minStackSize, optRequestedStackSize.value_or(defaultQtThreadStackSize), maxStackSize);
681
682 qOhosPrintfInfo("%s: preferred stack size for Qt Thread: %zu", Q_FUNC_INFO, preferredStackSize);
683
684 return preferredStackSize;
685}
686
687QOhosConsumer<std::vector<std::string>> makeQtThreadWithMainFuncLauncher(
688 QOhosConsumer<std::vector<std::string>> baseMainFuncLauncher)
689{
690 SingleThreadExecutorConfig qtThreadExecutorConfig = {
691 .threadPreferredStackSize = getPreferredStackSizeForQtThread(),
692 };
693 auto qtThreadExecutor = makeSingleThreadExecutor(qtThreadExecutorConfig);
694
695 struct InitContext
696 {
697 std::mutex initializedMutex;
698 std::condition_variable initializedCv;
699 bool initialized = false;
700 };
701
702 auto initContext = std::make_shared<InitContext>();
703
704 qtThreadExecutor(
705 [initContext] {
706 pthread_setname_np(pthread_self(), "QtMainThread");
707 //
708 // Following call to QThread::currentThread() forces this thread to be
709 // the main Qt/GUI thread. It sets the QCoreApplication::theMainThread field
710 // if this call is the first one.
711 //
712 auto *currentThread = QThread::currentThread();
713 QThread *mainThread = QCoreApplicationPrivate::theMainThread;
714 if (mainThread != currentThread) {
715 qOhosReportFatalErrorAndAbort(
716 "%s: mainThread (%p) != currentThread (%p). Qt API was likely used before Qt initialization. Aborting.",
717 Q_FUNC_INFO, mainThread, currentThread);
718 }
719
720 qt_setQOhosPermissionsHelper(getQOhosPermissionsHelperImpl());
721
722 QtOhos::initQtThreadState();
723
724 {
725 std::lock_guard<std::mutex> initializedLock(initContext->initializedMutex);
726 initContext->initialized = true;
727 initContext->initializedCv.notify_one();
728 }
729 });
730
731 {
732 std::unique_lock<std::mutex> initializedLock(initContext->initializedMutex);
733 initContext->initializedCv.wait(
734 initializedLock,
735 [&]() {
736 return initContext->initialized;
737 });
738 }
739
740 auto sharedBaseMainFuncLauncher = moveToSharedPtr(std::move(baseMainFuncLauncher));
741
742 return [qtThreadExecutor = std::move(qtThreadExecutor), sharedBaseMainFuncLauncher](std::vector<std::string> appArgs) {
743 qtThreadExecutor(
744 [sharedBaseMainFuncLauncher, appArgs = std::move(appArgs)]() mutable {
745 (*sharedBaseMainFuncLauncher)(std::move(appArgs));
746 });
747 };
748}
749
750void handleDefaultQAbilityInstanceStartup(JsState &jsState, std::shared_ptr<QAbilityPeer> qAbilityPeer)
751{
752 QNapi::Object launchWant = qAbilityPeer->launchWant();
753
754 if (!s_qtAppThreadMainFuncLauncher) {
755 auto qtAppThreadIdleSetFunc = std::make_shared<QOhosConsumer<bool>>();
756 std::function<void()> qtAppThreadIdleStateWaitFunc;
757 std::tie(*qtAppThreadIdleSetFunc, qtAppThreadIdleStateWaitFunc) = makeConditionFlagMTAccessors("Qt thread idle");
758
759 auto launchOpts = getProcessLaunchOptionsFromWant(launchWant);
760
761 setGlobalFlagsFromAppProcessLaunchOptions(launchOpts);
762
764 QAbilityInstancesManager::instance(jsState).setUnusedAutoStartedQAbilityPeer(qAbilityPeer);
765
766 if (!launchOpts.redirectStdoutToFile.IsEmpty())
767 redirectStandardDescriptorsToFile(launchOpts.redirectStdoutToFile.Utf8Value());
768
769 if (!launchOpts.exitCodeFile.IsEmpty())
770 s_exitCodeFilePath = launchOpts.exitCodeFile.Utf8Value();
771
772 if (!launchOpts.autoRequestPermissions.IsEmpty())
773 requestAppPermissionsInBackground(jsState, splitString(launchOpts.autoRequestPermissions, ','));
774
775 QOhosRawFile::installEngineHandler(jsState, qAbilityPeer->qAbility());
776
777 std::string appSharedLibName =
778 !launchOpts.appSharedLibNameOverride.IsEmpty()
779 ? launchOpts.appSharedLibNameOverride
781
782 auto appMainFuncLauncher = makeAppMainFuncLauncher(
783 {
784 .appLibraryPath = s_appSharedLibsDirPath + "/" + appSharedLibName,
785 .watchdogEnabled = !launchOpts.watchdogEnabled.IsEmpty()
786 ? launchOpts.watchdogEnabled.Value()
787 : true,
788 },
789 [qtAppThreadIdleSetFunc](int exitCode) {
790 if (s_hotStartEnabled)
791 s_autoStartedAbilityInstanceWaitingForQtWindow = true;
792 else
793 s_appExitCode = exitCode;
794
795 qOhosPrintfInfo("Qt: asynchronously terminating remaining QAbility instances, if any");
796 QOhosJsThreadGateway::invoke(
797 [](QOhosJsState &jsState) {
798 auto &pluginJsState = JsState::castFrom(jsState);
799 auto &qAbilityInstancesManager = QAbilityInstancesManager::instance(jsState);
800 if (s_hotStartEnabled)
801 qAbilityInstancesManager.registerPendingAutoStartedInstance(&handleDefaultQAbilityInstanceStartup);
802
803 qOhosPrintfInfo(
804 "Qt: force-resolving pending QWindow destroy Promises before termination if needed");
805 qAbilityInstancesManager.visitEachQAbilityPeer(
806 [&](std::shared_ptr<QtOhos::QAbilityPeer> peer) {
807 peer->forceResolveQWindowDestroyPromiseIfPresent(
808 Napi::Env(jsState.env()));
809 });
810
811 terminateAllAbilityInstances(pluginJsState, "Qt main() exit");
812 });
813
814 (*qtAppThreadIdleSetFunc)(true);
815 });
816
817 auto mainFuncLauncher = moveToSharedPtr(
818 makeQtThreadWithMainFuncLauncher(std::move(appMainFuncLauncher)));
819 s_qtAppThreadMainFuncLauncher = [mainFuncLauncher, qtAppThreadIdleSetFunc](std::vector<std::string> appArgs) {
820 (*qtAppThreadIdleSetFunc)(false);
821 s_hotStartIteration.activeInQtThread = s_hotStartIteration.activeInQtThread.value_or(0) + 1;
822 (*mainFuncLauncher)(std::move(appArgs));
823 };
824 s_qtAppThreadIdleStateWaitFunc = std::move(qtAppThreadIdleStateWaitFunc);
825 }
826
827 s_hotStartIteration.lastRequestedInJsThread = s_hotStartIteration.lastRequestedInJsThread.value_or(0) + 1;
829 s_appArgs
830 ? *s_appArgs
831 : getQtAppArgsFromWant(launchWant));
832}
833
834std::map<std::string, QNapi::Reference<QNapi::Function>> makeJsModulesFactoriesMap(
835 const QNapi::Object &jsModulesFactoriesObj)
836{
837 std::map<std::string, QNapi::Reference<QNapi::Function>> jsModulesFactoriesMap;
838 for (const auto &prop : jsModulesFactoriesObj) {
839 if (prop.first.IsString()) {
840 auto propName = QNapi::checkedCast<QNapi::String>(prop.first);
841 QNapi::Value propValue = prop.second;
842 if (propValue.IsFunction()) {
843 jsModulesFactoriesMap.emplace(
844 propName.Utf8Value(),
845 QNapi::Reference<QNapi::Function>::makePersistentFrom(
846 QNapi::checkedCast<QNapi::Function>(propValue)));
847 }
848 }
849 }
850
851 return jsModulesFactoriesMap;
852}
853
854class AppFunctionsImpl : public AppFunctions
855{
856public:
857 void startAppProcess(
858 QNapi::Object baseQAbility, const std::string &processId, QNapi::Object requestWant,
859 QNapi::Object optStartOptions, std::function<void(JsState &)> continueFunc) override;
860
861 void startNoUiChildProcess(JsState &jsState, const std::string &libraryName, const std::vector<std::string> &args) override;
862};
863
864void AppFunctionsImpl::startAppProcess(
865 QNapi::Object baseQAbility, const std::string &processId, QNapi::Object requestWant,
866 QNapi::Object optStartOptions, std::function<void(JsState &)> continueFunc)
867{
868 auto __dbg = make_QCScopedDebugJS("AppFunctionsImpl::startAppProcess");
869
870 static const char * const clonedWantPropsNames[] = {
871 "uri",
872 "type",
873 "action",
874 "flags",
875 "entities",
876 };
877
878 auto env = baseQAbility.Env();
879
880 auto qAbilityInfo = QAbilityInstancesManager::readAbilityInfo(baseQAbility);
881
882 auto startWantParams = QNapi::Object::New(env);
883 auto requestWantParams = QNapi::getOptionalPropOrEmpty<QNapi::Object>(requestWant, "parameters");
884 if (!requestWantParams.IsEmpty()) {
885 for (const auto &requestWantParamEntry : requestWantParams) {
886 startWantParams.Set(
887 requestWantParamEntry.first, static_cast<QNapi::Value>(requestWantParamEntry.second));
888 }
889 }
890 startWantParams.Set(qtAppProcessIdWantArgName, processId);
891
892 auto startWant = QNapi::makeObject(
893 env,
894 {
895 {"bundleName", qAbilityInfo.bundleName},
896 {"moduleName", qAbilityInfo.moduleName},
897 {"abilityName", qAbilityInfo.name},
898 {"parameters", startWantParams},
899 });
900
901 for (const auto &propName : clonedWantPropsNames) {
902 auto optProp = QNapi::getOptionalPropOrEmpty<QNapi::Value>(requestWant, propName);
903 if (!optProp.IsEmpty())
904 startWant.Set(propName, optProp);
905 }
906
907 std::vector<QNapi::ValueWrapper> startAbilityArgs = {startWant};
908 if (!optStartOptions.IsEmpty())
909 startAbilityArgs.push_back(optStartOptions);
910
911 baseQAbility.evalToPromiseOrRejectOnThrow("context.startAbility(*)", startAbilityArgs)
912 .onCatch(QtOhos::makeErrorLoggingJsCallback("startAbility()"))
913 .onFinally(
914 [continueFunc = std::move(continueFunc)](const CallbackInfo &cbInfo) {
915 continueFunc(cbInfo.jsState());
916 });
917}
918
919void AppFunctionsImpl::startNoUiChildProcess(
920 JsState &jsState, const std::string &libraryName, const std::vector<std::string> &args)
921{
922 const auto *childProcessSrcEntry = "./ets/process/QChildProcess.ets";
923
924 // FIXME:
925 // We want to use childProcessManager.StartMode.APP_SPAWN_FORK here, but the "StartMode"
926 // is defined as "const enum" in the TS code, which makes it a compile-time-only thing
927 // (contrary to non-const enums, which are real objects, const enums don't exist at runtime).
928 // We should consider adding a separate mechanism for handling const enums in the code
929 // if we have more of them in the future.
930 constexpr int startModeAppSpawnFork = 1;
931
932 auto appContextDirs = AppContextDirs::mapFromQOhosAppContextProperties(QOhosAppContext::getAllProperties());
933
934 QJsonArray argsArray;
935 std::transform(args.begin(), args.end(), std::back_inserter(argsArray), QString::fromStdString);
936
937 QJsonObject childSetupJson = {
938 {QString::fromUtf8("appContext"), appContextDirs.mapToQJsonObject()},
939 {QString::fromUtf8("appName"), QString::fromStdString(libraryName)},
940 {QString::fromUtf8("appArgs"), argsArray},
941 };
942
943 jsState.eval(
944 "@ohos.app.ability.childProcessManager.startChildProcess(*)",
945 {
946 childProcessSrcEntry,
947 startModeAppSpawnFork,
948 [childSetupJson](const CallbackInfo &cbInfo) {
949 QNapi::Value error;
950 QNapi::Value data;
951 cbInfo.getLeadingArgs(Q_FUNC_INFO, error, data);
952
953 int childPid = data.IsNumber()
954 ? QNapi::checkedCast<QNapi::Number>(data)
955 : -1;
956
957 if (childPid > 0) {
958 qOhosPrintfDebug("%s: child started: %d", Q_FUNC_INFO, childPid);
959 sendChildProcessSetupData(childPid, childSetupJson);
960 } else {
961 qOhosPrintfError("%s: child NOT started", Q_FUNC_INFO);
962 }
963 },
964 });
965}
966
967void handleAbilityOnForeground(const CallbackInfo &cbInfo)
968{
969 const auto qAbility = cbInfo.getFirstArg<QNapi::Object>(Q_FUNC_INFO);
970 auto &qAbilityInstancesManager = QAbilityInstancesManager::instance(cbInfo.jsState());
971
972 const bool hadForegroundQAbility = qAbilityInstancesManager.hasForegroundQAbility();
973 qAbilityInstancesManager.handleQAbilityOnForeground(qAbility);
974
975 if (!hadForegroundQAbility && qAbilityInstancesManager.hasForegroundQAbility()) {
976 QtOhos::invokeInQtThread([]() {
977 const auto setQosRes = OH_QoS_SetThreadQoS(QoS_Level::QOS_USER_INTERACTIVE);
978 if (setQosRes != 0) {
979 qOhosWarning(QtForOhos)
980 << "Setting QoS level of Qt thread to USER_INTERACTIVE failed, error code:"
981 << setQosRes;
982 }
983 updateApplicationState(Qt::ApplicationActive);
984 });
985 }
986}
987
988void handleAbilityOnBackground(const CallbackInfo &cbInfo)
989{
990 const auto qAbility = cbInfo.getFirstArg<QNapi::Object>(Q_FUNC_INFO);
991 auto &qAbilityInstancesManager = QAbilityInstancesManager::instance(cbInfo.jsState());
992
993 qAbilityInstancesManager.handleQAbilityOnBackground(qAbility);
994
995 if (!qAbilityInstancesManager.hasForegroundQAbility()) {
996 QtOhos::invokeInQtThread([]() {
997 const auto resetQosRes = OH_QoS_ResetThreadQoS();
998 if (resetQosRes != 0) {
999 qOhosWarning(QtForOhos)
1000 << "Resetting QoS level of Qt thread failed, error code:"
1001 << resetQosRes;
1002 }
1003 updateApplicationState(Qt::ApplicationHidden);
1004 updateApplicationState(Qt::ApplicationInactive);
1005 });
1006 }
1007}
1008
1009std::vector<QNapi::Value> getAllArgs(const CallbackInfo &cbInfo)
1010{
1011 const Napi::CallbackInfo &napiCbInfo = cbInfo;
1012 std::vector<QNapi::Value> args;
1013 for (std::size_t i = 0; i < napiCbInfo.Length(); ++i)
1014 args.push_back(napiCbInfo[i]);
1015 return args;
1016}
1017
1018QNapi::Value handleAbilityOnContinue(const CallbackInfo &cbInfo)
1019{
1020 QNapi::Object qAbility;
1021 QNapi::Object wantParamsObj;
1022 cbInfo.getLeadingArgs(Q_FUNC_INFO, qAbility, wantParamsObj);
1023
1024 auto optDelegateResult = tryCallFirstUiAbilityDelegate(
1025 "onContinue", getAllArgs(cbInfo),
1026 cbInfo.jsState().mapOhosEnumToJs(QOhosAbilityOnContinueResult::REJECT));
1027 if (optDelegateResult)
1028 return optDelegateResult.value();
1029
1031 QAbilityInstancesManager::instance(cbInfo.jsState()).tryGetQAbilityPeerByInstance(qAbility));
1032 if (!uiAbilityPeer) {
1033 qOhosPrintfWarning("%s: got unknown Ability, rejecting", Q_FUNC_INFO);
1034 return makeResolvedPromise(
1035 cbInfo.jsState().mapOhosEnumToJs(
1036 QOhosAbilityOnContinueResult::REJECT));
1037 }
1038
1039 return adaptAsyncCallResultToJsPromise<QOhosAbilityOnContinueResult>(
1040 cbInfo.jsState(),
1041 [](QOhosJsState &jsState, auto result) {
1042 return jsState.mapOhosEnumToJs(result);
1043 },
1044 [&](QOhosJsState &jsState, auto resultConsumer) {
1045 QAbilityInstancesManager::instance(jsState).getAbilityPeerBackend(uiAbilityPeer)->handleOnContinueRequestFromSystem(
1046 JsState::castFrom(jsState), wantParamsObj, std::move(resultConsumer));
1047 });
1048}
1049
1050std::string targetLibraryDirectory() {
1051 #if defined(Q_PROCESSOR_ARM_64)
1052 return "/libs/arm64";
1053 #elif defined(Q_PROCESSOR_ARM_32)
1054 return "/libs/arm";
1055 #elif defined(Q_PROCESSOR_X86_64)
1056 return "/libs/x86_64";
1057 #else
1058 #error "Unknown system architecture, aborting!"
1059 #endif
1060}
1061
1062void tryDetectBrokenWant(JsState &jsState, QNapi::Object want)
1063{
1064 Napi::HandleScope checkScope(want.Env());
1065
1066 auto optDefaultQAbility = jsState.defaultQAbility();
1067
1068 if (optDefaultQAbility) {
1069 bool fromThisApp = QAbilityInstancesManager::instance(jsState).isWantFromThisApp(optDefaultQAbility.value(), want);
1070 auto optCallerPid = getWantParamOrEmptyIfNotPresent<QNapi::Number>(want, callerPidWantArgName);
1071 if (fromThisApp && !optCallerPid.IsEmpty() && ::kill(optCallerPid.Int64Value(), 0) != 0) {
1072 qOhosPrintfError(
1073 "%s: got Want from non-existing app process (pid: %lld), which most likely means that we received"
1074 " broken Want (platform bug). That's fatal error for us!",
1075 Q_FUNC_INFO, static_cast<long long>(optCallerPid.Int64Value()));
1076 std::abort();
1077 }
1078 }
1079}
1080
1081std::string readInitialBytesOfFile(const std::string &filePath, std::size_t maxReadSize)
1082{
1083 FILE *inputFile = std::fopen(filePath.c_str(), "rb");
1084 if (inputFile == nullptr) {
1085 auto fopenErrno = errno;
1086 qOhosReportFatalErrorAndAbort(
1087 "%s: can't open file '%s': %s",
1088 Q_FUNC_INFO, filePath.c_str(), std::strerror(fopenErrno));
1089 }
1090
1091 std::unique_ptr<FILE, decltype(&std::fclose)> inputFileCloseGuard(inputFile, &std::fclose);
1092
1093 auto readBuffer = std::string(maxReadSize, '\0');
1094
1095 auto bytesRead = std::fread(&readBuffer[0], 1, maxReadSize, inputFile);
1096 if (std::ferror(inputFile)) {
1097 qOhosReportFatalErrorAndAbort(
1098 "%s: error reading '%s': (%zu bytes read)",
1099 Q_FUNC_INFO, filePath.c_str(), bytesRead);
1100 }
1101
1102 readBuffer.resize(bytesRead);
1103 readBuffer.shrink_to_fit();
1104
1105 return readBuffer;
1106}
1107
1108std::string readCurrentProcessNameFromProcFs()
1109{
1110 const auto *procCmdlinePath = "/proc/self/cmdline";
1111 auto procCmdlineData = readInitialBytesOfFile(procCmdlinePath, 64 * 1024);
1112
1113 auto processNameTerminatorPos = procCmdlineData.find('\0');
1114 if (processNameTerminatorPos == std::string::npos)
1115 qOhosReportFatalErrorAndAbort("%s: found unexpected content in '%s'", Q_FUNC_INFO, procCmdlinePath);
1116
1117 procCmdlineData.resize(processNameTerminatorPos);
1118 procCmdlineData.shrink_to_fit();
1119
1120 return procCmdlineData;
1121}
1122
1123bool isThisEmbeddedUIExtensionProcess(const QNapi::Object &appContext)
1124{
1125 std::string appName = appContext.eval<QNapi::String>("applicationInfo.name");
1126 return readCurrentProcessNameFromProcFs() == appName + ":embeddedUI";
1127}
1128
1129void handleAbilityStageOnCreate(const CallbackInfo &cbInfo)
1130{
1131 auto abilityStage = cbInfo.getFirstArg<QNapi::Object>(Q_FUNC_INFO);
1132
1133 if (qEnvironmentVariableIntValue(enableHotStartEnvVariableName) != 0) {
1134 auto appContext = abilityStage.eval<QNapi::Object>("context.getApplicationContext()");
1135 if (!isThisEmbeddedUIExtensionProcess(appContext)) {
1136 try {
1137 appContext.eval<QNapi::Value>("setSupportedProcessCache(*)", {true});
1138 s_hotStartEnabled = true;
1139 } catch (const Napi::Error &error) {
1140 qOhosPrintfError("setSupportedProcessCache() failed with error: %s", error.what());
1141 }
1142 }
1143 }
1144
1145 qOhosPrintfInfo(
1146 "AbilityStage::onCreate: hot start enabled: %s",
1148}
1149
1150QNapi::Value handleAbilityStageOnNewProcessRequest(const CallbackInfo &cbInfo)
1151{
1152 auto __dbg = make_QCScopedDebugJS(Q_FUNC_INFO);
1153
1154 QNapi::Object qAbilityStage;
1155 QNapi::Object want;
1156 cbInfo.getLeadingArgs(Q_FUNC_INFO, qAbilityStage, want);
1157
1158 qOhosPrintfInfo("AbilityStage::onNewProcessRequest: input Want: %s", QNapi::toJsonString(want).c_str());
1159
1160 tryDetectBrokenWant(cbInfo.jsState(), want);
1161
1162 auto optProcessIdParam = getWantParamOrEmptyIfNotPresent<QNapi::String>(want, qtAppProcessIdWantArgName);
1163
1164 std::string processId = !optProcessIdParam.IsEmpty() ? optProcessIdParam : std::string();
1165
1166 qOhosPrintfInfo("AbilityStage::onNewProcessRequest: returning processId='%s'", processId.c_str());
1167
1168 return QNapi::String::New(cbInfo.Env(), processId);
1169}
1170
1171QNapi::Value handleAbilityStageOnAcceptWant(const CallbackInfo &cbInfo)
1172{
1173 using namespace std::string_literals;
1174
1175 QNapi::Object qAbilityStage;
1176 QNapi::Object want;
1177 cbInfo.getLeadingArgs(Q_FUNC_INFO, qAbilityStage, want);
1178
1179 qOhosPrintfInfo("AbilityStage::onAcceptWant: input Want: %s", QNapi::toJsonString(want).c_str());
1180
1181 tryDetectBrokenWant(cbInfo.jsState(), want);
1182
1183 auto optProcessIdParam = getWantParamOrEmptyIfNotPresent<QNapi::String>(want, qtAppProcessIdWantArgName);
1184 if (!optProcessIdParam.IsEmpty()) {
1185 std::string processIdParamStr = QNapi::checkedCast<QNapi::String>(optProcessIdParam);
1186 auto instanceId = "//"s + processIdParamStr;
1187 qOhosPrintfInfo("AbilityStage::onAcceptWant: returning instanceId='%s'", instanceId.c_str());
1188 return QNapi::String::New(cbInfo.Env(), instanceId);
1189 }
1190
1191 auto &qAbilityInstancesManager = QAbilityInstancesManager::instance(cbInfo.jsState());
1192
1193 std::shared_ptr<QAbilityPeer> defaultQAbilityPeer = qAbilityInstancesManager.defaultQAbilityPeer();
1194
1195 auto defaultQAbility = defaultQAbilityPeer->qAbility();
1196 auto receivedQAbilityInstanceId =
1197 !defaultQAbility.IsEmpty()
1198 ? qAbilityInstancesManager.tryGetQAbilityInstanceIdFromWant(defaultQAbility, want)
1199 : std::nullopt;
1200
1201 auto qAbilityInstanceId =
1202 receivedQAbilityInstanceId.has_value()
1203 ? receivedQAbilityInstanceId.value()
1204 : qAbilityInstancesManager.pendingAutoStartedInstanceId().value_or(
1205 defaultQAbilityPeer->instanceId());
1206
1207 qOhosPrintfInfo("AbilityStage::onAcceptWant: returning instanceId='%s'", qAbilityInstanceId.c_str());
1208
1209 return QNapi::String::New(cbInfo.Env(), qAbilityInstanceId);
1210}
1211
1212void asyncRunTaskInTemporaryThread(std::function<void()> task, std::function<void(QOhosJsState &)> continueFunc)
1213{
1214 auto taskRunnerThread = std::thread(
1215 [task = std::move(task), continueFunc = std::move(continueFunc)]() mutable {
1216 task();
1217 QOhosJsThreadGateway::invoke(std::move(continueFunc));
1218 });
1219 taskRunnerThread.detach();
1220}
1221
1222void asyncRunTaskInTemporaryThreadWithTimeout(
1223 QOhosJsState &jsState, std::function<void()> task, std::chrono::milliseconds waitTimeout,
1224 QOhosConsumer<QOhosJsState &, bool> successConsumer)
1225{
1226 auto successNotifyFunc = moveToSharedPtr(
1227 makeCallOnceConsumerWrapper<QOhosJsState &, bool>(
1228 std::move(successConsumer)));
1229
1230 setJsTimeout(
1231 jsState,
1232 [successNotifyFunc](const QOhosCallbackInfo &cbInfo) {
1233 (*successNotifyFunc)(cbInfo.jsState(), false);
1234 },
1235 waitTimeout);
1236
1237 asyncRunTaskInTemporaryThread(
1238 std::move(task),
1239 [successNotifyFunc](QOhosJsState &jsState) {
1240 (*successNotifyFunc)(jsState, true);
1241 });
1242}
1243
1244QNapi::Value handleAbilityStageOnPrepareTerminationAsync(const CallbackInfo &cbInfo)
1245{
1246 qOhosPrintfInfo("%s", Q_FUNC_INFO);
1247
1248 return makeResolvedPromise(
1249 cbInfo.jsState().eval<QNapi::Number>(
1250 "@ohos.app.ability.AbilityConstant.PrepareTermination.TERMINATE_IMMEDIATELY"));
1251}
1252
1253void handleAbilityStageOnDestroy(const CallbackInfo &)
1254{
1255 qOhosPrintfInfo("AbilityStage::onDestroy: start");
1256
1257 qOhosPrintfInfo("AbilityStage::onDestroy: destroying the Qt thread object");
1259
1260 if (!s_exitCodeFilePath.empty()) {
1261 if (FILE *f = fopen(s_exitCodeFilePath.c_str(), "w")) {
1262 fprintf(f, "%d\n", s_appExitCode);
1263 fclose(f);
1264 }
1265 }
1266
1267 qOhosPrintfInfo("AbilityStage::onDestroy: calling _Exit(%d)", s_appExitCode);
1268 std::_Exit(s_appExitCode);
1269}
1270
1271void handleAbilityOnNewWant(const CallbackInfo &cbInfo)
1272{
1273 QNapi::Object qAbility;
1274 QNapi::Object want;
1275 QNapi::Object launchParam;
1276 cbInfo.getLeadingArgs(Q_FUNC_INFO, qAbility, want, launchParam);
1277
1278 qOhosPrintfDebug(
1279 "%s: input Want: %s, launchParam: %s",
1280 Q_FUNC_INFO, QNapi::toJsonString(want).c_str(), QNapi::toJsonString(launchParam).c_str());
1281
1282 tryDetectBrokenWant(cbInfo.jsState(), want);
1283
1284 if (!QAbilityInstancesManager::isQtInternalWantFromThisProcess(want)) {
1285 dispatchNewWant(qAbility, want, launchParam);
1286 callUiAbilityDelegates("onNewWant", getAllArgs(cbInfo));
1287 } else {
1288 qOhosPrintfDebug("%s: received qt-internal Want from current process, nothing to do", Q_FUNC_INFO);
1289 }
1290}
1291
1292void loadWindowStageContentPage(JsState &jsState, QNapi::Object &qAbility, const QNapi::Object &windowStage)
1293{
1294 auto *jsEnv = jsState.env();
1295
1296 auto qAbilityInstanceId = QAbilityInstancesManager::instance(jsState).getQAbilityInstanceIdOrPendingAutoStartedId(qAbility);
1297 auto xComponentId = QXComponentId::createForNativeNodeMainWindow(qAbilityInstanceId);
1298
1299 auto qAbilityRef = moveToSharedPtr(QNapi::Reference<>::makePersistentFrom(qAbility));
1300 auto windowStageRef = moveToSharedPtr(QNapi::Reference<>::makePersistentFrom(windowStage));
1301
1302 auto localStorage = jsState.eval<QNapi::Object>("LocalStorage.makeNewLocalStorage()");
1303 localStorage.eval(
1304 "setOrCreate(*)",
1305 {
1306 "createInfo",
1307 QNapi::makeObject(
1308 jsEnv,
1309 {
1310 {"xComponentId", xComponentId.toNapiValue(jsEnv)},
1311 {"onDisAppear", []() {}},
1312 {
1313 "onAttach",
1314 [qAbilityRef, windowStageRef](const QtOhos::CallbackInfo &cbInfo) {
1315 QAbilityInstancesManager::instance(cbInfo.jsState()).handleStartedUiInstance(
1316 cbInfo.jsState(), qAbilityRef->Value(), windowStageRef->Value());
1317 }},
1318 {
1319 "onAppear",
1320 [xComponentId]() {
1321 qOhosPrintfDebug("XComponentId: %s onAppear", xComponentId.stringId().c_str());
1322 }
1323 },
1324 }),
1325 });
1326 qAbility.set("localStorage", localStorage);
1327
1328 const std::string mainWindowNativeNodePagePath = "pages/MainWindowNativeNode";
1329 windowStage.evalToPromiseOrRejectOnThrow("loadContent(*)", {mainWindowNativeNodePagePath, localStorage})
1330 .onThen([qAbilityRef](const CallbackInfo &) {
1331 auto launchWant = qAbilityRef->eval<QNapi::Object>("launchWant");
1332 qOhosPrintfDebug("%s: launchWant: %s", Q_FUNC_INFO, QNapi::toJsonString(launchWant).c_str());
1333 })
1334 .onCatch([qAbilityInstanceId](const CallbackInfo &cbInfo) {
1335 QtOhos::logJsCallbackError(cbInfo, "windowStage.loadContent failed");
1336 qOhosReportFatalErrorAndAbort(
1337 "%s: Failed to loadContent for QAbility instance(qAbilityInstanceId: %s)", Q_FUNC_INFO, qAbilityInstanceId.c_str());
1338 });
1339}
1340
1341QNapi::Symbol getAbilityWindowStageCreatedOrRestoredPropSymbol(JsState &jsState)
1342{
1343 struct Symbol
1344 {
1345 };
1346 return jsState.getJsSymbolForType<Symbol>();
1347}
1348
1349void handleAbilityOnWindowStageCreate(const CallbackInfo &cbInfo)
1350{
1351 QNapi::Object qAbility;
1352 QNapi::Object windowStage;
1353 cbInfo.getLeadingArgs(Q_FUNC_INFO, qAbility, windowStage);
1354
1355 qAbility.set(getAbilityWindowStageCreatedOrRestoredPropSymbol(cbInfo.jsState()), true);
1356 loadWindowStageContentPage(cbInfo.jsState(), qAbility, windowStage);
1357}
1358
1359void handleAbilityOnWindowStageRestore(const CallbackInfo &cbInfo)
1360{
1361 QNapi::Object qAbility;
1362 QNapi::Object windowStage;
1363 cbInfo.getLeadingArgs(Q_FUNC_INFO, qAbility, windowStage);
1364
1365 auto optCreatedOrRestoredProp = QNapi::getOptionalPropOrEmpty<QNapi::Boolean>(
1366 qAbility, getAbilityWindowStageCreatedOrRestoredPropSymbol(cbInfo.jsState()));
1367 bool createdOrRestoredProp = !optCreatedOrRestoredProp.IsEmpty()
1368 ? optCreatedOrRestoredProp.Value()
1369 : false;
1370
1371 if (!createdOrRestoredProp) {
1372 qAbility.set(getAbilityWindowStageCreatedOrRestoredPropSymbol(cbInfo.jsState()), true);
1373 loadWindowStageContentPage(cbInfo.jsState(), qAbility, windowStage);
1374 } else {
1375 qOhosPrintfDebug(
1376 "%s: window page already created or restored. Skip page reloading", Q_FUNC_INFO);
1377 }
1378}
1379
1380void handleAbilityOnWindowStageDestroy(const CallbackInfo &)
1381{
1382}
1383
1384QNapi::Value handleAbilityOnPrepareToTerminate(const CallbackInfo &cbInfo)
1385{
1386 auto __dbg = make_QCScopedDebugJS(Q_FUNC_INFO);
1387 auto ability = cbInfo.getFirstArg<QNapi::Object>(Q_FUNC_INFO);
1388
1389 auto abilityPeer = QAbilityInstancesManager::instance(cbInfo.jsState()).tryGetQAbilityPeerByInstance(ability);
1390 if (!abilityPeer) {
1391 qOhosPrintfWarning("%s: unrecognized ability, returning immediately", Q_FUNC_INFO);
1392 return QNapi::Boolean::New(cbInfo.Env(), false);
1393 }
1394
1395 bool destroyAllowed = abilityPeer->destroyAllowedFlag()->load();
1396 qOhosPrintfDebug(
1397 "%s: ability id: '%s', destroyAllowed=%s",
1398 Q_FUNC_INFO, abilityPeer->instanceId().c_str(), mapBoolToTrueFalseStr(destroyAllowed));
1399
1400 if (!destroyAllowed) {
1401 QtOhos::invokeInQtThread(
1402 [qwindowRef = abilityPeer->qWindowRef()]() {
1403 auto *qwindow = qobject_cast<QWindow *>(qwindowRef.data());
1404 if (qwindow != nullptr) {
1405 qOhosPrintfInfo("handleAbilityOnPrepareToTerminate: calling QWindow::close()");
1406 QOhosCloseEventContext::runWithCloseRootCauseSet(
1407 QOhosCloseEventContext::CloseRootCause::OnPrepareToTerminate,
1408 [&]() {
1409 qwindow->close();
1410 });
1411 } else {
1412 qOhosPrintfDebug("%s: QWindow is null", Q_FUNC_INFO);
1413 }
1414 });
1415 }
1416
1417 return QNapi::Boolean::New(cbInfo.Env(), !destroyAllowed);
1418}
1419
1420QNapi::Value handleAbilityOnPrepareToTerminateAsync(const CallbackInfo &cbInfo)
1421{
1422 auto __dbg = make_QCScopedDebugJS(Q_FUNC_INFO);
1423
1424 auto qAbility = cbInfo.getFirstArg<QNapi::Object>(Q_FUNC_INFO);
1425
1426 JsState &jsState = cbInfo.jsState();
1427 auto &qAbilityInstancesManager = QAbilityInstancesManager::instance(jsState);
1428
1429 auto optQUiAbilityPeer = QUiAbilityPeer::tryCastFromQAbilityPeerOrNull(
1430 qAbilityInstancesManager.tryGetQAbilityPeerByInstance(qAbility));
1431
1432 if (optQUiAbilityPeer) {
1433 return qAbilityInstancesManager.getAbilityPeerBackend(optQUiAbilityPeer)->handleCloseRequestFromSystem(
1434 jsState, "UIAbility::onPrepareToTerminateAsync",
1436 [](QOhosJsState &jsState, QUiAbilityPeerBackend::CloseAbilityRequestResolution ohosRequestResolution) {
1437 return QNapi::Boolean::New(
1438 jsState.env(),
1439 ohosRequestResolution == QUiAbilityPeerBackend::CloseAbilityRequestResolution::DontClose);
1440 });
1441 } else {
1442 qOhosPrintfWarning("%s: no matching QAbilityPeer, resolving immediately with 'false'", Q_FUNC_INFO);
1443 return makeResolvedPromise(QNapi::Boolean::New(cbInfo.Env(), false));
1444 }
1445}
1446
1447void forceLoadAllJsModulesIfRequested(JsState &jsState)
1448{
1449 if (qEnvironmentVariableIntValue(forceLoadJsModulesEnvVariableName) == 0)
1450 return;
1451
1452 qOhosPrintfDebug("%s: forcibly loading all JS modules", Q_FUNC_INFO);
1453
1454 for (const auto &moduleName : predefinedJsModuleNames())
1455 jsState.tryGetModule(moduleName);
1456}
1457
1458void handleAbilityOnCreate(const CallbackInfo &cbInfo)
1459{
1460 auto __dbg = make_QCScopedDebugJS(Q_FUNC_INFO);
1461
1462 QNapi::Object ability;
1463 QNapi::Object want;
1464 QNapi::Object launchParam;
1465 cbInfo.getLeadingArgs(Q_FUNC_INFO, ability, want, launchParam);
1466
1467 forceLoadAllJsModulesIfRequested(cbInfo.jsState());
1468
1469 QOhosAbilityLaunchParamStore::instance(cbInfo.jsState()).set(ability, launchParam);
1470}
1471
1472QNapi::Value handleAbilityOnDestroy(const CallbackInfo &cbInfo)
1473{
1474 auto __dbg = make_QCScopedDebugJS(Q_FUNC_INFO);
1475
1476 auto qAbility = cbInfo.getFirstArg<QNapi::Object>(Q_FUNC_INFO);
1477
1478 auto qAbilityPeer = QAbilityInstancesManager::instance(cbInfo.jsState()).tryGetQAbilityPeerByInstance(qAbility);
1479 if (!qAbilityPeer) {
1480 qOhosPrintfDebug("%s: no matching QAbilityPeer, returning resolved Promise", Q_FUNC_INFO);
1481 return makeResolvedPromise(cbInfo.Env());
1482 }
1483
1484 auto optQWindowDestroyPromise = qAbilityPeer->qWindowDestroyPromise();
1485
1486 auto initialPromise = optQWindowDestroyPromise.has_value()
1487 ? optQWindowDestroyPromise.value()
1488 : makeResolvedPromise(cbInfo.Env());
1489
1490 auto resultPromiseDeferred = std::make_shared<QNapi::Promise::Deferred>(cbInfo.Env());
1491
1492 initialPromise.onFinally(
1493 [qAbilityPeer, resultPromiseDeferred](const CallbackInfo &cbInfo) {
1494 qOhosPrintfDebug("%s: initial Promise resolved for id='%s'", Q_FUNC_INFO, qAbilityPeer->instanceId().c_str());
1495
1496 QAbilityInstancesManager::instance(cbInfo.jsState()).removeMatchingQAbilityPeer(qAbilityPeer->qAbility());
1497
1498 if (!cbInfo.jsState().defaultQAbility()) {
1500
1501 qOhosPrintfInfo("Qt: requested Qt app quit, waiting for the main() function to return");
1502
1503 constexpr auto resultPromiseAutoresolveTimeout = 5s;
1504
1505 asyncRunTaskInTemporaryThreadWithTimeout(
1506 cbInfo.jsState(),
1507 []() {
1509 },
1510 resultPromiseAutoresolveTimeout,
1511 [instanceId = qAbilityPeer->instanceId(), resultPromiseDeferred](QOhosJsState &jsState, bool threadExited) {
1512 qOhosPrintfInfo(
1513 "Qt: end waiting for Qt app's main() function, returned: %s",
1514 mapBoolToTrueFalseStr(threadExited));
1515 qOhosPrintfDebug("%s: resolving result Promise for id='%s'", Q_FUNC_INFO, instanceId.c_str());
1516 resultPromiseDeferred->Resolve(Napi::Env(jsState.env()).Undefined());
1517 });
1518 } else {
1519 resultPromiseDeferred->Resolve(cbInfo.Env().Undefined());
1520 }
1521 });
1522
1523 qOhosPrintfDebug("%s: returning Promise for id='%s'", Q_FUNC_INFO, qAbilityPeer->instanceId().c_str());
1524
1525 return resultPromiseDeferred->Promise();
1526}
1527
1528void initDeviceInfo(JsState &jsState)
1529{
1530 using Type = QOhosDeviceInfo::Type;
1531
1532 static const std::pair<Type, const char *> strPropertiesMap[] = {
1533 {Type::deviceType, "deviceType"},
1534 {Type::manufacture, "manufacture"},
1535 {Type::brand, "brand"},
1536 {Type::marketName, "marketName"},
1537 {Type::productSeries, "productSeries"},
1538 {Type::productModel, "productModel"},
1539 {Type::softwareModel, "softwareModel"},
1540 {Type::hardwareModel, "hardwareModel"},
1541 {Type::hardwareProfile, "hardwareProfile"},
1542 {Type::serial, "serial"},
1543 {Type::bootloaderVersion, "bootloaderVersion"},
1544 {Type::abiList, "abiList"},
1545 {Type::securityPatchTag, "securityPatchTag"},
1546 {Type::displayVersion, "displayVersion"},
1547 {Type::incrementalVersion, "incrementalVersion"},
1548 {Type::osReleaseType, "osReleaseType"},
1549 {Type::osFullName, "osFullName"},
1550 {Type::versionId, "versionId"},
1551 {Type::buildType, "buildType"},
1552 {Type::buildUser, "buildUser"},
1553 {Type::buildHost, "buildHost"},
1554 {Type::buildTime, "buildTime"},
1555 {Type::buildRootHash, "buildRootHash"},
1556 {Type::udid, "udid"},
1557 {Type::distributionOSName, "distributionOSName"},
1558 {Type::distributionOSVersion, "distributionOSVersion"},
1559 {Type::distributionOSReleaseType, "distributionOSReleaseType"},
1560 };
1561
1562 static const std::pair<Type, const char *> intPropertiesMap[] = {
1563 {Type::majorVersion, "majorVersion"},
1564 {Type::seniorVersion, "seniorVersion"},
1565 {Type::featureVersion, "featureVersion"},
1566 {Type::buildVersion, "buildVersion"},
1567 {Type::sdkApiVersion, "sdkApiVersion"},
1568 {Type::firstApiVersion, "firstApiVersion"},
1569 {Type::distributionOSApiVersion, "distributionOSApiVersion"},
1570 };
1571
1572 auto deviceInfoObj = jsState.eval<QNapi::Object>("@ohos.deviceInfo");
1573
1574 QMap<Type, QVariant> deviceInfo;
1575 for (const auto &propEntry : strPropertiesMap)
1576 deviceInfo[propEntry.first] = QString::fromStdString(deviceInfoObj.get<QNapi::String>(propEntry.second));
1577 for (const auto &propEntry : intPropertiesMap)
1578 deviceInfo[propEntry.first] = static_cast<int>(deviceInfoObj.get<QNapi::Number>(propEntry.second));
1579
1580 QOhosDeviceInfo::init(std::move(deviceInfo));
1581}
1582
1583void initAppData(JsState &jsState, QNapi::Object appContext)
1584{
1585 initDeviceInfo(jsState);
1586
1587 auto systemLocaleId = QString::fromStdString(
1588 jsState.eval<QNapi::String>("@ohos.intl.Locale<new>().toString()"));
1589 auto systemPreferredLanguages = QNapi::getArrayElements<QStringList, QNapi::String>(
1590 jsState.eval<QNapi::Array>("@ohos.i18n.System.getPreferredLanguageList()"),
1591 &QString::fromStdString);
1592 QtOhos::invokeInQtThread(
1593 [systemLocaleId, systemPreferredLanguages]() {
1594 QOhosPlatformIntegration::setSystemLocale(new QOhosSystemLocale(systemLocaleId, systemPreferredLanguages));
1595 });
1596
1598 appContext.eval("setColorMode(*)", {jsState.mapOhosEnumToJs(defaultColorMode)});
1599}
1600
1601std::string buildFcLangEnvVariableValue(JsState &jsState)
1602{
1603 std::string language = jsState.eval<QNapi::String>("@ohos.intl.Locale<new>().language");
1604 std::string region = jsState.eval<QNapi::String>("@ohos.intl.Locale<new>().region");
1605
1606 return language + "_" + region + ".UTF-8";
1607}
1608
1609void setupQtApplicationImpl(JsState &jsState, QNapi::Object appStartupObj, QtRunMode qtRunMode)
1610{
1611 auto appContext = appStartupObj.get<QNapi::Object>("appContext");
1612 auto appContextDirs = AppContextDirs::mapFromNapiObject(appContext);
1613 if (appContextDirs.resourceDir.empty()) {
1614 auto optResourceDirProp = QNapi::getOptionalPropOrEmpty<QNapi::String>(appStartupObj, "resourceDir");
1615 std::string resourceDir = !optResourceDirProp.IsEmpty() ? optResourceDirProp : std::string();
1616 appContextDirs.resourceDir = !resourceDir.empty()
1617 ? resourceDir
1618 : appContextDirs.bundleCodeDir + "/entry/resources/resfile";
1619 }
1620
1621 auto jsModulesFactories = appStartupObj.get<QNapi::Object>("modulesFactories");
1622
1623 qOhosPrintfDebug("%s: setting up Qt in %s mode", Q_FUNC_INFO, mapQtRunModeToString(qtRunMode));
1624
1625 QAbilityInstancesManager::instance(jsState).registerPendingAutoStartedInstance(&handleDefaultQAbilityInstanceStartup);
1626
1627 currentQtRunMode = qtRunMode;
1629 jsModulesFactories.Env(), makeJsModulesFactoriesMap(jsModulesFactories),
1630 std::make_shared<AppFunctionsImpl>(), qtRunMode);
1631
1632 QOhosAppContext::init(appContextDirs.mapToQOhosAppContextProperties());
1633 initAppData(jsState, appContext);
1634
1635 const auto ohosSdkApiVersion = QOhosDeviceInfo::sdkApiVersion();
1636 if (ohosSdkApiVersion < minSupportedOhosSdkApiVersion) {
1637 qOhosReportFatalErrorAndAbort(
1638 "%s: unsupported OHOS version! Current API version: %d, minimum supported version: %d. Aborting.",
1639 Q_FUNC_INFO, ohosSdkApiVersion, minSupportedOhosSdkApiVersion);
1640 }
1641
1642 const auto recognizedDeviceType = QOhosDeviceInfo::tryGetRecognizedDeviceType();
1643 if (!recognizedDeviceType.has_value()) {
1644 qOhosReportFatalErrorAndAbort(
1645 "%s: Unrecognized device type: %s. Qt does not support unrecognized devices. Aborting.",
1646 Q_FUNC_INFO, qPrintable(QOhosDeviceInfo::getProperty(QOhosDeviceInfo::Type::deviceType).toString()));
1647 }
1648
1649 bool allowUnsupportedDevices =
1650 qEnvironmentVariable("QT_IO_EXPERIMENTAL_ALLOW_UNSUPPORTED_DEVICES", {})
1651 == QLatin1String("true");
1652 if (!QOhosDeviceInfo::isCurrentDeviceSupported() && !allowUnsupportedDevices) {
1653 qOhosReportFatalErrorAndAbort(
1654 "%s: Unsupported device type: %s. Aborting.",
1655 Q_FUNC_INFO, qPrintable(QOhosDeviceInfo::getProperty(QOhosDeviceInfo::Type::deviceType).toString()));
1656 }
1657
1658 s_appSharedLibName = appStartupObj.get<QNapi::String>("appName");
1659
1660 qOhosPrintfDebug("setupQtApplication() - sharedLibraryName: %s", s_appSharedLibName.c_str());
1661 qOhosPrintfDebug("setupQtApplication() - bundleCodeDir: %s", appContextDirs.bundleCodeDir.c_str());
1662
1663 s_appSharedLibsDirPath = appContextDirs.bundleCodeDir + targetLibraryDirectory();
1664 qOhosPrintfDebug("setupQtApplication() - Shared libraries directory: %s", s_appSharedLibsDirPath.c_str());
1665
1666 auto jsAppArgs = QNapi::getPropOrUndefined(appStartupObj, "appArgs");
1667 if (jsAppArgs.IsArray()) {
1668 s_appArgs = std::make_unique<std::vector<std::string>>(
1669 QNapi::getArrayElements<std::vector<std::string>, QNapi::String>(
1670 QNapi::checkedCast<QNapi::Array>(jsAppArgs)));
1671 }
1672
1673 struct {
1674 const char *variable;
1675 std::string value;
1676 } env_variables[] = {
1677 {"QT_QPA_PLATFORM_PLUGIN_PATH", s_appSharedLibsDirPath },
1678 {"QML2_IMPORT_PATH", appContextDirs.resourceDir + "/qml" },
1679 {"QT_PRINTER_MODULE", "ohosprintersupport"},
1680 {"TMPDIR", QOhosAppContext::getProperty(QOhosAppContext::Type::tempDir).toStdString()},
1681 {"HOME", QOhosAppContext::getProperty(QOhosAppContext::Type::filesDir).toStdString()},
1682 {"FC_LANG", buildFcLangEnvVariableValue(jsState)},
1683 };
1684
1685 for (const auto &e : env_variables) {
1686 if (::setenv(e.variable, e.value.c_str(), 1) != 0)
1687 qOhosReportFatalErrorAndAbort("%s: Cannot set '%s' environment variable", Q_FUNC_INFO, e.variable);
1688 }
1689
1690 if (::chdir(appContextDirs.filesDir.c_str()) != 0) {
1691 auto chdirErrno = errno;
1692 qOhosPrintfWarning(
1693 "%s: failed to change current directory to '%s': %s",
1694 Q_FUNC_INFO, appContextDirs.filesDir.c_str(), std::strerror(chdirErrno));
1695 }
1696}
1697
1698QtRunMode getQtRunModeFromAppStartupObj(QNapi::Object appStartupObj)
1699{
1700 std::unordered_map<std::string, QtRunMode> abilityClassNameToQtRunModeMap = {
1701 {"QAbility", QtRunMode::Normal},
1702 };
1703
1704 const auto optAbilityClassName = QNapi::getOptionalPropOrEmpty<QNapi::String>(appStartupObj, "abilityClassName");
1705 if (!optAbilityClassName.IsEmpty()) {
1706 const std::string abilityClassName = optAbilityClassName;
1707 if (abilityClassNameToQtRunModeMap.find(abilityClassName) != abilityClassNameToQtRunModeMap.end())
1708 return abilityClassNameToQtRunModeMap[abilityClassName];
1709
1710 qOhosReportFatalErrorAndAbort(
1711 "%s: got unsupported name of the Ability class: '%s'", Q_FUNC_INFO, abilityClassName.c_str());
1712 }
1713
1714 return QtRunMode::Normal;
1715}
1716
1717void setupQtApplication(const CallbackInfo &cbInfo)
1718{
1719 auto appStartupObj = cbInfo.getFirstArg<QNapi::Object>(Q_FUNC_INFO);
1720 auto qtRunMode = getQtRunModeFromAppStartupObj(appStartupObj);
1721 setupQtApplicationImpl(cbInfo.jsState(), appStartupObj, qtRunMode);
1722}
1723
1724void runQtChildProcess(const CallbackInfo &cbInfo)
1725{
1726 auto __dbg = make_QCScopedDebugJS(Q_FUNC_INFO);
1727
1728 auto paramsObj = cbInfo.getFirstArg<QNapi::Object>(Q_FUNC_INFO);
1729
1731
1732 auto childSetupObj = readChildProcessSetupData(cbInfo.Env());
1733 childSetupObj["modulesFactories"] = paramsObj.get<QNapi::Object>("modulesFactories");
1734
1735 setupQtApplicationImpl(cbInfo.jsState(), childSetupObj, QtRunMode::NoUiChildProcess);
1736
1737 auto appArgs = s_appArgs ? *s_appArgs : std::vector<std::string>();
1738
1739 QThread::currentThread();
1740 QtOhos::initQtThreadState();
1741 auto appMainFuncLauncher = makeAppMainFuncLauncher(
1742 {
1743 .appLibraryPath = s_appSharedLibsDirPath + "/" + s_appSharedLibName,
1744 },
1745 [](int) {
1746 });
1747 appMainFuncLauncher(appArgs);
1748}
1749
1750QNapi::Value makeXComponentIdForMainWindowWithQAbilityInstanceId(const CallbackInfo &cbInfo)
1751{
1752 std::string qAbilityInstanceId = cbInfo.getFirstArg<QNapi::String>(Q_FUNC_INFO);
1753 return QXComponentId::createForNativeNodeMainWindow(qAbilityInstanceId).toNapiValue(cbInfo.Env());
1754}
1755
1756QNapi::Value checkIsAdapterCApiSupported(const CallbackInfo &cbInfo)
1757{
1758 constexpr bool adapterCApiSupported = true;
1759 return QNapi::Boolean::New(cbInfo.Env(), adapterCApiSupported);
1760}
1761
1762}
1763
1765{
1766 return currentQtRunMode == QtRunMode::NoUiChildProcess;
1767}
1768
1770{
1771 return vsyncOnSoftwareBackingStoreEnabled;
1772}
1773
1775{
1776 auto __dbg = make_QCScopedDebugJS("quitApplicationFromJsThread");
1777 auto hotStartIterationToQuit = s_hotStartIteration.lastRequestedInJsThread;
1778 QtOhos::invokeInQtThread(
1779 [hotStartIterationToQuit]() {
1780 if (s_hotStartIteration.activeInQtThread == hotStartIterationToQuit)
1781 QCoreApplication::quit();
1782 });
1783}
1784
1786{
1787 qOhosDebug(QtForOhos) << "QOhos updateApplicationState" << state;
1788
1790 return;
1791
1792 if (state != Qt::ApplicationActive) {
1793 // NOTE: sometimes we will receive two consecutive suspended notifications,
1794 // In the second suspended notification, QWindowSystemInterface::flushWindowSystemEvents()
1795 // will deadlock since the dispatcher has been stopped in the first suspended notification.
1796 // To avoid the deadlock we simply return if we found the event dispatcher has been stopped.
1798 return;
1799
1800 // Don't send timers and sockets events anymore if we are going to hide all windows
1802 QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationState(state));
1803 } else {
1805 QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationState(state));
1807 }
1808}
1809
1811{
1812 static const bool block = []() {
1813 const QByteArray envVarBytes = qgetenv("QT_BLOCK_EVENT_LOOPS_WHEN_SUSPENDED");
1814 bool parsedAsInt = false;
1815 const int intValue = envVarBytes.toInt(&parsedAsInt);
1816 return parsedAsInt ? intValue != 0
1817 : envVarBytes.compare("true", Qt::CaseInsensitive) == 0;
1818 }();
1819 return block;
1820}
1821
1823{
1824 return experimentalEnableGlBackinStore;
1825}
1826
1828{
1829 return debugDrawQtRasterBackingStoreFlushedRegion;
1830}
1831
1833{
1834 return debugUseBasicStyleAndTheme;
1835}
1836
1838{
1839 return enableNativeNodeApiKeyEvents;
1840}
1841
1843{
1844 return enableNativeNodeApiMouseEvents;
1845}
1846
1848{
1849 return emulatorQuirkWorkaroundsEnabled;
1850}
1851
1853{
1854 return std::exchange(s_autoStartedAbilityInstanceWaitingForQtWindow, false);
1855}
1856
1857}
1858
1859QT_END_NAMESPACE
1860
1861EXTERN_C_START
1862
1863static napi_value Init(napi_env env, napi_value exports)
1864{
1865 auto __dbg = make_QCScopedDebugJS("qohosjsmain Init");
1866
1867 QNapi::Object(env, exports).DefineProperties(
1868 {
1869 Napi::PropertyDescriptor::Function("handleAbilityStageOnCreate", QtOhos::handleAbilityStageOnCreate),
1870 Napi::PropertyDescriptor::Function("handleAbilityStageOnNewProcessRequest", QtOhos::handleAbilityStageOnNewProcessRequest),
1871 Napi::PropertyDescriptor::Function("handleAbilityStageOnAcceptWant", QtOhos::handleAbilityStageOnAcceptWant),
1872 Napi::PropertyDescriptor::Function("handleAbilityStageOnPrepareTerminationAsync", QtOhos::handleAbilityStageOnPrepareTerminationAsync),
1873 Napi::PropertyDescriptor::Function("handleAbilityStageOnDestroy", QtOhos::handleAbilityStageOnDestroy),
1874 Napi::PropertyDescriptor::Function("handleAbilityOnNewWant", QtOhos::handleAbilityOnNewWant),
1875 Napi::PropertyDescriptor::Function("handleAbilityOnWindowStageCreate", QtOhos::handleAbilityOnWindowStageCreate),
1876 Napi::PropertyDescriptor::Function("handleAbilityOnWindowStageRestore", QtOhos::handleAbilityOnWindowStageRestore),
1877 Napi::PropertyDescriptor::Function("handleAbilityOnWindowStageDestroy", QtOhos::handleAbilityOnWindowStageDestroy),
1878 Napi::PropertyDescriptor::Function("onStageDestroy", QtOhos::handleAbilityOnWindowStageDestroy),
1879 Napi::PropertyDescriptor::Function("handleAbilityOnPrepareToTerminate", QtOhos::handleAbilityOnPrepareToTerminate),
1880 Napi::PropertyDescriptor::Function("handleAbilityOnPrepareToTerminateAsync", QtOhos::handleAbilityOnPrepareToTerminateAsync),
1881 Napi::PropertyDescriptor::Function("handleAbilityOnCreate", QtOhos::handleAbilityOnCreate),
1882 Napi::PropertyDescriptor::Function("handleAbilityOnDestroy", QtOhos::handleAbilityOnDestroy),
1883 Napi::PropertyDescriptor::Function("handleAbilityOnBackground", QtOhos::handleAbilityOnBackground),
1884 Napi::PropertyDescriptor::Function("handleAbilityOnContinue", QtOhos::handleAbilityOnContinue),
1885 Napi::PropertyDescriptor::Function("onBackground", QtOhos::handleAbilityOnBackground),
1886 Napi::PropertyDescriptor::Function("handleAbilityOnForeground", QtOhos::handleAbilityOnForeground),
1887 Napi::PropertyDescriptor::Function("onForeground", QtOhos::handleAbilityOnForeground),
1888 Napi::PropertyDescriptor::Function("setupQtApplication", QtOhos::setupQtApplication),
1889 Napi::PropertyDescriptor::Function("runQtChildProcess", QtOhos::runQtChildProcess),
1890 Napi::PropertyDescriptor::Function(
1891 "makeXComponentIdForMainWindowWithQAbilityInstanceId",
1892 QtOhos::makeXComponentIdForMainWindowWithQAbilityInstanceId),
1893 Napi::PropertyDescriptor::Function("checkIsAdapterCApiSupported", QtOhos::checkIsAdapterCApiSupported),
1894 });
1895
1896 // Here put elements that
1897 QArkUi::QXComponentRegistry::Init(env, exports);
1898
1899 return exports;
1900}
1901
1902EXTERN_C_END
1903
1904extern "C" __attribute__((constructor)) void RegisterEntryModule(void)
1905{
1906 static napi_module qtMainModule = {
1907 .nm_version = 1,
1908 .nm_flags = 0,
1909 .nm_filename = nullptr,
1910 .nm_register_func = Init,
1911 .nm_modname = "qohos",
1912 .nm_priv = nullptr,
1913 .reserved = {nullptr},
1914 };
1915
1916 napi_module_register(&qtMainModule);
1917}
static QOhosEventDispatcherStopper * instance()
static QOhosPlatformIntegration * instance()
static QXComponentId createForNativeNodeMainWindow(const std::string &qAbilityInstanceId)
JsState & jsState() const
static std::shared_ptr< QUiAbilityPeer > tryCastFromQAbilityPeerOrNull(std::shared_ptr< QAbilityPeer > qAbilityPeer)
bool isCurrentDeviceSupported()
void init(QMap< Type, QVariant > devinfo)
std::optional< RecognizedDeviceType > tryGetRecognizedDeviceType()
void installEngineHandler(QtOhos::JsState &jsState, QNapi::Object qAbility)
Combined button and popup list for selecting options.
std::shared_ptr< void > makeWatchdog()
bool acquireAndCleanPendingAutoStartedInstanceWindowFlag()
std::string const char * mapBoolToTrueFalseStr(bool value)
bool blockEventLoopsWhenSuspended()
bool isEmulatorQuirkWorkaroundsEnabled()
void updateApplicationState(int state)
bool isOhosNoUiChildMode()
void initJsThreadState(napi_env env, std::map< std::string, QNapi::Reference< QNapi::Function > > &&jsModulesFactories, std::shared_ptr< AppFunctions > appFunctions, QtRunMode qtRunMode)
bool isGlBackingStoreDefaultEnabled()
void quitApplicationFromJsThread()
bool isVsyncOnSoftwareBackingStoreEnabled()
bool isNativeNodeApiMouseEventsEnabled()
QtOhosQpa::enums::ohos::app::ability::AbilityConstant::OnContinueResult QOhosAbilityOnContinueResult
bool isNativeNodeApiKeyEventsEnabled()
bool isDebugUseBasicStyleAndThemeEnabled()
bool isDebugDrawQtRasterBackingStoreFlushedRegionEnabled()
static bool s_hotStartEnabled
static bool s_autoStartedAbilityInstanceWaitingForQtWindow
QT_END_NAMESPACE static EXTERN_C_START napi_value Init(napi_env env, napi_value exports)
std::function< void()> s_qtAppThreadIdleStateWaitFunc
static std::string s_appSharedLibName
static QList< QByteArray > s_applicationParams
static std::unique_ptr< std::vector< std::string > > s_appArgs
static int s_appExitCode
static std::string s_appSharedLibsDirPath
static std::string s_exitCodeFilePath
QOhosConsumer< std::vector< std::string > > s_qtAppThreadMainFuncLauncher