Compare commits

..

13 Commits
0.0.4 ... 0.0.5

Author SHA1 Message Date
969c1ceedd chore: v0.0.5 2018-08-19 13:43:41 +02:00
52a4e761a8 fix(workspaces): avoid useless mutex lock 2018-08-19 13:43:00 +02:00
16b856c8bc fix: remove debug flag 2018-08-19 13:41:22 +02:00
6705134034 Handle screens disconnection (#29) 2018-08-19 13:39:57 +02:00
ce50a627be refactor: move command execution into their own file 2018-08-18 17:54:20 +02:00
b794ca63d1 feat(custom): exec-if 2018-08-18 17:27:40 +02:00
38ede5b3d5 refactor(ipc): clean 2018-08-18 16:01:56 +02:00
27dfffa4e3 refactor: style issue 2018-08-18 15:05:18 +02:00
b1fd4d7b82 feat(modules): generic label module to allow max-length on all labels 2018-08-18 11:43:48 +02:00
c128562284 feat(bar): clean exit 2018-08-17 20:28:26 +02:00
d280f5e8bd Network detect (#26) 2018-08-17 14:24:00 +02:00
0603b99714 fix(bar): proper center modules 2018-08-16 18:11:16 +02:00
0371271465 fix(custom): hide first 2018-08-16 17:59:45 +02:00
34 changed files with 704 additions and 382 deletions

19
include/ALabel.hpp Normal file
View File

@ -0,0 +1,19 @@
#pragma once
#include <json/json.h>
#include "IModule.hpp"
namespace waybar {
class ALabel : public IModule {
public:
ALabel(Json::Value);
virtual ~ALabel() = default;
virtual auto update() -> void;
virtual operator Gtk::Widget &();
protected:
Gtk::Label label_;
Json::Value config_;
};
}

View File

@ -4,17 +4,18 @@
#include <gtkmm.h>
#include "wlr-layer-shell-unstable-v1-client-protocol.h"
#include "xdg-output-unstable-v1-client-protocol.h"
#include "IModule.hpp"
namespace waybar {
class Client;
class Factory;
class Bar {
public:
Bar(Client&, std::unique_ptr<struct wl_output *>&&);
Bar(Client&, std::unique_ptr<struct wl_output *>&&, uint32_t wl_name);
Bar(const Bar&) = delete;
auto setWidth(uint32_t) -> void;
auto toggle() -> void;
Client& client;
@ -22,7 +23,8 @@ class Bar {
struct wl_surface *surface;
struct zwlr_layer_surface_v1 *layer_surface;
std::unique_ptr<struct wl_output *> output;
std::string outputName;
std::string output_name;
uint32_t wl_name;
bool visible = true;
private:
static void handleLogicalPosition(void *, struct zxdg_output_v1 *, int32_t,
@ -41,6 +43,7 @@ class Bar {
auto setupConfig() -> void;
auto setupWidgets() -> void;
auto setupCss() -> void;
void getModules(Factory factory, const std::string& pos);
uint32_t width_ = 0;
uint32_t height_ = 30;
@ -48,6 +51,9 @@ class Bar {
Glib::RefPtr<Gtk::StyleContext> style_context_;
Glib::RefPtr<Gtk::CssProvider> css_provider_;
struct zxdg_output_v1 *xdg_output_;
std::vector<std::unique_ptr<waybar::IModule>> modules_left_;
std::vector<std::unique_ptr<waybar::IModule>> modules_center_;
std::vector<std::unique_ptr<waybar::IModule>> modules_right_;
};
}

View File

@ -19,7 +19,7 @@ class Client {
Client(int argc, char *argv[]);
int main(int argc, char *argv[]);
Gtk::Main gtk_main;
Glib::RefPtr<Gtk::Application> gtk_app;
std::string css_file;
std::string config_file;
Glib::RefPtr<Gdk::Display> gdk_display;

View File

@ -1,6 +1,5 @@
#pragma once
#include <json/json.h>
#include <filesystem>
#include <fstream>
#include <iostream>
@ -8,26 +7,25 @@
#include <sys/inotify.h>
#include <algorithm>
#include "util/chrono.hpp"
#include "IModule.hpp"
#include "ALabel.hpp"
namespace waybar::modules {
namespace fs = std::filesystem;
class Battery : public IModule {
class Battery : public ALabel {
public:
Battery(Json::Value);
~Battery();
auto update() -> void;
operator Gtk::Widget&();
private:
std::string getIcon(uint16_t percentage);
static inline const fs::path data_dir_ = "/sys/class/power_supply/";
Gtk::Label label_;
Json::Value config_;
util::SleeperThread thread_;
std::vector<fs::path> batteries_;
int fd_;
};
}

View File

@ -1,22 +1,18 @@
#pragma once
#include <json/json.h>
#include <fmt/format.h>
#include "fmt/time.h"
#include "util/chrono.hpp"
#include "IModule.hpp"
#include "ALabel.hpp"
namespace waybar::modules {
class Clock : public IModule {
class Clock : public ALabel {
public:
Clock(Json::Value);
auto update() -> void;
operator Gtk::Widget &();
private:
Gtk::Label label_;
waybar::util::SleeperThread thread_;
Json::Value config_;
};
}

View File

@ -1,22 +1,18 @@
#pragma once
#include <json/json.h>
#include <fmt/format.h>
#include <sys/sysinfo.h>
#include "util/chrono.hpp"
#include "IModule.hpp"
#include "ALabel.hpp"
namespace waybar::modules {
class Cpu : public IModule {
class Cpu : public ALabel {
public:
Cpu(Json::Value);
auto update() -> void;
operator Gtk::Widget &();
private:
Gtk::Label label_;
waybar::util::SleeperThread thread_;
Json::Value config_;
};
}

View File

@ -1,22 +1,20 @@
#pragma once
#include <json/json.h>
#include <fmt/format.h>
#include <iostream>
#include "util/chrono.hpp"
#include "IModule.hpp"
#include "util/command.hpp"
#include "ALabel.hpp"
namespace waybar::modules {
class Custom : public IModule {
class Custom : public ALabel {
public:
Custom(const std::string&, Json::Value);
Custom(std::string, Json::Value);
auto update() -> void;
operator Gtk::Widget &();
private:
const std::string name_;
Gtk::Label label_;
std::string name_;
waybar::util::SleeperThread thread_;
Json::Value config_;
};
}

View File

@ -1,22 +1,18 @@
#pragma once
#include <json/json.h>
#include <fmt/format.h>
#include <sys/sysinfo.h>
#include "util/chrono.hpp"
#include "IModule.hpp"
#include "ALabel.hpp"
namespace waybar::modules {
class Memory : public IModule {
class Memory : public ALabel {
public:
Memory(Json::Value);
auto update() -> void;
operator Gtk::Widget &();
private:
Gtk::Label label_;
waybar::util::SleeperThread thread_;
Json::Value config_;
};
}

View File

@ -5,31 +5,37 @@
#include <netlink/genl/genl.h>
#include <netlink/genl/ctrl.h>
#include <linux/nl80211.h>
#include <json/json.h>
#include <fmt/format.h>
#include "util/chrono.hpp"
#include "IModule.hpp"
#include "ALabel.hpp"
namespace waybar::modules {
class Network : public IModule {
class Network : public ALabel {
public:
Network(Json::Value);
~Network();
auto update() -> void;
operator Gtk::Widget &();
private:
static uint64_t netlinkRequest(int, void*, uint32_t, uint32_t groups = 0);
static uint64_t netlinkResponse(int, void*, uint32_t, uint32_t groups = 0);
static int scanCb(struct nl_msg*, void*);
void disconnected();
int getExternalInterface();
void parseEssid(struct nlattr**);
void parseSignal(struct nlattr**);
bool associatedOrJoined(struct nlattr**);
auto getInfo() -> void;
Gtk::Label label_;
waybar::util::SleeperThread thread_;
Json::Value config_;
std::size_t ifid_;
int ifid_;
sa_family_t family_;
int sock_fd_;
struct sockaddr_nl nladdr_ = {0};
std::string essid_;
std::string ifname_;
int signal_strength_dbm_;
uint16_t signal_strength_;
};

View File

@ -1,18 +1,17 @@
#pragma once
#include <pulse/pulseaudio.h>
#include <json/json.h>
#include <fmt/format.h>
#include <algorithm>
#include "IModule.hpp"
#include "ALabel.hpp"
namespace waybar::modules {
class Pulseaudio : public IModule {
class Pulseaudio : public ALabel {
public:
Pulseaudio(Json::Value);
~Pulseaudio();
auto update() -> void;
operator Gtk::Widget &();
private:
static void subscribeCb(pa_context*, pa_subscription_event_type_t,
uint32_t, void*);
@ -22,8 +21,6 @@ class Pulseaudio : public IModule {
std::string getIcon(uint16_t);
Gtk::Label label_;
Json::Value config_;
pa_threaded_mainloop* mainloop_;
pa_mainloop_api* mainloop_api_;
pa_context* context_;

View File

@ -25,7 +25,8 @@ int ipcOpenSocket(const std::string &socketPath);
* Issues a single IPC command and returns the buffer. len will be updated with
* the length of the buffer returned from sway.
*/
std::string ipcSingleCommand(int socketfd, uint32_t type, const char *payload, uint32_t *len);
struct ipc_response ipcSingleCommand(int socketfd, uint32_t type,
const std::string& payload);
/**
* Receives a single IPC response and returns an ipc_response.
*/

View File

@ -5,23 +5,21 @@
#include "client.hpp"
#include "util/chrono.hpp"
#include "util/json.hpp"
#include "IModule.hpp"
#include "ALabel.hpp"
namespace waybar::modules::sway {
class Window : public IModule {
class Window : public ALabel {
public:
Window(waybar::Bar&, Json::Value);
~Window();
auto update() -> void;
operator Gtk::Widget &();
private:
std::string getFocusedNode(Json::Value nodes);
void getFocusedWindow();
Bar& bar_;
Json::Value config_;
waybar::util::SleeperThread thread_;
Gtk::Label label_;
util::JsonParser parser_;
int ipcfd_;
int ipc_eventfd_;

View File

@ -12,6 +12,7 @@ namespace waybar::modules::sway {
class Workspaces : public IModule {
public:
Workspaces(waybar::Bar&, Json::Value);
~Workspaces();
auto update() -> void;
operator Gtk::Widget &();
private:

View File

@ -5,6 +5,7 @@
#include <functional>
#include <condition_variable>
#include <thread>
#include <gtkmm.h>
namespace waybar::chrono {
@ -14,18 +15,6 @@ namespace waybar::chrono {
using duration = clock::duration;
using time_point = std::chrono::time_point<clock, duration>;
inline struct timespec to_timespec(time_point t) noexcept
{
long secs = duration_cast<seconds>(t.time_since_epoch()).count();
long nsc = duration_cast<nanoseconds>(t.time_since_epoch() % seconds(1)).count();
return {secs, nsc};
}
inline time_point to_time_point(struct timespec t) noexcept
{
return time_point(duration_cast<duration>(seconds(t.tv_sec) + nanoseconds(t.tv_nsec)));
}
}
namespace waybar::util {
@ -34,59 +23,71 @@ namespace waybar::util {
SleeperThread() = default;
SleeperThread(std::function<void()> func)
: thread{[this, func] {
do {
func();
} while (do_run);
}}
: thread_{[this, func] {
while(true) {
{
defined = true;
std::lock_guard<std::mutex> lock(mutex_);
if (!do_run_) {
break;
}
}
func();
}
}}
{}
SleeperThread& operator=(std::function<void()> func)
{
thread = std::thread([this, func] {
do {
thread_ = std::thread([this, func] {
while(true) {
{
std::lock_guard<std::mutex> lock(mutex_);
if (!do_run_) {
break;
}
}
func();
} while (do_run);
}
});
defined = true;
return *this;
}
auto sleep_for(chrono::duration dur)
{
auto lock = std::unique_lock(mutex);
return condvar.wait_for(lock, dur);
auto lock = std::unique_lock(mutex_);
return condvar_.wait_for(lock, dur);
}
auto sleep_until(chrono::time_point time)
{
auto lock = std::unique_lock(mutex);
return condvar.wait_until(lock, time);
auto lock = std::unique_lock(mutex_);
return condvar_.wait_until(lock, time);
}
auto wake_up()
{
condvar.notify_all();
condvar_.notify_all();
}
~SleeperThread()
{
do_run = false;
if (defined) {
condvar.notify_all();
thread.join();
do_run_ = false;
condvar_.notify_all();
auto native_handle = thread_.native_handle();
pthread_cancel(native_handle);
if (thread_.joinable()) {
thread_.join();
}
}
sigc::signal<void> sig_update;
private:
std::thread thread;
std::condition_variable condvar;
std::mutex mutex;
bool defined = false;
bool do_run = true;
std::thread thread_;
std::condition_variable condvar_;
std::mutex mutex_;
bool do_run_ = true;
};
}

35
include/util/command.hpp Normal file
View File

@ -0,0 +1,35 @@
#pragma once
#include <sys/wait.h>
namespace waybar::util::command {
struct cmd_res {
int exit_code;
std::string out;
};
inline struct cmd_res exec(const std::string cmd)
{
FILE* fp(popen(cmd.c_str(), "r"));
if (!fp) {
return { -1, "" };
}
std::array<char, 128> buffer = {0};
std::string output;
while (feof(fp) == 0) {
if (fgets(buffer.data(), 128, fp) != nullptr) {
output += buffer.data();
}
}
// Remove last newline
if (!output.empty() && output[output.length()-1] == '\n') {
output.erase(output.length()-1);
}
int exit_code = WEXITSTATUS(pclose(fp));
return { exit_code, output };
}
}

View File

@ -14,6 +14,9 @@ namespace waybar::util {
{
Json::Value root;
std::string err;
if (_reader == nullptr) {
throw std::runtime_error("Unable to parse");
}
bool res =
_reader->parse(data.c_str(), data.c_str() + data.size(), &root, &err);
if (!res)
@ -24,6 +27,7 @@ namespace waybar::util {
~JsonParser()
{
delete _reader;
_reader = nullptr;
}
private:

View File

@ -1,6 +1,6 @@
project(
'waybar', 'cpp', 'c',
version: '0.0.4',
version: '0.0.5',
license: 'MIT',
default_options : ['cpp_std=c++17'],
)

View File

@ -19,6 +19,9 @@
// "5": ""
// }
},
"sway/window": {
"max-length": 50
},
"cpu": {
"format": "{}% "
},
@ -30,8 +33,10 @@
"format-icons": ["", "", "", "", ""]
},
"network": {
"interface": "wlp2s0",
"format": "{essid} ({signalStrength}%) "
// "interface": "wlp2s0", // (Optional) To force the use of this interface
"format-wifi": "{essid} ({signalStrength}%) ",
"format-ethernet": "{ifname} ",
"format-disconnected": "Disconnected ⚠"
},
"pulseaudio": {
"format": "{volume}% {icon}",
@ -41,6 +46,7 @@
"custom/spotify": {
"format": " {}",
"max-length": 40,
"exec": "$HOME/.bin/mediaplayer.sh"
"exec": "$HOME/.bin/mediaplayer.sh",
"exec-if": "pgrep spotify"
}
}

View File

@ -76,6 +76,10 @@ window {
background: #2980b9;
}
#network.disconnected {
background: #f53c3c;
}
#pulseaudio {
background: #f1c40f;
color: black;

19
src/ALabel.cpp Normal file
View File

@ -0,0 +1,19 @@
#include "ALabel.hpp"
waybar::ALabel::ALabel(Json::Value config)
: config_(std::move(config))
{
if (config_["max-length"]) {
label_.set_max_width_chars(config_["max-length"].asUInt());
label_.set_ellipsize(Pango::EllipsizeMode::ELLIPSIZE_END);
}
}
auto waybar::ALabel::update() -> void
{
// Nothing here
}
waybar::ALabel::operator Gtk::Widget &() {
return label_;
}

View File

@ -3,9 +3,10 @@
#include "factory.hpp"
#include "util/json.hpp"
waybar::Bar::Bar(Client &client, std::unique_ptr<struct wl_output *> &&p_output)
waybar::Bar::Bar(Client &client,
std::unique_ptr<struct wl_output *> &&p_output, uint32_t p_wl_name)
: client(client), window{Gtk::WindowType::WINDOW_TOPLEVEL},
output(std::move(p_output))
output(std::move(p_output)), wl_name(std::move(p_wl_name))
{
static const struct zxdg_output_v1_listener xdgOutputListener = {
.logical_position = handleLogicalPosition,
@ -22,29 +23,39 @@ waybar::Bar::Bar(Client &client, std::unique_ptr<struct wl_output *> &&p_output)
setupConfig();
setupCss();
setupWidgets();
if (config_["height"]) {
height_ = config_["height"].asUInt();
}
Gtk::Widget& wrap(window);
gtk_widget_realize(wrap.gobj());
GdkWindow *gdk_window = gtk_widget_get_window(wrap.gobj());
gdk_wayland_window_set_use_custom_surface(gdk_window);
surface = gdk_wayland_window_get_wl_surface(gdk_window);
std::size_t layer_top = config_["layer"] == "top"
? ZWLR_LAYER_SHELL_V1_LAYER_TOP : ZWLR_LAYER_SHELL_V1_LAYER_BOTTOM;
layer_surface = zwlr_layer_shell_v1_get_layer_surface(
client.layer_shell, surface, *output, layer_top, "waybar");
std::size_t position_bottom = config_["position"] == "bottom"
? ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM : ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP;
zwlr_layer_surface_v1_set_anchor(layer_surface, position_bottom
| ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT | ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT);
zwlr_layer_surface_v1_set_size(layer_surface, width_, height_);
static const struct zwlr_layer_surface_v1_listener layer_surface_listener = {
.configure = layerSurfaceHandleConfigure,
.closed = layerSurfaceHandleClosed,
};
zwlr_layer_surface_v1_add_listener(layer_surface,
&layer_surface_listener, this);
std::size_t anchor = ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT
| ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT;
if (config_["position"] == "bottom") {
anchor |= ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM;
} else {
anchor |= ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP;
}
auto height = config_["height"] ? config_["height"].asUInt() : height_;
auto width = config_["width"] ? config_["width"].asUInt() : width_;
zwlr_layer_surface_v1_set_anchor(layer_surface, anchor);
zwlr_layer_surface_v1_set_exclusive_zone(layer_surface, height);
zwlr_layer_surface_v1_set_size(layer_surface, width, height);
wl_surface_commit(surface);
}
@ -71,7 +82,7 @@ void waybar::Bar::handleName(void* data, struct zxdg_output_v1* /*xdg_output*/,
const char* name)
{
auto o = static_cast<waybar::Bar *>(data);
o->outputName = name;
o->output_name = name;
}
void waybar::Bar::handleDescription(void* /*data*/,
@ -86,13 +97,17 @@ void waybar::Bar::layerSurfaceHandleConfigure(void* data,
{
auto o = static_cast<waybar::Bar *>(data);
o->window.show_all();
o->setWidth(o->config_["width"] ? o->config_["width"].asUInt() : width);
zwlr_layer_surface_v1_ack_configure(surface, serial);
if (o->height_ != height) {
height = o->height_;
std::cout << fmt::format("New Height: {}", height) << std::endl;
zwlr_layer_surface_v1_set_size(surface, o->width_, height);
zwlr_layer_surface_v1_set_exclusive_zone(surface, o->visible ? height : 0);
if (width != o->width_ || height != o->height_) {
o->width_ = width;
o->height_ = height;
std::cout << fmt::format(
"Bar configured (width: {}, height: {}) for output: {}",
o->width_, o->height_, o->output_name) << std::endl;
o->window.set_size_request(o->width_, o->height_);
o->window.resize(o->width_, o->height_);
zwlr_layer_surface_v1_set_exclusive_zone(surface, o->height_);
zwlr_layer_surface_v1_set_size(surface, o->width_, o->height_);
wl_surface_commit(o->surface);
}
}
@ -101,24 +116,13 @@ void waybar::Bar::layerSurfaceHandleClosed(void* data,
struct zwlr_layer_surface_v1* /*surface*/)
{
auto o = static_cast<waybar::Bar *>(data);
std::cout << "Bar removed from output: " + o->output_name << std::endl;
zwlr_layer_surface_v1_destroy(o->layer_surface);
o->layer_surface = nullptr;
wl_surface_destroy(o->surface);
o->surface = nullptr;
o->window.close();
}
auto waybar::Bar::setWidth(uint32_t width) -> void
{
if (width == width_) {
return;
}
std::cout << fmt::format("Bar width configured: {}", width) << std::endl;
width_ = width;
window.set_size_request(width);
window.resize(width, height_);
zwlr_layer_surface_v1_set_size(layer_surface, width, height_ + 1);
wl_surface_commit(surface);
wl_output_destroy(*o->output);
zxdg_output_v1_destroy(o->xdg_output_);
o->modules_left_.clear();
o->modules_center_.clear();
o->modules_right_.clear();
}
auto waybar::Bar::toggle() -> void
@ -154,44 +158,51 @@ auto waybar::Bar::setupCss() -> void
}
}
void waybar::Bar::getModules(Factory factory, const std::string& pos)
{
if (config_[pos]) {
for (const auto &name : config_[pos]) {
try {
if (pos == "modules-left") {
modules_left_.emplace_back(factory.makeModule(name.asString()));
}
if (pos == "modules-center") {
modules_center_.emplace_back(factory.makeModule(name.asString()));
}
if (pos == "modules-right") {
modules_right_.emplace_back(factory.makeModule(name.asString()));
}
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
}
}
}
}
auto waybar::Bar::setupWidgets() -> void
{
auto &left = *Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 0));
auto &center = *Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 0));
auto &right = *Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 0));
auto &box1 = *Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 0));
window.add(box1);
box1.set_homogeneous(true);
box1.pack_start(left, true, true);
box1.pack_start(center, false, false);
box1.pack_end(right, true, true);
auto &box = *Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 0));
window.add(box);
box.pack_start(left, true, true);
box.set_center_widget(center);
box.pack_end(right, true, true);
Factory factory(*this, config_);
if (config_["modules-left"]) {
for (const auto &name : config_["modules-left"]) {
auto module = factory.makeModule(name.asString());
if (module != nullptr) {
getModules(factory, "modules-left");
getModules(factory, "modules-center");
getModules(factory, "modules-right");
for (auto& module : modules_left_) {
left.pack_start(*module, false, true, 0);
}
for (auto& module : modules_center_) {
center.pack_start(*module, true, true, 0);
}
}
if (config_["modules-center"]) {
for (const auto &name : config_["modules-center"]) {
auto module = factory.makeModule(name.asString());
if (module != nullptr) {
center.pack_start(*module, true, false, 10);
}
}
}
if (config_["modules-right"]) {
std::reverse(config_["modules-right"].begin(), config_["modules-right"].end());
for (const auto &name : config_["modules-right"]) {
auto module = factory.makeModule(name.asString());
if (module != nullptr) {
std::reverse(modules_right_.begin(), modules_right_.end());
for (auto& module : modules_right_) {
right.pack_end(*module, false, false, 0);
}
}
}
}

View File

@ -1,7 +1,8 @@
#include "client.hpp"
waybar::Client::Client(int argc, char* argv[])
: gtk_main(argc, argv), gdk_display(Gdk::Display::get_default()),
: gtk_app(Gtk::Application::create(argc, argv, "org.alexays.waybar")),
gdk_display(Gdk::Display::get_default()),
wl_display(gdk_wayland_display_get_wl_display(gdk_display->gobj()))
{
auto getFirstValidPath = [] (std::vector<std::string> possiblePaths) {
@ -48,7 +49,7 @@ void waybar::Client::handleGlobal(void *data, struct wl_registry *registry,
*output = static_cast<struct wl_output *>(wl_registry_bind(registry, name,
&wl_output_interface, version));
if (o->xdg_output_manager != nullptr) {
o->bars.emplace_back(std::make_unique<Bar>(*o, std::move(output)));
o->bars.emplace_back(std::make_unique<Bar>(*o, std::move(output), name));
}
} else if (strcmp(interface, wl_seat_interface.name) == 0) {
o->seat = static_cast<struct wl_seat *>(wl_registry_bind(registry, name,
@ -61,10 +62,16 @@ void waybar::Client::handleGlobal(void *data, struct wl_registry *registry,
}
}
void waybar::Client::handleGlobalRemove(void* /*data*/,
struct wl_registry* /*registry*/, uint32_t /*name*/)
void waybar::Client::handleGlobalRemove(void* data,
struct wl_registry* /*registry*/, uint32_t name)
{
// TODO(someone)
auto o = static_cast<waybar::Client *>(data);
for (auto it = o->bars.begin(); it != o->bars.end(); ++it) {
if ((**it).wl_name == name) {
o->bars.erase(it);
break;
}
}
}
void waybar::Client::bindInterfaces()
@ -81,6 +88,13 @@ void waybar::Client::bindInterfaces()
int waybar::Client::main(int /*argc*/, char* /*argv*/[])
{
bindInterfaces();
gtk_main.run();
gtk_app->hold();
gtk_app->run();
bars.clear();
zxdg_output_manager_v1_destroy(xdg_output_manager);
zwlr_layer_shell_v1_destroy(layer_shell);
wl_registry_destroy(registry);
wl_seat_destroy(seat);
wl_display_disconnect(wl_display);
return 0;
}

View File

@ -34,13 +34,12 @@ waybar::IModule *waybar::Factory::makeModule(const std::string &name)
if (name.compare(0, 7, "custom/") == 0 && name.size() > 7) {
return new waybar::modules::Custom(name.substr(7), _config[name]);
}
std::cerr << "Unknown module: " + name << std::endl;
} catch (const std::exception& e) {
auto err = fmt::format("Disabling module \"{}\", {}", name, e.what());
std::cerr << err << std::endl;
throw std::runtime_error(err);
} catch (...) {
auto err = fmt::format("Disabling module \"{}\", Unknown reason", name);
std::cerr << err << std::endl;
throw std::runtime_error(err);
}
return nullptr;
throw std::runtime_error("Unknown module: " + name);
}

View File

@ -1,7 +1,7 @@
#include "modules/battery.hpp"
waybar::modules::Battery::Battery(Json::Value config)
: config_(std::move(config))
: ALabel(std::move(config))
{
try {
for (auto &node : fs::directory_iterator(data_dir_)) {
@ -16,26 +16,32 @@ waybar::modules::Battery::Battery(Json::Value config)
if (batteries_.empty()) {
throw std::runtime_error("No batteries.");
}
auto fd = inotify_init();
if (fd == -1) {
fd_ = inotify_init1(IN_CLOEXEC);
if (fd_ == -1) {
throw std::runtime_error("Unable to listen batteries.");
}
for (auto &bat : batteries_) {
inotify_add_watch(fd, (bat / "uevent").c_str(), IN_ACCESS);
inotify_add_watch(fd_, (bat / "uevent").c_str(), IN_ACCESS);
}
// Trigger first value
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Battery::update));
// Trigger first values
update();
label_.set_name("battery");
thread_ = [this, fd] {
struct inotify_event event = {};
int nbytes = read(fd, &event, sizeof(event));
thread_.sig_update.connect(sigc::mem_fun(*this, &Battery::update));
thread_ = [this] {
struct inotify_event event = {0};
int nbytes = read(fd_, &event, sizeof(event));
if (nbytes != sizeof(event)) {
return;
}
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Battery::update));
thread_.sig_update.emit();
};
}
waybar::modules::Battery::~Battery()
{
close(fd_);
}
auto waybar::modules::Battery::update() -> void
{
try {
@ -83,8 +89,3 @@ std::string waybar::modules::Battery::getIcon(uint16_t percentage)
auto idx = std::clamp(percentage / (100 / size), 0U, size - 1);
return config_["format-icons"][idx].asString();
}
waybar::modules::Battery::operator Gtk::Widget &()
{
return label_;
}

View File

@ -1,18 +1,19 @@
#include "modules/clock.hpp"
waybar::modules::Clock::Clock(Json::Value config)
: config_(std::move(config))
: ALabel(std::move(config))
{
label_.set_name("clock");
uint32_t interval = config_["interval"] ? config_["inveral"].asUInt() : 60;
thread_.sig_update.connect(sigc::mem_fun(*this, &Clock::update));
thread_ = [this, interval] {
auto now = waybar::chrono::clock::now();
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Clock::update));
thread_.sig_update.emit();
auto timeout = std::chrono::floor<std::chrono::seconds>(now
+ std::chrono::seconds(interval));
thread_.sleep_until(timeout);
};
};
}
auto waybar::modules::Clock::update() -> void
{
@ -20,7 +21,3 @@ auto waybar::modules::Clock::update() -> void
auto format = config_["format"] ? config_["format"].asString() : "{:%H:%M}";
label_.set_text(fmt::format(format, localtime));
}
waybar::modules::Clock::operator Gtk::Widget &() {
return label_;
}

View File

@ -1,27 +1,24 @@
#include "modules/cpu.hpp"
waybar::modules::Cpu::Cpu(Json::Value config)
: config_(std::move(config))
: ALabel(std::move(config))
{
label_.set_name("cpu");
uint32_t interval = config_["interval"] ? config_["inveral"].asUInt() : 10;
thread_.sig_update.connect(sigc::mem_fun(*this, &Cpu::update));
thread_ = [this, interval] {
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Cpu::update));
thread_.sig_update.emit();
thread_.sleep_for(chrono::seconds(interval));
};
};
}
auto waybar::modules::Cpu::update() -> void
{
struct sysinfo info = {};
struct sysinfo info = {0};
if (sysinfo(&info) == 0) {
float f_load = 1.f / (1U << SI_LOAD_SHIFT);
float f_load = 1.f / (1u << SI_LOAD_SHIFT);
uint16_t load = info.loads[0] * f_load * 100 / get_nprocs();
auto format = config_["format"] ? config_["format"].asString() : "{}%";
label_.set_text(fmt::format(format, load));
}
}
waybar::modules::Cpu::operator Gtk::Widget &() {
return label_;
}

View File

@ -1,58 +1,42 @@
#include "modules/custom.hpp"
#include <iostream>
waybar::modules::Custom::Custom(const std::string &name, Json::Value config)
: name_(name), config_(std::move(config))
waybar::modules::Custom::Custom(std::string name, Json::Value config)
: ALabel(std::move(config)), name_(std::move(name))
{
if (!config_["exec"]) {
throw std::runtime_error(name_ + " has no exec path.");
}
if (config_["max-length"]) {
label_.set_max_width_chars(config_["max-length"].asUInt());
label_.set_ellipsize(Pango::EllipsizeMode::ELLIPSIZE_END);
}
uint32_t interval = config_["interval"] ? config_["inveral"].asUInt() : 30;
thread_ = [this, interval] {
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Custom::update));
bool can_update = true;
if (config_["exec-if"]) {
auto res = waybar::util::command::exec(config_["exec-if"].asString());
if (res.exit_code != 0) {
can_update = false;
}
}
if (can_update) {
thread_.sig_update.emit();
}
thread_.sleep_for(chrono::seconds(interval));
};
};
thread_.sig_update.connect(sigc::mem_fun(*this, &Custom::update));
}
auto waybar::modules::Custom::update() -> void
{
std::array<char, 128> buffer = {0};
std::string output;
std::shared_ptr<FILE> fp(popen(config_["exec"].asCString(), "r"), pclose);
if (!fp) {
std::cerr << name_ + " can't exec " + config_["exec"].asString() << std::endl;
return;
}
while (feof(fp.get()) == 0) {
if (fgets(buffer.data(), 128, fp.get()) != nullptr) {
output += buffer.data();
}
}
// Remove last newline
if (!output.empty() && output[output.length()-1] == '\n') {
output.erase(output.length()-1);
}
auto res = waybar::util::command::exec(config_["exec"].asString());
// Hide label if output is empty
if (output.empty()) {
label_.set_name("");
if (res.out.empty() || res.exit_code != 0) {
label_.hide();
label_.set_name("");
} else {
label_.set_name("custom-" + name_);
auto format = config_["format"] ? config_["format"].asString() : "{}";
auto str = fmt::format(format, output);
auto str = fmt::format(format, res.out);
label_.set_text(str);
label_.set_tooltip_text(str);
label_.show();
}
}
waybar::modules::Custom::operator Gtk::Widget &() {
return label_;
}

View File

@ -1,19 +1,20 @@
#include "modules/memory.hpp"
waybar::modules::Memory::Memory(Json::Value config)
: config_(std::move(config))
: ALabel(std::move(config))
{
label_.set_name("memory");
uint32_t interval = config_["interval"] ? config_["inveral"].asUInt() : 30;
thread_.sig_update.connect(sigc::mem_fun(*this, &Memory::update));
thread_ = [this, interval] {
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Memory::update));
thread_.sig_update.emit();
thread_.sleep_for(chrono::seconds(interval));
};
};
}
auto waybar::modules::Memory::update() -> void
{
struct sysinfo info = {};
struct sysinfo info = {0};
if (sysinfo(&info) == 0) {
auto total = info.totalram * info.mem_unit;
auto freeram = info.freeram * info.mem_unit;
@ -24,7 +25,3 @@ auto waybar::modules::Memory::update() -> void
label_.set_tooltip_text(fmt::format("{:.{}f}Gb used", used_ram_gigabytes, 1));
}
}
waybar::modules::Memory::operator Gtk::Widget &() {
return label_;
}

View File

@ -1,34 +1,279 @@
#include "modules/network.hpp"
#include <iostream>
waybar::modules::Network::Network(Json::Value config)
: config_(std::move(config)),
ifid_(if_nametoindex(config_["interface"].asCString())),
: ALabel(std::move(config)), family_(AF_INET),
signal_strength_dbm_(0), signal_strength_(0)
{
if (ifid_ == 0) {
sock_fd_ = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (sock_fd_ < 0) {
throw std::runtime_error("Can't open network socket");
}
nladdr_.nl_family = AF_NETLINK;
nladdr_.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR;
if (bind(sock_fd_, reinterpret_cast<struct sockaddr *>(&nladdr_),
sizeof(nladdr_)) != 0) {
throw std::runtime_error("Can't bind network socket");
}
if (config_["interface"]) {
ifid_ = if_nametoindex(config_["interface"].asCString());
ifname_ = config_["interface"].asString();
if (ifid_ <= 0) {
throw std::runtime_error("Can't found network interface");
}
} else {
ifid_ = getExternalInterface();
if (ifid_ > 0) {
char ifname[IF_NAMESIZE];
if_indextoname(ifid_, ifname);
ifname_ = ifname;
}
}
label_.set_name("network");
uint32_t interval = config_["interval"] ? config_["inveral"].asUInt() : 30;
thread_ = [this, interval] {
// Trigger first values
getInfo();
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Network::update));
thread_.sleep_for(chrono::seconds(interval));
};
update();
thread_.sig_update.connect(sigc::mem_fun(*this, &Network::update));
thread_ = [this] {
char buf[4096];
uint64_t len = netlinkResponse(sock_fd_, buf, sizeof(buf),
RTMGRP_LINK | RTMGRP_IPV4_IFADDR);
bool need_update = false;
for (auto nh = reinterpret_cast<struct nlmsghdr *>(buf); NLMSG_OK(nh, len);
nh = NLMSG_NEXT(nh, len)) {
if (nh->nlmsg_type == NLMSG_DONE) {
break;
}
if (nh->nlmsg_type == NLMSG_ERROR) {
continue;
}
if (nh->nlmsg_type < RTM_NEWADDR) {
auto rtif = static_cast<struct ifinfomsg *>(NLMSG_DATA(nh));
if (rtif->ifi_index == static_cast<int>(ifid_)) {
need_update = true;
if (!(rtif->ifi_flags & IFF_RUNNING)) {
disconnected();
}
}
}
}
if (ifid_ <= 0 && !config_["interface"]) {
// Need to wait before get external interface
thread_.sleep_for(std::chrono::seconds(1));
ifid_ = getExternalInterface();
if (ifid_ > 0) {
char ifname[IF_NAMESIZE];
if_indextoname(ifid_, ifname);
ifname_ = ifname;
need_update = true;
}
}
if (need_update) {
getInfo();
thread_.sig_update.emit();
}
};
}
waybar::modules::Network::~Network()
{
close(sock_fd_);
}
auto waybar::modules::Network::update() -> void
{
auto format = config_["format"] ? config_["format"].asString() : "{essid}";
auto format = config_["format"] ? config_["format"].asString() : "{ifname}";
if (ifid_ <= 0) {
format = config_["format-disconnected"]
? config_["format-disconnected"].asString() : format;
label_.get_style_context()->add_class("disconnected");
} else {
if (essid_.empty()) {
format = config_["format-ethernet"]
? config_["format-ethernet"].asString() : format;
} else {
format = config_["format-wifi"]
? config_["format-wifi"].asString() : format;
}
label_.get_style_context()->remove_class("disconnected");
}
label_.set_text(fmt::format(format,
fmt::arg("essid", essid_),
fmt::arg("signaldBm", signal_strength_dbm_),
fmt::arg("signalStrength", signal_strength_)
fmt::arg("signalStrength", signal_strength_),
fmt::arg("ifname", ifname_)
));
}
void waybar::modules::Network::disconnected()
{
essid_.clear();
signal_strength_dbm_ = 0;
signal_strength_ = 0;
ifname_.clear();
ifid_ = -1;
}
// Based on https://gist.github.com/Yawning/c70d804d4b8ae78cc698
int waybar::modules::Network::getExternalInterface()
{
struct nlmsghdr *hdr = nullptr;
struct rtmsg *rt = nullptr;
void *resp = nullptr;
int ifidx = -1;
/* Allocate space for the request. */
uint32_t reqlen = NLMSG_SPACE(sizeof(*rt));
void *req = nullptr;
if ((req = calloc(1, reqlen)) == nullptr) {
goto out; /* ENOBUFS */
}
/* Build the RTM_GETROUTE request. */
hdr = static_cast<struct nlmsghdr *>(req);
hdr->nlmsg_len = NLMSG_LENGTH(sizeof(*rt));
hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
hdr->nlmsg_type = RTM_GETROUTE;
rt = static_cast<struct rtmsg *>(NLMSG_DATA(hdr));
rt->rtm_family = family_;
rt->rtm_table = RT_TABLE_MAIN;
/* Issue the query. */
if (netlinkRequest(sock_fd_, req, reqlen) < 0) {
goto out;
}
/* Allocate space for the response. */
static const uint32_t route_buffer_size = 8192;
if ((resp = calloc(1, route_buffer_size)) == nullptr) {
goto out; /* ENOBUFS */
}
/* Read the response(s).
*
* WARNING: All the packets generated by the request must be consumed (as in,
* consume responses till NLMSG_DONE/NLMSG_ERROR is encountered).
*/
do {
uint64_t len = netlinkResponse(sock_fd_, resp, route_buffer_size);
if (len < 0) {
goto out;
}
/* Parse the response payload into netlink messages. */
for (hdr = static_cast<struct nlmsghdr *>(resp); NLMSG_OK(hdr, len);
hdr = NLMSG_NEXT(hdr, len)) {
if (hdr->nlmsg_type == NLMSG_DONE) {
goto out;
}
if (hdr->nlmsg_type == NLMSG_ERROR) {
/* Even if we found the interface index, something is broken with the
* netlink socket, so return an error.
*/
ifidx = -1;
goto out;
}
/* If we found the correct answer, skip parsing the attributes. */
if (ifidx != -1) {
continue;
}
/* Find the message(s) concerting the main routing table, each message
* corresponds to a single routing table entry.
*/
rt = static_cast<struct rtmsg *>(NLMSG_DATA(hdr));
if (rt->rtm_table != RT_TABLE_MAIN) {
continue;
}
/* Parse all the attributes for a single routing table entry. */
struct rtattr *attr = RTM_RTA(rt);
uint64_t attrlen = RTM_PAYLOAD(hdr);
bool has_gateway = false;
bool has_destination = false;
int temp_idx = -1;
for (; RTA_OK(attr, attrlen); attr = RTA_NEXT(attr, attrlen)) {
/* Determine if this routing table entry corresponds to the default
* route by seeing if it has a gateway, and if a destination addr is
* set, that it is all 0s.
*/
switch (attr->rta_type) {
case RTA_GATEWAY:
/* The gateway of the route.
*
* If someone every needs to figure out the gateway address as well,
* it's here as the attribute payload.
*/
has_gateway = true;
break;
case RTA_DST: {
/* The destination address.
* Should be either missing, or maybe all 0s. Accept both.
*/
const uint32_t nr_zeroes = (family_ == AF_INET) ? 4 : 16;
unsigned char c = 0;
size_t dstlen = RTA_PAYLOAD(attr);
if (dstlen != nr_zeroes) {
break;
}
for (uint32_t i = 0; i < dstlen; i += 1) {
c |= *(unsigned char *)(RTA_DATA(attr) + i);
}
has_destination = (c == 0);
break;
}
case RTA_OIF:
/* The output interface index. */
temp_idx = *static_cast<int*>(RTA_DATA(attr));
break;
default:
break;
}
}
/* If this is the default route, and we know the interface index,
* we can stop parsing this message.
*/
if (has_gateway && !has_destination && temp_idx != -1) {
ifidx = temp_idx;
break;
}
}
} while (true);
out:
if (req != nullptr)
free(req);
if (resp != nullptr)
free(resp);
return ifidx;
}
uint64_t waybar::modules::Network::netlinkRequest(int fd, void *req,
uint32_t reqlen, uint32_t groups)
{
struct sockaddr_nl sa = {0};
sa.nl_family = AF_NETLINK;
sa.nl_groups = groups;
struct iovec iov = { req, reqlen };
struct msghdr msg = { &sa, sizeof(sa), &iov, 1, nullptr, 0, 0 };
return sendmsg(fd, &msg, 0);
}
uint64_t waybar::modules::Network::netlinkResponse(int fd, void *resp,
uint32_t resplen, uint32_t groups)
{
uint64_t ret;
struct sockaddr_nl sa = {0};
sa.nl_family = AF_NETLINK;
sa.nl_groups = groups;
struct iovec iov = { resp, resplen };
struct msghdr msg = { &sa, sizeof(sa), &iov, 1, nullptr, 0, 0 };
ret = recvmsg(fd, &msg, 0);
if (msg.msg_flags & MSG_TRUNC)
return -1;
return ret;
}
int waybar::modules::Network::scanCb(struct nl_msg *msg, void *data) {
auto net = static_cast<waybar::modules::Network *>(data);
auto gnlh = static_cast<genlmsghdr *>(nlmsg_data(nlmsg_hdr(msg)));
@ -143,7 +388,3 @@ auto waybar::modules::Network::getInfo() -> void
nl_send_sync(sk, msg);
nl_socket_free(sk);
}
waybar::modules::Network::operator Gtk::Widget &() {
return label_;
}

View File

@ -1,7 +1,7 @@
#include "modules/pulseaudio.hpp"
waybar::modules::Pulseaudio::Pulseaudio(Json::Value config)
: config_(std::move(config)), mainloop_(nullptr), mainloop_api_(nullptr),
: ALabel(std::move(config)), mainloop_(nullptr), mainloop_api_(nullptr),
context_(nullptr), sink_idx_(0), volume_(0), muted_(false)
{
label_.set_name("pulseaudio");
@ -26,7 +26,14 @@ waybar::modules::Pulseaudio::Pulseaudio(Json::Value config)
throw std::runtime_error("pa_mainloop_run() failed.");
}
pa_threaded_mainloop_unlock(mainloop_);
};
}
waybar::modules::Pulseaudio::~Pulseaudio()
{
mainloop_api_->quit(mainloop_api_, 0);
pa_threaded_mainloop_stop(mainloop_);
pa_threaded_mainloop_free(mainloop_);
}
void waybar::modules::Pulseaudio::contextStateCb(pa_context *c, void *data)
{
@ -123,7 +130,3 @@ std::string waybar::modules::Pulseaudio::getIcon(uint16_t percentage)
auto idx = std::clamp(percentage / (100 / size), 0U, size - 1);
return config_["format-icons"][idx].asString();
}
waybar::modules::Pulseaudio::operator Gtk::Widget &() {
return label_;
}

View File

@ -5,8 +5,8 @@
#include <sys/socket.h>
#include <sys/un.h>
static const char ipc_magic[] = {'i', '3', '-', 'i', 'p', 'c'};
static const size_t ipc_header_size = sizeof(ipc_magic)+8;
static const std::string ipc_magic("i3-ipc");
static const size_t ipc_header_size = ipc_magic.size() + 8;
std::string getSocketPath() {
const char *env = getenv("SWAYSOCK");
@ -34,7 +34,7 @@ std::string getSocketPath() {
}
int ipcOpenSocket(const std::string &socketPath) {
struct sockaddr_un addr = {};
struct sockaddr_un addr = {0};
int socketfd;
if ((socketfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
throw std::runtime_error("Unable to open Unix socket");
@ -50,50 +50,48 @@ int ipcOpenSocket(const std::string &socketPath) {
}
struct ipc_response ipcRecvResponse(int socketfd) {
struct ipc_response response;
char data[ipc_header_size];
auto data32 = reinterpret_cast<uint32_t *>(data + sizeof(ipc_magic));
std::string header;
header.reserve(ipc_header_size);
auto data32 = reinterpret_cast<uint32_t *>(header.data() + ipc_magic.size());
size_t total = 0;
while (total < ipc_header_size) {
ssize_t received = recv(socketfd, data + total, ipc_header_size - total, 0);
if (received <= 0) {
ssize_t res =
::recv(socketfd, header.data() + total, ipc_header_size - total, 0);
if (res <= 0) {
throw std::runtime_error("Unable to receive IPC response");
}
total += received;
total += res;
}
total = 0;
response.size = data32[0];
response.type = data32[1];
char payload[response.size + 1];
while (total < response.size) {
ssize_t received = recv(socketfd, payload + total, response.size - total, 0);
if (received < 0) {
std::string payload;
payload.reserve(data32[0]);
while (total < data32[0]) {
ssize_t res =
::recv(socketfd, payload.data() + total, data32[0] - total, 0);
if (res < 0) {
throw std::runtime_error("Unable to receive IPC response");
}
total += received;
total += res;
}
payload[response.size] = '\0';
response.payload = std::string(payload);
return response;
return { data32[0], data32[1], &payload.front() };
}
std::string ipcSingleCommand(int socketfd, uint32_t type, const char *payload, uint32_t *len) {
char data[ipc_header_size];
auto data32 = reinterpret_cast<uint32_t *>(data + sizeof(ipc_magic));
memcpy(data, ipc_magic, sizeof(ipc_magic));
data32[0] = *len;
struct ipc_response ipcSingleCommand(int socketfd, uint32_t type,
const std::string& payload) {
std::string header;
header.reserve(ipc_header_size);
auto data32 = reinterpret_cast<uint32_t *>(header.data() + ipc_magic.size());
memcpy(header.data(), ipc_magic.c_str(), ipc_magic.size());
data32[0] = payload.size();
data32[1] = type;
if (send(socketfd, data, ipc_header_size, 0) == -1) {
if (send(socketfd, header.data(), ipc_header_size, 0) == -1) {
throw std::runtime_error("Unable to send IPC header");
}
if (send(socketfd, payload, *len, 0) == -1) {
if (send(socketfd, payload.c_str(), payload.size(), 0) == -1) {
throw std::runtime_error("Unable to send IPC payload");
}
struct ipc_response resp = ipcRecvResponse(socketfd);
*len = resp.size;
return resp.payload;
return ipcRecvResponse(socketfd);
}

View File

@ -2,16 +2,15 @@
#include "modules/sway/ipc/client.hpp"
waybar::modules::sway::Window::Window(Bar &bar, Json::Value config)
: bar_(bar), config_(std::move(config))
: ALabel(std::move(config)), bar_(bar)
{
label_.set_name("window");
std::string socketPath = getSocketPath();
ipcfd_ = ipcOpenSocket(socketPath);
ipc_eventfd_ = ipcOpenSocket(socketPath);
const char *subscribe = "[ \"window\" ]";
uint32_t len = strlen(subscribe);
ipcSingleCommand(ipc_eventfd_, IPC_SUBSCRIBE, subscribe, &len);
ipcSingleCommand(ipc_eventfd_, IPC_SUBSCRIBE, "[ \"window\" ]");
getFocusedWindow();
thread_.sig_update.connect(sigc::mem_fun(*this, &Window::update));
thread_ = [this] {
try {
auto res = ipcRecvResponse(ipc_eventfd_);
@ -19,7 +18,7 @@ waybar::modules::sway::Window::Window(Bar &bar, Json::Value config)
if ((parsed["change"] == "focus" || parsed["change"] == "title")
&& parsed["container"]["focused"].asBool()) {
window_ = parsed["container"]["name"].asString();
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Window::update));
thread_.sig_update.emit();
}
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
@ -27,6 +26,12 @@ waybar::modules::sway::Window::Window(Bar &bar, Json::Value config)
};
}
waybar::modules::sway::Window::~Window()
{
close(ipcfd_);
close(ipc_eventfd_);
}
auto waybar::modules::sway::Window::update() -> void
{
label_.set_text(window_);
@ -50,16 +55,11 @@ std::string waybar::modules::sway::Window::getFocusedNode(Json::Value nodes)
void waybar::modules::sway::Window::getFocusedWindow()
{
try {
uint32_t len = 0;
auto res = ipcSingleCommand(ipcfd_, IPC_GET_TREE, nullptr, &len);
auto parsed = parser_.parse(res);
auto res = ipcSingleCommand(ipcfd_, IPC_GET_TREE, "");
auto parsed = parser_.parse(res.payload);
window_ = getFocusedNode(parsed["nodes"]);
Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Window::update));
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
}
}
waybar::modules::sway::Window::operator Gtk::Widget &() {
return label_;
}

View File

@ -8,34 +8,36 @@ waybar::modules::sway::Workspaces::Workspaces(Bar &bar, Json::Value config)
std::string socketPath = getSocketPath();
ipcfd_ = ipcOpenSocket(socketPath);
ipc_eventfd_ = ipcOpenSocket(socketPath);
const char *subscribe = "[ \"workspace\" ]";
uint32_t len = strlen(subscribe);
ipcSingleCommand(ipc_eventfd_, IPC_SUBSCRIBE, subscribe, &len);
ipcSingleCommand(ipc_eventfd_, IPC_SUBSCRIBE, "[ \"workspace\" ]");
thread_.sig_update.connect(sigc::mem_fun(*this, &Workspaces::update));
thread_ = [this] {
try {
// Wait for the name of the output
if (!config_["all-outputs"].asBool() && bar_.outputName.empty()) {
while (bar_.outputName.empty()) {
if (!config_["all-outputs"].asBool() && bar_.output_name.empty()) {
while (bar_.output_name.empty()) {
thread_.sleep_for(chrono::milliseconds(150));
}
} else if (!workspaces_.empty()) {
ipcRecvResponse(ipc_eventfd_);
}
uint32_t len = 0;
std::lock_guard<std::mutex> lock(mutex_);
auto str = ipcSingleCommand(ipcfd_, IPC_GET_WORKSPACES, nullptr, &len);
workspaces_ = parser_.parse(str);
Glib::signal_idle()
.connect_once(sigc::mem_fun(*this, &Workspaces::update));
thread_.sig_update.emit();
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
}
};
}
waybar::modules::sway::Workspaces::~Workspaces()
{
close(ipcfd_);
close(ipc_eventfd_);
}
auto waybar::modules::sway::Workspaces::update() -> void
{
std::lock_guard<std::mutex> lock(mutex_);
auto res = ipcSingleCommand(ipcfd_, IPC_GET_WORKSPACES, "");
workspaces_ = parser_.parse(res.payload);
bool needReorder = false;
for (auto it = buttons_.begin(); it != buttons_.end();) {
auto ws = std::find_if(workspaces_.begin(), workspaces_.end(),
@ -49,7 +51,7 @@ auto waybar::modules::sway::Workspaces::update() -> void
}
for (auto node : workspaces_) {
if (!config_["all-outputs"].asBool()
&& bar_.outputName != node["output"].asString()) {
&& bar_.output_name != node["output"].asString()) {
continue;
}
auto it = buttons_.find(node["num"].asInt());
@ -97,9 +99,8 @@ void waybar::modules::sway::Workspaces::addWorkspace(Json::Value node)
button.signal_clicked().connect([this, pair] {
try {
std::lock_guard<std::mutex> lock(mutex_);
auto value = fmt::format("workspace \"{}\"", pair.first->first);
uint32_t size = value.size();
ipcSingleCommand(ipcfd_, IPC_COMMAND, value.c_str(), &size);
auto cmd = fmt::format("workspace \"{}\"", pair.first->first);
ipcSingleCommand(ipcfd_, IPC_COMMAND, cmd);
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
}
@ -135,7 +136,6 @@ std::string waybar::modules::sway::Workspaces::getIcon(std::string name)
bool waybar::modules::sway::Workspaces::handleScroll(GdkEventScroll *e)
{
std::lock_guard<std::mutex> lock(mutex_);
// Avoid concurrent scroll event
if (scrolling_) {
return false;
@ -143,6 +143,7 @@ bool waybar::modules::sway::Workspaces::handleScroll(GdkEventScroll *e)
scrolling_ = true;
int id = -1;
uint16_t idx = 0;
std::lock_guard<std::mutex> lock(mutex_);
for (; idx < workspaces_.size(); idx += 1) {
if (workspaces_[idx]["focused"].asBool()) {
id = workspaces_[idx]["num"].asInt();
@ -173,9 +174,7 @@ bool waybar::modules::sway::Workspaces::handleScroll(GdkEventScroll *e)
scrolling_ = false;
return false;
}
auto value = fmt::format("workspace \"{}\"", id);
uint32_t size = value.size();
ipcSingleCommand(ipcfd_, IPC_COMMAND, value.c_str(), &size);
ipcSingleCommand(ipcfd_, IPC_COMMAND, fmt::format("workspace \"{}\"", id));
std::this_thread::sleep_for(std::chrono::milliseconds(150));
return true;
}