Config: reformat all descriptions to fill 80 columns
[ncmpcpp.git] / src / status.cpp
blobbf0bc58da182e9afc9a50d3842c8323a84e8aee3
1 /***************************************************************************
2 * Copyright (C) 2008-2017 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 "curses/menu_impl.h"
26 #include "screens/browser.h"
27 #include "charset.h"
28 #include "format_impl.h"
29 #include "global.h"
30 #include "helpers.h"
31 #include "screens/lyrics.h"
32 #include "screens/media_library.h"
33 #include "screens/outputs.h"
34 #include "screens/playlist.h"
35 #include "screens/playlist_editor.h"
36 #include "screens/search_engine.h"
37 #include "screens/sel_items_adder.h"
38 #include "settings.h"
39 #include "status.h"
40 #include "statusbar.h"
41 #include "screens/tag_editor.h"
42 #include "screens/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)
412 ScopedUnfilteredMenu<MPD::Song> sunfilter(ReapplyFilter::Yes, myPlaylist->main());
414 if (m_playlist_length < myPlaylist->main().size())
416 auto it = myPlaylist->main().begin()+m_playlist_length;
417 auto end = myPlaylist->main().end();
418 for (; it != end; ++it)
419 myPlaylist->unregisterSong(it->value());
420 myPlaylist->main().resizeList(m_playlist_length);
423 MPD::SongIterator s = Mpd.GetPlaylistChanges(previous_version), end;
424 for (; s != end; ++s)
426 size_t pos = s->getPosition();
427 myPlaylist->registerSong(*s);
428 if (pos < myPlaylist->main().size())
430 // if song's already in playlist, replace it with a new one
431 MPD::Song &old_s = myPlaylist->main()[pos].value();
432 myPlaylist->unregisterSong(old_s);
433 old_s = std::move(*s);
435 else // otherwise just add it to playlist
436 myPlaylist->main().addItem(std::move(*s));
440 myPlaylist->reloadTotalLength();
441 myPlaylist->reloadRemaining();
444 void Status::Changes::storedPlaylists()
446 myPlaylistEditor->requestPlaylistsUpdate();
447 myPlaylistEditor->requestContentUpdate();
448 if (!myBrowser->isLocal() && myBrowser->inRootDirectory())
449 myBrowser->requestUpdate();
452 void Status::Changes::database()
454 myBrowser->requestUpdate();
455 # ifdef HAVE_TAGLIB_H
456 myTagEditor->Dirs->clear();
457 # endif // HAVE_TAGLIB_H
458 myLibrary->requestTagsUpdate();
459 myLibrary->requestAlbumsUpdate();
460 myLibrary->requestSongsUpdate();
463 void Status::Changes::playerState()
465 if (!Config.execute_on_player_state_change.empty())
467 auto stateToEnv = [](MPD::PlayerState st) -> const char * {
468 switch (st)
470 case MPD::psPlay: return "play";
471 case MPD::psStop: return "stop";
472 case MPD::psPause: return "pause";
473 case MPD::psUnknown: return "unknown";
475 throw std::logic_error("unreachable");
477 GNUC_UNUSED int res;
478 setenv("MPD_PLAYER_STATE", stateToEnv(m_player_state), 1);
479 res = system(Config.execute_on_player_state_change.c_str());
480 unsetenv("MPD_PLAYER_STATE");
483 switch (m_player_state)
485 case MPD::psPlay:
487 auto np = myPlaylist->nowPlayingSong();
488 if (!np.empty())
489 drawTitle(np);
490 myPlaylist->reloadRemaining();
491 break;
493 case MPD::psStop:
494 windowTitle("ncmpcpp " VERSION);
495 if (Progressbar::isUnlocked())
496 Progressbar::draw(0, 0);
497 myPlaylist->reloadRemaining();
498 if (Config.design == Design::Alternative)
500 *wHeader << NC::XY(0, 0) << NC::TermManip::ClearToEOL;
501 *wHeader << NC::XY(0, 1) << NC::TermManip::ClearToEOL;
502 mixer();
503 flags();
505 # ifdef ENABLE_VISUALIZER
506 if (isVisible(myVisualizer))
507 myVisualizer->main().clear();
508 # endif // ENABLE_VISUALIZER
509 break;
510 default:
511 break;
514 std::string state = playerStateToString(m_player_state);
515 if (Config.design == Design::Alternative)
517 *wHeader << NC::XY(0, 1) << NC::Format::Bold << state << NC::Format::NoBold;
518 wHeader->refresh();
520 else if (Statusbar::isUnlocked() && Config.statusbar_visibility)
522 *wFooter << NC::XY(0, 1);
523 if (state.empty())
524 *wFooter << NC::TermManip::ClearToEOL;
525 else
526 *wFooter << NC::Format::Bold << state << NC::Format::NoBold;
529 // needed for immediate display after starting
530 // player from stopped state or seeking
531 elapsedTime(false);
534 void Status::Changes::songID(int song_id)
536 // update information about current song
537 myPlaylist->reloadRemaining();
538 playing_song_scroll_begin = 0;
539 first_line_scroll_begin = 0;
540 second_line_scroll_begin = 0;
541 # ifdef ENABLE_VISUALIZER
542 myVisualizer->ResetAutoScaleMultiplier();
543 # endif // ENABLE_VISUALIZER
544 if (m_player_state != MPD::psStop)
546 auto &pl = myPlaylist->main();
548 // try to find the song with new id in the playlist
549 auto it = std::find_if(pl.beginV(), pl.endV(), [song_id](const MPD::Song &s) {
550 return s.getID() == unsigned(song_id);
552 // if it's not there (playlist may be outdated), fetch it
553 const auto &s = it != pl.endV() ? *it : Mpd.GetCurrentSong();
554 if (!s.empty())
556 GNUC_UNUSED int res;
557 if (!Config.execute_on_song_change.empty())
558 res = system(Config.execute_on_song_change.c_str());
560 if (Config.fetch_lyrics_in_background)
561 myLyrics->fetchInBackground(s, false);
563 drawTitle(s);
565 if (Config.autocenter_mode)
566 myPlaylist->locateSong(s);
568 if (Config.now_playing_lyrics
569 && isVisible(myLyrics)
570 && myLyrics->previousScreen() == myPlaylist)
571 myLyrics->fetch(s);
574 elapsedTime(false);
577 void Status::Changes::elapsedTime(bool update_elapsed)
579 auto np = myPlaylist->nowPlayingSong();
580 if (m_player_state == MPD::psStop || np.empty())
582 // MPD is not playing, clear statusbar and exit.
583 if (Statusbar::isUnlocked() && Config.statusbar_visibility)
584 *wFooter << NC::XY(0, 1)
585 << NC::TermManip::ClearToEOL;
586 return;
589 if (update_elapsed)
591 auto st = Mpd.getStatus();
592 m_elapsed_time = st.elapsedTime();
593 m_kbps = st.kbps();
596 std::string ps = playerStateToString(m_player_state);
597 std::string tracklength;
599 drawTitle(np);
600 switch (Config.design)
602 case Design::Classic:
603 if (Statusbar::isUnlocked() && Config.statusbar_visibility)
605 if (Config.display_bitrate && m_kbps)
607 tracklength += "(";
608 tracklength += boost::lexical_cast<std::string>(m_kbps);
609 tracklength += " kbps) ";
611 tracklength += "[";
612 if (m_total_time)
614 if (Config.display_remaining_time)
616 tracklength += "-";
617 tracklength += MPD::Song::ShowTime(m_total_time-m_elapsed_time);
619 else
620 tracklength += MPD::Song::ShowTime(m_elapsed_time);
621 tracklength += "/";
622 tracklength += MPD::Song::ShowTime(m_total_time);
624 else
625 tracklength += MPD::Song::ShowTime(m_elapsed_time);
626 tracklength += "]";
627 NC::WBuffer np_song;
628 Format::print(Config.song_status_wformat, np_song, &np);
629 *wFooter << NC::XY(0, 1)
630 << NC::TermManip::ClearToEOL
631 << Config.player_state_color
632 << ps
633 << NC::FormattedColor::End(Config.player_state_color)
634 << " ";
635 writeCyclicBuffer(
636 np_song, *wFooter, playing_song_scroll_begin,
637 wFooter->getWidth()-ps.length()-tracklength.length()-2, L" ** ");
638 *wFooter << NC::XY(wFooter->getWidth()-tracklength.length(), 1)
639 << Config.statusbar_time_color
640 << tracklength
641 << NC::FormattedColor::End(Config.statusbar_time_color);
643 break;
644 case Design::Alternative:
645 if (Config.display_remaining_time)
647 tracklength = "-";
648 tracklength += MPD::Song::ShowTime(m_total_time-m_elapsed_time);
650 else
651 tracklength = MPD::Song::ShowTime(m_elapsed_time);
652 if (m_total_time)
654 tracklength += "/";
655 tracklength += MPD::Song::ShowTime(m_total_time);
657 // bitrate here doesn't look good, but it can be moved somewhere else later
658 if (Config.display_bitrate && m_kbps)
660 tracklength += " (";
661 tracklength += boost::lexical_cast<std::string>(m_kbps);
662 tracklength += " kbps)";
665 NC::WBuffer first, second;
666 Format::print(Config.new_header_first_line, first, &np);
667 Format::print(Config.new_header_second_line, second, &np);
669 size_t first_len = wideLength(first.str());
670 size_t first_margin = std::max(tracklength.length()+1, VolumeState.length())*2;
671 size_t first_start = first_len < COLS-first_margin
672 ? (COLS-first_len)/2
673 : tracklength.length()+1;
674 size_t second_len = wideLength(second.str());
675 size_t second_margin = (std::max(ps.length(), size_t(8))+1)*2;
676 size_t second_start = second_len < COLS-second_margin
677 ? (COLS-second_len)/2
678 : ps.length()+1;
679 if (!Global::SeekingInProgress)
680 *wHeader << NC::XY(0, 0)
681 << NC::TermManip::ClearToEOL
682 << Config.statusbar_time_color
683 << tracklength
684 << NC::FormattedColor::End(Config.statusbar_time_color);
686 *wHeader << NC::XY(first_start, 0);
688 writeCyclicBuffer(first, *wHeader, first_line_scroll_begin,
689 COLS-tracklength.length()-VolumeState.length()-1, L" ** ");
691 *wHeader << NC::XY(0, 1)
692 << NC::TermManip::ClearToEOL
693 << Config.player_state_color
694 << ps
695 << NC::FormattedColor::End(Config.player_state_color)
696 << NC::XY(second_start, 1);
698 writeCyclicBuffer(second, *wHeader, second_line_scroll_begin,
699 COLS-ps.length()-8-2, L" ** ");
701 *wHeader << NC::XY(wHeader->getWidth()-VolumeState.length(), 0)
702 << Config.volume_color
703 << VolumeState
704 << NC::FormattedColor::End(Config.volume_color);
706 flags();
708 if (Progressbar::isUnlocked())
709 Progressbar::draw(m_elapsed_time, m_total_time);
712 void Status::Changes::flags()
714 if (!Config.header_visibility && Config.design == Design::Classic)
715 return;
717 std::string switch_state;
718 switch (Config.design)
720 case Design::Classic:
721 if (m_repeat)
722 switch_state += m_repeat;
723 if (m_random)
724 switch_state += m_random;
725 if (m_single)
726 switch_state += m_single;
727 if (m_consume)
728 switch_state += m_consume;
729 if (m_crossfade)
730 switch_state += m_crossfade;
731 if (m_db_updating)
732 switch_state += m_db_updating;
734 *wHeader << Config.state_line_color;
735 mvwhline(wHeader->raw(), 1, 0, 0, COLS);
736 *wHeader << NC::FormattedColor::End(Config.state_line_color);
738 if (!switch_state.empty())
739 *wHeader << NC::XY(COLS-switch_state.length()-3, 1)
740 << Config.state_line_color
741 << "["
742 << NC::FormattedColor::End(Config.state_line_color)
743 << Config.state_flags_color
744 << switch_state
745 << NC::FormattedColor::End(Config.state_flags_color)
746 << Config.state_line_color
747 << "]"
748 << NC::FormattedColor::End(Config.state_line_color);
750 break;
751 case Design::Alternative:
752 switch_state += '[';
753 switch_state += m_repeat ? m_repeat : '-';
754 switch_state += m_random ? m_random : '-';
755 switch_state += m_single ? m_single : '-';
756 switch_state += m_consume ? m_consume : '-';
757 switch_state += m_crossfade ? m_crossfade : '-';
758 switch_state += m_db_updating ? m_db_updating : '-';
759 switch_state += ']';
760 *wHeader << NC::XY(COLS-switch_state.length(), 1)
761 << Config.state_flags_color
762 << switch_state
763 << NC::FormattedColor::End(Config.state_flags_color);
764 if (!Config.header_visibility) // in this case also draw separator
766 *wHeader << Config.alternative_ui_separator_color;
767 mvwhline(wHeader->raw(), 2, 0, 0, COLS);
768 *wHeader << NC::FormattedColor::End(Config.alternative_ui_separator_color);
770 break;
772 wHeader->refresh();
775 void Status::Changes::mixer()
777 if (!Config.display_volume_level
778 || (!Config.header_visibility && Config.design == Design::Classic))
779 return;
781 switch (Config.design)
783 case Design::Classic:
784 VolumeState = " Volume: ";
785 break;
786 case Design::Alternative:
787 VolumeState = " Vol: ";
788 break;
790 if (m_volume < 0)
791 VolumeState += "n/a";
792 else
794 VolumeState += boost::lexical_cast<std::string>(m_volume);
795 VolumeState += "%";
797 *wHeader << NC::XY(wHeader->getWidth()-VolumeState.length(), 0)
798 << Config.volume_color
799 << VolumeState
800 << NC::FormattedColor::End(Config.volume_color);
801 wHeader->refresh();
804 void Status::Changes::outputs()
806 # ifdef ENABLE_OUTPUTS
807 myOutputs->fetchList();
808 if (isVisible(myOutputs))
809 myOutputs->refreshWindow();
810 # endif // ENABLE_OUTPUTS