2021-01-04 04:25:52 -05:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <cassert>
|
|
|
|
#include <stdexcept>
|
|
|
|
#include <unordered_map>
|
|
|
|
|
|
|
|
#include "common.hpp"
|
|
|
|
|
|
|
|
POLYBAR_NS
|
|
|
|
|
|
|
|
/**
|
2021-10-02 20:57:49 -04:00
|
|
|
* Maps action names to lambdas and invokes them.
|
2021-01-04 04:25:52 -05:00
|
|
|
*
|
|
|
|
* Each module has one instance of this class and uses it to register action.
|
|
|
|
* For each action the module has to register the name, whether it can take
|
2021-10-02 20:57:49 -04:00
|
|
|
* additional data, and a callback that is called whenever the action is triggered.
|
2021-01-04 04:25:52 -05:00
|
|
|
*
|
|
|
|
* The input() function in the base class uses this for invoking the actions
|
|
|
|
* of that module.
|
|
|
|
*
|
|
|
|
* Any module that does not reimplement that function will automatically use
|
|
|
|
* this class for action routing.
|
|
|
|
*/
|
|
|
|
class action_router {
|
2021-10-02 20:57:49 -04:00
|
|
|
using callback = std::function<void(void)>;
|
|
|
|
using callback_data = std::function<void(const std::string&)>;
|
2021-01-04 04:25:52 -05:00
|
|
|
|
|
|
|
public:
|
2021-10-02 20:57:49 -04:00
|
|
|
void register_action(const string& name, callback func);
|
|
|
|
void register_action_with_data(const string& name, callback_data func);
|
|
|
|
bool has_action(const string& name);
|
|
|
|
void invoke(const string& name, const string& data);
|
2021-01-04 04:25:52 -05:00
|
|
|
|
|
|
|
protected:
|
|
|
|
struct entry {
|
|
|
|
union {
|
|
|
|
callback without;
|
|
|
|
callback_data with;
|
|
|
|
};
|
|
|
|
bool with_data;
|
2021-10-02 20:57:49 -04:00
|
|
|
|
|
|
|
entry(callback func);
|
|
|
|
entry(callback_data func);
|
|
|
|
~entry();
|
2021-01-04 04:25:52 -05:00
|
|
|
};
|
|
|
|
|
2021-10-02 20:57:49 -04:00
|
|
|
template <typename F>
|
|
|
|
void register_entry(const string& name, const F& e) {
|
2021-01-04 04:25:52 -05:00
|
|
|
if (has_action(name)) {
|
|
|
|
throw std::invalid_argument("Tried to register action '" + name + "' twice. THIS IS A BUG!");
|
|
|
|
}
|
2021-10-02 20:57:49 -04:00
|
|
|
|
|
|
|
callbacks.emplace(name, std::move(e));
|
2021-01-04 04:25:52 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
std::unordered_map<string, entry> callbacks;
|
|
|
|
};
|
|
|
|
|
|
|
|
POLYBAR_NS_END
|