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
qcore_ohos_p.h
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#ifndef QCORE_OHOS_P_H
5#define QCORE_OHOS_P_H
6
7//
8// W A R N I N G
9// -------------
10//
11// This file is not part of the Qt API. It exists purely as an
12// implementation detail. This header file may change from version to
13// version without notice, or even be removed.
14//
15// We mean it.
16//
17
18#include <QtCore/private/qnapi_p.h>
19#include <QtCore/private/qohoscommon_p.h>
20#include <QtCore/qglobal.h>
21#include <QtCore/qobject.h>
22#include <QtCore/qpointer.h>
23#include <QtCore/qmutex.h>
24#include <algorithm>
25#include <cstdint>
26#include <functional>
27#include <map>
28#include <memory>
29#include <optional>
30#include <pthread.h>
31#include <string>
32#include <tuple>
33#include <type_traits>
34#include <typeinfo>
35#include <vector>
36
37QT_BEGIN_NAMESPACE
38
39namespace QtOhos {
40
41class QObjectThreadSafeRef;
42
43template<typename Enum>
45{
46};
47
48}
49
50class Q_CORE_EXPORT QOhosJsState
51{
52public:
53 QOhosJsState(const QOhosJsState &) = delete;
54 QOhosJsState &operator=(const QOhosJsState &) = delete;
55
56 virtual ~QOhosJsState();
57
58 virtual napi_env env() = 0;
59
60 virtual QNapi::Object defaultWindowStageOrEmpty() = 0;
61 virtual QNapi::Object defaultUiContextOrEmpty() = 0;
62
63 virtual std::optional<QNapi::Object> tryGetJsWindowByQWindow(QtOhos::QObjectThreadSafeRef qwindow) = 0;
64 virtual std::optional<QNapi::Object> tryGetQAbilityByQWindow(QtOhos::QObjectThreadSafeRef qwindow) = 0;
65 virtual std::optional<QNapi::Object> defaultQAbility() = 0;
66
67 virtual QNapi::Object appLaunchWant() = 0;
68 virtual std::optional<QNapi::Object> optAppLaunchParam() = 0;
69
70 // a registered module, or an unknown one loaded with napi_load_module() and memoized; empty if that load fails
71 virtual std::optional<QNapi::Object> tryGetModule(const std::string &moduleName) = 0;
72
73 template<typename T>
74 std::enable_if_t<std::is_default_constructible<T>::value, T> &getAttachedObjectWithLazyCreate();
75
76 virtual void startAppProcess(
77 const std::string &processId, QNapi::Object requestWant,
78 QNapi::Object optStartOptions, std::function<void(QOhosJsState &)> continueFunc) = 0;
79
80 virtual void startNoUiChildProcess(const std::string &libraryName, const std::vector<std::string> &args) = 0;
81
82 // wantConsumer's parameters: jsState, qAbility, want, launchParam
83 [[nodiscard]] virtual std::shared_ptr<void> registerNewWantConsumer(
84 QOhosConsumer<QOhosJsState &, QNapi::Object, QNapi::Object, QNapi::Object> wantConsumer) = 0;
85
86 // requestsHandler's parameters: jsState, wantParams, resultConsumer
87 virtual void setOnContinueRequestsHandler(
88 QNapi::Object qAbility,
89 std::function<void(QOhosJsState &, QNapi::Object, QOhosConsumer<QOhosJsState &, QNapi::Number>)> requestsHandler) = 0;
90
91 // delegate's methods are called from the matching UIAbility methods, with the ability added before the other arguments
92 [[nodiscard]] virtual std::shared_ptr<void> registerUiAbilityDelegate(QNapi::Object delegate) = 0;
93
94 virtual void setDestroyFromSystemAllowed(QNapi::Object qAbility, bool destroyAllowed) = 0;
95
96 template<typename T = QNapi::Value>
97 T eval(const std::string &expr, const std::vector<QNapi::ValueWrapper> &exprArgs = {});
98
99 QNapi::Promise evalToPromiseOrRejectOnThrow(
100 const std::string &expr, const std::vector<QNapi::ValueWrapper> &exprArgs = {});
101
102 template<typename Enum>
103 QNapi::Number mapOhosEnumToJs(Enum enumValue);
104
105 template<typename Enum>
106 std::optional<Enum> tryMapOhosEnumFromJs(QNapi::Number enumJsValue);
107
108 template<typename Enum>
109 Enum mapOhosEnumFromJs(QNapi::Number enumJsValue);
110
111protected:
112 struct OhosEnumInfo
113 {
114 std::string fullTypeName;
115 std::vector<std::pair<int, const char *>> enumeratorsNames;
116 };
117
118 QOhosJsState();
119
120private:
121 template<typename Enum, typename = void>
122 struct OhosEnumFullTypeNameFetcher
123 {
124 static std::string fullTypeName()
125 {
126 return QtOhos::OhosEnumMeta<Enum>::moduleName + std::string(".") + QtOhos::OhosEnumMeta<Enum>::typeName;
127 }
128 };
129
130 template<typename Enum>
131 struct OhosEnumFullTypeNameFetcher<Enum, decltype(static_cast<void>(&QtOhos::OhosEnumMeta<Enum>::fullTypeName))>
132 {
133 static std::string fullTypeName()
134 {
135 return QtOhos::OhosEnumMeta<Enum>::fullTypeName;
136 }
137 };
138
139 template<typename Enum>
140 static OhosEnumInfo makeOhosEnumInfo();
141
142 virtual std::tuple<QNapi::Object, std::string> extractModuleFromEvalExpr(const std::string &expr) = 0;
143 virtual void *getAttachedObjectWithLazyCreate(
144 const std::type_info &objectTypeInfo, QOhosSupplier<std::shared_ptr<void>> objectFactory) = 0;
145 virtual QNapi::Number mapOhosEnumToJs(int enumValue, const std::type_info &enumTypeInfo, OhosEnumInfo (*ohosEnumInfoFactory)()) = 0;
146 virtual std::optional<int> tryMapOhosEnumFromJs(QNapi::Number enumJsValue, const std::type_info &enumTypeInfo, OhosEnumInfo (*ohosEnumInfoFactory)()) = 0;
147 virtual int mapOhosEnumFromJs(QNapi::Number enumJsValue, const std::type_info &enumTypeInfo, OhosEnumInfo (*ohosEnumInfoFactory)()) = 0;
148};
149
150class Q_CORE_EXPORT QOhosCallbackInfo : public QNapi::CallbackInfo
151{
152public:
153 using QNapi::CallbackInfo::CallbackInfo;
154
155 QOhosJsState &jsState() const;
156};
157
159{
160 std::optional<std::string> optName;
161 std::optional<std::string> optMessage;
162 std::optional<std::int64_t> optCode;
163};
164
166
167Q_CORE_EXPORT void invoke(std::function<void(QOhosJsState &)> &&task);
168
169Q_CORE_EXPORT void invokeAndWaitForContinue(
170 std::function<void(QOhosJsState &, QOhosTaskPromise<>)> &&task,
171 std::string callerContextName = {});
172
173Q_CORE_EXPORT void runAndWait(
174 const std::function<void(QOhosJsState &)> &task,
175 std::string callerContextName = {});
176
177template<typename Func>
178auto eval(Func &&func, std::string callerContextName = {})
179 -> decltype(func(std::declval<QOhosJsState &>()));
180
181template<typename T>
183 std::function<void(QOhosJsState &, QOhosTaskPromise<T>)> evalFunc,
184 std::string callerContextName = {});
185
186}
187
188class Q_CORE_EXPORT QOhosJsThreadOps
189{
190public:
191 virtual ~QOhosJsThreadOps();
192
193 virtual QOhosJsState &jsState() = 0;
194
195 virtual void invoke(std::function<void(QOhosJsState &)> &&task) = 0;
196 virtual void invokeAndWaitForContinue(
197 std::function<void(QOhosJsState &, QOhosTaskPromise<>)> &&task,
198 std::string callerContextName) = 0;
199 virtual void runAndWait(
200 const std::function<void(QOhosJsState &)> &task,
201 std::string callerContextName) = 0;
202
203 static void registerInstance(QOhosJsThreadOps *ops);
204 static QOhosJsThreadOps &instance();
205
206protected:
207 QOhosJsThreadOps();
208};
209
210namespace QtOhos {
211
212class Q_CORE_EXPORT QObjectThreadSafeRef
213{
214public:
217
220
221 bool operator==(const QObjectThreadSafeRef &other) const;
222 bool operator!=(const QObjectThreadSafeRef &other) const;
223
224 std::string refName() const;
225
226 // it may be called only inside Qt thread that created the reference
227 QPointer<QObject> data() const;
228
229 void visitInQtThreadIfAlive(std::function<void(QObject &)> &&visitFunc) const;
230
231private:
232 struct QObjectRef
233 {
236 };
237
239 Q_CONSTINIT inline static std::uint64_t refsMapInsertCounter = 0;
240
244
245public:
247};
248
249template<typename T>
251{
252public:
253 static_assert(std::is_base_of<QObject, T>::value, "The class supports QObject subtypes only");
254
256 QThreadSafeRef(QPointer<T> obj);
257
260
261 QObjectThreadSafeRef toQObjectThreadSafeRef() const;
262
263 std::string refName() const;
264
265 // it may be called only inside Qt thread that created the reference
266 QPointer<T> data() const;
267
268 void visitInQtThreadIfAlive(std::function<void(T &)> &&visitFunc) const;
269
270private:
271 QObjectThreadSafeRef m_ref;
272};
273
275{
276public:
277 QtState(const QtState &) = delete;
278 QtState &operator=(const QtState &) = delete;
279
280 virtual ~QtState();
281
282 virtual bool isQtThread() const = 0;
283
284 virtual void invokeTask(std::function<void()> &&task) = 0;
285
286protected:
288};
289
290template<typename T>
292
293// this function should be called once from Qt thread at some point during startup
294Q_CORE_EXPORT void initQtThreadState();
295
296// Creates a proxy for the base shared_ptr which uses custom deleter to ensure
297// that the underlying shared_ptr is destroyed (synchronously) in the JS thread.
298// This ensures that the managed object will be also destroyed in the JS thread,
299// as long as the caller passes the only existing shared_ptr instance managing
300// that object to the function. This is the caller's responsibility to do this
301// (preferably by using a call to some std::shared_ptr<T> factory function as
302// the function's argument).
303template<typename T>
304std::shared_ptr<T> makeProxyWithJsThreadDeleter(std::shared_ptr<T> &&baseSharedPtr);
305
306// as makeProxyWithJsThreadDeleter(), but the release is posted to the JS thread instead of awaited
307template<typename T>
308std::shared_ptr<T> makeProxyWithAsyncJsThreadDeleter(std::shared_ptr<T> &&baseSharedPtr);
309
310// invokes the task inside the Qt thread, can be called from any thread at any time
311Q_CORE_EXPORT void invokeInQtThread(std::function<void()> &&task);
312
313Q_CORE_EXPORT QtState &getQtState();
314
315// logs error message with supplied prefix and error details extracted from
316// JS error object passed as an argument via CallbackInfo
317Q_CORE_EXPORT void logJsCallbackError(const QOhosCallbackInfo &cbInfo, const char *errorMessagePrefix);
318
319// reads the string name and message and the integer code (a number or an integer string) of a JS error, where present
320Q_CORE_EXPORT QOhosJsErrorInfo tryExtractErrorInfoFromJsError(QNapi::Value jsErrorOrEmpty);
321
322// Creates JS callback that expects JS error object as a JS argument
323// and logs details of the error. The logged message includes provided
324// call context string (usually the name of called method).
326
327template<typename T>
329{
330 return QThreadSafeRef<T>(obj);
331}
332
333template<typename T>
334QThreadSafeRef<T>::QThreadSafeRef() = default;
335
336template<typename T>
337QThreadSafeRef<T>::QThreadSafeRef(QPointer<T> obj)
338 : QObjectThreadSafeRef(obj.data())
339{
340}
341
342template<typename T>
343QThreadSafeRef<T>::QThreadSafeRef(const QThreadSafeRef<T> &other) = default;
344
345template<typename T>
346QThreadSafeRef<T> &QThreadSafeRef<T>::operator=(const QThreadSafeRef<T> &other) = default;
347
348template<typename T>
349std::string QThreadSafeRef<T>::refName() const
350{
351 return QObjectThreadSafeRef::refName();
352}
353
354template<typename T>
355QObjectThreadSafeRef QThreadSafeRef<T>::toQObjectThreadSafeRef() const
356{
357 return static_cast<const QObjectThreadSafeRef &>(*this);
358}
359
360template<typename T>
362{
363 return static_cast<T *>(
364 static_cast<QObject *>(
365 QObjectThreadSafeRef::data()));
366}
367
368template<typename T>
369void QThreadSafeRef<T>::visitInQtThreadIfAlive(std::function<void(T &)> &&visitFunc) const
370{
371 QObjectThreadSafeRef::visitInQtThreadIfAlive(
372 [sharedVisitFunc = takeFunctionToSharedPtr(visitFunc)](QObject &obj) {
373 const auto takenVisitFunc = std::exchange(*sharedVisitFunc, nullptr);
374 takenVisitFunc(static_cast<T &>(obj));
375 });
376}
377
378template<typename T>
379std::shared_ptr<T> makeProxyWithJsThreadDeleter(std::shared_ptr<T> &&baseSharedPtr)
380{
381 auto *baseRawPtr = baseSharedPtr.get();
382 return std::shared_ptr<T>(
383 baseRawPtr,
384 [baseSharedPtr = std::move(baseSharedPtr)](T *) mutable {
386 [&](QOhosJsState &) {
387 baseSharedPtr.reset();
388 },
389 Q_FUNC_INFO);
390 });
391}
392
393template<typename T>
394std::shared_ptr<T> makeProxyWithAsyncJsThreadDeleter(std::shared_ptr<T> &&baseSharedPtr)
395{
396 auto *baseRawPtr = baseSharedPtr.get();
397 return std::shared_ptr<T>(
398 baseRawPtr,
399 [baseSharedPtr = std::move(baseSharedPtr)](T *) mutable {
401 [baseSharedPtr = std::move(baseSharedPtr)](QOhosJsState &) mutable {
402 baseSharedPtr.reset();
403 });
404 });
405}
406
407}
408
409template<typename T>
410T QOhosJsState::eval(const std::string &expr, const std::vector<QNapi::ValueWrapper> &exprArgs)
411{
412 using namespace std::string_literals;
413
414 QNapi::Object module;
415 std::string subExpr;
416 std::tie(module, subExpr) = extractModuleFromEvalExpr(expr);
417
418 return !subExpr.empty()
419 ? module.eval<T>(subExpr, exprArgs)
420 : QNapi::checkedCast<T>(
421 module,
422 [&]() {
423 return "module '"s + expr + "'"s;
424 });
425}
426
427inline QNapi::Promise QOhosJsState::evalToPromiseOrRejectOnThrow(
428 const std::string &expr, const std::vector<QNapi::ValueWrapper> &exprArgs)
429{
430 QNapi::Object module;
431 std::string subExpr;
432 std::tie(module, subExpr) = extractModuleFromEvalExpr(expr);
433
434 return module.evalToPromiseOrRejectOnThrow(subExpr, exprArgs);
435}
436
437template<typename T>
438std::enable_if_t<std::is_default_constructible<T>::value, T> &QOhosJsState::getAttachedObjectWithLazyCreate()
439{
440 auto *objectPtr = reinterpret_cast<T *>(
441 getAttachedObjectWithLazyCreate(typeid(T), &std::make_shared<T>));
442 return *objectPtr;
443}
444
445template<typename Enum>
446QNapi::Number QOhosJsState::mapOhosEnumToJs(Enum enumValue)
447{
448 return mapOhosEnumToJs(static_cast<int>(enumValue), typeid(Enum), &makeOhosEnumInfo<Enum>);
449}
450
451template<typename Enum>
452std::optional<Enum> QOhosJsState::tryMapOhosEnumFromJs(QNapi::Number enumJsValue)
453{
454 auto intValue = tryMapOhosEnumFromJs(enumJsValue, typeid(Enum), &makeOhosEnumInfo<Enum>);
455 return intValue.has_value()
456 ? std::optional(static_cast<Enum>(intValue.value()))
457 : std::nullopt;
458}
459
460template<typename Enum>
461Enum QOhosJsState::mapOhosEnumFromJs(QNapi::Number enumJsValue)
462{
463 return static_cast<Enum>(mapOhosEnumFromJs(enumJsValue, typeid(Enum), &makeOhosEnumInfo<Enum>));
464}
465
466template<typename Enum>
467QOhosJsState::OhosEnumInfo QOhosJsState::makeOhosEnumInfo()
468{
469 static const auto enumEnumeratorsNames = QtOhos::OhosEnumMeta<Enum>::enumeratorsNames;
470
471 std::vector<std::pair<int, const char *>> intEnumeratorsNames;
472 std::transform(
473 enumEnumeratorsNames.begin(), enumEnumeratorsNames.end(),
474 std::back_inserter(intEnumeratorsNames),
475 [](const auto &valueNamePair) {
476 return std::pair<int, const char *>(static_cast<int>(valueNamePair.first), valueNamePair.second);
477 });
478
479 return OhosEnumInfo {
480 .fullTypeName = OhosEnumFullTypeNameFetcher<Enum>::fullTypeName(),
481 .enumeratorsNames = std::move(intEnumeratorsNames),
482 };
483}
484
485template<typename Func>
486auto QOhosJsThreadGateway::eval(Func &&func, std::string callerContextName)
487 -> decltype(func(std::declval<QOhosJsState &>()))
488{
489 using Result = decltype(func(std::declval<QOhosJsState &>()));
490 static_assert(
491 !(std::is_class<Result>::value
492 && (
493 std::is_convertible<Result, napi_value>::value
494 || std::is_convertible<Result, napi_ref>::value)),
495 "NAPI values/references must not be accessed outside the JS thread");
496
497 std::unique_ptr<Result> result;
498 runAndWait(
499 [&](QOhosJsState &jsState) {
500 result = std::make_unique<Result>(func(jsState));
501 },
502 std::move(callerContextName));
503 return std::move(*result);
504}
505
506template<typename T>
508 std::function<void(QOhosJsState &, QOhosTaskPromise<T>)> evalFunc,
509 std::string callerContextName)
510{
511 static_assert(
512 !(std::is_class<T>::value
513 && (
514 std::is_convertible<T, napi_value>::value
515 || std::is_convertible<T, napi_ref>::value)),
516 "NAPI values/references must not be accessed outside the JS thread");
517
518 std::unique_ptr<T> result;
519 invokeAndWaitForContinue(
520 [&](QOhosJsState &jsState, QOhosTaskPromise<> taskPromise) {
521 evalFunc(
522 jsState,
523 QOhosTaskPromise<T>(
524 [&result, taskPromise = std::move(taskPromise)](T value) {
525 result = std::make_unique<T>(std::move(value));
526 taskPromise();
527 },
528 {},
529 std::move(callerContextName)));
530 },
531 callerContextName);
532
533 return std::move(*result);
534}
535
536QT_END_NAMESPACE
537
538#endif
QPointer< T > data() const
QThreadSafeRef(const QThreadSafeRef< T > &other)
std::string refName() const
void visitInQtThreadIfAlive(std::function< void(T &)> &&visitFunc) const
QThreadSafeRef & operator=(const QThreadSafeRef< T > &other)
QObjectThreadSafeRef toQObjectThreadSafeRef() const
QtState & operator=(const QtState &)=delete
virtual void invokeTask(std::function< void()> &&task)=0
QtState(const QtState &)=delete
virtual bool isQtThread() const =0
virtual ~QtState()
T evalWithPromise(std::function< void(QOhosJsState &, QOhosTaskPromise< T >)> evalFunc, std::string callerContextName={})
Q_CORE_EXPORT void invoke(std::function< void(QOhosJsState &)> &&task)
auto eval(Func &&func, std::string callerContextName={}) -> decltype(func(std::declval< QOhosJsState & >()))
Q_CORE_EXPORT void runAndWait(const std::function< void(QOhosJsState &)> &task, std::string callerContextName={})
Q_CORE_EXPORT void invokeAndWaitForContinue(std::function< void(QOhosJsState &, QOhosTaskPromise<>)> &&task, std::string callerContextName={})
void initQtThreadState()
QThreadSafeRef< T > makeQThreadSafeRef(T *obj)
std::shared_ptr< T > makeProxyWithJsThreadDeleter(std::shared_ptr< T > &&baseSharedPtr)
void logJsCallbackError(const QOhosCallbackInfo &cbInfo, const char *errorMessagePrefix)
QtState & getQtState()
std::shared_ptr< T > makeProxyWithAsyncJsThreadDeleter(std::shared_ptr< T > &&baseSharedPtr)
std::function< void(const QOhosCallbackInfo &)> makeErrorLoggingJsCallback(std::string callContext)
QOhosJsErrorInfo tryExtractErrorInfoFromJsError(QNapi::Value jsErrorOrEmpty)
void invokeInQtThread(std::function< void()> &&task)
static QOhosJsThreadOps * qOhosJsThreadOpsInstance
std::optional< std::string > optName
std::optional< std::string > optMessage
std::optional< std::int64_t > optCode