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
qohosappcontext.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 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
5
6#include <QtHarmonyExtras/private/qohosabilitycontext_p.h>
7#include <QtHarmonyExtras/private/qohosappbundleinfo_p.h>
8#include <QtHarmonyExtras/private/qohoswantinfo_p.h>
9#include <QtHarmonyExtras/private/qohoswantutils_p.h>
10
11#include <QtCore/qcoreapplication_platform.h>
12#include <QtCore/qharmonyappjscontext.h>
13#include <QtCore/qharmonyjscontext.h>
14#include <QtCore/qharmonyjsonconversions.h>
15#include <QtCore/private/qcore_ohos_p.h>
16#include <QtCore/private/qnapi_p.h>
17#include <QtCore/private/qohoscommon_p.h>
18#include <QtCore/private/qohosjstools_p.h>
19#include <QtCore/private/qohoslogger_p.h>
20
21#include <algorithm>
22#include <chrono>
23#include <csignal>
24#include <cstdint>
25#include <cstdlib>
26#include <functional>
27#include <iterator>
28#include <memory>
29#include <optional>
30#include <string>
31#include <thread>
32#include <unordered_map>
33#include <vector>
34
35#include <unistd.h>
36
37QT_BEGIN_NAMESPACE
38
39namespace QtHarmonyExtras {
40
41using namespace Private;
42
43namespace {
44
45template<typename T>
46using QOhosSupplier = std::function<T()>;
47
48int getCurrentApplicationVersionCode()
49{
50 return QNativeInterface::QHarmonyApplication::runOnJsThreadAndWait(
51 [](QHarmonyJsContext &jsContext) {
52 auto optBundleManager = QNapi::Object(jsContext.env(), jsContext.tryImportModule("@ohos.bundle.bundleManager"));
53 if (optBundleManager.IsEmpty())
54 return 0;
55
56 auto applicationInfoFlag = optBundleManager.eval<QNapi::Number>(
57 "BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION");
58 auto bundleInfo = optBundleManager.eval<QNapi::Object>(
59 "getBundleInfoForSelfSync(*)", {applicationInfoFlag});
60 int versionCode = bundleInfo.get<QNapi::Number>("versionCode");
61
62 return versionCode;
63 });
64}
65
66Q_NORETURN void killCurrentProcess()
67{
68 ::kill(getpid(), SIGKILL);
69 std::abort();
70}
71
72std::optional<std::uint32_t> tryGetCodeFromJsBusinessError(const Napi::Error &error)
73{
74 if (!error.Value().IsObject())
75 return std::nullopt;
76
77 auto errorObject = QNapi::checkedCast<QNapi::Object>(error.Value());
78 auto optErrorCode = QNapi::getOptionalPropOrEmpty<QNapi::Number>(errorObject, "code");
79
80 return !optErrorCode.IsEmpty()
81 ? std::make_optional(optErrorCode.Uint32Value())
82 : std::nullopt;
83}
84
85Q_NORETURN void restartAppImpl(std::optional<QJsonObject> want)
86{
87 QOhosJsThreadGateway::runAndWait(
88 [&](QOhosJsState &jsState) {
89 auto napiWant = want.has_value()
90 ? QNapi::Object(jsState.env(), QtHarmony::mapQJsonObjectToJsObject(jsState.env(), want.value()))
91 : jsState.appLaunchWant();
92 if (want.has_value() && napiWant.IsEmpty())
93 qOhosReportFatalErrorAndAbort("%s: cannot map the Want to restart the app with", Q_FUNC_INFO);
94
95 constexpr auto sleepTimeBeforeRetry = std::chrono::seconds(3);
96
97 unsigned remainingTries = 3;
98
99 while (true) {
100 --remainingTries;
101
102 qOhosPrintfInfo(
103 "%s: calling restartApp() using Want: %s",
104 Q_FUNC_INFO, QNapi::toJsonString(napiWant).c_str());
105
106 auto optQAbility = jsState.defaultQAbility();
107 if (!optQAbility.has_value())
108 qOhosReportFatalErrorAndAbort("%s: no default UIAbility available to restart the app", Q_FUNC_INFO);
109
110 try {
111 optQAbility.value().eval(
112 "context.getApplicationContext().restartApp(*)", {napiWant});
113
114 qOhosPrintfWarning("%s: restartApp() call unexpectedly returned, killing self", Q_FUNC_INFO);
115 killCurrentProcess();
116 } catch (const Napi::Error &error) {
117 constexpr std::uint32_t restartTooFrequentlyErrorCode = 16000064;
118
119 auto errorCode = tryGetCodeFromJsBusinessError(error);
120
121 if (errorCode == restartTooFrequentlyErrorCode && remainingTries != 0) {
122 qOhosPrintfWarning(
123 "%s: restartApp() returned with error %u, sleeping before retry",
124 Q_FUNC_INFO, restartTooFrequentlyErrorCode);
125
126 std::this_thread::sleep_for(sleepTimeBeforeRetry);
127 } else {
128 auto errorCodeStr = errorCode.has_value()
129 ? std::to_string(errorCode.value())
130 : "?";
131 qOhosPrintfWarning(
132 "%s: restartApp() returned with error %s, killing self",
133 Q_FUNC_INFO, errorCodeStr.c_str());
134
135 killCurrentProcess();
136 }
137 }
138 }
139 },
140 Q_FUNC_INFO);
141
142 qOhosReportFatalErrorAndAbort("%s: unexpected return from the JS thread call", Q_FUNC_INFO);
143}
144
145struct SerialPortPermissionsState
146{
147 std::unordered_map<std::uint32_t, std::vector<QOhosConsumer<std::shared_ptr<void>>>> m_pendingSerialPortsPermissionRequestsConsumers;
148 std::unordered_map<std::uint32_t, std::weak_ptr<void>> m_grantedSerialPortsPermissionContexts;
149};
150
151std::shared_ptr<SerialPortPermissionsState> serialPortPermissionsState()
152{
153 static auto state = std::make_shared<SerialPortPermissionsState>();
154 return state;
155}
156
157std::optional<std::uint32_t> tryConvertPortNameToSystemPortId(const QString &portName)
158{
159 constexpr const char *serialPortPrefix = "COM";
160 const QString prefix = QLatin1String(serialPortPrefix);
161
162 if (!portName.startsWith(prefix))
163 return {};
164
165 bool parsedOk = false;
166 const uint parsedValue = portName.mid(prefix.length()).toUInt(&parsedOk);
167 if (!parsedOk)
168 return {};
169
170 return static_cast<std::uint32_t>(parsedValue);
171}
172
173QNapi::Object usbSerialModuleOrEmpty(QHarmonyJsContext &jsContext)
174{
175 return QNapi::Object(jsContext.env(), jsContext.tryImportModule("@ohos.usbManager.serial"));
176}
177
178bool hasSerialPortAccessRightJsImpl(QHarmonyJsContext &jsContext, std::uint32_t serialPortId)
179{
180 auto optUsbSerialModule = usbSerialModuleOrEmpty(jsContext);
181 if (optUsbSerialModule.IsEmpty())
182 return false;
183
184 try {
185 return optUsbSerialModule.eval<QNapi::Boolean>("hasSerialRight(*)", {serialPortId});
186 } catch (const Napi::Error &error) {
187 qOhosPrintfError(
188 "%s: hasSerialRight for port %d failed with error: %s",
189 Q_FUNC_INFO, serialPortId, error.what());
190 return false;
191 }
192}
193
194void requestSerialPortAccessRightJsImpl(
195 QHarmonyJsContext &jsContext, std::uint32_t serialPortId, QOhosConsumer<bool> resultConsumer)
196{
197 auto optUsbSerialModule = usbSerialModuleOrEmpty(jsContext);
198 if (optUsbSerialModule.IsEmpty()) {
199 resultConsumer(false);
200 return;
201 }
202
203 auto sharedResultConsumer = QtOhos::moveToSharedPtr(std::move(resultConsumer));
204 optUsbSerialModule.evalToPromiseOrRejectOnThrow("requestSerialRight(*)", {serialPortId})
205 .onThen(
206 [sharedResultConsumer](const QOhosCallbackInfo &cbInfo) {
207 bool granted = cbInfo.getFirstArg<QNapi::Boolean>(Q_FUNC_INFO);
208 (*sharedResultConsumer)(granted);
209 })
210 .onCatch(
211 [sharedResultConsumer](const QOhosCallbackInfo &cbInfo) {
212 QtOhos::logJsCallbackError(
213 cbInfo, "@ohos.usbManager.serial.requestSerialRight() failed");
214 (*sharedResultConsumer)(false);
215 });
216}
217
218void cancelSerialPortAccessRightJsImpl(QHarmonyJsContext &jsContext, std::uint32_t serialPortId)
219{
220 auto optUsbSerialModule = usbSerialModuleOrEmpty(jsContext);
221 if (optUsbSerialModule.IsEmpty() || !hasSerialPortAccessRightJsImpl(jsContext, serialPortId))
222 return;
223
224 try {
225 optUsbSerialModule.eval("cancelSerialRight(*)", {serialPortId});
226 } catch (const Napi::Error &error) {
227 qOhosPrintfError(
228 "%s: cancelSerialRight(%u) failed with error (ignoring): %s",
229 Q_FUNC_INFO, serialPortId, error.what());
230 }
231}
232
233void processSerialPortPermissionResponse(std::uint32_t serialPortId, bool granted)
234{
235 auto self = serialPortPermissionsState();
236
237 auto permissionContext = granted
238 ? QtOhos::makeDestroyNotifier(
239 [serialPortId, weakSelf = QtOhos::makeWeakPtr(serialPortPermissionsState())]() {
240 QNativeInterface::QHarmonyApplication::runOnQtThread(
241 [serialPortId, weakSelf]() {
242 QNativeInterface::QHarmonyApplication::runOnJsThreadAndWait(
243 [&](QHarmonyJsContext &jsContext) {
244 cancelSerialPortAccessRightJsImpl(jsContext, serialPortId);
245 });
246
247 auto self = weakSelf.lock();
248 if (self)
249 self->m_grantedSerialPortsPermissionContexts.erase(serialPortId);
250 });
251 })
252 : nullptr;
253
254 if (permissionContext)
255 self->m_grantedSerialPortsPermissionContexts[serialPortId] = permissionContext;
256
257 for (const auto &asyncPermissionRequestConsumer : self->m_pendingSerialPortsPermissionRequestsConsumers[serialPortId])
258 asyncPermissionRequestConsumer(permissionContext);
259
260 self->m_pendingSerialPortsPermissionRequestsConsumers.erase(serialPortId);
261}
262
263void requestSerialPortAccessRight(
264 const QString &portName, QObject *resultConsumerQtContext,
265 QOhosConsumer<std::shared_ptr<void>> resultConsumer)
266{
267 auto resultConsumerQtContextRef = QtOhos::makeQThreadSafeRef(resultConsumerQtContext);
268 auto asyncResultConsumer = [resultConsumerQtContextRef, resultConsumer = std::move(resultConsumer)](std::shared_ptr<void> permissionContext) {
269 resultConsumerQtContextRef.visitInQtThreadIfAlive(
270 [resultConsumer = std::move(resultConsumer), permissionContext](auto &resultConsumerQtContext) {
271 QMetaObject::invokeMethod(
272 &resultConsumerQtContext,
273 [resultConsumer = std::move(resultConsumer), permissionContext]() {
274 resultConsumer(permissionContext);
275 },
276 Qt::QueuedConnection);
277 });
278 };
279
280 const auto optSerialPortId = tryConvertPortNameToSystemPortId(portName);
281 if (!optSerialPortId.has_value()) {
282 qOhosPrintfError(
283 "%s: cannot convert serial port name '%s' to port id.",
284 Q_FUNC_INFO, portName.toStdString().c_str());
285
286 asyncResultConsumer(nullptr);
287 return;
288 }
289
290 QNativeInterface::QHarmonyApplication::runOnQtThread(
291 [serialPortId = optSerialPortId.value(), weakSelf = QtOhos::makeWeakPtr(serialPortPermissionsState()), asyncResultConsumer = std::move(asyncResultConsumer)]() {
292 auto self = weakSelf.lock();
293 if (!self)
294 return;
295
296 auto alreadyGrantedPermissionContextIt =
297 self->m_grantedSerialPortsPermissionContexts.find(serialPortId);
298 auto optAlreadyGrantedPermissionContext =
299 alreadyGrantedPermissionContextIt != self->m_grantedSerialPortsPermissionContexts.end()
300 ? alreadyGrantedPermissionContextIt->second.lock()
301 : nullptr;
302
303 if (optAlreadyGrantedPermissionContext) {
304 asyncResultConsumer(optAlreadyGrantedPermissionContext);
305 return;
306 }
307
308 self->m_pendingSerialPortsPermissionRequestsConsumers[serialPortId].push_back(
309 std::move(asyncResultConsumer));
310
311 if (self->m_pendingSerialPortsPermissionRequestsConsumers[serialPortId].size() == 1) {
312 QNativeInterface::QHarmonyApplication::runOnJsThread(
313 [serialPortId, weakSelf](QHarmonyJsContext &jsContext) {
314 requestSerialPortAccessRightJsImpl(
315 jsContext,
316 serialPortId,
317 [serialPortId, weakSelf](bool granted) {
318 QNativeInterface::QHarmonyApplication::runOnQtThread(
319 [serialPortId, weakSelf, granted]() {
320 auto self = weakSelf.lock();
321 if (self)
322 processSerialPortPermissionResponse(serialPortId, granted);
323 });
324 });
325 });
326 }
327 });
328}
329
330class QOhosAppContextImpl : public AppContext
331{
332public:
333 QOhosAppContextImpl();
334
335 bool hasSerialPortAccessRight(const QString &portName) const override;
336 void requestSerialPortAccessRightIfNeeded(
337 const QString &portName, QObject *context,
338 std::function<void(std::shared_ptr<QObject>)> callback) override;
339 std::shared_ptr<BundleInfo> bundleInfo() const override;
340 Q_NORETURN void restartApp(const std::optional<Want> &want) override;
341
342 double fontSizeScale() const override;
343
344private:
345 QOhosSupplier<double> m_fontSizeScaleSupplier;
346};
347
348template<typename T>
349std::shared_ptr<QObject> makeQObjectLifetimeHandleOrNull(std::shared_ptr<T> handle)
350{
351 if (!handle)
352 return {};
353
354 return std::shared_ptr<QObject>(
355 new QObject(),
356 [handle](QObject *ptr) {
357 ptr->deleteLater();
358 });
359}
360
361}
362
363/*!
364 \class QtHarmonyExtras::AppContext
365 \inmodule QtHarmonyExtras
366 \since 5.12.12
367 \brief The AppContext class contains API to manage native application context.
368*/
369
370AppContext::AppContext() = default;
371
372AppContext::~AppContext() = default;
373
374/*!
375 \fn static AppContext *QtHarmonyExtras::AppContext::instance()
376
377 Gets AppContext global instance.
378*/
384
385/*!
386 \fn static bool QtHarmonyExtras::AppContext::isNoUiChildMode()
387
388 Returns \c true if the current process was started as a "No UI" child
389 process (see startNoUiChildProcess()), otherwise returns \c false.
390*/
399
400/*!
401 \fn static void QtHarmonyExtras::AppContext::startNoUiChildProcess(const QString &libraryName, const QStringList &args)
402
403 Starts "No UI" child process for a given \a libraryName and \a args. Arguments passed to the
404 startNoUiChildProcess() function are forwarded to the child's main() function.
405 See \l {https://developer.huawei.com/consumer/en/doc/harmonyos-references-V5/js-apis-app-ability-childprocessmanager-V5}
406 {Child Process Manager}.
407
408 \code
409 QtHarmonyExtras::AppContext::startNoUiChildProcess(
410 "libapp.so",
411 QStringList{
412 "first arg",
413 "second arg",
414 });
415 \endcode
416*/
429
430/*!
431 \fn static std::shared_ptr<QtHarmonyExtras::WantInfo> QtHarmonyExtras::AppContext::appLaunchWantInfo()
432
433 Returns the Want object that was used to launch initial instance of the application's QAbility.
434*/
439
440/*!
441 \fn static void QtHarmonyExtras::AppContext::restartApp(const std::optional<QtHarmonyExtras::Want> &want)
442
443 Restarts the Application. If \a want is set, the new instance is launched with it; if \a want is
444 empty, the application is restarted with the app launch want.
445
446 The current application will be killed using SIGKILL and a new instance of the application will
447 be launched.
448
449 All abilities and sub-widnows created within this process will be closed.
450
451 The application will be killed ungracefully. This function won't return to the caller.
452
453 The caller must ensure, that the application has system focus when this function is called,
454 otherwise the application will be killed but the new application won't be started. OHOS system
455 treats some system dialogs (for example File Dialog) as separate from the application. If such
456 dialog is open, the application loses the system focus.
457
458 If restartApp is called too frequently, the system call will be throttled to avoid errors.
459
460 \code
461 QtHarmonyExtras::Want requestWant = QtHarmonyExtras::AppContext::getAppLaunchWant();
462 requestWant.parameters["first_parameter"] = "first_parameter_value";
463 requestWant.parameters["second_parameter"] = "second_parameter_value";
464 QtHarmonyExtras::AppContext::restartApp(requestWant);
465 \endcode
466*/
467Q_NORETURN void QOhosAppContextImpl::restartApp(const std::optional<Want> &want)
468{
469 restartAppImpl(want ? std::optional(convertWantToJsonObject(*want)) : std::nullopt);
470}
471
472QOhosAppContextImpl::QOhosAppContextImpl()
473{
474 qRegisterMetaType<std::shared_ptr<QObject>>();
475
476 m_fontSizeScaleSupplier = makeQOhosDataSource<double>(
477 [](QOhosJsState &jsState) -> double {
478 auto optQAbility = jsState.defaultQAbility();
479 if (!optQAbility.has_value())
480 return 1.0;
481 return optQAbility->eval<QNapi::Number>("context.config.fontSizeScale");
482 },
483 [](QOhosJsState &jsState, QOhosConsumer<double> valueUpdatesConsumer) {
484 return registerOhosAppContextEnvironmentCallback(
485 jsState,
486 {
487 {
488 "onConfigurationUpdated",
489 [valueUpdatesConsumer = std::move(valueUpdatesConsumer)](const QOhosCallbackInfo &cbInfo) {
490 auto config = cbInfo.getFirstArg<QNapi::Object>(Q_FUNC_INFO);
491 valueUpdatesConsumer(config.get<QNapi::Number>("fontSizeScale"));
492 }
493 },
494 });
495 },
496 [this](double fontSizeScale) {
497 Q_EMIT fontSizeScaleChanged(fontSizeScale);
498 },
499 QNativeInterface::QHarmonyApplication::runOnQtThread,
500 Q_FUNC_INFO);
501}
502
503double QOhosAppContextImpl::fontSizeScale() const
504{
505 return m_fontSizeScaleSupplier();
506}
507
508/*!
509 \fn bool QtHarmonyExtras::AppContext::hasSerialPortAccessRight(const QString &portName) const
510
511 Checks whether the application currently has permission to access the serial port identified by \a portName.
512
513 Returns \c true if access rights for the specified serial port are currently granted, otherwise returns \c false.
514
515 This function performs a synchronous check of the current permission state and does not trigger
516 any permission request. To request access rights when they are not yet granted, use
517 requestSerialPortAccessRightIfNeeded().
518
519 For details about the underlying platform API, see
520 \l {https://developer.huawei.com/consumer/en/doc/harmonyos-references/js-apis-serialmanager}
521 {Serial Port Manager}.
522
523 \sa requestSerialPortAccessRightIfNeeded()
524*/
525bool QOhosAppContextImpl::hasSerialPortAccessRight(const QString &portName) const
526{
527 const auto optSerialPortId = tryConvertPortNameToSystemPortId(portName);
528 if (!optSerialPortId.has_value()) {
529 qOhosPrintfError(
530 "%s: cannot convert serial port name '%s' to port id.",
531 Q_FUNC_INFO, portName.toStdString().c_str());
532 return false;
533 }
534
535 return QNativeInterface::QHarmonyApplication::runOnJsThreadAndWait(
536 [&](QHarmonyJsContext &jsContext) {
537 return hasSerialPortAccessRightJsImpl(jsContext, optSerialPortId.value());
538 });
539}
540
541/*!
542 \fn void QtHarmonyExtras::AppContext::requestSerialPortAccessRightIfNeeded(const QString &portName, QObject *context, std::function<void(std::shared_ptr<QObject>)> callback)
543
544 Requests permission for the application to access the serial port identified by \a portName.
545
546 This function performs an asynchronous permission request. The result of the request is delivered by
547 invoking \a callback on the thread of \a context; if \a context is destroyed before the response
548 arrives, \a callback is not invoked.
549
550 The outcome of the request (granted or denied) is reported asynchronously through \a callback.
551 If access is granted, \a callback provides a context object that must be kept alive for as long as the application
552 requires access to the serial port.
553
554 If access is not granted, \a callback delivers nullptr. This may happen if:
555 \list
556 \li a provided \a portName cannot be mapped to a valid system serial port,
557 \li an error occurred while requesting the access right,
558 \li user denied the access right.
559 \endlist
560
561 For details about the underlying platform API, see
562 \l {https://developer.huawei.com/consumer/en/doc/harmonyos-references/js-apis-serialmanager}
563 {Serial Port Manager}.
564*/
565void QOhosAppContextImpl::requestSerialPortAccessRightIfNeeded(
566 const QString &portName, QObject *context,
567 std::function<void(std::shared_ptr<QObject>)> callback)
568{
569 requestSerialPortAccessRight(
570 portName, context,
571 [callback = std::move(callback)](std::shared_ptr<void> serialPortAccessRightContext) {
572 callback(makeQObjectLifetimeHandleOrNull(serialPortAccessRightContext));
573 });
574}
575
576/*!
577 \fn std::shared_ptr<BundleInfo> QtHarmonyExtras::AppContext::bundleInfo() const
578
579 Returns BundleInfo object for the current application. The obtained information does not
580 contain information about the signature, HAP module, ability, ExtensionAbility, or permission.
581*/
582std::shared_ptr<BundleInfo> QOhosAppContextImpl::bundleInfo() const
583{
584 return createBundleInfo(getCurrentApplicationVersionCode());
585}
586
587}
588
589QT_END_NAMESPACE