waybar/src/modules/sway/window.cpp

72 lines
2.0 KiB
C++
Raw Normal View History

2018-08-15 20:17:17 +02:00
#include "modules/sway/window.hpp"
2018-08-20 14:50:45 +02:00
waybar::modules::sway::Window::Window(Bar &bar, const Json::Value& config)
2018-09-18 21:16:35 +02:00
: ALabel(config, "{}"), bar_(bar), windowId_(-1)
2018-08-15 20:17:17 +02:00
{
2018-08-16 14:29:41 +02:00
label_.set_name("window");
2018-08-20 14:50:45 +02:00
ipc_.connect();
ipc_.subscribe("[ \"window\" ]");
2018-08-16 14:29:41 +02:00
getFocusedWindow();
2018-08-20 14:50:45 +02:00
// Launch worker
worker();
}
void waybar::modules::sway::Window::worker()
{
2018-08-16 14:29:41 +02:00
thread_ = [this] {
2018-08-15 20:17:17 +02:00
try {
2018-08-20 14:50:45 +02:00
auto res = ipc_.handleEvent();
2018-08-16 14:29:41 +02:00
auto parsed = parser_.parse(res.payload);
if ((parsed["change"] == "focus" || parsed["change"] == "title")
&& parsed["container"]["focused"].asBool()) {
2018-08-16 14:29:41 +02:00
window_ = parsed["container"]["name"].asString();
2018-09-18 21:16:35 +02:00
windowId_ = parsed["container"]["id"].asInt();
dp.emit();
} else if (parsed["change"] == "close"
&& parsed["container"]["focused"].asBool()
&& windowId_ == parsed["container"]["id"].asInt()) {
window_.clear();
windowId_ = -1;
2018-08-20 14:50:45 +02:00
dp.emit();
}
2018-08-15 20:17:17 +02:00
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
}
};
}
auto waybar::modules::sway::Window::update() -> void
{
2018-08-27 01:36:25 +02:00
label_.set_text(fmt::format(format_, window_));
2018-08-16 14:29:41 +02:00
label_.set_tooltip_text(window_);
2018-08-15 20:17:17 +02:00
}
2018-09-18 21:16:35 +02:00
std::tuple<int, std::string> waybar::modules::sway::Window::getFocusedNode(
Json::Value nodes)
2018-08-15 20:17:17 +02:00
{
2018-09-04 23:50:08 +02:00
for (auto const& node : nodes) {
2018-08-19 20:37:33 +02:00
if (node["focused"].asBool() && node["type"] == "con") {
2018-09-18 21:16:35 +02:00
return { node["id"].asInt(), node["name"].asString() };
2018-08-16 14:29:41 +02:00
}
2018-09-18 21:16:35 +02:00
auto [id, name] = getFocusedNode(node["nodes"]);
if (id > -1 && !name.empty()) {
return { id, name };
2018-08-16 14:29:41 +02:00
}
2018-08-15 20:17:17 +02:00
}
2018-09-18 21:16:35 +02:00
return { -1, std::string() };
2018-08-15 20:17:17 +02:00
}
2018-08-16 14:29:41 +02:00
void waybar::modules::sway::Window::getFocusedWindow()
2018-08-15 20:17:17 +02:00
{
try {
2018-08-20 14:50:45 +02:00
auto res = ipc_.sendCmd(IPC_GET_TREE);
2018-08-18 16:01:56 +02:00
auto parsed = parser_.parse(res.payload);
2018-09-18 21:16:35 +02:00
auto [id, name] = getFocusedNode(parsed["nodes"]);
windowId_ = id;
window_ = name;
2018-08-15 20:17:17 +02:00
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Window::update));
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
}
}