Files

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

37 lines
1.1 KiB
C++
Raw Permalink Normal View History

2017-07-25 20:46:35 -07:00
// Copyright 2017 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
2017-07-25 20:46:35 -07:00
#pragma once
#include <concepts>
#include <functional>
#include <optional>
2017-07-25 20:46:35 -07:00
#include <QMetaObject>
2017-07-25 20:46:35 -07:00
#include "Common/OneShotEvent.h"
2017-07-25 20:46:35 -07:00
// QWidget and subclasses are not thread-safe! This helper takes arbitrary code from any thread,
// safely runs it on the appropriate GUI thread, waits for it to finish, and returns the result.
//
// If the target object is destructed before the code gets to run the function will return nullopt.
2017-07-25 20:46:35 -07:00
auto RunOnObject(QObject* object, std::invocable<> auto&& functor)
2017-07-25 20:46:35 -07:00
{
Common::OneShotEvent task_complete;
std::optional<decltype(functor())> result;
QMetaObject::invokeMethod(
object, [&, guard = Common::ScopedSetter{&task_complete}] { result = functor(); });
2017-07-25 20:46:35 -07:00
// Wait for the lambda to go out of scope. The result may or may not have been assigned.
task_complete.Wait();
2017-07-25 20:46:35 -07:00
return result;
}
template <std::derived_from<QObject> Receiver>
auto RunOnObject(Receiver* obj, auto Receiver::* func)
{
return RunOnObject(obj, std::bind(func, obj));
}