1 /***************************************************************************
2 * Copyright (C) 2008-2014 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>
27 #include "format_impl.h"
31 #include "media_library.h"
32 #include "menu_impl.h"
35 #include "playlist_editor.h"
36 #include "search_engine.h"
37 #include "sel_items_adder.h"
40 #include "statusbar.h"
41 #include "tag_editor.h"
42 #include "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 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();
92 void drawTitle(const MPD::Song
&np
)
95 windowTitle(Format::stringify
<char>(Config
.song_window_title_format
, &np
));
98 std::string
playerStateToString(MPD::PlayerState ps
)
104 switch (Config
.design
)
106 case Design::Alternative
:
107 result
= "[unknown]";
109 case Design::Classic
:
114 switch (Config
.design
)
116 case Design::Alternative
:
117 result
= "[playing]";
119 case Design::Classic
:
125 switch (Config
.design
)
127 case Design::Alternative
:
130 case Design::Classic
:
136 switch (Config
.design
)
138 case Design::Alternative
:
139 result
= "[stopped]";
141 case Design::Classic
:
149 void initialize_status()
151 // get full info about new connection
154 if (Config
.jump_to_now_playing_song_at_start
)
156 int curr_pos
= Status::State::currentSongPosition();
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.
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
)
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));
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
)
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
);
231 if (!m_status_initialized
)
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);
243 applyToVisibleWindows(&BaseScreen::update
);
244 Statusbar::tryRedraw();
250 void Status::update(int event
)
252 auto st
= Mpd
.getStatus();
253 m_current_song_pos
= st
.currentSongPosition();
254 m_elapsed_time
= st
.elapsedTime();
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
)
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
)
281 if (event
& MPD_IDLE_OUTPUT
)
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
);
327 m_status_initialized
= true;
329 if (event
& MPD_IDLE_PLAYER
)
332 if (event
& (MPD_IDLE_PLAYLIST
| MPD_IDLE_DATABASE
| MPD_IDLE_PLAYER
))
333 applyToVisibleWindows(&BaseScreen::refreshWindow
);
338 // reset local variables
339 m_status_initialized
= false;
346 m_current_song_id
= -1;
347 m_current_song_pos
= -1;
349 m_player_state
= MPD::psUnknown
;
350 m_playlist_length
= 0;
351 m_playlist_version
= 0;
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()
408 int Status::State::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();
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
)
492 drawTitle(getCurrentSong());
493 myPlaylist
->reloadRemaining();
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
;
507 # ifdef ENABLE_VISUALIZER
508 if (isVisible(myVisualizer
))
509 myVisualizer
->main().clear();
510 # endif // ENABLE_VISUALIZER
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
;
522 else if (Statusbar::isUnlocked() && Config
.statusbar_visibility
)
524 *wFooter
<< NC::XY(0, 1);
526 *wFooter
<< NC::TermManip::ClearToEOL
;
528 *wFooter
<< NC::Format::Bold
<< state
<< NC::Format::NoBold
;
531 // needed for immediate display after starting
532 // player from stopped state or seeking
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();
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
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;
577 void Status::Changes::elapsedTime(bool update_elapsed
)
581 auto st
= Mpd
.getStatus();
582 m_elapsed_time
= st
.elapsedTime();
586 if (m_player_state
== MPD::psStop
)
588 if (Statusbar::isUnlocked() && Config
.statusbar_visibility
)
589 *wFooter
<< NC::XY(0, 1) << NC::TermManip::ClearToEOL
;
593 MPD::Song np
= getCurrentSong();
594 std::string ps
= playerStateToString(m_player_state
);
595 std::string tracklength
;
598 switch (Config
.design
)
600 case Design::Classic
:
601 if (Statusbar::isUnlocked() && Config
.statusbar_visibility
)
603 if (Config
.display_bitrate
&& m_kbps
)
606 tracklength
+= boost::lexical_cast
<std::string
>(m_kbps
);
607 tracklength
+= " kbps) ";
612 if (Config
.display_remaining_time
)
615 tracklength
+= MPD::Song::ShowTime(m_total_time
-m_elapsed_time
);
618 tracklength
+= MPD::Song::ShowTime(m_elapsed_time
);
620 tracklength
+= MPD::Song::ShowTime(m_total_time
);
623 tracklength
+= MPD::Song::ShowTime(m_elapsed_time
);
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
;
632 case Design::Alternative
:
633 if (Config
.display_remaining_time
)
636 tracklength
+= MPD::Song::ShowTime(m_total_time
-m_elapsed_time
);
639 tracklength
= MPD::Song::ShowTime(m_elapsed_time
);
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
)
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
;
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
)
687 std::string switch_state
;
688 switch (Config
.design
)
690 case Design::Classic
:
692 switch_state
+= m_repeat
;
694 switch_state
+= m_random
;
696 switch_state
+= m_single
;
698 switch_state
+= m_consume
;
700 switch_state
+= m_crossfade
;
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
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, "]");
720 case Design::Alternative
:
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
: '-';
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
;
741 void Status::Changes::mixer()
743 if (!Config
.display_volume_level
|| (!Config
.header_visibility
&& Config
.design
== Design::Classic
))
746 switch (Config
.design
)
748 case Design::Classic
:
749 VolumeState
= " Volume: ";
751 case Design::Alternative
:
752 VolumeState
= " Vol: ";
756 VolumeState
+= "n/a";
759 VolumeState
+= boost::lexical_cast
<std::string
>(m_volume
);
762 *wHeader
<< Config
.volume_color
;
763 *wHeader
<< NC::XY(wHeader
->getWidth()-VolumeState
.length(), 0) << VolumeState
;
764 *wHeader
<< NC::Color::End
;
768 void Status::Changes::outputs()
770 # ifdef ENABLE_OUTPUTS
771 myOutputs
->FetchList();
772 # endif // ENABLE_OUTPUTS