1 /***************************************************************************
2 * Copyright (C) 2008-2017 by Andrzej Rybczak *
3 * electricityispower@gmail.com *
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. *
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. *
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"
28 #include "format_impl.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"
40 #include "statusbar.h"
41 #include "screens/tag_editor.h"
42 #include "screens/visualizer.h"
44 #include "utility/string.h"
46 using Global::myScreen
;
48 using Global::wFooter
;
49 using Global::wHeader
;
52 using Global::VolumeState
;
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
;
71 int m_current_song_id
;
72 int m_current_song_pos
;
73 unsigned m_elapsed_time
;
75 MPD::PlayerState m_player_state
;
76 unsigned m_playlist_version
;
77 unsigned m_playlist_length
;
78 unsigned m_total_time
;
81 void drawTitle(const MPD::Song
&np
)
84 windowTitle(Format::stringify
<char>(Config
.song_window_title_format
, &np
));
87 std::string
playerStateToString(MPD::PlayerState ps
)
93 switch (Config
.design
)
95 case Design::Alternative
:
103 switch (Config
.design
)
105 case Design::Alternative
:
106 result
= "[playing]";
108 case Design::Classic
:
114 switch (Config
.design
)
116 case Design::Alternative
:
119 case Design::Classic
:
125 switch (Config
.design
)
127 case Design::Alternative
:
128 result
= "[stopped]";
130 case Design::Classic
:
138 void initialize_status()
140 // get full info about new connection
143 if (Config
.jump_to_now_playing_song_at_start
)
145 int curr_pos
= Status::State::currentSongPosition();
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.
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
)
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));
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
)
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
);
220 if (!m_status_initialized
)
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);
232 applyToVisibleWindows(&BaseScreen::update
);
233 Statusbar::tryRedraw();
239 void Status::update(int event
)
241 auto st
= Mpd
.getStatus();
242 m_current_song_pos
= st
.currentSongPosition();
243 m_elapsed_time
= st
.elapsedTime();
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
)
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
)
270 if (event
& MPD_IDLE_OUTPUT
)
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
);
316 m_status_initialized
= true;
318 if (event
& MPD_IDLE_PLAYER
)
321 if (event
& (MPD_IDLE_PLAYLIST
| MPD_IDLE_DATABASE
| MPD_IDLE_PLAYER
))
322 applyToVisibleWindows(&BaseScreen::refreshWindow
);
327 // reset local variables
328 m_status_initialized
= false;
335 m_current_song_id
= -1;
336 m_current_song_pos
= -1;
338 m_player_state
= MPD::psUnknown
;
339 m_playlist_length
= 0;
340 m_playlist_version
= 0;
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()
402 int Status::State::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();
443 // When we're in multi-column screens, it might happen that songs visible on
444 // the screen are added, but they will not be immediately marked as such
445 // because the window that contains them is not the active one at the moment,
446 // so we need to refresh them manually.
447 if (isVisible(myLibrary
)
448 && !myLibrary
->isActiveWindow(myLibrary
->Songs
))
449 myLibrary
->Songs
.refresh();
450 if (isVisible(myPlaylistEditor
)
451 && !myPlaylistEditor
->isActiveWindow(myPlaylistEditor
->Content
))
452 myPlaylistEditor
->Content
.refresh();
455 void Status::Changes::storedPlaylists()
457 myPlaylistEditor
->requestPlaylistsUpdate();
458 myPlaylistEditor
->requestContentUpdate();
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 if (!Config
.execute_on_player_state_change
.empty())
478 auto stateToEnv
= [](MPD::PlayerState st
) -> const char * {
481 case MPD::psPlay
: return "play";
482 case MPD::psStop
: return "stop";
483 case MPD::psPause
: return "pause";
484 case MPD::psUnknown
: return "unknown";
486 throw std::logic_error("unreachable");
489 setenv("MPD_PLAYER_STATE", stateToEnv(m_player_state
), 1);
490 res
= system(Config
.execute_on_player_state_change
.c_str());
491 unsetenv("MPD_PLAYER_STATE");
494 switch (m_player_state
)
498 auto np
= myPlaylist
->nowPlayingSong();
501 myPlaylist
->reloadRemaining();
505 windowTitle("ncmpcpp " VERSION
);
506 if (Progressbar::isUnlocked())
507 Progressbar::draw(0, 0);
508 myPlaylist
->reloadRemaining();
509 if (Config
.design
== Design::Alternative
)
511 *wHeader
<< NC::XY(0, 0) << NC::TermManip::ClearToEOL
;
512 *wHeader
<< NC::XY(0, 1) << NC::TermManip::ClearToEOL
;
516 # ifdef ENABLE_VISUALIZER
517 if (isVisible(myVisualizer
))
518 myVisualizer
->main().clear();
519 # endif // ENABLE_VISUALIZER
525 std::string state
= playerStateToString(m_player_state
);
526 if (Config
.design
== Design::Alternative
)
528 *wHeader
<< NC::XY(0, 1) << NC::Format::Bold
<< state
<< NC::Format::NoBold
;
531 else if (Statusbar::isUnlocked() && Config
.statusbar_visibility
)
533 *wFooter
<< NC::XY(0, 1);
535 *wFooter
<< NC::TermManip::ClearToEOL
;
537 *wFooter
<< NC::Format::Bold
<< state
<< NC::Format::NoBold
;
540 // needed for immediate display after starting
541 // player from stopped state or seeking
545 void Status::Changes::songID(int song_id
)
547 // update information about current song
548 myPlaylist
->reloadRemaining();
549 playing_song_scroll_begin
= 0;
550 first_line_scroll_begin
= 0;
551 second_line_scroll_begin
= 0;
552 # ifdef ENABLE_VISUALIZER
553 myVisualizer
->ResetAutoScaleMultiplier();
554 # endif // ENABLE_VISUALIZER
555 if (m_player_state
!= MPD::psStop
)
557 auto &pl
= myPlaylist
->main();
559 // try to find the song with new id in the playlist
560 auto it
= std::find_if(pl
.beginV(), pl
.endV(), [song_id
](const MPD::Song
&s
) {
561 return s
.getID() == unsigned(song_id
);
563 // if it's not there (playlist may be outdated), fetch it
564 const auto &s
= it
!= pl
.endV() ? *it
: Mpd
.GetCurrentSong();
568 if (!Config
.execute_on_song_change
.empty())
569 res
= system(Config
.execute_on_song_change
.c_str());
571 if (Config
.fetch_lyrics_in_background
)
572 myLyrics
->fetchInBackground(s
, false);
576 if (Config
.autocenter_mode
)
577 myPlaylist
->locateSong(s
);
579 if (Config
.now_playing_lyrics
580 && isVisible(myLyrics
)
581 && myLyrics
->previousScreen() == myPlaylist
)
588 void Status::Changes::elapsedTime(bool update_elapsed
)
590 auto np
= myPlaylist
->nowPlayingSong();
591 if (m_player_state
== MPD::psStop
|| np
.empty())
593 // MPD is not playing, clear statusbar and exit.
594 if (Statusbar::isUnlocked() && Config
.statusbar_visibility
)
595 *wFooter
<< NC::XY(0, 1)
596 << NC::TermManip::ClearToEOL
;
597 if (Progressbar::isUnlocked())
598 Progressbar::draw(0, 0);
604 auto st
= Mpd
.getStatus();
605 m_elapsed_time
= st
.elapsedTime();
609 std::string ps
= playerStateToString(m_player_state
);
610 std::string tracklength
;
613 switch (Config
.design
)
615 case Design::Classic
:
616 if (Statusbar::isUnlocked() && Config
.statusbar_visibility
)
618 if (Config
.display_bitrate
&& m_kbps
)
621 tracklength
+= boost::lexical_cast
<std::string
>(m_kbps
);
622 tracklength
+= " kbps) ";
627 if (Config
.display_remaining_time
)
630 tracklength
+= MPD::Song::ShowTime(m_total_time
-m_elapsed_time
);
633 tracklength
+= MPD::Song::ShowTime(m_elapsed_time
);
635 tracklength
+= MPD::Song::ShowTime(m_total_time
);
638 tracklength
+= MPD::Song::ShowTime(m_elapsed_time
);
641 Format::print(Config
.song_status_wformat
, np_song
, &np
);
642 *wFooter
<< NC::XY(0, 1)
643 << NC::TermManip::ClearToEOL
644 << Config
.player_state_color
646 << NC::FormattedColor::End
<>(Config
.player_state_color
)
649 np_song
, *wFooter
, playing_song_scroll_begin
,
650 wFooter
->getWidth()-ps
.length()-tracklength
.length()-2, L
" ** ");
651 *wFooter
<< NC::XY(wFooter
->getWidth()-tracklength
.length(), 1)
652 << Config
.statusbar_time_color
654 << NC::FormattedColor::End
<>(Config
.statusbar_time_color
);
657 case Design::Alternative
:
658 if (Config
.display_remaining_time
)
661 tracklength
+= MPD::Song::ShowTime(m_total_time
-m_elapsed_time
);
664 tracklength
= MPD::Song::ShowTime(m_elapsed_time
);
668 tracklength
+= MPD::Song::ShowTime(m_total_time
);
670 // bitrate here doesn't look good, but it can be moved somewhere else later
671 if (Config
.display_bitrate
&& m_kbps
)
674 tracklength
+= boost::lexical_cast
<std::string
>(m_kbps
);
675 tracklength
+= " kbps)";
678 NC::WBuffer first
, second
;
679 Format::print(Config
.new_header_first_line
, first
, &np
);
680 Format::print(Config
.new_header_second_line
, second
, &np
);
682 size_t first_len
= wideLength(first
.str());
683 size_t first_margin
= std::max(tracklength
.length()+1, VolumeState
.length())*2;
684 size_t first_start
= first_len
< COLS
-first_margin
686 : tracklength
.length()+1;
687 size_t second_len
= wideLength(second
.str());
688 size_t second_margin
= (std::max(ps
.length(), size_t(8))+1)*2;
689 size_t second_start
= second_len
< COLS
-second_margin
690 ? (COLS
-second_len
)/2
692 if (!Global::SeekingInProgress
)
693 *wHeader
<< NC::XY(0, 0)
694 << NC::TermManip::ClearToEOL
695 << Config
.statusbar_time_color
697 << NC::FormattedColor::End
<>(Config
.statusbar_time_color
);
699 *wHeader
<< NC::XY(first_start
, 0);
701 writeCyclicBuffer(first
, *wHeader
, first_line_scroll_begin
,
702 COLS
-tracklength
.length()-VolumeState
.length()-1, L
" ** ");
704 *wHeader
<< NC::XY(0, 1)
705 << NC::TermManip::ClearToEOL
706 << Config
.player_state_color
708 << NC::FormattedColor::End
<>(Config
.player_state_color
)
709 << NC::XY(second_start
, 1);
711 writeCyclicBuffer(second
, *wHeader
, second_line_scroll_begin
,
712 COLS
-ps
.length()-8-2, L
" ** ");
714 *wHeader
<< NC::XY(wHeader
->getWidth()-VolumeState
.length(), 0)
715 << Config
.volume_color
717 << NC::FormattedColor::End
<>(Config
.volume_color
);
721 if (Progressbar::isUnlocked())
722 Progressbar::draw(m_elapsed_time
, m_total_time
);
725 void Status::Changes::flags()
727 if (!Config
.header_visibility
&& Config
.design
== Design::Classic
)
730 std::string switch_state
;
731 switch (Config
.design
)
733 case Design::Classic
:
735 switch_state
+= m_repeat
;
737 switch_state
+= m_random
;
739 switch_state
+= m_single
;
741 switch_state
+= m_consume
;
743 switch_state
+= m_crossfade
;
745 switch_state
+= m_db_updating
;
747 *wHeader
<< Config
.state_line_color
;
748 mvwhline(wHeader
->raw(), 1, 0, 0, COLS
);
749 *wHeader
<< NC::FormattedColor::End
<>(Config
.state_line_color
);
751 if (!switch_state
.empty())
752 *wHeader
<< NC::XY(COLS
-switch_state
.length()-3, 1)
753 << Config
.state_line_color
755 << NC::FormattedColor::End
<>(Config
.state_line_color
)
756 << Config
.state_flags_color
758 << NC::FormattedColor::End
<>(Config
.state_flags_color
)
759 << Config
.state_line_color
761 << NC::FormattedColor::End
<>(Config
.state_line_color
);
764 case Design::Alternative
:
766 switch_state
+= m_repeat
? m_repeat
: '-';
767 switch_state
+= m_random
? m_random
: '-';
768 switch_state
+= m_single
? m_single
: '-';
769 switch_state
+= m_consume
? m_consume
: '-';
770 switch_state
+= m_crossfade
? m_crossfade
: '-';
771 switch_state
+= m_db_updating
? m_db_updating
: '-';
773 *wHeader
<< NC::XY(COLS
-switch_state
.length(), 1)
774 << Config
.state_flags_color
776 << NC::FormattedColor::End
<>(Config
.state_flags_color
);
777 if (!Config
.header_visibility
) // in this case also draw separator
779 *wHeader
<< Config
.alternative_ui_separator_color
;
780 mvwhline(wHeader
->raw(), 2, 0, 0, COLS
);
781 *wHeader
<< NC::FormattedColor::End
<>(Config
.alternative_ui_separator_color
);
788 void Status::Changes::mixer()
790 if (!Config
.display_volume_level
791 || (!Config
.header_visibility
&& Config
.design
== Design::Classic
))
794 switch (Config
.design
)
796 case Design::Classic
:
797 VolumeState
= " Volume: ";
799 case Design::Alternative
:
800 VolumeState
= " Vol: ";
804 VolumeState
+= "n/a";
807 VolumeState
+= boost::lexical_cast
<std::string
>(m_volume
);
810 *wHeader
<< NC::XY(wHeader
->getWidth()-VolumeState
.length(), 0)
811 << Config
.volume_color
813 << NC::FormattedColor::End
<>(Config
.volume_color
);
817 void Status::Changes::outputs()
819 # ifdef ENABLE_OUTPUTS
820 myOutputs
->fetchList();
821 if (isVisible(myOutputs
))
822 myOutputs
->refreshWindow();
823 # endif // ENABLE_OUTPUTS