diff --git a/.clang-format b/.clang-format index 4bd6b396..c428ccc8 100644 --- a/.clang-format +++ b/.clang-format @@ -1,5 +1,6 @@ --- BasedOnStyle: Google -ColumnLimit: '100' - +AlignConsecutiveDeclarations: true +BinPackArguments: false +ColumnLimit: 100 ... diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..8c2ecb0d --- /dev/null +++ b/.editorconfig @@ -0,0 +1,19 @@ +# EditorConfig configuration for Waybar +# http://EditorConfig.org + +# Top-most EditorConfig file +root = true + +[*] +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +charset = utf-8 + +[*.{build,css}] +indent_style = space +indent_size = 4 + +[*.{hpp,cpp}] +indent_style = space +indent_size = 2 diff --git a/README.md b/README.md index 717c80c8..e4464a27 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ - Memory - Cpu load average - Temperature +- MPD - Custom scripts - Multiple output configuration - And much more customizations @@ -49,6 +50,7 @@ libpulse [Pulseaudio module] libnl [Network module] sway [Sway modules] libdbusmenu-gtk3 [Tray module] +libmpdclient [MPD module] ``` Contributions welcome! - have fun :)
diff --git a/include/factory.hpp b/include/factory.hpp index f896d052..2f550463 100644 --- a/include/factory.hpp +++ b/include/factory.hpp @@ -23,6 +23,9 @@ #ifdef HAVE_LIBPULSE #include "modules/pulseaudio.hpp" #endif +#ifdef HAVE_LIBMPDCLIENT +#include "modules/mpd.hpp" +#endif #include "modules/temperature.hpp" #include "modules/custom.hpp" diff --git a/include/modules/mpd.hpp b/include/modules/mpd.hpp new file mode 100644 index 00000000..b3134f42 --- /dev/null +++ b/include/modules/mpd.hpp @@ -0,0 +1,67 @@ +#pragma once + +#include +#include +#include +#include +#include "ALabel.hpp" + +namespace waybar::modules { + +class MPD : public ALabel { + public: + MPD(const std::string&, const Json::Value&); + auto update() -> void; + + private: + std::thread periodic_updater(); + void setLabel(); + std::string getStateIcon(); + std::string getOptionIcon(std::string optionName, bool activated); + + std::thread event_listener(); + + // Assumes `connection_lock_` is locked + void tryConnect(); + // If checking errors on the main connection, make sure to lock it using + // `connection_lock_` before calling checkErrors + void checkErrors(mpd_connection* conn); + + // Assumes `connection_lock_` is locked + void fetchState(); + void waitForEvent(); + + bool handlePlayPause(GdkEventButton* const&); + + bool stopped(); + bool playing(); + + const std::string module_name_; + + using unique_connection = std::unique_ptr; + using unique_status = std::unique_ptr; + using unique_song = std::unique_ptr; + + // Not using unique_ptr since we don't manage the pointer + // (It's either nullptr, or from the config) + const char* server_; + const unsigned port_; + + // We need a mutex here because we can trigger updates from multiple thread: + // the event based updates, the periodic updates needed for the elapsed time, + // and the click play/pause feature + std::mutex connection_lock_; + unique_connection connection_; + // The alternate connection will be used to wait for events: since it will + // be blocking (idle) we can't send commands via this connection + // + // No lock since only used in the event listener thread + unique_connection alternate_connection_; + + // Protect them using the `connection_lock_` + unique_status status_; + mpd_state state_; + unique_song song_; +}; + +} // namespace waybar::modules diff --git a/meson.build b/meson.build index 94385186..2898e4e4 100644 --- a/meson.build +++ b/meson.build @@ -56,6 +56,7 @@ libnl = dependency('libnl-3.0', required: get_option('libnl')) libnlgen = dependency('libnl-genl-3.0', required: get_option('libnl')) libpulse = dependency('libpulse', required: get_option('pulseaudio')) libudev = dependency('libudev', required: get_option('libudev')) +libmpdclient = dependency('libmpdclient', required: get_option('mpd')) src_files = files( 'src/factory.cpp', @@ -107,6 +108,11 @@ if libudev.found() src_files += 'src/modules/backlight.cpp' endif +if libmpdclient.found() + add_project_arguments('-DHAVE_LIBMPDCLIENT', language: 'cpp') + src_files += 'src/modules/mpd.cpp' +endif + subdir('protocol') executable( @@ -128,7 +134,8 @@ executable( libnl, libnlgen, libpulse, - libudev + libudev, + libmpdclient ], include_directories: [include_directories('include')], install: true, diff --git a/meson_options.txt b/meson_options.txt index 4c2f03a0..f49d9c14 100644 --- a/meson_options.txt +++ b/meson_options.txt @@ -2,4 +2,5 @@ option('libnl', type: 'feature', value: 'auto', description: 'Enable libnl suppo option('libudev', type: 'feature', value: 'auto', description: 'Enable libudev support for udev related features') option('pulseaudio', type: 'feature', value: 'auto', description: 'Enable support for pulseaudio') option('dbusmenu-gtk', type: 'feature', value: 'auto', description: 'Enable support for tray') +option('mpd', type: 'feature', value: 'auto', description: 'Enable support for the Music Player Daemon') option('out', type: 'string', value : '/', description: 'output prefix directory') diff --git a/resources/config b/resources/config index 8b4a4be6..c06ec1a8 100644 --- a/resources/config +++ b/resources/config @@ -6,7 +6,7 @@ // Choose the order of the modules "modules-left": ["sway/workspaces", "sway/mode", "custom/media"], "modules-center": ["sway/window"], - "modules-right": ["idle_inhibitor", "pulseaudio", "network", "cpu", "memory", "temperature", "backlight", "battery", "battery#bat2", "clock", "tray"], + "modules-right": ["mpd", "idle_inhibitor", "pulseaudio", "network", "cpu", "memory", "temperature", "backlight", "battery", "battery#bat2", "clock", "tray"], // Modules configuration // "sway/workspaces": { // "disable-scroll": true, @@ -26,6 +26,31 @@ "sway/mode": { "format": "{}" }, + "mpd": { + "format": "{stateIcon} {consumeIcon}{randomIcon}{repeatIcon}{singleIcon}{artist} - {album} - {title} ({elapsedTime:%M:%S}/{totalTime:%M:%S}) ", + "format-disconnected": "Disconnected ", + "format-stopped": "{consumeIcon}{randomIcon}{repeatIcon}{singleIcon}Stopped ", + "interval": 2, + "consume-icons": { + "on": " " + }, + "random-icons": { + "off": " ", + "on": " " + }, + "repeat-icons": { + "on": " " + }, + "single-icons": { + "on": "1 " + }, + "state-icons": { + "paused": "", + "playing": "" + }, + "tooltip-format": "MPD (connected)", + "tooltip-format-disconnected": "MPD (disconnected)" + } "idle_inhibitor": { "format": "{icon}", "format-icons": { diff --git a/resources/style.css b/resources/style.css index 2a6f9bea..c29569ad 100644 --- a/resources/style.css +++ b/resources/style.css @@ -138,3 +138,20 @@ window#waybar.hidded { background-color: #ecf0f1; color: #2d3436; } + +#mpd { + background: #66cc99; + color: #2a5c45; +} + +#mpd.disconnected { + background: #f53c3c; +} + +#mpd.stopped { + background: #90b1b1; +} + +#mpd.paused { + background: #51a37a; +} diff --git a/src/factory.cpp b/src/factory.cpp index 11e3db26..067ecac7 100644 --- a/src/factory.cpp +++ b/src/factory.cpp @@ -56,6 +56,11 @@ waybar::IModule* waybar::Factory::makeModule(const std::string &name) const return new waybar::modules::Pulseaudio(id, config_[name]); } #endif + #ifdef HAVE_LIBMPDCLIENT + if (ref == "mpd") { + return new waybar::modules::MPD(id, config_[name]); + } + #endif if (ref == "temperature") { return new waybar::modules::Temperature(id, config_[name]); } diff --git a/src/modules/mpd.cpp b/src/modules/mpd.cpp new file mode 100644 index 00000000..ae3ca477 --- /dev/null +++ b/src/modules/mpd.cpp @@ -0,0 +1,305 @@ +#include "modules/mpd.hpp" + +#include +#include + +waybar::modules::MPD::MPD(const std::string& id, const Json::Value& config) + : ALabel(config, "{album} - {artist} - {title}", 5), + module_name_(id.empty() ? "mpd" : "mpd#" + id), + server_(nullptr), + port_(config["port"].asUInt()), + connection_(nullptr, &mpd_connection_free), + alternate_connection_(nullptr, &mpd_connection_free), + status_(nullptr, &mpd_status_free), + song_(nullptr, &mpd_song_free) { + label_.set_name("mpd"); + if (!id.empty()) { + label_.get_style_context()->add_class(id); + } + + if (!config["server"].isNull()) { + server_ = config["server"].asCString(); + } + + event_listener().detach(); + + event_box_.add_events(Gdk::BUTTON_PRESS_MASK); + event_box_.signal_button_press_event().connect(sigc::mem_fun(*this, &MPD::handlePlayPause)); +} + +auto waybar::modules::MPD::update() -> void { + std::lock_guard guard(connection_lock_); + tryConnect(); + + if (connection_ != nullptr) { + try { + bool wasPlaying = playing(); + fetchState(); + if (!wasPlaying && playing()) { + periodic_updater().detach(); + } + } catch (const std::exception& e) { + std::cerr << module_name_ + ": " + e.what() << std::endl; + state_ = MPD_STATE_UNKNOWN; + } + } + + setLabel(); +} + +std::thread waybar::modules::MPD::event_listener() { + return std::thread([this] { + while (true) { + if (connection_ == nullptr) { + // Retry periodically if no connection + try { + update(); + } catch (const std::exception& e) { + std::cerr << module_name_ + ": " + e.what() << std::endl; + } + std::this_thread::sleep_for(interval_); + } else { + waitForEvent(); + dp.emit(); + } + } + }); +} + +std::thread waybar::modules::MPD::periodic_updater() { + return std::thread([this] { + while (connection_ != nullptr && playing()) { + dp.emit(); + std::this_thread::sleep_for(std::chrono::seconds(1)); + } + }); +} + +void waybar::modules::MPD::setLabel() { + if (connection_ == nullptr) { + label_.get_style_context()->add_class("disconnected"); + // In the case connection closed while MPD is stopped + label_.get_style_context()->remove_class("stopped"); + + auto format = config_["format-disconnected"].isString() + ? config_["format-disconnected"].asString() + : "disconnected"; + label_.set_markup(format); + + if (tooltipEnabled()) { + std::string tooltip_format; + tooltip_format = config_["tooltip-format-disconnected"].isString() + ? config_["tooltip-format-disconnected"].asString() + : "MPD (disconnected)"; + // Nothing to format + label_.set_tooltip_text(tooltip_format); + } + return; + } else { + label_.get_style_context()->remove_class("disconnected"); + } + + auto format = format_; + + std::string artist, album_artist, album, title, date; + std::chrono::seconds elapsedTime, totalTime; + + std::string stateIcon = ""; + if (stopped()) { + format = + config_["format-stopped"].isString() ? config_["format-stopped"].asString() : "stopped"; + label_.get_style_context()->add_class("stopped"); + label_.get_style_context()->remove_class("playing"); + label_.get_style_context()->remove_class("paused"); + } else { + label_.get_style_context()->remove_class("stopped"); + if (playing()) { + label_.get_style_context()->add_class("playing"); + label_.get_style_context()->remove_class("paused"); + } else { + label_.get_style_context()->add_class("paused"); + label_.get_style_context()->remove_class("playing"); + } + + stateIcon = getStateIcon(); + + artist = mpd_song_get_tag(song_.get(), MPD_TAG_ARTIST, 0); + album_artist = mpd_song_get_tag(song_.get(), MPD_TAG_ALBUM_ARTIST, 0); + album = mpd_song_get_tag(song_.get(), MPD_TAG_ALBUM, 0); + title = mpd_song_get_tag(song_.get(), MPD_TAG_TITLE, 0); + date = mpd_song_get_tag(song_.get(), MPD_TAG_DATE, 0); + elapsedTime = std::chrono::seconds(mpd_status_get_elapsed_time(status_.get())); + totalTime = std::chrono::seconds(mpd_status_get_total_time(status_.get())); + } + + bool consumeActivated = mpd_status_get_consume(status_.get()); + std::string consumeIcon = getOptionIcon("consume", consumeActivated); + bool randomActivated = mpd_status_get_random(status_.get()); + std::string randomIcon = getOptionIcon("random", randomActivated); + bool repeatActivated = mpd_status_get_repeat(status_.get()); + std::string repeatIcon = getOptionIcon("repeat", repeatActivated); + bool singleActivated = mpd_status_get_single(status_.get()); + std::string singleIcon = getOptionIcon("single", singleActivated); + + // TODO: format can fail + label_.set_markup(fmt::format(format, + fmt::arg("artist", artist), + fmt::arg("albumArtist", album_artist), + fmt::arg("album", album), + fmt::arg("title", title), + fmt::arg("date", date), + fmt::arg("elapsedTime", elapsedTime), + fmt::arg("totalTime", totalTime), + fmt::arg("stateIcon", stateIcon), + fmt::arg("consumeIcon", consumeIcon), + fmt::arg("randomIcon", randomIcon), + fmt::arg("repeatIcon", repeatIcon), + fmt::arg("singleIcon", singleIcon))); + + if (tooltipEnabled()) { + std::string tooltip_format; + tooltip_format = config_["tooltip-format"].isString() ? config_["tooltip-format"].asString() + : "MPD (connected)"; + auto tooltip_text = fmt::format(tooltip_format, + fmt::arg("artist", artist), + fmt::arg("albumArtist", album_artist), + fmt::arg("album", album), + fmt::arg("title", title), + fmt::arg("date", date), + fmt::arg("stateIcon", stateIcon), + fmt::arg("consumeIcon", consumeIcon), + fmt::arg("randomIcon", randomIcon), + fmt::arg("repeatIcon", repeatIcon), + fmt::arg("singleIcon", singleIcon)); + label_.set_tooltip_text(tooltip_text); + } +} + +std::string waybar::modules::MPD::getStateIcon() { + if (!config_["state-icons"].isObject()) { + return ""; + } + + if (connection_ == nullptr) { + std::cerr << module_name_ << ": Trying to fetch state icon while disconnected" << std::endl; + return ""; + } + + if (stopped()) { + std::cerr << module_name_ << ": Trying to fetch state icon while stopped" << std::endl; + return ""; + } + + if (playing()) { + return config_["state-icons"]["playing"].asString(); + } else { + return config_["state-icons"]["paused"].asString(); + } +} + +std::string waybar::modules::MPD::getOptionIcon(std::string optionName, bool activated) { + if (!config_[optionName + "-icons"].isObject()) { + return ""; + } + + if (connection_ == nullptr) { + std::cerr << module_name_ << ": Trying to fetch option icon while disconnected" << std::endl; + return ""; + } + + if (activated) { + return config_[optionName + "-icons"]["on"].asString(); + } else { + return config_[optionName + "-icons"]["off"].asString(); + } +} + +void waybar::modules::MPD::tryConnect() { + if (connection_ != nullptr) { + return; + } + + connection_ = unique_connection(mpd_connection_new(server_, port_, 5'000), &mpd_connection_free); + + alternate_connection_ = + unique_connection(mpd_connection_new(server_, port_, 5'000), &mpd_connection_free); + + if (connection_ == nullptr || alternate_connection_ == nullptr) { + std::cerr << module_name_ << ": Failed to connect to MPD" << std::endl; + connection_.reset(); + alternate_connection_.reset(); + return; + } + + try { + checkErrors(connection_.get()); + } catch (std::runtime_error e) { + std::cerr << module_name_ << ": Failed to connect to MPD: " << e.what() << std::endl; + connection_.reset(); + alternate_connection_.reset(); + } +} + +void waybar::modules::MPD::checkErrors(mpd_connection* conn) { + switch (mpd_connection_get_error(conn)) { + case MPD_ERROR_SUCCESS: + return; + case MPD_ERROR_CLOSED: + std::cerr << module_name_ << ": Connection to MPD closed" << std::endl; + mpd_connection_clear_error(conn); + connection_.reset(); + alternate_connection_.reset(); + state_ = MPD_STATE_UNKNOWN; + return; + default: + auto error_message = mpd_connection_get_error_message(conn); + mpd_connection_clear_error(conn); + throw std::runtime_error(std::string(error_message)); + } +} + +void waybar::modules::MPD::fetchState() { + auto conn = connection_.get(); + status_ = unique_status(mpd_run_status(conn), &mpd_status_free); + checkErrors(conn); + state_ = mpd_status_get_state(status_.get()); + checkErrors(conn); + + song_ = unique_song(mpd_run_current_song(conn), &mpd_song_free); + checkErrors(conn); +} + +void waybar::modules::MPD::waitForEvent() { + auto conn = alternate_connection_.get(); + // Wait for a player (play/pause), option (random, shuffle, etc.), or playlist + // change + mpd_run_idle_mask(conn, + static_cast(MPD_IDLE_PLAYER | MPD_IDLE_OPTIONS | MPD_IDLE_PLAYLIST)); + checkErrors(conn); +} + +bool waybar::modules::MPD::handlePlayPause(GdkEventButton* const& e) { + if (e->type == GDK_2BUTTON_PRESS || e->type == GDK_3BUTTON_PRESS || connection_ == nullptr) { + return false; + } + + if (e->button == 1) { + std::lock_guard guard(connection_lock_); + if (stopped()) { + mpd_run_play(connection_.get()); + } else { + mpd_run_toggle_pause(connection_.get()); + } + } else if (e->button == 3) { + std::lock_guard guard(connection_lock_); + mpd_run_stop(connection_.get()); + } + + return true; +} + +bool waybar::modules::MPD::stopped() { + return connection_ == nullptr || state_ == MPD_STATE_UNKNOWN || state_ == MPD_STATE_STOP; +} + +bool waybar::modules::MPD::playing() { return connection_ != nullptr && state_ == MPD_STATE_PLAY; }