// SPDX-FileCopyrightText: 2020 - 2023 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: LGPL-3.0-or-later #ifndef DTHREADUTILS_H #define DTHREADUTILS_H #include #include #include #include #include #include #include #if DTK_VERSION >= DTK_VERSION_CHECK(6, 0, 0, 0) #include #include #include #endif DCORE_BEGIN_NAMESPACE #if DTK_VERSION < DTK_VERSION_CHECK(6, 0, 0, 0) namespace DThreadUtil { typedef std::function FunctionType; class LIBDTKCORESHARED_EXPORT FunctionCallProxy : public QObject { Q_OBJECT public: explicit FunctionCallProxy(QThread *thread); static void proxyCall(QSemaphore *s, QThread *thread, QObject *target, FunctionType fun); Q_SIGNALS: void callInLiveThread(QSemaphore *s, QPointer target, FunctionType *func); }; template class LIBDTKCORESHARED_EXPORT _TMP { public: inline static ReturnType runInThread(QSemaphore *s, QThread *thread, QObject *target, std::function fun) { ReturnType result; FunctionType proxyFun = [&result, &fun] () { result = fun(); }; FunctionCallProxy::proxyCall(s, thread, target, proxyFun); return result; } template inline static typename std::enable_if::value, ReturnType>::type runInThread(QSemaphore *s, QThread *thread, T *, std::function fun) { return runInThread(s, thread, static_cast(nullptr), fun); } }; template <> class LIBDTKCORESHARED_EXPORT _TMP { public: inline static void runInThread(QSemaphore *s, QThread *thread, QObject *target, std::function fun) { FunctionCallProxy::proxyCall(s, thread, target, fun); } template inline static typename std::enable_if::value, void>::type runInThread(QSemaphore *s, QThread *thread, T *, std::function fun) { return runInThread(s, thread, static_cast(nullptr), fun); } }; template inline auto runInThread(QSemaphore *s, QThread *thread, QObject *target, Fun fun, Args&&... args) -> decltype(fun(args...)) { return _TMP::runInThread(s, thread, target, std::bind(fun, std::forward(args)...)); } template inline auto runInThread(QSemaphore *s, QThread *thread, Fun fun, Args&&... args) -> decltype(fun(args...)) { return runInThread(s, thread, nullptr, fun, std::forward(args)...); } template inline typename QtPrivate::FunctionPointer::ReturnType runInThread(QSemaphore *s, QThread *thread, QObject *target, typename QtPrivate::FunctionPointer::Object *obj, Fun fun, Args&&... args) { return _TMP::ReturnType>::runInThread(s, thread, target, std::bind(fun, obj, std::forward(args)...)); } template inline typename QtPrivate::FunctionPointer::ReturnType runInThread(QSemaphore *s, QThread *thread, typename QtPrivate::FunctionPointer::Object *obj, Fun fun, Args&&... args) { return _TMP::ReturnType>::runInThread(s, thread, obj, std::bind(fun, obj, std::forward(args)...)); } template inline auto runInThread(QThread *thread, QObject *target, Fun fun, Args&&... args) -> decltype(fun(args...)) { QSemaphore s; return runInThread(&s, thread, target, fun, std::forward(args)...); } template inline auto runInThread(QThread *thread, Fun fun, Args&&... args) -> decltype(fun(args...)) { return runInThread(thread, nullptr, fun, std::forward(args)...); } template inline typename QtPrivate::FunctionPointer::ReturnType runInThread(QThread *thread, T *target, typename QtPrivate::FunctionPointer::Object *obj, Fun fun, Args&&... args) { QSemaphore s; return runInThread(&s, thread, target, obj, fun, std::forward(args)...); } template inline typename QtPrivate::FunctionPointer::ReturnType runInThread(QThread *thread, typename QtPrivate::FunctionPointer::Object *obj, Fun fun, Args&&... args) { return runInThread(thread, obj, obj, fun, std::forward(args)...); } template inline auto runInMainThread(QObject *target, Fun fun, Args&&... args) -> decltype(fun(args...)) { if (!QCoreApplication::instance()) { return fun(std::forward(args)...); } return runInThread(QCoreApplication::instance()->thread(), target, fun, std::forward(args)...); } template inline auto runInMainThread(Fun fun, Args&&... args) -> decltype(fun(args...)) { return runInMainThread(nullptr, fun, std::forward(args)...); } template inline typename QtPrivate::FunctionPointer::ReturnType runInMainThread(T *target, typename QtPrivate::FunctionPointer::Object *obj, Fun fun, Args&&... args) { if (!QCoreApplication::instance()) { return (obj->*fun)(std::forward(args)...); } return runInThread(QCoreApplication::instance()->thread(), target, obj, fun, std::forward(args)...); } template inline typename QtPrivate::FunctionPointer::ReturnType runInMainThread(typename QtPrivate::FunctionPointer::Object *obj, Fun fun, Args&&... args) { return runInMainThread(obj, obj, fun, std::forward(args)...); } } #else class LIBDTKCORESHARED_EXPORT DThreadUtils final { friend class Caller; public: explicit DThreadUtils(QThread *thread); ~DThreadUtils(); static DThreadUtils &gui(); QThread *thread() const noexcept; template inline auto run(QObject *context,typename QtPrivate::FunctionPointer::Object *obj, Func fun, Args &&...args) { return call(context, fun, *obj, std::forward(args)...); } template inline auto run(typename QtPrivate::FunctionPointer::Object *obj, Func fun, Args &&...args) { if constexpr (std::is_base_of::Object>::value) { return call(obj, fun, *obj, std::forward(args)...); } else { return call(static_cast(nullptr), fun, *obj, std::forward(args)...); } } template inline QFuture, Args...>> run(QObject *context, Func fun, Args &&...args) { return call(context, fun, std::forward(args)...); } template inline QFuture, Args...>> run(Func fun, Args &&...args) { return call(static_cast(nullptr), fun, std::forward(args)...); } template inline decltype(auto) exec(T &&...args) { auto future = run(std::forward(args)...); if (!thread()->isRunning()) { qWarning() << "The target thread is not running, maybe lead to deadlock."; } future.waitForFinished(); if constexpr (std::is_same_v>) { return; } else { return future.result(); } } private: class AbstractCallEvent : public QEvent { public: AbstractCallEvent(QEvent::Type type) : QEvent(type) { } virtual void call() = 0; }; template class Q_DECL_HIDDEN CallEvent : public AbstractCallEvent { using FunInfo = QtPrivate::FunctionPointer>; using ReturnType = std::invoke_result_t, Args...>; public: CallEvent(QEvent::Type type, Func &&fun, Args &&...args) : AbstractCallEvent(type) , function(std::forward(fun)) , arguments(std::forward(args)...) { } QEvent *clone() const override { return nullptr; } void call() override { if (promise.isCanceled()) { return; } if (contextChecker == context) { promise.start(); #ifndef QT_NO_EXCEPTIONS try { #endif if constexpr (std::is_void_v) { std::apply(function, arguments); } else { promise.addResult(std::apply(function, arguments)); } #ifndef QT_NO_EXCEPTIONS } catch (...) { promise.setException(std::current_exception()); } #endif promise.finish(); } else { promise.start(); promise.setException(std::make_exception_ptr(std::runtime_error("The context object is destroyed."))); promise.finish(); } } Func function; const std::tuple arguments; QPromise promise; QObject *context{nullptr}; QPointer contextChecker; }; template inline auto call(QObject *context, Func fun, Args &&...args) { using FuncInfo = QtPrivate::FunctionPointer>; using ReturnType = std::invoke_result_t, Args...> ; if constexpr (FuncInfo::IsPointerToMemberFunction) { static_assert(std::is_same_v::Car>, typename FuncInfo::Object>, "The obj and function are not compatible."); static_assert( QtPrivate::CheckCompatibleArguments::Cdr, typename FuncInfo::Arguments>::value, "The args and function are not compatible."); } else if constexpr (FuncInfo::ArgumentCount != -1) { static_assert(QtPrivate::CheckCompatibleArguments, typename FuncInfo::Arguments>::value, "The args and function are not compatible."); } else { // for lambda and impl operator() static_assert(std::is_invocable_r_v, "The callable object can't invoke with supplied args"); } QPromise promise; auto future = promise.future(); if (Q_UNLIKELY(QThread::currentThread() == m_thread)) { promise.start(); if constexpr (std::is_void_v) { std::invoke(fun, std::forward(args)...); } else { promise.addResult(std::invoke(fun, std::forward(args)...)); } promise.finish(); } else { auto event = new CallEvent(eventType, std::move(fun), std::forward(args)...); event->promise = std::move(promise); event->context = context; event->contextChecker = context; QCoreApplication::postEvent(ensureThreadContextObject(), event); } return future; } QObject *ensureThreadContextObject(); static inline QEvent::Type eventType; QThread *m_thread; QAtomicPointer threadContext; }; #endif // version macro end DCORE_END_NAMESPACE #endif // protect macro end