Debian Codegraph @

Source/Core/DolphinQt/QtUtils/RunOnObject.h

raw symbols SCIP
1 // Copyright 2017 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #pragma once
5
6 #include <concepts>
7 #include <functional>
8 #include <optional>
9
10 #include <QMetaObject>
11
12 #include "Common/OneShotEvent.h"
13
14 // QWidget and subclasses are not thread-safe! This helper takes arbitrary code from any thread,
15 // safely runs it on the appropriate GUI thread, waits for it to finish, and returns the result.
16 //
17 // If the target object is destructed before the code gets to run the function will return nullopt.
18
19 auto RunOnObject(QObject* object, std::invocable<> auto&& functor)
20 {
21 Common::OneShotEvent task_complete;
22 std::optional<decltype(functor())> result;
23
24 QMetaObject::invokeMethod(
25 object, [&, guard = Common::ScopedSetter{&task_complete}] { result = functor(); });
26
27 // Wait for the lambda to go out of scope. The result may or may not have been assigned.
28 task_complete.Wait();
29 return result;
30 }
31
32 template <std::derived_from<QObject> Receiver>
33 auto RunOnObject(Receiver* obj, auto Receiver::* func)
34 {
35 return RunOnObject(obj, std::bind(func, obj));
36 }