change version to 0.7.3
[ncmpcpp.git] / src / status.cpp
blob54c68efa878c950ea5892c96a0f17658339642c1
1 /***************************************************************************
2 * Copyright (C) 2008-2014 by Andrzej Rybczak *
3 * electricityispower@gmail.com *
4 * *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
19 ***************************************************************************/
21 #include <boost/date_time/posix_time/posix_time.hpp>
22 #include <netinet/tcp.h>
23 #include <netinet/in.h>
25 #include "browser.h"
26 #include "charset.h"
27 #include "format_impl.h"
28 #include "global.h"
29 #include "helpers.h"
30 #include "lyrics.h"
31 #include "media_library.h"
32 #include "menu_impl.h"
33 #include "outputs.h"
34 #include "playlist.h"
35 #include "playlist_editor.h"
36 #include "search_engine.h"
37 #include "sel_items_adder.h"
38 #include "settings.h"
39 #include "status.h"
40 #include "statusbar.h"
41 #include "tag_editor.h"
42 #include "visualizer.h"
43 #include "title.h"
44 #include "utility/string.h"
46 using Global::myScreen;
48 using Global::wFooter;
49 using Global::wHeader;
51 using Global::Timer;
52 using Global::VolumeState;
54 namespace {
56 boost::posix_time::ptime past = boost::posix_time::from_time_t(0);
58 size_t playing_song_scroll_begin = 0;
59 size_t first_line_scroll_begin = 0;
60 size_t second_line_scroll_begin = 0;
62 bool m_status_initialized;
64 char m_consume;
65 char m_crossfade;
66 char m_db_updating;
67 char m_repeat;
68 char m_random;
69 char m_single;
71 int m_current_song_id;
72 int m_current_song_pos;
73 unsigned m_elapsed_time;
74 unsigned m_kbps;
75 MPD::PlayerState m_player_state;
76 unsigned m_playlist_version;
77 unsigned m_playlist_length;
78 unsigned m_total_time;
79 int m_volume;
81 void drawTitle(const MPD::Song &np)
83 assert(!np.empty());
84 windowTitle(Format::stringify<char>(Config.song_window_title_format, &np));
87 std::string playerStateToString(MPD::PlayerState ps)
89 std::string result;
90 switch (ps)
92 case MPD::psUnknown:
93 switch (Config.design)
95 case Design::Alternative:
96 result = "[unknown]";
97 break;
98 case Design::Classic:
99 break;
101 break;
102 case MPD::psPlay:
103 switch (Config.design)
105 case Design::Alternative:
106 result = "[playing]";
107 break;
108 case Design::Classic:
109 result = "Playing:";
110 break;
112 break;
113 case MPD::psPause:
114 switch (Config.design)
116 case Design::Alternative:
117 result = "[paused]";
118 break;
119 case Design::Classic:
120 result = "Paused:";
121 break;
123 break;
124 case MPD::psStop:
125 switch (Config.design)
127 case Design::Alternative:
128 result = "[stopped]";
129 break;
130 case Design::Classic:
131 break;
133 break;
135 return result;
138 void initialize_status()
140 // get full info about new connection
141 Status::update(-1);
143 if (Config.jump_to_now_playing_song_at_start)
145 int curr_pos = Status::State::currentSongPosition();
146 if (curr_pos >= 0)
148 myPlaylist->main().highlight(curr_pos);
149 if (isVisible(myPlaylist))
150 myPlaylist->refresh();
154 // Set TCP_NODELAY on the tcp socket as we are using write-write-read pattern
155 // a lot (noidle - write, command - write, then read the result of command),
156 // which kills the performance.
157 int flag = 1;
158 setsockopt(Mpd.GetFD(), IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(flag));
160 myBrowser->fetchSupportedExtensions();
161 # ifdef ENABLE_OUTPUTS
162 myOutputs->fetchList();
163 # endif // ENABLE_OUTPUTS
164 # ifdef ENABLE_VISUALIZER
165 myVisualizer->ResetFD();
166 myVisualizer->SetFD();
167 myVisualizer->FindOutputID();
168 # endif // ENABLE_VISUALIZER
170 m_status_initialized = true;
171 wFooter->addFDCallback(Mpd.GetFD(), Statusbar::Helpers::mpd);
172 Statusbar::printf("Connected to %1%", Mpd.GetHostname());
177 /*************************************************************************/
179 void Status::handleClientError(MPD::ClientError &e)
181 if (!e.clearable())
182 Mpd.Disconnect();
183 Statusbar::printf("ncmpcpp: %1%", e.what());
186 void Status::handleServerError(MPD::ServerError &e)
188 Statusbar::printf("MPD: %1%", e.what());
189 if (e.code() == MPD_SERVER_ERROR_PERMISSION)
191 NC::Window::ScopedPromptHook helper(*wFooter, nullptr);
192 Statusbar::put() << "Password: ";
193 Mpd.SetPassword(wFooter->prompt("", -1, true));
194 try {
195 Mpd.SendPassword();
196 Statusbar::print("Password accepted");
197 } catch (MPD::ServerError &e_prim) {
198 handleServerError(e_prim);
203 /*************************************************************************/
205 void Status::trace(bool update_timer, bool update_window_timeout)
207 if (update_timer)
208 Timer = boost::posix_time::microsec_clock::local_time();
209 if (update_window_timeout)
211 // set appropriate window timeout
212 int nc_wtimeout = std::numeric_limits<int>::max();
213 applyToVisibleWindows([&nc_wtimeout](BaseScreen *s) {
214 nc_wtimeout = std::min(nc_wtimeout, s->windowTimeout());
216 wFooter->setTimeout(nc_wtimeout);
218 if (Mpd.Connected())
220 if (!m_status_initialized)
221 initialize_status();
223 if (m_player_state == MPD::psPlay
224 && Global::Timer - past > boost::posix_time::seconds(1))
226 // update elapsed time/bitrate of the current song
227 Status::Changes::elapsedTime(true);
228 wFooter->refresh();
229 past = Timer;
232 applyToVisibleWindows(&BaseScreen::update);
233 Statusbar::tryRedraw();
235 Mpd.idle();
239 void Status::update(int event)
241 auto st = Mpd.getStatus();
242 m_current_song_pos = st.currentSongPosition();
243 m_elapsed_time = st.elapsedTime();
244 m_kbps = st.kbps();
245 m_player_state = st.playerState();
246 m_playlist_length = st.playlistLength();
247 m_total_time = st.totalTime();
248 m_volume = st.volume();
250 if (event & MPD_IDLE_DATABASE)
251 Changes::database();
252 if (event & MPD_IDLE_STORED_PLAYLIST)
253 Changes::storedPlaylists();
254 if (event & MPD_IDLE_PLAYLIST)
256 Changes::playlist(m_playlist_version);
257 m_playlist_version = st.playlistVersion();
259 if (event & MPD_IDLE_PLAYER)
261 Changes::playerState();
262 if (m_current_song_id != st.currentSongID())
264 Changes::songID(st.currentSongID());
265 m_current_song_id = st.currentSongID();
268 if (event & MPD_IDLE_MIXER)
269 Changes::mixer();
270 if (event & MPD_IDLE_OUTPUT)
271 Changes::outputs();
272 if (event & (MPD_IDLE_UPDATE | MPD_IDLE_OPTIONS))
274 if (event & MPD_IDLE_UPDATE)
276 m_db_updating = st.updateID() ? 'U' : 0;
277 if (m_status_initialized)
278 Statusbar::printf("Database update %1%", m_db_updating ? "started" : "finished");
280 if (event & MPD_IDLE_OPTIONS)
282 if (('r' == m_repeat) != st.repeat())
284 m_repeat = st.repeat() ? 'r' : 0;
285 if (m_status_initialized)
286 Statusbar::printf("Repeat mode is %1%", !m_repeat ? "off" : "on");
288 if (('z' == m_random) != st.random())
290 m_random = st.random() ? 'z' : 0;
291 if (m_status_initialized)
292 Statusbar::printf("Random mode is %1%", !m_random ? "off" : "on");
294 if (('s' == m_single) != st.single())
296 m_single = st.single() ? 's' : 0;
297 if (m_status_initialized)
298 Statusbar::printf("Single mode is %1%", !m_single ? "off" : "on");
300 if (('c' == m_consume) != st.consume())
302 m_consume = st.consume() ? 'c' : 0;
303 if (m_status_initialized)
304 Statusbar::printf("Consume mode is %1%", !m_consume ? "off" : "on");
306 if (('x' == m_crossfade) != (st.crossfade() != 0))
308 int crossfade = st.crossfade();
309 m_crossfade = crossfade ? 'x' : 0;
310 if (m_status_initialized)
311 Statusbar::printf("Crossfade set to %1% seconds", crossfade);
314 Changes::flags();
316 m_status_initialized = true;
318 if (event & MPD_IDLE_PLAYER)
319 wFooter->refresh();
321 if (event & (MPD_IDLE_PLAYLIST | MPD_IDLE_DATABASE | MPD_IDLE_PLAYER))
322 applyToVisibleWindows(&BaseScreen::refreshWindow);
325 void Status::clear()
327 // reset local variables
328 m_status_initialized = false;
329 m_repeat = 0;
330 m_random = 0;
331 m_single = 0;
332 m_consume = 0;
333 m_crossfade = 0;
334 m_db_updating = 0;
335 m_current_song_id = -1;
336 m_current_song_pos = -1;
337 m_kbps = 0;
338 m_player_state = MPD::psUnknown;
339 m_playlist_length = 0;
340 m_playlist_version = 0;
341 m_total_time = 0;
342 m_volume = -1;
345 /*************************************************************************/
347 bool Status::State::consume()
349 return m_consume != 0;
352 bool Status::State::crossfade()
354 return m_crossfade != 0;
357 bool Status::State::repeat()
359 return m_repeat != 0;
362 bool Status::State::random()
364 return m_random != 0;
367 bool Status::State::single()
369 return m_single != 0;
372 int Status::State::currentSongID()
374 return m_current_song_id;
377 int Status::State::currentSongPosition()
379 return m_current_song_pos;
382 unsigned Status::State::playlistLength()
384 return m_playlist_length;
387 unsigned Status::State::elapsedTime()
389 return m_elapsed_time;
392 MPD::PlayerState Status::State::player()
394 return m_player_state;
397 unsigned Status::State::totalTime()
399 return m_total_time;
402 int Status::State::volume()
404 return m_volume;
407 /*************************************************************************/
409 void Status::Changes::playlist(unsigned previous_version)
411 if (m_playlist_length < myPlaylist->main().size())
413 auto it = myPlaylist->main().begin()+m_playlist_length;
414 auto end = myPlaylist->main().end();
415 for (; it != end; ++it)
416 myPlaylist->unregisterSong(it->value());
417 myPlaylist->main().resizeList(m_playlist_length);
420 MPD::SongIterator s = Mpd.GetPlaylistChanges(previous_version), end;
421 for (; s != end; ++s)
423 size_t pos = s->getPosition();
424 myPlaylist->registerSong(*s);
425 if (pos < myPlaylist->main().size())
427 // if song's already in playlist, replace it with a new one
428 MPD::Song &old_s = myPlaylist->main()[pos].value();
429 myPlaylist->unregisterSong(old_s);
430 old_s = std::move(*s);
432 else // otherwise just add it to playlist
433 myPlaylist->main().addItem(std::move(*s));
436 myPlaylist->reloadTotalLength();
437 myPlaylist->reloadRemaining();
439 if (isVisible(myBrowser))
440 markSongsInPlaylist(myBrowser->main());
441 if (isVisible(mySearcher))
442 markSongsInPlaylist(mySearcher->main());
443 if (isVisible(myLibrary))
445 markSongsInPlaylist(myLibrary->Songs);
446 myLibrary->Songs.refresh();
448 if (isVisible(myPlaylistEditor))
450 markSongsInPlaylist(myPlaylistEditor->Content);
451 myPlaylistEditor->Content.refresh();
455 void Status::Changes::storedPlaylists()
457 myPlaylistEditor->requestPlaylistsUpdate();
458 myPlaylistEditor->requestContentsUpdate();
459 if (!myBrowser->isLocal() && myBrowser->inRootDirectory())
460 myBrowser->requestUpdate();
463 void Status::Changes::database()
465 myBrowser->requestUpdate();
466 # ifdef HAVE_TAGLIB_H
467 myTagEditor->Dirs->clear();
468 # endif // HAVE_TAGLIB_H
469 myLibrary->requestTagsUpdate();
470 myLibrary->requestAlbumsUpdate();
471 myLibrary->requestSongsUpdate();
474 void Status::Changes::playerState()
476 switch (m_player_state)
478 case MPD::psPlay:
480 auto np = myPlaylist->nowPlayingSong();
481 if (!np.empty())
482 drawTitle(np);
483 myPlaylist->reloadRemaining();
484 break;
486 case MPD::psStop:
487 windowTitle("ncmpcpp " VERSION);
488 if (Progressbar::isUnlocked())
489 Progressbar::draw(0, 0);
490 myPlaylist->reloadRemaining();
491 if (Config.design == Design::Alternative)
493 *wHeader << NC::XY(0, 0) << NC::TermManip::ClearToEOL;
494 *wHeader << NC::XY(0, 1) << NC::TermManip::ClearToEOL;
495 mixer();
496 flags();
498 # ifdef ENABLE_VISUALIZER
499 if (isVisible(myVisualizer))
500 myVisualizer->main().clear();
501 # endif // ENABLE_VISUALIZER
502 break;
503 default:
504 break;
507 std::string state = playerStateToString(m_player_state);
508 if (Config.design == Design::Alternative)
510 *wHeader << NC::XY(0, 1) << NC::Format::Bold << state << NC::Format::NoBold;
511 wHeader->refresh();
513 else if (Statusbar::isUnlocked() && Config.statusbar_visibility)
515 *wFooter << NC::XY(0, 1);
516 if (state.empty())
517 *wFooter << NC::TermManip::ClearToEOL;
518 else
519 *wFooter << NC::Format::Bold << state << NC::Format::NoBold;
522 // needed for immediate display after starting
523 // player from stopped state or seeking
524 elapsedTime(false);
527 void Status::Changes::songID(int song_id)
529 // update information about current song
530 myPlaylist->reloadRemaining();
531 playing_song_scroll_begin = 0;
532 first_line_scroll_begin = 0;
533 second_line_scroll_begin = 0;
534 # ifdef ENABLE_VISUALIZER
535 myVisualizer->ResetAutoScaleMultiplier();
536 # endif // ENABLE_VISUALIZER
537 if (m_player_state != MPD::psStop)
539 auto &pl = myPlaylist->main();
541 // try to find the song with new id in the playlist
542 auto it = std::find_if(pl.beginV(), pl.endV(), [song_id](const MPD::Song &s) {
543 return s.getID() == unsigned(song_id);
545 // if it's not there (playlist may be outdated), fetch it
546 const auto &s = it != pl.endV() ? *it : Mpd.GetCurrentSong();
547 if (!s.empty())
549 GNUC_UNUSED int res;
550 if (!Config.execute_on_song_change.empty())
551 res = system(Config.execute_on_song_change.c_str());
553 # ifdef HAVE_CURL_CURL_H
554 if (Config.fetch_lyrics_in_background)
555 Lyrics::DownloadInBackground(s);
556 # endif // HAVE_CURL_CURL_H
558 drawTitle(s);
560 if (Config.autocenter_mode)
561 pl.highlight(Status::State::currentSongPosition());
563 if (Config.now_playing_lyrics && isVisible(myLyrics) && myLyrics->previousScreen() == myPlaylist)
565 if (myLyrics->SetSong(s))
566 myLyrics->Reload = 1;
570 elapsedTime(false);
573 void Status::Changes::elapsedTime(bool update_elapsed)
575 auto np = myPlaylist->nowPlayingSong();
576 if (m_player_state == MPD::psStop || np.empty())
578 // MPD is not playing, clear statusbar and exit.
579 if (Statusbar::isUnlocked() && Config.statusbar_visibility)
580 *wFooter << NC::XY(0, 1) << NC::TermManip::ClearToEOL;
581 return;
584 if (update_elapsed)
586 auto st = Mpd.getStatus();
587 m_elapsed_time = st.elapsedTime();
588 m_kbps = st.kbps();
591 std::string ps = playerStateToString(m_player_state);
592 std::string tracklength;
594 drawTitle(np);
595 switch (Config.design)
597 case Design::Classic:
598 if (Statusbar::isUnlocked() && Config.statusbar_visibility)
600 if (Config.display_bitrate && m_kbps)
602 tracklength += "(";
603 tracklength += boost::lexical_cast<std::string>(m_kbps);
604 tracklength += " kbps) ";
606 tracklength += "[";
607 if (m_total_time)
609 if (Config.display_remaining_time)
611 tracklength += "-";
612 tracklength += MPD::Song::ShowTime(m_total_time-m_elapsed_time);
614 else
615 tracklength += MPD::Song::ShowTime(m_elapsed_time);
616 tracklength += "/";
617 tracklength += MPD::Song::ShowTime(m_total_time);
619 else
620 tracklength += MPD::Song::ShowTime(m_elapsed_time);
621 tracklength += "]";
622 NC::WBuffer np_song;
623 Format::print(Config.song_status_wformat, np_song, &np);
624 *wFooter << NC::XY(0, 1) << NC::TermManip::ClearToEOL << NC::Format::Bold << ps << ' ' << NC::Format::NoBold;
625 writeCyclicBuffer(np_song, *wFooter, playing_song_scroll_begin, wFooter->getWidth()-ps.length()-tracklength.length()-2, L" ** ");
626 *wFooter << NC::Format::Bold << NC::XY(wFooter->getWidth()-tracklength.length(), 1) << tracklength << NC::Format::NoBold;
628 break;
629 case Design::Alternative:
630 if (Config.display_remaining_time)
632 tracklength = "-";
633 tracklength += MPD::Song::ShowTime(m_total_time-m_elapsed_time);
635 else
636 tracklength = MPD::Song::ShowTime(m_elapsed_time);
637 if (m_total_time)
639 tracklength += "/";
640 tracklength += MPD::Song::ShowTime(m_total_time);
642 // bitrate here doesn't look good, but it can be moved somewhere else later
643 if (Config.display_bitrate && m_kbps)
645 tracklength += " (";
646 tracklength += boost::lexical_cast<std::string>(m_kbps);
647 tracklength += " kbps)";
650 NC::WBuffer first, second;
651 Format::print(Config.new_header_first_line, first, &np);
652 Format::print(Config.new_header_second_line, second, &np);
654 size_t first_len = wideLength(first.str());
655 size_t first_margin = (std::max(tracklength.length()+1, VolumeState.length()))*2;
656 size_t first_start = first_len < COLS-first_margin ? (COLS-first_len)/2 : tracklength.length()+1;
658 size_t second_len = wideLength(second.str());
659 size_t second_margin = (std::max(ps.length(), size_t(8))+1)*2;
660 size_t second_start = second_len < COLS-second_margin ? (COLS-second_len)/2 : ps.length()+1;
662 if (!Global::SeekingInProgress)
663 *wHeader << NC::XY(0, 0) << NC::TermManip::ClearToEOL << tracklength;
664 *wHeader << NC::XY(first_start, 0);
665 writeCyclicBuffer(first, *wHeader, first_line_scroll_begin, COLS-tracklength.length()-VolumeState.length()-1, L" ** ");
667 *wHeader << NC::XY(0, 1) << NC::TermManip::ClearToEOL << NC::Format::Bold << ps << NC::Format::NoBold;
668 *wHeader << NC::XY(second_start, 1);
669 writeCyclicBuffer(second, *wHeader, second_line_scroll_begin, COLS-ps.length()-8-2, L" ** ");
671 *wHeader << NC::XY(wHeader->getWidth()-VolumeState.length(), 0) << Config.volume_color << VolumeState << NC::Color::End;
673 flags();
675 if (Progressbar::isUnlocked())
676 Progressbar::draw(m_elapsed_time, m_total_time);
679 void Status::Changes::flags()
681 if (!Config.header_visibility && Config.design == Design::Classic)
682 return;
684 std::string switch_state;
685 switch (Config.design)
687 case Design::Classic:
688 if (m_repeat)
689 switch_state += m_repeat;
690 if (m_random)
691 switch_state += m_random;
692 if (m_single)
693 switch_state += m_single;
694 if (m_consume)
695 switch_state += m_consume;
696 if (m_crossfade)
697 switch_state += m_crossfade;
698 if (m_db_updating)
699 switch_state += m_db_updating;
701 // this is done by raw ncurses because creating another
702 // window only for handling this is quite silly
703 attrset(A_BOLD);
704 color_set(Config.state_line_color.pairNumber(), nullptr);
705 mvhline(1, 0, 0, COLS);
706 if (!switch_state.empty())
708 mvprintw(1, COLS-switch_state.length()-3, "[");
709 color_set(Config.state_flags_color.pairNumber(), nullptr);
710 mvprintw(1, COLS-switch_state.length()-2, "%s", switch_state.c_str());
711 color_set(Config.state_line_color.pairNumber(), nullptr);
712 mvprintw(1, COLS-2, "]");
714 standend();
715 refresh();
716 break;
717 case Design::Alternative:
718 switch_state += '[';
719 switch_state += m_repeat ? m_repeat : '-';
720 switch_state += m_random ? m_random : '-';
721 switch_state += m_single ? m_single : '-';
722 switch_state += m_consume ? m_consume : '-';
723 switch_state += m_crossfade ? m_crossfade : '-';
724 switch_state += m_db_updating ? m_db_updating : '-';
725 switch_state += ']';
726 *wHeader << NC::XY(COLS-switch_state.length(), 1) << NC::Format::Bold << Config.state_flags_color << switch_state << NC::Color::End << NC::Format::NoBold;
727 if (!Config.header_visibility) // in this case also draw separator
729 *wHeader << NC::Format::Bold << Config.alternative_ui_separator_color;
730 mvwhline(wHeader->raw(), 2, 0, 0, COLS);
731 *wHeader << NC::Color::End << NC::Format::NoBold;
733 wHeader->refresh();
734 break;
738 void Status::Changes::mixer()
740 if (!Config.display_volume_level || (!Config.header_visibility && Config.design == Design::Classic))
741 return;
743 switch (Config.design)
745 case Design::Classic:
746 VolumeState = " Volume: ";
747 break;
748 case Design::Alternative:
749 VolumeState = " Vol: ";
750 break;
752 if (m_volume < 0)
753 VolumeState += "n/a";
754 else
756 VolumeState += boost::lexical_cast<std::string>(m_volume);
757 VolumeState += "%";
759 *wHeader << Config.volume_color;
760 *wHeader << NC::XY(wHeader->getWidth()-VolumeState.length(), 0) << VolumeState;
761 *wHeader << NC::Color::End;
762 wHeader->refresh();
765 void Status::Changes::outputs()
767 # ifdef ENABLE_OUTPUTS
768 myOutputs->fetchList();
769 # endif // ENABLE_OUTPUTS