File indexing completed on 2024-05-12 16:59:21

0001 /*
0002  *   SPDX-FileCopyrightText: 2014-2016 Ivan Cukic <ivan.cukic@kde.org>
0003  *
0004  *   SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
0005  */
0006 
0007 #ifndef UTILS_CONTINUE_WITH_H
0008 #define UTILS_CONTINUE_WITH_H
0009 
0010 #include <QFuture>
0011 #include <QFutureWatcher>
0012 
0013 #include "utils/optional_view.h"
0014 // #include <boost/optional.hpp>
0015 
0016 #ifdef ENABLE_QJSVALUE_CONTINUATION
0017 #include <QJSValue>
0018 #endif
0019 
0020 namespace kamd
0021 {
0022 namespace utils
0023 {
0024 namespace detail
0025 { //_
0026 #ifdef ENABLE_QJSVALUE_CONTINUATION
0027 inline void test_continuation(const QJSValue &continuation)
0028 {
0029     if (!continuation.isCallable()) {
0030         qCWarning(KAMD_LOG_RESOURCES) << "Passed handler is not callable: " << continuation.toString();
0031     }
0032 }
0033 
0034 template<typename _ReturnType>
0035 inline void pass_value(const QFuture<_ReturnType> &future, QJSValue continuation)
0036 {
0037     auto result = continuation.call({future.result()});
0038     if (result.isError()) {
0039         qCWarning(KAMD_LOG_RESOURCES) << "Handler returned this error: " << result.toString();
0040     }
0041 }
0042 
0043 inline void pass_value(const QFuture<void> &future, QJSValue continuation)
0044 {
0045     Q_UNUSED(future);
0046     auto result = continuation.call({});
0047     if (result.isError()) {
0048         qCWarning(KAMD_LOG_RESOURCES) << "Handler returned this error: " << result.toString();
0049     }
0050 }
0051 #endif
0052 
0053 template<typename _Continuation>
0054 inline void test_continuation(_Continuation &&continuation)
0055 {
0056     Q_UNUSED(continuation);
0057 }
0058 
0059 template<typename _ReturnType, typename _Continuation>
0060 inline void pass_value(const QFuture<_ReturnType> &future, _Continuation &&continuation)
0061 {
0062     using namespace kamd::utils;
0063     continuation(future.resultCount() > 0 ? make_optional_view(future.result()) : none());
0064 }
0065 
0066 template<typename _Continuation>
0067 inline void pass_value(_Continuation &&continuation)
0068 {
0069     continuation();
0070 }
0071 
0072 } //^ namespace detail
0073 
0074 template<typename _ReturnType, typename _Continuation>
0075 inline void continue_with(const QFuture<_ReturnType> &future, _Continuation &&continuation)
0076 {
0077     detail::test_continuation(continuation);
0078 
0079     auto watcher = new QFutureWatcher<_ReturnType>();
0080     QObject::connect(watcher, &QFutureWatcherBase::finished, [=]() mutable {
0081         detail::pass_value(future, continuation);
0082     });
0083 
0084     watcher->setFuture(future);
0085 }
0086 
0087 } // namespace utils
0088 } // namespace kamd
0089 
0090 #endif /* !UTILS_CONTINUE_WITH_H */