aboutsummaryrefslogtreecommitdiffstats
path: root/src/libs/utils/runextensions.h
blob: ba779e131f445d8c9169d5c3ed7a6cad4882091e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0

#pragma once

#include "utils_global.h"

#include "functiontraits.h"

#include <QCoreApplication>
#include <QFuture>
#include <QFutureInterface>
#include <QFutureWatcher>
#include <QRunnable>
#include <QThread>
#include <QThreadPool>

#include <functional>
#include <optional>

// hasCallOperator & Co must be outside of any namespace
// because of internal compiler error with MSVC2015 Update 2

using testCallOperatorYes = char;
using testCallOperatorNo = struct { char foo[2]; };

template<typename C>
static testCallOperatorYes testCallOperator(decltype(&C::operator()));

template<typename>
static testCallOperatorNo testCallOperator(...);

template<typename T>
struct hasCallOperator
{
    static const bool value = (sizeof(testCallOperator<T>(nullptr)) == sizeof(testCallOperatorYes));
};

namespace Utils {

using StackSizeInBytes = std::optional<uint>;

namespace Internal {

/*
   resultType<F>::type

   Returns the type of results that would be reported by a callable of type F
   when called through the runAsync methods. I.e. the ResultType in

   void f(QFutureInterface<Result> &fi, ...)
   ResultType f(...)

   Returns void if F is not callable, and if F is a callable that does not take
   a QFutureInterface& as its first parameter and returns void.
*/

template <typename Function>
struct resultType;

template <typename Function, typename Arg>
struct resultTypeWithArgument;

template <typename Function, int index, bool>
struct resultTypeTakesArguments;

template <typename Function, bool>
struct resultTypeIsMemberFunction;

template <typename Function, bool>
struct resultTypeIsFunctionLike;

template <typename Function, bool>
struct resultTypeHasCallOperator;

template <typename Function, typename ResultType>
struct resultTypeWithArgument<Function, QFutureInterface<ResultType>&>
{
    using type = ResultType;
};

template <typename Function, typename Arg>
struct resultTypeWithArgument
{
    using type = functionResult_t<Function>;
};

template <typename Function, int index>
struct resultTypeTakesArguments<Function, index, true>
        : public resultTypeWithArgument<Function, typename functionTraits<Function>::template argument<index>::type>
{
};

template <typename Function, int index>
struct resultTypeTakesArguments<Function, index, false>
{
    using type = functionResult_t<Function>;
};

template <typename Function>
struct resultTypeIsFunctionLike<Function, true>
        : public resultTypeTakesArguments<Function, 0, (functionTraits<Function>::arity > 0)>
{
};

template <typename Function>
struct resultTypeIsMemberFunction<Function, true>
        : public resultTypeTakesArguments<Function, 1, (functionTraits<Function>::arity > 1)>
{
};

template <typename Function>
struct resultTypeIsMemberFunction<Function, false>
{
    using type = void;
};

template <typename Function>
struct resultTypeIsFunctionLike<Function, false>
        : public resultTypeIsMemberFunction<Function, std::is_member_function_pointer<Function>::value>
{
};

template <typename Function>
struct resultTypeHasCallOperator<Function, false>
        : public resultTypeIsFunctionLike<Function, std::is_function<std::remove_pointer_t<std::decay_t<Function>>>::value>
{
};

template <typename Callable>
struct resultTypeHasCallOperator<Callable, true>
        : public resultTypeTakesArguments<Callable, 0, (functionTraits<Callable>::arity > 0)>
{
};

template <typename Function>
struct resultType
        : public resultTypeHasCallOperator<Function, hasCallOperator<Function>::value>
{
};

template <typename Function>
struct resultType<Function&> : public resultType<Function>
{
};

template <typename Function>
struct resultType<const Function&> : public resultType<Function>
{
};

template <typename Function>
struct resultType<Function &&> : public resultType<Function>
{
};

template <typename Function>
struct resultType<std::reference_wrapper<Function>> : public resultType<Function>
{
};
template <typename Function>
struct resultType<std::reference_wrapper<const Function>> : public resultType<Function>
{
};

/*
   Callable object that wraps a member function pointer with the object it
   will be called on.
*/

template <typename Function>
class MemberCallable;

template <typename Result, typename Obj, typename... Args>
class MemberCallable<Result(Obj::*)(Args...) const>
{
public:
    MemberCallable(Result(Obj::* function)(Args...) const, const Obj *obj)
        : m_function(function),
          m_obj(obj)
    {
    }

