2020-12-29 01:26:55 +00:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <glibmm/dispatcher.h>
|
|
|
|
#include <sigc++/signal.h>
|
|
|
|
|
|
|
|
#include <functional>
|
|
|
|
#include <mutex>
|
|
|
|
#include <queue>
|
|
|
|
#include <tuple>
|
|
|
|
#include <type_traits>
|
2020-10-20 01:42:25 +00:00
|
|
|
#include <utility>
|
2020-12-29 01:26:55 +00:00
|
|
|
|
|
|
|
namespace waybar {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Thread-safe signal wrapper.
|
|
|
|
* Uses Glib::Dispatcher to pass events to another thread and locked queue to pass the arguments.
|
|
|
|
*/
|
|
|
|
template <typename... Args>
|
|
|
|
struct SafeSignal : sigc::signal<void(std::decay_t<Args>...)> {
|
|
|
|
public:
|
|
|
|
SafeSignal() { dp_.connect(sigc::mem_fun(*this, &SafeSignal::handle_event)); }
|
|
|
|
|
|
|
|
template <typename... EmitArgs>
|
|
|
|
void emit(EmitArgs&&... args) {
|
|
|
|
{
|
|
|
|
std::unique_lock lock(mutex_);
|
|
|
|
queue_.emplace(std::forward<EmitArgs>(args)...);
|
|
|
|
}
|
|
|
|
dp_.emit();
|
|
|
|
}
|
|
|
|
|
|
|
|
template <typename... EmitArgs>
|
|
|
|
inline void operator()(EmitArgs&&... args) {
|
|
|
|
emit(std::forward<EmitArgs>(args)...);
|
|
|
|
}
|
|
|
|
|
|
|
|
protected:
|
|
|
|
using signal_t = sigc::signal<void(std::decay_t<Args>...)>;
|
2020-10-20 01:42:25 +00:00
|
|
|
using slot_t = decltype(std::declval<signal_t>().make_slot());
|
2020-12-29 01:26:55 +00:00
|
|
|
using arg_tuple_t = std::tuple<std::decay_t<Args>...>;
|
|
|
|
// ensure that unwrapped methods are not accessible
|
|
|
|
using signal_t::emit_reverse;
|
|
|
|
using signal_t::make_slot;
|
|
|
|
|
|
|
|
void handle_event() {
|
|
|
|
for (std::unique_lock lock(mutex_); !queue_.empty(); lock.lock()) {
|
|
|
|
auto args = queue_.front();
|
|
|
|
queue_.pop();
|
|
|
|
lock.unlock();
|
2020-10-20 01:42:25 +00:00
|
|
|
std::apply(cached_fn_, args);
|
2020-12-29 01:26:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Glib::Dispatcher dp_;
|
|
|
|
std::mutex mutex_;
|
|
|
|
std::queue<arg_tuple_t> queue_;
|
2020-10-20 01:42:25 +00:00
|
|
|
// cache functor for signal emission to avoid recreating it on each event
|
|
|
|
const slot_t cached_fn_ = make_slot();
|
2020-12-29 01:26:55 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
} // namespace waybar
|