polybar/src/components/ipc.cpp

88 lines
2.1 KiB
C++
Raw Normal View History

2021-01-16 11:53:26 +00:00
#include "components/ipc.hpp"
2016-11-13 18:05:30 +00:00
#include <fcntl.h>
#include <sys/stat.h>
2021-09-21 19:27:42 +00:00
#include <unistd.h>
2016-11-13 18:05:30 +00:00
2017-01-11 02:07:28 +00:00
#include "components/logger.hpp"
2021-01-16 11:53:26 +00:00
#include "errors.hpp"
#include "events/signal.hpp"
#include "events/signal_emitter.hpp"
2016-11-13 18:05:30 +00:00
#include "utils/file.hpp"
#include "utils/string.hpp"
2016-11-19 05:22:44 +00:00
POLYBAR_NS
2016-11-13 18:05:30 +00:00
/**
* Message types
*/
static constexpr const char* ipc_command_prefix{"cmd:"};
static constexpr const char* ipc_hook_prefix{"hook:"};
static constexpr const char* ipc_action_prefix{"action:"};
2016-12-09 08:02:47 +00:00
/**
* Create instance
*/
2016-12-09 08:40:46 +00:00
ipc::make_type ipc::make() {
return std::make_unique<ipc>(signal_emitter::make(), logger::make());
2016-12-09 08:02:47 +00:00
}
2016-11-13 18:05:30 +00:00
/**
* Construct ipc handler
2016-11-13 18:05:30 +00:00
*/
ipc::ipc(signal_emitter& emitter, const logger& logger) : m_sig(emitter), m_log(logger) {
m_path = string_util::replace(PATH_MESSAGING_FIFO, "%pid%", to_string(getpid()));
2016-11-13 18:05:30 +00:00
2017-01-24 01:14:19 +00:00
if (file_util::exists(m_path) && unlink(m_path.c_str()) == -1) {
throw system_error("Failed to remove ipc channel");
}
if (mkfifo(m_path.c_str(), 0666) == -1) {
throw system_error("Failed to create ipc channel");
}
m_log.info("Created ipc channel at: %s", m_path);
}
2016-11-13 18:05:30 +00:00
/**
* Deconstruct ipc handler
*/
ipc::~ipc() {
2021-09-13 17:56:24 +00:00
m_log.trace("ipc: Removing file handle at: %s", m_path);
unlink(m_path.c_str());
}
string ipc::get_path() const {
return m_path;
2016-11-13 18:05:30 +00:00
}
/**
* Receive parts of an IPC message
*/
void ipc::receive_data(string buf) {
m_buffer += buf;
}
/**
* Called once the end of the message arrives.
2016-11-13 18:05:30 +00:00
*/
void ipc::receive_eof() {
if (m_buffer.empty()) {
return;
}
string payload{string_util::trim(std::move(m_buffer), '\n')};
2016-11-13 18:05:30 +00:00
m_buffer = std::string();
2016-11-13 18:05:30 +00:00
2021-02-20 20:26:45 +00:00
if (payload.find(ipc_command_prefix) == 0) {
m_sig.emit(signals::ipc::command{payload.substr(strlen(ipc_command_prefix))});
} else if (payload.find(ipc_hook_prefix) == 0) {
m_sig.emit(signals::ipc::hook{payload.substr(strlen(ipc_hook_prefix))});
} else if (payload.find(ipc_action_prefix) == 0) {
m_sig.emit(signals::ipc::action{payload.substr(strlen(ipc_action_prefix))});
} else {
2021-02-20 20:26:45 +00:00
m_log.warn("Received unknown ipc message: (payload=%s)", payload);
2016-11-13 18:05:30 +00:00
}
}
2016-11-19 05:22:44 +00:00
POLYBAR_NS_END