    Result operator()(Args&&... args) const
    {
        return ((*m_obj).*m_function)(std::forward<Args>(args)...);
    }

private:
    Result(Obj::* m_function)(Args...) const;
    const Obj *m_obj;
};

template <typename Result, typename Obj, typename... Args>
class MemberCallable<Result(Obj::*)(Args...)>
{
public:
    MemberCallable(Result(Obj::* function)(Args...), Obj *obj)
        : m_function(function),
          m_obj(obj)
    {
    }

    Result operator()(Args&&... args) const
    {
        return ((*m_obj).*m_function)(std::forward<Args>(args)...);
    }

private:
    Result(Obj::* m_function)(Args...);
    Obj *m_obj;
};

/*
   Helper functions for runAsync that run in the started thread.
*/

// void function that does not take QFutureInterface
template <typename ResultType, typename Function, typename... Args>
void runAsyncReturnVoidDispatch(std::true_type, QFutureInterface<ResultType> &, Function &&function, Args&&... args)
{
    function(std::forward<Args>(args)...);
}

// non-void function that does not take QFutureInterface
template <typename ResultType, typename Function, typename... Args>
void runAsyncReturnVoidDispatch(std::false_type, QFutureInterface<ResultType> &futureInterface, Function &&function, Args&&... args)
{
    futureInterface.reportResult(function(std::forward<Args>(args)...));
}

// function that takes QFutureInterface
template <typename ResultType, typename Function, typename... Args>
void runAsyncQFutureInterfaceDispatch(std::true_type, QFutureInterface<ResultType> &futureInterface, Function &&function, Args&&... args)
{
    function(futureInterface, std::forward<Args>(args)...);
}

// function that does not take QFutureInterface
template <typename ResultType, typename Function, typename... Args>
void runAsyncQFutureInterfaceDispatch(std::false_type, QFutureInterface<ResultType> &futureInterface, Function &&function, Args&&... args)
{
    runAsyncReturnVoidDispatch(std::is_void<std::invoke_result_t<Function, Args...>>(),
                               futureInterface, std::forward<Function>(function), std::forward<Args>(args)...);
}

// function, function pointer, or other callable object that is no member pointer
template <typename ResultType, typename Function, typename... Args,
          typename = std::enable_if_t<!std::is_member_pointer<std::decay_t<Function>>::value>
         >
void runAsyncMemberDispatch(QFutureInterface<ResultType> &futureInterface, Function &&function, Args&&... args)
{
    runAsyncQFutureInterfaceDispatch(functionTakesArgument<Function, 0, QFutureInterface<ResultType>&>(),
                                     futureInterface, std::forward<Function>(function), std::forward<Args>(args)...);
}

// Function = member function
template <typename ResultType, typename Function, typename Obj, typename... Args,
          typename = std::enable_if_t<std::is_member_pointer<std::decay_t<Function>>::value>
         >
void runAsyncMemberDispatch(QFutureInterface<ResultType> &futureInterface, Function &&function, Obj &&obj, Args&&... args)
{
    // Wrap member function with object into callable
    runAsyncImpl(futureInterface,
                 MemberCallable<std::decay_t<Function>>(std::forward<Function>(function), std::forward<Obj>(obj)),
                 std::forward<Args>(args)...);
}

// cref to function/callable
template <typename ResultType, typename Function, typename... Args>
void runAsyncImpl(QFutureInterface<ResultType> &futureInterface,
                  std::reference_wrapper<Function> functionWrapper, Args&&... args)
{
    runAsyncMemberDispatch(futureInterface, functionWrapper.get(), std::forward<Args>(args)...);
}

// function/callable, no cref
template <typename ResultType, typename Function, typename... Args>
void runAsyncImpl(QFutureInterface<ResultType> &futureInterface,
                  Function &&function, Args&&... args)
{
    runAsyncMemberDispatch(futureInterface, std::forward<Function>(function),
                           std::forward<Args>(args)...);
}
/*
   AsyncJob is a QRunnable that wraps a function with the
   arguments that are passed to it when it is run in a thread.
*/

template <class T>
std::decay_t<T>
decayCopy(T&& v)
{
    return std::forward<T>(v);
}

template <typename ResultType, typename Function, typename... Args>
class AsyncJob : public QRunnable
{
public:
    AsyncJob(Function &&function, Args&&... args)
          // decay copy like std::thread
        : data(decayCopy(std::forward<Function>(function)), decayCopy(std::forward<Args>(args))...)
    {
        // we need to report it as started even though it isn't yet, because someone might
        // call waitForFinished on the future, which does _not_ block if the future is not started
        futureInterface.setRunnable(this);
        futureInterface.reportStarted();
    }

