polybar/src/modules/ipc.cpp

230 lines
6.8 KiB
C++
Raw Normal View History

#include "modules/ipc.hpp"
2021-09-21 19:27:42 +00:00
#include <unistd.h>
2016-11-20 22:04:31 +00:00
#include "modules/meta/base.inl"
2016-11-19 05:22:44 +00:00
POLYBAR_NS
namespace modules {
2016-11-20 22:04:31 +00:00
template class module<ipc_module>;
/**
* Load user-defined ipc hooks and
* create formatting tags
*/
ipc_module::ipc_module(const bar_settings& bar, string name_) : module<ipc_module>(bar, move(name_)) {
m_router->register_action_with_data(EVENT_SEND, [this](const std::string& data) { action_send(data); });
m_router->register_action_with_data(EVENT_HOOK, [this](const std::string& data) { action_hook(data); });
m_router->register_action(EVENT_NEXT, [this]() { action_next(); });
m_router->register_action(EVENT_PREV, [this]() { action_prev(); });
m_router->register_action(EVENT_RESET, [this]() { action_reset(); });
size_t index = 0;
for (auto&& command : m_conf.get_list<string>(name(), "hook", {})) {
m_hooks.emplace_back(std::make_unique<hook>(hook{name() + to_string(++index), command}));
}
m_log.info("%s: Loaded %d hooks", name(), m_hooks.size());
// Negative initial values should always be -1
m_initial = std::max(-1, m_conf.get(name(), "initial", 0) - 1);
if (has_initial()) {
if ((size_t)m_initial >= m_hooks.size()) {
throw module_error("Initial hook out of bounds: '" + to_string(m_initial + 1) +
"'. Defined hooks go from 1 to " + to_string(m_hooks.size()) + ")");
}
m_current_hook = m_initial;
} else {
m_current_hook = -1;
}
2017-01-13 23:55:55 +00:00
// clang-format off
2017-01-13 23:27:29 +00:00
m_actions.emplace(make_pair<mousebtn, string>(mousebtn::LEFT, m_conf.get(name(), "click-left", ""s)));
m_actions.emplace(make_pair<mousebtn, string>(mousebtn::MIDDLE, m_conf.get(name(), "click-middle", ""s)));
m_actions.emplace(make_pair<mousebtn, string>(mousebtn::RIGHT, m_conf.get(name(), "click-right", ""s)));
m_actions.emplace(make_pair<mousebtn, string>(mousebtn::SCROLL_UP, m_conf.get(name(), "scroll-up", ""s)));
m_actions.emplace(make_pair<mousebtn, string>(mousebtn::SCROLL_DOWN, m_conf.get(name(), "scroll-down", ""s)));
m_actions.emplace(make_pair<mousebtn, string>(mousebtn::DOUBLE_LEFT, m_conf.get(name(), "double-click-left", ""s)));
m_actions.emplace(make_pair<mousebtn, string>(mousebtn::DOUBLE_MIDDLE, m_conf.get(name(), "double-click-middle", ""s)));
m_actions.emplace(make_pair<mousebtn, string>(mousebtn::DOUBLE_RIGHT, m_conf.get(name(), "double-click-right", ""s)));
2017-01-13 23:55:55 +00:00
// clang-format on
2021-09-21 19:27:42 +00:00
const auto pid_token = [](const string& s) { return string_util::replace_all(s, "%pid%", to_string(getpid())); };
2017-01-13 23:55:55 +00:00
for (auto& action : m_actions) {
action.second = pid_token(action.second);
2017-01-13 23:55:55 +00:00
}
for (auto& hook : m_hooks) {
hook->command = pid_token(hook->command);
2017-01-13 23:55:55 +00:00
}
m_formatter->add(DEFAULT_FORMAT, TAG_OUTPUT, {TAG_OUTPUT});
}
/**
* Start module and run first defined hook if configured to
*/
void ipc_module::start() {
this->module::start();
m_mainthread = thread([&] {
m_log.trace("%s: Thread id = %i", this->name(), concurrency_util::thread_id(this_thread::get_id()));
update();
broadcast();
});
}
void ipc_module::update() {
if (has_hook()) {
exec_hook();
}
}
/**
* Wrap the output with defined mouse actions
*/
string ipc_module::get_output() {
2016-12-05 04:32:10 +00:00
// Get the module output early so that
// the format prefix/suffix also gets wrapper
// with the cmd handlers
string output{module::get_output()};
if (output.empty()) {
return "";
}
2016-12-05 04:32:10 +00:00
2017-01-13 23:10:55 +00:00
for (auto&& action : m_actions) {
if (!action.second.empty()) {
m_builder->action(action.first, action.second);
2017-01-13 23:10:55 +00:00
}
2016-11-25 12:55:15 +00:00
}
m_builder->node(output);
return m_builder->flush();
}
/**
* Output content retrieved from hook commands
*/
2016-11-25 12:55:15 +00:00
bool ipc_module::build(builder* builder, const string& tag) const {
if (tag == TAG_OUTPUT) {
builder->node(m_output);
return true;
2016-11-25 12:55:15 +00:00
} else {
return false;
2016-11-25 12:55:15 +00:00
}
}
/**
* Map received message hook to the ones
* configured from the user config and
* execute its command
*
* This code path is deprecated, all messages to ipc modules should go through actions.
*/
2016-12-26 09:36:14 +00:00
void ipc_module::on_message(const string& message) {
for (size_t i = 0; i < m_hooks.size(); i++) {
const auto& hook = m_hooks[i];
if (hook->payload == message) {
m_log.info("%s: Found matching hook (%s)", name(), hook->payload);
set_hook(i);
break;
}
}
}
void ipc_module::action_send(const string& data) {
m_output = data;
broadcast();
}
void ipc_module::action_hook(const string& data) {
try {
int hook = std::stoi(data);
if (hook < 0 || (size_t)hook >= m_hooks.size()) {
m_log.err("%s: Hook action received with an out of bounds hook '%s'. Defined hooks go from 0 to %zu.", name(),
data, m_hooks.size() - 1);
} else {
set_hook(hook);
}
} catch (const std::invalid_argument& err) {
m_log.err(
"%s: Hook action received '%s' cannot be converted to a valid hook index. Defined hooks goes from 0 to %zu.",
name(), data, m_hooks.size() - 1);
}
}
void ipc_module::action_next() {
hook_offset(1);
}
void ipc_module::action_prev() {
hook_offset(-1);
}
void ipc_module::action_reset() {
if (has_initial()) {
set_hook(m_initial);
} else {
m_current_hook = -1;
m_output.clear();
broadcast();
}
}
/**
* Changes the current hook by the given offset.
*
* Also deals with the case where the there is no active hook, in which case a positive offset starts from -1 and a
* negative from 0. This ensures that 'next' executes the first and 'prev' the last hook if no hook is set.
*/
void ipc_module::hook_offset(int offset) {
int start_hook;
if (has_hook()) {
start_hook = m_current_hook;
} else {
if (offset > 0) {
start_hook = -1;
} else {
start_hook = 0;
}
}
set_hook((start_hook + offset + m_hooks.size()) % m_hooks.size());
}
bool ipc_module::has_initial() const {
return m_initial >= 0;
}
bool ipc_module::has_hook() const {
return m_current_hook >= 0;
}
void ipc_module::set_hook(int h) {
Use sockets for IPC (#2539) Deprecates not using `polybar-msg` for IPC. Fixes #2532 Closes #2465 Fixes #2504 * Create FIFO specific NamedPipeHandle subclass to PipeHandle * Prototype SocketHandle * Move mainloop up to main.cpp * Pass eventloop to ipc class * Deprecate sending ipc over the named pipe Unfortunately, we can only show the warning in the polybar log and not give the user any feedback because the pipe is one-way * Move eventloop into its own namespace * Prototype ipc socket handling * Remove handles from ipc_client Should be independent from eventloop logic * Remove ipc clients when finished * Add tests for ipc_client decoding * Add callback for complete ipc messages * Remove template param from mixins * Move signal handler to new callback system * Move poll handle to new callback system * Move FSEventHandle to new callback system * Move TimerHandle and AsyncHandle to new callback system * Move PipeHandle to new callback system * Implement socket functionality in new callback system * Correctly reset ipc named pipe handle * Let client close handles in error callback * Wrap client pipe and ipc::client in connection class * Better decoder log messages * Socket path logic * Fix CI warnings * Remove UVHandleGeneric * Fix error when socket folder already exists * Proof of concept message writeback * Restructure ipc files * polybar-msg: Use sockets * polybar-msg: Better syntax for actions * Fix memory leak with fifo After EOF, the pipe wasn't closed and EOF was called all the time, each time allocating a new pipe. * Make polybar-msg compile on its own * Rudimentary writeback for polybar-msg * Fix payload reference going out of scope. * Add IPC documentation * Cleanup polybar-msg code * Specify the v0 ipc message format * Close ipc connection after message * Fix ipc tests * Properly close ipc connections * Fix polybar-msg not working with action string * Write polybar-msg manpage * polybar-msg: Stop using exit() * ipc: Print log message with PID * Add tests for ipc util * polybar-msg: Print PID with success message * ipc: Propagate message errors * Rename ipc::client to ipc::decoder * Rename ipc.cpp to polybar-msg.cpp * ipc: Write encoder function and fix decoder bugs * ipc: Use message format for responses * ipc: Handle wrong message types * ipc: Write back error message if ipc message cannot be processed This only happens for commands and empty actions. Non-empty actions are not immediately executed, but deferred until the next loop iteration. * Remove TODO about deleting runtime directory The socket file is not deleted after socket.close() is called, only after libuv executes the close callback. So we can't just call rmdir because it will probably always fail. * CLeanup WriteRequest * Update manpage authors * Cleanup
2022-01-22 19:35:37 +00:00
assert(h >= 0 && (size_t)h < m_hooks.size());
m_current_hook = h;
exec_hook();
}
void ipc_module::exec_hook() {
// Clear the output in case the command produces no output
m_output.clear();
try {
2022-03-06 16:44:48 +00:00
command<output_policy::REDIRECTED> cmd(m_log, m_hooks[m_current_hook]->command);
cmd.exec(false);
cmd.tail([this](string line) { m_output = line; });
} catch (const exception& err) {
m_log.err("%s: Failed to execute hook command (err: %s)", name(), err.what());
m_output.clear();
}
broadcast();
}
2022-03-06 16:44:48 +00:00
} // namespace modules
2016-11-19 05:22:44 +00:00
POLYBAR_NS_END