File indexing completed on 2022-11-29 13:02:28

0001 /*
0002     SPDX-FileCopyrightText: 2014-2016 Ivan Cukic <ivan.cukic(at)kde.org>
0003 
0004     SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
0005 */
0006 
0007 #include "mainthreadexecutor_p.h"
0008 
0009 #include <mutex>
0010 
0011 #include <QCoreApplication>
0012 #include <QMetaObject>
0013 #include <QThread>
0014 
0015 namespace KActivities
0016 {
0017 namespace detail
0018 {
0019 MainThreadExecutor::MainThreadExecutor(std::function<void()> &&f)
0020     : m_function(std::forward<std::function<void()>>(f))
0021 {
0022 }
0023 
0024 void MainThreadExecutor::start()
0025 {
0026     m_function();
0027     deleteLater();
0028 }
0029 
0030 } // namespace detail
0031 
0032 void runInMainThread(std::function<void()> &&f)
0033 {
0034     static auto mainThread = QCoreApplication::instance()->thread();
0035 
0036     if (QThread::currentThread() == mainThread) {
0037         f();
0038 
0039     } else {
0040         auto executor = new detail::MainThreadExecutor(std::forward<std::function<void()>>(f));
0041 
0042         executor->moveToThread(mainThread);
0043 
0044         QMetaObject::invokeMethod(executor, "start", Qt::BlockingQueuedConnection);
0045     }
0046 }
0047 
0048 } // namespace KActivities