    ~AsyncJob() override
    {
        // QThreadPool can delete runnables even if they were never run (e.g. QThreadPool::clear).
        // Since we reported them as started, we make sure that we always report them as finished.
        // reportFinished only actually sends the signal if it wasn't already finished.
        futureInterface.reportFinished();
    }

    QFuture<ResultType> future() { return futureInterface.future(); }

    void run() override
    {
        if (priority != QThread::InheritPriority)
            if (QThread *thread = QThread::currentThread())
                if (thread != qApp->thread())
                    thread->setPriority(priority);
        if (futureInterface.isCanceled()) {
            futureInterface.reportFinished();
            return;
        }
        runHelper(std::make_index_sequence<std::tuple_size<Data>::value>());
    }

    void setThreadPool(QThreadPool *pool)
    {
        futureInterface.setThreadPool(pool);
    }

    void setThreadPriority(QThread::Priority p)
    {
        priority = p;
    }

private:
    using Data = std::tuple<std::decay_t<Function>, std::decay_t<Args>...>;

    template <std::size_t... index>
    void runHelper(std::index_sequence<index...>)
    {
        // invalidates data, which is moved into the call
        runAsyncImpl(futureInterface, std::move(std::get<index>(data))...);
        if (futureInterface.isPaused())
            futureInterface.waitForResume();
        futureInterface.reportFinished();
    }

