split PressSpace action into modular pieces
[ncmpcpp.git] / src / status.cpp
blob57de236857c331934bbf948bd104f062b81a6b1e
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 MPD::Song getCurrentSong()
83 MPD::Song result = myPlaylist->nowPlayingSong();
84 // It may happen that playlist wasn't yet updated
85 // and current song is not there yet. In such case
86 // try fetching it from the server.
87 if (result.empty() && m_player_state != MPD::psUnknown)
88 result = Mpd.GetCurrentSong();
89 return result;
92 void drawTitle(const MPD::Song &np)
94 assert(!np.empty());
95 windowTitle(Format::stringify<char>(Config.song_window_title_format, &np));
98 std::string playerStateToString(MPD::PlayerState ps)
100 std::string result;
101 switch (ps)
103 case MPD::psUnknown:
104 switch (Config.design)
106 case Design::Alternative:
107 result = "[unknown]";
108 break;
109 case Design::Classic:
110 break;
112 break;
113 case MPD::psPlay:
114 switch (Config.design)
116 case Design::Alternative:
117 result = "[playing]";
118 break;
119 case Design::Classic:
120 result = "Playing:";
121 break;
123 break;
124 case MPD::psPause:
125 switch (Config.design)
127 case Design::Alternative:
128 result = "[paused]";
129 break;
130 case Design::Classic:
131 result = "Paused:";
132 break;
134 break;
135 case MPD::psStop:
136 switch (Config.design)
138 case Design::Alternative:
139 result = "[stopped]";
140 break;
141 case Design::Classic:
142 break;
144 break;
146 return result;
149 void initialize_status()
151 // get full info about new connection
152 Status::update(-1);
154 if (Config.jump_to_now_playing_song_at_start)
156 int curr_pos = Status::State::currentSongPosition();
157 if (curr_pos >= 0)
159 myPlaylist->main().highlight(curr_pos);
160 if (isVisible(myPlaylist))
161 myPlaylist->refresh();
165 // Set TCP_NODELAY on the tcp socket as we are using write-write-read pattern
166 // a lot (noidle - write, command - write, then read the result of command),
167 // which kills the performance.
168 int flag = 1;
169 setsockopt(Mpd.GetFD(), IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(flag));
171 myBrowser->fetchSupportedExtensions();
172 # ifdef ENABLE_OUTPUTS
173 myOutputs->FetchList();
174 # endif // ENABLE_OUTPUTS
175 # ifdef ENABLE_VISUALIZER
176 myVisualizer->ResetFD();
177 myVisualizer->SetFD();
178 myVisualizer->FindOutputID();
179 # endif // ENABLE_VISUALIZER
181 m_status_initialized = true;
182 wFooter->addFDCallback(Mpd.GetFD(), Statusbar::Helpers::mpd);
183 Statusbar::printf("Connected to %1%", Mpd.GetHostname());
188 /*************************************************************************/
190 void Status::handleClientError(MPD::ClientError &e)
192 if (!e.clearable())
193 Mpd.Disconnect();
194 Statusbar::printf("ncmpcpp: %1%", e.what());
197 void Status::handleServerError(MPD::ServerError &e)
199 Statusbar::printf("MPD: %1%", e.what());
200 if (e.code() == MPD_SERVER_ERROR_PERMISSION)
202 NC::Window::ScopedPromptHook helper(*wFooter, nullptr);
203 Statusbar::put() << "Password: ";
204 Mpd.SetPassword(wFooter->prompt("", -1, true));
205 try {
206 Mpd.SendPassword();
207 Statusbar::print("Password accepted");
208 } catch (MPD::ServerError &e_prim) {
209 handleServerError(e_prim);
214 /*************************************************************************/
216 void Status::trace(bool update_timer, bool update_window_timeout)
218 if (update_timer)
219 Timer = boost::posix_time::microsec_clock::local_time();
220 if (update_window_timeout)
222 // set appropriate window timeout
223 int nc_wtimeout = std::numeric_limits<int>::max();
224 applyToVisibleWindows([&nc_wtimeout](BaseScreen *s) {
225 nc_wtimeout = std::min(nc_wtimeout, s->windowTimeout());
227 wFooter->setTimeout(nc_wtimeout);
229 if (Mpd.Connected())
231 if (!m_status_initialized)
232 initialize_status();
234 if (m_player_state == MPD::psPlay
235 && Global::Timer - past > boost::posix_time::seconds(1))
237 // update elapsed time/bitrate of the current song
238 Status::Changes::elapsedTime(true);
239 wFooter->refresh();
240 past = Timer;
243 applyToVisibleWindows(&BaseScreen::update);
244 Statusbar::tryRedraw();
246 Mpd.idle();
250 void Status::update(int event)
252 auto st = Mpd.getStatus();
253 m_current_song_pos = st.currentSongPosition();
254 m_elapsed_time = st.elapsedTime();
255 m_kbps = st.kbps();
256 m_player_state = st.playerState();
257 m_playlist_length = st.playlistLength();
258 m_total_time = st.totalTime();
259 m_volume = st.volume();
261 if (event & MPD_IDLE_DATABASE)
262 Changes::database();
263 if (event & MPD_IDLE_STORED_PLAYLIST)
264 Changes::storedPlaylists();
265 if (event & MPD_IDLE_PLAYLIST)
267 Changes::playlist(m_playlist_version);
268 m_playlist_version = st.playlistVersion();
270 if (event & MPD_IDLE_PLAYER)
272 Changes::playerState();
273 if (m_current_song_id != st.currentSongID())
275 Changes::songID(st.currentSongID());
276 m_current_song_id = st.currentSongID();
279 if (event & MPD_IDLE_MIXER)
280 Changes::mixer();
281 if (event & MPD_IDLE_OUTPUT)
282 Changes::outputs();
283 if (event & (MPD_IDLE_UPDATE | MPD_IDLE_OPTIONS))
285 if (event & MPD_IDLE_UPDATE)
287 m_db_updating = st.updateID() ? 'U' : 0;
288 if (m_status_initialized)
289 Statusbar::printf("Database update %1%", m_db_updating ? "started" : "finished");
291 if (event & MPD_IDLE_OPTIONS)
293 if (('r' == m_repeat) != st.repeat())
295 m_repeat = st.repeat() ? 'r' : 0;
296 if (m_status_initialized)
297 Statusbar::printf("Repeat mode is %1%", !m_repeat ? "off" : "on");
299 if (('z' == m_random) != st.random())
301 m_random = st.random() ? 'z' : 0;
302 if (m_status_initialized)
303 Statusbar::printf("Random mode is %1%", !m_random ? "off" : "on");
305 if (('s' == m_single) != st.single())
307 m_single = st.single() ? 's' : 0;
308 if (m_status_initialized)
309 Statusbar::printf("Single mode is %1%", !m_single ? "off" : "on");
311 if (('c' == m_consume) != st.consume())
313 m_consume = st.consume() ? 'c' : 0;
314 if (m_status_initialized)
315 Statusbar::printf("Consume mode is %1%", !m_consume ? "off" : "on");
317 if (('x' == m_crossfade) != (st.crossfade() != 0))
319 int crossfade = st.crossfade();
320 m_crossfade = crossfade ? 'x' : 0;
321 if (m_status_initialized)
322 Statusbar::printf("Crossfade set to %1% seconds", crossfade);
325 Changes::flags();
327 m_status_initialized = true;
329 if (event & MPD_IDLE_PLAYER)
330 wFooter->refresh();
332 if (event & (MPD_IDLE_PLAYLIST | MPD_IDLE_DATABASE | MPD_IDLE_PLAYER))
333 applyToVisibleWindows(&BaseScreen::refreshWindow);
336 void Status::clear()
338 // reset local variables
339 m_status_initialized = false;
340 m_repeat = 0;
341 m_random = 0;
342 m_single = 0;
343 m_consume = 0;
344 m_crossfade = 0;
345 m_db_updating = 0;
346 m_current_song_id = -1;
347 m_current_song_pos = -1;
348 m_kbps = 0;
349 m_player_state = MPD::psUnknown;
350 m_playlist_length = 0;
351 m_playlist_version = 0;
352 m_total_time = 0;
353 m_volume = -1;
356 /*************************************************************************/
358 bool Status::State::consume()
360 return m_consume != 0;
363 bool Status::State::crossfade()
365 return m_crossfade != 0;
368 bool Status::State::repeat()
370 return m_repeat != 0;
373 bool Status::State::random()
375 return m_random != 0;
378 bool Status::State::single()
380 return m_single != 0;
383 int Status::State::currentSongID()
385 return m_current_song_id;
388 int Status::State::currentSongPosition()
390 return m_current_song_pos;
393 unsigned Status::State::elapsedTime()
395 return m_elapsed_time;
398 MPD::PlayerState Status::State::player()
400 return m_player_state;
403 unsigned Status::State::totalTime()
405 return m_total_time;
408 int Status::State::volume()
410 return m_volume;
413 /*************************************************************************/
415 void Status::Changes::playlist(unsigned previous_version)
417 if (m_playlist_length < myPlaylist->main().size())
419 auto it = myPlaylist->main().begin()+m_playlist_length;
420 auto end = myPlaylist->main().end();
421 for (; it != end; ++it)
422 myPlaylist->unregisterSong(it->value());
423 myPlaylist->main().resizeList(m_playlist_length);
426 MPD::SongIterator s = Mpd.GetPlaylistChanges(previous_version), end;
427 for (; s != end; ++s)
429 size_t pos = s->getPosition();
430 if (pos < myPlaylist->main().size())
432 // if song's already in playlist, replace it with a new one
433 MPD::Song &old_s = myPlaylist->main()[pos].value();
434 if (old_s != *s)
436 myPlaylist->registerSong(*s);
437 myPlaylist->unregisterSong(old_s);
438 myPlaylist->main()[pos].setSelected(false);
439 old_s = std::move(*s);
442 else // otherwise just add it to playlist
444 myPlaylist->registerSong(*s);
445 myPlaylist->main().addItem(std::move(*s));
449 myPlaylist->reloadTotalLength();
450 myPlaylist->reloadRemaining();
452 if (isVisible(myBrowser))
453 markSongsInPlaylist(myBrowser->main());
454 if (isVisible(mySearcher))
455 markSongsInPlaylist(mySearcher->main());
456 if (isVisible(myLibrary))
458 markSongsInPlaylist(myLibrary->Songs);
459 myLibrary->Songs.refresh();
461 if (isVisible(myPlaylistEditor))
463 markSongsInPlaylist(myPlaylistEditor->Content);
464 myPlaylistEditor->Content.refresh();
468 void Status::Changes::storedPlaylists()
470 myPlaylistEditor->requestPlaylistsUpdate();
471 myPlaylistEditor->requestContentsUpdate();
472 if (!myBrowser->isLocal() && myBrowser->inRootDirectory())
473 myBrowser->requestUpdate();
476 void Status::Changes::database()
478 myBrowser->requestUpdate();
479 # ifdef HAVE_TAGLIB_H
480 myTagEditor->Dirs->clear();
481 # endif // HAVE_TAGLIB_H
482 myLibrary->requestTagsUpdate();
483 myLibrary->requestAlbumsUpdate();
484 myLibrary->requestSongsUpdate();
487 void Status::Changes::playerState()
489 switch (m_player_state)
491 case MPD::psPlay:
492 drawTitle(getCurrentSong());
493 myPlaylist->reloadRemaining();
494 break;
495 case MPD::psStop:
496 windowTitle("ncmpcpp " VERSION);
497 if (Progressbar::isUnlocked())
498 Progressbar::draw(0, 0);
499 myPlaylist->reloadRemaining();
500 if (Config.design == Design::Alternative)
502 *wHeader << NC::XY(0, 0) << NC::TermManip::ClearToEOL;
503 *wHeader << NC::XY(0, 1) << NC::TermManip::ClearToEOL;
504 mixer();
505 flags();
507 # ifdef ENABLE_VISUALIZER
508 if (isVisible(myVisualizer))
509 myVisualizer->main().clear();
510 # endif // ENABLE_VISUALIZER
511 break;
512 default:
513 break;
516 std::string state = playerStateToString(m_player_state);
517 if (Config.design == Design::Alternative)
519 *wHeader << NC::XY(0, 1) << NC::Format::Bold << state << NC::Format::NoBold;
520 wHeader->refresh();
522 else if (Statusbar::isUnlocked() && Config.statusbar_visibility)
524 *wFooter << NC::XY(0, 1);
525 if (state.empty())
526 *wFooter << NC::TermManip::ClearToEOL;
527 else
528 *wFooter << NC::Format::Bold << state << NC::Format::NoBold;
531 // needed for immediate display after starting
532 // player from stopped state or seeking
533 elapsedTime(false);
536 void Status::Changes::songID(int song_id)
538 // update information about current song
539 myPlaylist->reloadRemaining();
540 playing_song_scroll_begin = 0;
541 first_line_scroll_begin = 0;
542 second_line_scroll_begin = 0;
543 if (m_player_state != MPD::psStop)
545 auto &pl = myPlaylist->main();
547 // try to find the song with new id in the playlist
548 auto it = std::find_if(pl.beginV(), pl.endV(), [song_id](const MPD::Song &s) {
549 return s.getID() == unsigned(song_id);
551 // if it's not there (playlist may be outdated), fetch it
552 const auto &s = it != pl.endV() ? *it : Mpd.GetCurrentSong();
554 GNUC_UNUSED int res;
555 if (!Config.execute_on_song_change.empty())
556 res = system(Config.execute_on_song_change.c_str());
558 # ifdef HAVE_CURL_CURL_H
559 if (Config.fetch_lyrics_in_background)
560 Lyrics::DownloadInBackground(s);
561 # endif // HAVE_CURL_CURL_H
563 drawTitle(s);
565 if (Config.autocenter_mode)
566 pl.highlight(Status::State::currentSongPosition());
568 if (Config.now_playing_lyrics && isVisible(myLyrics) && myLyrics->previousScreen() == myPlaylist)
570 if (myLyrics->SetSong(s))
571 myLyrics->Reload = 1;
574 elapsedTime(false);
577 void Status::Changes::elapsedTime(bool update_elapsed)
579 if (update_elapsed)
581 auto st = Mpd.getStatus();
582 m_elapsed_time = st.elapsedTime();
583 m_kbps = st.kbps();
586 if (m_player_state == MPD::psStop)
588 if (Statusbar::isUnlocked() && Config.statusbar_visibility)
589 *wFooter << NC::XY(0, 1) << NC::TermManip::ClearToEOL;
590 return;
593 MPD::Song np = getCurrentSong();
594 std::string ps = playerStateToString(m_player_state);
595 std::string tracklength;
597 drawTitle(np);
598 switch (Config.design)
600 case Design::Classic:
601 if (Statusbar::isUnlocked() && Config.statusbar_visibility)
603 if (Config.display_bitrate && m_kbps)
605 tracklength += "(";
606 tracklength += boost::lexical_cast<std::string>(m_kbps);
607 tracklength += " kbps) ";
609 tracklength += "[";
610 if (m_total_time)
612 if (Config.display_remaining_time)
614 tracklength += "-";
615 tracklength += MPD::Song::ShowTime(m_total_time-m_elapsed_time);
617 else
618 tracklength += MPD::Song::ShowTime(m_elapsed_time);
619 tracklength += "/";
620 tracklength += MPD::Song::ShowTime(m_total_time);
622 else
623 tracklength += MPD::Song::ShowTime(m_elapsed_time);
624 tracklength += "]";
625 NC::WBuffer np_song;
626 Format::print(Config.song_status_wformat, np_song, &np);
627 *wFooter << NC::XY(0, 1) << NC::TermManip::ClearToEOL << NC::Format::Bold << ps << ' ' << NC::Format::NoBold;
628 writeCyclicBuffer(np_song, *wFooter, playing_song_scroll_begin, wFooter->getWidth()-ps.length()-tracklength.length()-2, L" ** ");
629 *wFooter << NC::Format::Bold << NC::XY(wFooter->getWidth()-tracklength.length(), 1) << tracklength << NC::Format::NoBold;
631 break;
632 case Design::Alternative:
633 if (Config.display_remaining_time)
635 tracklength = "-";
636 tracklength += MPD::Song::ShowTime(m_total_time-m_elapsed_time);
638 else
639 tracklength = MPD::Song::ShowTime(m_elapsed_time);
640 if (m_total_time)
642 tracklength += "/";
643 tracklength += MPD::Song::ShowTime(m_total_time);
645 // bitrate here doesn't look good, but it can be moved somewhere else later
646 if (Config.display_bitrate && m_kbps)
648 tracklength += " (";
649 tracklength += boost::lexical_cast<std::string>(m_kbps);
650 tracklength += " kbps)";
653 NC::WBuffer first, second;
654 Format::print(Config.new_header_first_line, first, &np);
655 Format::print(Config.new_header_second_line, second, &np);
657 size_t first_len = wideLength(first.str());
658 size_t first_margin = (std::max(tracklength.length()+1, VolumeState.length()))*2;
659 size_t first_start = first_len < COLS-first_margin ? (COLS-first_len)/2 : tracklength.length()+1;
661 size_t second_len = wideLength(second.str());
662 size_t second_margin = (std::max(ps.length(), size_t(8))+1)*2;
663 size_t second_start = second_len < COLS-second_margin ? (COLS-second_len)/2 : ps.length()+1;
665 if (!Global::SeekingInProgress)
666 *wHeader << NC::XY(0, 0) << NC::TermManip::ClearToEOL << tracklength;
667 *wHeader << NC::XY(first_start, 0);
668 writeCyclicBuffer(first, *wHeader, first_line_scroll_begin, COLS-tracklength.length()-VolumeState.length()-1, L" ** ");
670 *wHeader << NC::XY(0, 1) << NC::TermManip::ClearToEOL << NC::Format::Bold << ps << NC::Format::NoBold;
671 *wHeader << NC::XY(second_start, 1);
672 writeCyclicBuffer(second, *wHeader, second_line_scroll_begin, COLS-ps.length()-8-2, L" ** ");
674 *wHeader << NC::XY(wHeader->getWidth()-VolumeState.length(), 0) << Config.volume_color << VolumeState << NC::Color::End;
676 flags();
678 if (Progressbar::isUnlocked())
679 Progressbar::draw(m_elapsed_time, m_total_time);
682 void Status::Changes::flags()
684 if (!Config.header_visibility && Config.design == Design::Classic)
685 return;
687 std::string switch_state;
688 switch (Config.design)
690 case Design::Classic:
691 if (m_repeat)
692 switch_state += m_repeat;
693 if (m_random)
694 switch_state += m_random;
695 if (m_single)
696 switch_state += m_single;
697 if (m_consume)
698 switch_state += m_consume;
699 if (m_crossfade)
700 switch_state += m_crossfade;
701 if (m_db_updating)
702 switch_state += m_db_updating;
704 // this is done by raw ncurses because creating another
705 // window only for handling this is quite silly
706 attrset(A_BOLD);
707 color_set(Config.state_line_color.pairNumber(), nullptr);
708 mvhline(1, 0, 0, COLS);
709 if (!switch_state.empty())
711 mvprintw(1, COLS-switch_state.length()-3, "[");
712 color_set(Config.state_flags_color.pairNumber(), nullptr);
713 mvprintw(1, COLS-switch_state.length()-2, "%s", switch_state.c_str());
714 color_set(Config.state_line_color.pairNumber(), nullptr);
715 mvprintw(1, COLS-2, "]");
717 standend();
718 refresh();
719 break;
720 case Design::Alternative:
721 switch_state += '[';
722 switch_state += m_repeat ? m_repeat : '-';
723 switch_state += m_random ? m_random : '-';
724 switch_state += m_single ? m_single : '-';
725 switch_state += m_consume ? m_consume : '-';
726 switch_state += m_crossfade ? m_crossfade : '-';
727 switch_state += m_db_updating ? m_db_updating : '-';
728 switch_state += ']';
729 *wHeader << NC::XY(COLS-switch_state.length(), 1) << NC::Format::Bold << Config.state_flags_color << switch_state << NC::Color::End << NC::Format::NoBold;
730 if (!Config.header_visibility) // in this case also draw separator
732 *wHeader << NC::Format::Bold << NC::Color::Black;
733 mvwhline(wHeader->raw(), 2, 0, 0, COLS);
734 *wHeader << NC::Color::End << NC::Format::NoBold;
736 wHeader->refresh();
737 break;
741 void Status::Changes::mixer()
743 if (!Config.display_volume_level || (!Config.header_visibility && Config.design == Design::Classic))
744 return;
746 switch (Config.design)
748 case Design::Classic:
749 VolumeState = " Volume: ";
750 break;
751 case Design::Alternative:
752 VolumeState = " Vol: ";
753 break;
755 if (m_volume < 0)
756 VolumeState += "n/a";
757 else
759 VolumeState += boost::lexical_cast<std::string>(m_volume);
760 VolumeState += "%";
762 *wHeader << Config.volume_color;
763 *wHeader << NC::XY(wHeader->getWidth()-VolumeState.length(), 0) << VolumeState;
764 *wHeader << NC::Color::End;
765 wHeader->refresh();
768 void Status::Changes::outputs()
770 # ifdef ENABLE_OUTPUTS
771 myOutputs->FetchList();
772 # endif // ENABLE_OUTPUTS