1 #include "modules/mpd/mpd.hpp"
2 
3 #include <fmt/chrono.h>
4 #include <spdlog/spdlog.h>
5 #include <glibmm/ustring.h>
6 #include "modules/mpd/state.hpp"
7 #if defined(MPD_NOINLINE)
8 namespace waybar::modules {
9 #include "modules/mpd/state.inl.hpp"
10 }  // namespace waybar::modules
11 #endif
12 
MPD(const std::string & id,const Json::Value & config)13 waybar::modules::MPD::MPD(const std::string& id, const Json::Value& config)
14     : ALabel(config, "mpd", id, "{album} - {artist} - {title}", 5),
15       module_name_(id.empty() ? "mpd" : "mpd#" + id),
16       server_(nullptr),
17       port_(config_["port"].isUInt() ? config["port"].asUInt() : 0),
18       password_(config_["password"].empty() ? "" : config_["password"].asString()),
19       timeout_(config_["timeout"].isUInt() ? config_["timeout"].asUInt() * 1'000 : 30'000),
20       connection_(nullptr, &mpd_connection_free),
21       status_(nullptr, &mpd_status_free),
22       song_(nullptr, &mpd_song_free) {
23   if (!config_["port"].isNull() && !config_["port"].isUInt()) {
24     spdlog::warn("{}: `port` configuration should be an unsigned int", module_name_);
25   }
26 
27   if (!config_["timeout"].isNull() && !config_["timeout"].isUInt()) {
28     spdlog::warn("{}: `timeout` configuration should be an unsigned int", module_name_);
29   }
30 
31   if (!config["server"].isNull()) {
32     if (!config_["server"].isString()) {
33       spdlog::warn("{}:`server` configuration should be a string", module_name_);
34     }
35     server_ = config["server"].asCString();
36   }
37 
38   event_box_.add_events(Gdk::BUTTON_PRESS_MASK);
39   event_box_.signal_button_press_event().connect(sigc::mem_fun(*this, &MPD::handlePlayPause));
40 }
41 
update()42 auto waybar::modules::MPD::update() -> void {
43   context_.update();
44 
45   // Call parent update
46   ALabel::update();
47 }
48 
queryMPD()49 void waybar::modules::MPD::queryMPD() {
50   if (connection_ != nullptr) {
51     spdlog::debug("{}: fetching state information", module_name_);
52     try {
53       fetchState();
54       spdlog::debug("{}: fetch complete", module_name_);
55     } catch (std::exception const& e) {
56       spdlog::error("{}: {}", module_name_, e.what());
57       state_ = MPD_STATE_UNKNOWN;
58     }
59 
60     dp.emit();
61   }
62 }
63 
getTag(mpd_tag_type type,unsigned idx) const64 std::string waybar::modules::MPD::getTag(mpd_tag_type type, unsigned idx) const {
65   std::string result =
66       config_["unknown-tag"].isString() ? config_["unknown-tag"].asString() : "N/A";
67   const char* tag = mpd_song_get_tag(song_.get(), type, idx);
68 
69   // mpd_song_get_tag can return NULL, so make sure it's valid before setting
70   if (tag) result = tag;
71 
72   return result;
73 }
74 
setLabel()75 void waybar::modules::MPD::setLabel() {
76   if (connection_ == nullptr) {
77     label_.get_style_context()->add_class("disconnected");
78     label_.get_style_context()->remove_class("stopped");
79     label_.get_style_context()->remove_class("playing");
80     label_.get_style_context()->remove_class("paused");
81 
82     auto format = config_["format-disconnected"].isString()
83                       ? config_["format-disconnected"].asString()
84                       : "disconnected";
85     label_.set_markup(format);
86 
87     if (tooltipEnabled()) {
88       std::string tooltip_format;
89       tooltip_format = config_["tooltip-format-disconnected"].isString()
90                            ? config_["tooltip-format-disconnected"].asString()
91                            : "MPD (disconnected)";
92       // Nothing to format
93       label_.set_tooltip_text(tooltip_format);
94     }
95     return;
96   } else {
97     label_.get_style_context()->remove_class("disconnected");
98   }
99 
100   auto format = format_;
101   Glib::ustring        artist, album_artist, album, title;
102   std::string          date;
103   int                  song_pos = 0, queue_length = 0, volume = 0;
104   std::chrono::seconds elapsedTime, totalTime;
105 
106   std::string stateIcon = "";
107   if (stopped()) {
108     format =
109         config_["format-stopped"].isString() ? config_["format-stopped"].asString() : "stopped";
110     label_.get_style_context()->add_class("stopped");
111     label_.get_style_context()->remove_class("playing");
112     label_.get_style_context()->remove_class("paused");
113   } else {
114     label_.get_style_context()->remove_class("stopped");
115     if (playing()) {
116       label_.get_style_context()->add_class("playing");
117       label_.get_style_context()->remove_class("paused");
118     } else if (paused()) {
119       format = config_["format-paused"].isString() ? config_["format-paused"].asString()
120                                                    : config_["format"].asString();
121       label_.get_style_context()->add_class("paused");
122       label_.get_style_context()->remove_class("playing");
123     }
124 
125     stateIcon = getStateIcon();
126 
127     artist = getTag(MPD_TAG_ARTIST);
128     album_artist = getTag(MPD_TAG_ALBUM_ARTIST);
129     album = getTag(MPD_TAG_ALBUM);
130     title = getTag(MPD_TAG_TITLE);
131     date = getTag(MPD_TAG_DATE);
132     song_pos = mpd_status_get_song_pos(status_.get()) + 1;
133     volume = mpd_status_get_volume(status_.get());
134     if (volume < 0) {
135       volume = 0;
136     }
137     queue_length = mpd_status_get_queue_length(status_.get());
138     elapsedTime = std::chrono::seconds(mpd_status_get_elapsed_time(status_.get()));
139     totalTime = std::chrono::seconds(mpd_status_get_total_time(status_.get()));
140   }
141 
142   bool        consumeActivated = mpd_status_get_consume(status_.get());
143   std::string consumeIcon = getOptionIcon("consume", consumeActivated);
144   bool        randomActivated = mpd_status_get_random(status_.get());
145   std::string randomIcon = getOptionIcon("random", randomActivated);
146   bool        repeatActivated = mpd_status_get_repeat(status_.get());
147   std::string repeatIcon = getOptionIcon("repeat", repeatActivated);
148   bool        singleActivated = mpd_status_get_single(status_.get());
149   std::string singleIcon = getOptionIcon("single", singleActivated);
150   if (config_["artist-len"].isInt()) artist = artist.substr(0, config_["artist-len"].asInt());
151   if (config_["album-artist-len"].isInt()) album_artist = album_artist.substr(0, config_["album-artist-len"].asInt());
152   if (config_["album-len"].isInt()) album = album.substr(0, config_["album-len"].asInt());
153   if (config_["title-len"].isInt()) title = title.substr(0,config_["title-len"].asInt());
154 
155   try {
156     label_.set_markup(
157         fmt::format(format,
158                     fmt::arg("artist", Glib::Markup::escape_text(artist).raw()),
159                     fmt::arg("albumArtist", Glib::Markup::escape_text(album_artist).raw()),
160                     fmt::arg("album", Glib::Markup::escape_text(album).raw()),
161                     fmt::arg("title", Glib::Markup::escape_text(title).raw()),
162                     fmt::arg("date", Glib::Markup::escape_text(date).raw()),
163                     fmt::arg("volume", volume),
164                     fmt::arg("elapsedTime", elapsedTime),
165                     fmt::arg("totalTime", totalTime),
166                     fmt::arg("songPosition", song_pos),
167                     fmt::arg("queueLength", queue_length),
168                     fmt::arg("stateIcon", stateIcon),
169                     fmt::arg("consumeIcon", consumeIcon),
170                     fmt::arg("randomIcon", randomIcon),
171                     fmt::arg("repeatIcon", repeatIcon),
172                     fmt::arg("singleIcon", singleIcon)));
173   } catch (fmt::format_error const& e) {
174     spdlog::warn("mpd: format error: {}", e.what());
175   }
176 
177   if (tooltipEnabled()) {
178     std::string tooltip_format;
179     tooltip_format = config_["tooltip-format"].isString() ? config_["tooltip-format"].asString()
180                                                           : "MPD (connected)";
181     try {
182       auto tooltip_text = fmt::format(tooltip_format,
183                                       fmt::arg("artist", artist.raw()),
184                                       fmt::arg("albumArtist", album_artist.raw()),
185                                       fmt::arg("album", album.raw()),
186                                       fmt::arg("title", title.raw()),
187                                       fmt::arg("date", date),
188                                       fmt::arg("volume", volume),
189                                       fmt::arg("elapsedTime", elapsedTime),
190                                       fmt::arg("totalTime", totalTime),
191                                       fmt::arg("songPosition", song_pos),
192                                       fmt::arg("queueLength", queue_length),
193                                       fmt::arg("stateIcon", stateIcon),
194                                       fmt::arg("consumeIcon", consumeIcon),
195                                       fmt::arg("randomIcon", randomIcon),
196                                       fmt::arg("repeatIcon", repeatIcon),
197                                       fmt::arg("singleIcon", singleIcon));
198       label_.set_tooltip_text(tooltip_text);
199     } catch (fmt::format_error const& e) {
200       spdlog::warn("mpd: format error (tooltip): {}", e.what());
201     }
202   }
203 }
204 
getStateIcon() const205 std::string waybar::modules::MPD::getStateIcon() const {
206   if (!config_["state-icons"].isObject()) {
207     return "";
208   }
209 
210   if (connection_ == nullptr) {
211     spdlog::warn("{}: Trying to fetch state icon while disconnected", module_name_);
212     return "";
213   }
214 
215   if (stopped()) {
216     spdlog::warn("{}: Trying to fetch state icon while stopped", module_name_);
217     return "";
218   }
219 
220   if (playing()) {
221     return config_["state-icons"]["playing"].asString();
222   } else {
223     return config_["state-icons"]["paused"].asString();
224   }
225 }
226 
getOptionIcon(std::string optionName,bool activated) const227 std::string waybar::modules::MPD::getOptionIcon(std::string optionName, bool activated) const {
228   if (!config_[optionName + "-icons"].isObject()) {
229     return "";
230   }
231 
232   if (connection_ == nullptr) {
233     spdlog::warn("{}: Trying to fetch option icon while disconnected", module_name_);
234     return "";
235   }
236 
237   if (activated) {
238     return config_[optionName + "-icons"]["on"].asString();
239   } else {
240     return config_[optionName + "-icons"]["off"].asString();
241   }
242 }
243 
tryConnect()244 void waybar::modules::MPD::tryConnect() {
245   if (connection_ != nullptr) {
246     return;
247   }
248 
249   connection_ =
250       detail::unique_connection(mpd_connection_new(server_, port_, timeout_), &mpd_connection_free);
251 
252   if (connection_ == nullptr) {
253     spdlog::error("{}: Failed to connect to MPD", module_name_);
254     connection_.reset();
255     return;
256   }
257 
258   try {
259     checkErrors(connection_.get());
260     spdlog::debug("{}: Connected to MPD", module_name_);
261 
262     if (!password_.empty()) {
263       bool res = mpd_run_password(connection_.get(), password_.c_str());
264       if (!res) {
265         spdlog::error("{}: Wrong MPD password", module_name_);
266         connection_.reset();
267         return;
268       }
269       checkErrors(connection_.get());
270     }
271   } catch (std::runtime_error& e) {
272     spdlog::error("{}: Failed to connect to MPD: {}", module_name_, e.what());
273     connection_.reset();
274   }
275 }
276 
checkErrors(mpd_connection * conn)277 void waybar::modules::MPD::checkErrors(mpd_connection* conn) {
278   switch (mpd_connection_get_error(conn)) {
279     case MPD_ERROR_SUCCESS:
280       mpd_connection_clear_error(conn);
281       return;
282     case MPD_ERROR_TIMEOUT:
283     case MPD_ERROR_CLOSED:
284       mpd_connection_clear_error(conn);
285       connection_.reset();
286       state_ = MPD_STATE_UNKNOWN;
287       throw std::runtime_error("Connection to MPD closed");
288     default:
289       if (conn) {
290         auto error_message = mpd_connection_get_error_message(conn);
291         std::string error(error_message);
292         mpd_connection_clear_error(conn);
293         throw std::runtime_error(error);
294       }
295       throw std::runtime_error("Invalid connection");
296   }
297 }
298 
fetchState()299 void waybar::modules::MPD::fetchState() {
300   if (connection_ == nullptr) {
301     spdlog::error("{}: Not connected to MPD", module_name_);
302     return;
303   }
304 
305   auto conn = connection_.get();
306 
307   status_ = detail::unique_status(mpd_run_status(conn), &mpd_status_free);
308   checkErrors(conn);
309 
310   state_ = mpd_status_get_state(status_.get());
311   checkErrors(conn);
312 
313   song_ = detail::unique_song(mpd_run_current_song(conn), &mpd_song_free);
314   checkErrors(conn);
315 }
316 
handlePlayPause(GdkEventButton * const & e)317 bool waybar::modules::MPD::handlePlayPause(GdkEventButton* const& e) {
318   if (e->type == GDK_2BUTTON_PRESS || e->type == GDK_3BUTTON_PRESS || connection_ == nullptr) {
319     return false;
320   }
321 
322   if (e->button == 1) {
323     if (state_ == MPD_STATE_PLAY)
324       context_.pause();
325     else
326       context_.play();
327   } else if (e->button == 3) {
328     context_.stop();
329   }
330 
331   return true;
332 }
333