    Data data;
    QFutureInterface<ResultType> futureInterface;
    QThread::Priority priority = QThread::InheritPriority;
};

class QTCREATOR_UTILS_EXPORT RunnableThread : public QThread
{
public:
    explicit RunnableThread(QRunnable *runnable, QObject *parent = nullptr);

protected:
    void run() override;

private:
    QRunnable *m_runnable;
};

template<typename Function,
         typename... Args,
         typename ResultType = typename Internal::resultType<Function>::type>
QFuture<ResultType> runAsync_internal(QThreadPool *pool,
                                      StackSizeInBytes stackSize,
                                      QThread::Priority priority,
                                      Function &&function,
                                      Args &&... args)
{
    Q_ASSERT(!(pool && stackSize)); // stack size cannot be changed once a thread is started
    auto job = new Internal::AsyncJob<ResultType,Function,Args...>
            (std::forward<Function>(function), std::forward<Args>(args)...);
    job->setThreadPriority(priority);
    QFuture<ResultType> future = job->future();
    if (pool) {
        job->setThreadPool(pool);
        pool->start(job);
    } else {
        auto thread = new Internal::RunnableThread(job);
        if (stackSize)
            thread->setStackSize(stackSize.value());
        thread->moveToThread(qApp->thread()); // make sure thread gets deleteLater on main thread
        QObject::connect(thread, &QThread::finished, thread, &QObject::deleteLater);
        thread->start(priority);
    }
    return future;
}

} // Internal

/*!
    The interface of \c {runAsync} is similar to the std::thread constructor and \c {std::invoke}.

    The \a function argument can be a member function,
    an object with \c {operator()} (with no overloads),
    a \c {std::function}, lambda, function pointer or function reference.
    The \a args are passed to the function call after they are copied/moved to the thread.

    The \a function can take a \c {QFutureInterface<ResultType>&} as its first argument, followed by
    other custom arguments which need to be passed to this function.
    If it does not take a \c {QFutureInterface<ResultType>&} as its first argument
    and its return type is not void, the function call's result is reported to the QFuture.
    If \a function is a (non-static) member function, the first argument in \a args is expected
    to be the object that the function is called on.

    If a thread \a pool is given, the function is run there. Otherwise a new, independent thread
    is started.

    \sa std::thread
    \sa std::invoke
    \sa QThreadPool
    \sa QThread::Priority
 */
template <typename Function, typename... Args,
          typename ResultType = typename Internal::resultType<Function>::type>
QFuture<ResultType>
runAsync(QThreadPool *pool, QThread::Priority priority, Function &&function, Args&&... args)
{
    return Internal::runAsync_internal(pool,
                                       StackSizeInBytes(),
                                       priority,
                                       std::forward<Function>(function),
                                       std::forward<Args>(args)...);
}

/*!
    Runs \a function with \a args in a new thread with given thread \a priority.
    \sa runAsync(QThreadPool*,QThread::Priority,Function&&,Args&&...)
    \sa QThread::Priority
 */
template <typename Function, typename... Args,
          typename ResultType = typename Internal::resultType<Function>::type>
QFuture<ResultType>
runAsync(QThread::Priority priority, Function &&function, Args&&... args)
{
    return runAsync(static_cast<QThreadPool *>(nullptr), priority,
                    std::forward<Function>(function), std::forward<Args>(args)...);
}

/*!
    Runs \a function with \a args in a new thread with given thread \a stackSize and
    thread priority QThread::InheritPriority .
    \sa runAsync(QThreadPool*,QThread::Priority,Function&&,Args&&...)
    \sa QThread::Priority
    \sa QThread::setStackSize
*/
template<typename Function,
         typename... Args,
         typename ResultType = typename Internal::resultType<Function>::type>
QFuture<ResultType> runAsync(StackSizeInBytes stackSize, Function &&function, Args &&... args)
{
    return Internal::runAsync_internal(static_cast<QThreadPool *>(nullptr),
                                       stackSize,
                                       QThread::InheritPriority,
                                       std::forward<Function>(function),
                                       std::forward<Args>(args)...);
}

/*!
    Runs \a function with \a args in a new thread with given thread \a stackSize and
    given thread \a priority.
    \sa runAsync(QThreadPool*,QThread::Priority,Function&&,Args&&...)
    \sa QThread::Priority
    \sa QThread::setStackSize
*/
template<typename Function,
         typename... Args,
         typename ResultType = typename Internal::resultType<Function>::type>
QFuture<ResultType> runAsync(StackSizeInBytes stackSize,
                             QThread::Priority priority,
                             Function &&function,
                             Args &&... args)
{
    return Internal::runAsync_internal(static_cast<QThreadPool *>(nullptr),
                                       stackSize,
                                       priority,
                                       std::forward<Function>(function),
                                       std::forward<Args>(args)...);
}

/*!
    Runs \a function with \a args in a new thread with thread priority QThread::InheritPriority.
    \sa runAsync(QThreadPool*,QThread::Priority,Function&&,Args&&...)
    \sa QThread::Priority
 */
template <typename Function, typename... Args,
          typename = std::enable_if_t<
                !std::is_same<std::decay_t<Function>, QThreadPool>::value
                && !std::is_same<std::decay_t<Function>, QThread::Priority>::value
              >,
          typename ResultType = typename Internal::resultType<Function>::type>
QFuture<ResultType>
runAsync(Function &&function, Args&&... args)
{
    return runAsync(static_cast<QThreadPool *>(nullptr),
                    QThread::InheritPriority, std::forward<Function>(function),
                    std::forward<Args>(args)...);
}

/*!
    Runs \a function with \a args in a thread \a pool with thread priority QThread::InheritPriority.
    \sa runAsync(QThreadPool*,QThread::Priority,Function&&,Args&&...)
    \sa QThread::Priority
 */
template <typename Function, typename... Args,
          typename = std::enable_if_t<!std::is_same<std::decay_t<Function>, QThread::Priority>::value>,
          typename ResultType = typename Internal::resultType<Function>::type>
QFuture<ResultType>
runAsync(QThreadPool *pool, Function &&function, Args&&... args)
{
    return runAsync(pool, QThread::InheritPriority, std::forward<Function>(function),
                    std::forward<Args>(args)...);
}


/*!
    Adds a handler for when a result is ready.
    This creates a new QFutureWatcher. Do not use if you intend to react on multiple conditions
    or create a QFutureWatcher already for other reasons.
*/
template <typename R, typename T>
const QFuture<T> &onResultReady(const QFuture<T> &future, R *receiver, void(R::*member)(const T &))
{
    auto watcher = new QFutureWatcher<T>();
    QObject::connect(watcher, &QFutureWatcherBase::finished, watcher, &QObject::deleteLater);
    QObject::connect(watcher, &QFutureWatcherBase::resultReadyAt, receiver,
                     [receiver, member, watcher](int index) {
                         (receiver->*member)(watcher->future().resultAt(index));
                     });
    watcher->setFuture(future);
    return future;
}

/*!
    Adds a handler for when a result is ready. The guard object determines the lifetime of
    the connection.
    This creates a new QFutureWatcher. Do not use if you intend to react on multiple conditions
    or create a QFutureWatcher already for other reasons.
*/
template <typename T, typename Function>
const QFuture<T> &onResultReady(const QFuture<T> &future, QObject *guard, Function f)
{
    auto watcher = new QFutureWatcher<T>();
    QObject::connect(watcher, &QFutureWatcherBase::finished, watcher, &QObject::deleteLater);
    QObject::connect(watcher, &QFutureWatcherBase::resultReadyAt, guard, [f, watcher](int index) {
        f(watcher->future().resultAt(index));
    });
    watcher->setFuture(future);
    return future;
}

/*!
    Adds a handler for when a result is ready.
    This creates a new QFutureWatcher. Do not use if you intend to react on multiple conditions
    or create a QFutureWatcher already for other reasons.
*/
template <typename T, typename Function>
const QFuture<T> &onResultReady(const QFuture<T> &future, Function f)
{
    auto watcher = new QFutureWatcher<T>();
    QObject::connect(watcher, &QFutureWatcherBase::finished, watcher, &QObject::deleteLater);
    QObject::connect(watcher, &QFutureWatcherBase::resultReadyAt, [f, watcher](int index) {
        f(watcher->future().resultAt(index));
    });
    watcher->setFuture(future);
    return future;
}

/*!
    Adds a handler for when the future is finished.
    This creates a new QFutureWatcher. Do not use if you intend to react on multiple conditions
    or create a QFutureWatcher already for other reasons.
*/
template<typename R, typename T>
const QFuture<T> &onFinished(const QFuture<T> &future,
                             R *receiver,
                             void (R::*member)(const QFuture<T> &))
{
    auto watcher = new QFutureWatcher<T>();
    QObject::connect(watcher, &QFutureWatcherBase::finished, watcher, &QObject::deleteLater);
    QObject::connect(watcher,
                     &QFutureWatcherBase::finished,
                     receiver,
                     [receiver, member, watcher]() { (receiver->*member)(watcher->future()); });
    watcher->setFuture(future);
    return future;
}

/*!
    Adds a handler for when the future is finished. The guard object determines the lifetime of
    the connection.
    This creates a new QFutureWatcher. Do not use if you intend to react on multiple conditions
    or create a QFutureWatcher already for other reasons.
*/
template<typename T, typename Function>
const QFuture<T> &onFinished(const QFuture<T> &future, QObject *guard, Function f)
{
    auto watcher = new QFutureWatcher<T>();
    QObject::connect(watcher, &QFutureWatcherBase::finished, watcher, &QObject::deleteLater);
    QObject::connect(watcher, &QFutureWatcherBase::finished, guard, [f, watcher]() {
        f(watcher->future());
    });
    watcher->setFuture(future);
    return future;
}

/*!
    Adds a handler for when the future is finished.
    This creates a new QFutureWatcher. Do not use if you intend to react on multiple conditions
    or create a QFutureWatcher already for other reasons.
*/
template<typename T, typename Function>
const QFuture<T> &onFinished(const QFuture<T> &future, Function f)
{
    auto watcher = new QFutureWatcher<T>();
    QObject::connect(watcher, &QFutureWatcherBase::finished, watcher, &QObject::deleteLater);
    QObject::connect(watcher, &QFutureWatcherBase::finished, [f, watcher]() {
        f(watcher->future());
    });
    watcher->setFuture(future);
    return future;
}

} // namespace Utils