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>
30 #include "media_library.h"
33 #include "playlist_editor.h"
34 #include "search_engine.h"
35 #include "sel_items_adder.h"
38 #include "statusbar.h"
39 #include "tag_editor.h"
40 #include "visualizer.h"
42 #include "utility/string.h"
44 using Global::myScreen
;
46 using Global::wFooter
;
47 using Global::wHeader
;
50 using Global::VolumeState
;
54 boost::posix_time::ptime past
= boost::posix_time::from_time_t(0);
56 size_t playing_song_scroll_begin
= 0;
57 size_t first_line_scroll_begin
= 0;
58 size_t second_line_scroll_begin
= 0;
60 bool m_status_initialized
;
69 int m_current_song_id
;
70 int m_current_song_pos
;
71 unsigned m_elapsed_time
;
73 MPD::PlayerState m_player_state
;
74 unsigned m_playlist_version
;
75 unsigned m_playlist_length
;
76 unsigned m_total_time
;
79 void drawTitle(const MPD::Song
&np
)
82 windowTitle(np
.toString(Config
.song_window_title_format
, Config
.tags_separator
));
85 std::string
playerStateToString(MPD::PlayerState ps
)
94 if (Config
.design
== Design::Alternative
)
100 if (Config
.design
== Design::Alternative
)
101 result
= "[paused] ";
103 result
= "[Paused] ";
106 if (Config
.design
== Design::Alternative
)
107 result
= "[stopped]";
115 void initialize_status()
117 // get full info about new connection
120 if (Config
.jump_to_now_playing_song_at_start
)
122 int curr_pos
= Status::State::currentSongPosition();
124 myPlaylist
->main().highlight(curr_pos
);
127 // Set TCP_NODELAY on the tcp socket as we are using write-write-read pattern
128 // a lot (noidle - write, command - write, then read the result of command),
129 // which kills the performance.
131 setsockopt(Mpd
.GetFD(), IPPROTO_TCP
, TCP_NODELAY
, &flag
, sizeof(flag
));
133 // go to startup screen
134 if (Config
.startup_screen_type
!= myScreen
->type())
135 toScreen(Config
.startup_screen_type
)->switchTo();
138 myBrowser
->fetchSupportedExtensions();
139 # ifdef ENABLE_OUTPUTS
140 myOutputs
->FetchList();
141 # endif // ENABLE_OUTPUTS
142 # ifdef ENABLE_VISUALIZER
143 myVisualizer
->ResetFD();
144 if (myScreen
== myVisualizer
)
145 myVisualizer
->SetFD();
146 myVisualizer
->FindOutputID();
147 # endif // ENABLE_VISUALIZER
149 m_status_initialized
= true;
150 wFooter
->addFDCallback(Mpd
.GetFD(), Statusbar::Helpers::mpd
);
151 Statusbar::printf("Connected to %1%", Mpd
.GetHostname());
156 /*************************************************************************/
158 void Status::handleClientError(MPD::ClientError
&e
)
162 Statusbar::printf("ncmpcpp: %1%", e
.what());
165 void Status::handleServerError(MPD::ServerError
&e
)
167 Statusbar::printf("MPD: %1%", e
.what());
168 if (e
.code() == MPD_SERVER_ERROR_PERMISSION
)
170 wFooter
->setGetStringHelper(nullptr);
171 Statusbar::put() << "Password: ";
172 Mpd
.SetPassword(wFooter
->getString(0, true));
175 Statusbar::print("Password accepted");
176 } catch (MPD::ServerError
&e_prim
) {
177 handleServerError(e_prim
);
179 wFooter
->setGetStringHelper(Statusbar::Helpers::getString
);
181 else if (e
.code() == MPD_SERVER_ERROR_NO_EXIST
&& myScreen
== myBrowser
)
183 myBrowser
->GetDirectory(getParentDirectory(myBrowser
->CurrentDir()));
184 myBrowser
->refresh();
188 /*************************************************************************/
190 void Status::trace(bool update_timer
, bool update_window_timeout
)
193 Timer
= boost::posix_time::microsec_clock::local_time();
196 if (!m_status_initialized
)
199 if (m_player_state
== MPD::psPlay
200 && Global::Timer
- past
> boost::posix_time::seconds(1))
202 // update elapsed time/bitrate of the current song
203 Status::Changes::elapsedTime(true);
208 applyToVisibleWindows(&BaseScreen::update
);
209 Statusbar::tryRedraw();
211 if (update_window_timeout
)
213 // set appropriate window timeout
214 int nc_wtimeout
= std::numeric_limits
<int>::max();
215 applyToVisibleWindows([&nc_wtimeout
](BaseScreen
*s
) {
216 nc_wtimeout
= std::min(nc_wtimeout
, s
->windowTimeout());
218 wFooter
->setTimeout(nc_wtimeout
);
225 void Status::update(int event
)
227 auto st
= Mpd
.getStatus();
228 m_current_song_pos
= st
.currentSongPosition();
229 m_elapsed_time
= st
.elapsedTime();
231 m_player_state
= st
.playerState();
232 m_playlist_length
= st
.playlistLength();
233 m_total_time
= st
.totalTime();
234 m_volume
= st
.volume();
236 if (event
& MPD_IDLE_DATABASE
)
238 if (event
& MPD_IDLE_STORED_PLAYLIST
)
239 Changes::storedPlaylists();
240 if (event
& MPD_IDLE_PLAYLIST
)
242 Changes::playlist(m_playlist_version
);
243 m_playlist_version
= st
.playlistVersion();
245 if (event
& MPD_IDLE_PLAYER
)
247 Changes::playerState();
248 if (m_current_song_id
!= st
.currentSongID())
251 m_current_song_id
= st
.currentSongID();
254 if (event
& MPD_IDLE_MIXER
)
256 if (event
& MPD_IDLE_OUTPUT
)
258 if (event
& (MPD_IDLE_UPDATE
| MPD_IDLE_OPTIONS
))
260 if (event
& MPD_IDLE_UPDATE
)
262 m_db_updating
= st
.updateID() ? 'U' : 0;
263 if (m_status_initialized
)
264 Statusbar::printf("Database update %1%", m_db_updating
? "started" : "finished");
266 if (event
& MPD_IDLE_OPTIONS
)
268 if (('r' == m_repeat
) != st
.repeat())
270 m_repeat
= st
.repeat() ? 'r' : 0;
271 if (m_status_initialized
)
272 Statusbar::printf("Repeat mode is %1%", !m_repeat
? "off" : "on");
274 if (('z' == m_random
) != st
.random())
276 m_random
= st
.random() ? 'z' : 0;
277 if (m_status_initialized
)
278 Statusbar::printf("Random mode is %1%", !m_random
? "off" : "on");
280 if (('s' == m_single
) != st
.single())
282 m_single
= st
.single() ? 's' : 0;
283 if (m_status_initialized
)
284 Statusbar::printf("Single mode is %1%", !m_single
? "off" : "on");
286 if (('c' == m_consume
) != st
.consume())
288 m_consume
= st
.consume() ? 'c' : 0;
289 if (m_status_initialized
)
290 Statusbar::printf("Consume mode is %1%", !m_consume
? "off" : "on");
292 if (('x' == m_crossfade
) != st
.crossfade())
294 int crossfade
= st
.crossfade();
295 m_crossfade
= crossfade
? 'x' : 0;
296 if (m_status_initialized
)
297 Statusbar::printf("Crossfade set to %1% seconds", crossfade
);
302 m_status_initialized
= true;
304 if (event
& MPD_IDLE_PLAYER
)
307 if (event
& (MPD_IDLE_PLAYLIST
| MPD_IDLE_DATABASE
| MPD_IDLE_PLAYER
))
308 applyToVisibleWindows(&BaseScreen::refreshWindow
);
313 // reset local variables
314 m_status_initialized
= false;
321 m_current_song_id
= -1;
322 m_current_song_pos
= -1;
324 m_player_state
= MPD::psUnknown
;
325 m_playlist_length
= 0;
326 m_playlist_version
= 0;
331 /*************************************************************************/
333 bool Status::State::consume()
335 return m_consume
!= 0;
338 bool Status::State::crossfade()
340 return m_crossfade
!= 0;
343 bool Status::State::repeat()
345 return m_repeat
!= 0;
348 bool Status::State::random()
350 return m_random
!= 0;
353 bool Status::State::single()
355 return m_single
!= 0;
358 int Status::State::currentSongID()
360 return m_current_song_id
;
363 int Status::State::currentSongPosition()
365 return m_current_song_pos
;
368 unsigned Status::State::elapsedTime()
370 return m_elapsed_time
;
373 MPD::PlayerState
Status::State::player()
375 return m_player_state
;
378 unsigned Status::State::totalTime()
383 int Status::State::volume()
388 /*************************************************************************/
390 void Status::Changes::playlist(unsigned previous_version
)
392 myPlaylist
->main().clearSearchResults();
393 withUnfilteredMenuReapplyFilter(myPlaylist
->main(), [previous_version
]() {
394 if (m_playlist_length
< myPlaylist
->main().size())
396 auto it
= myPlaylist
->main().begin()+m_playlist_length
;
397 auto end
= myPlaylist
->main().end();
398 for (; it
!= end
; ++it
)
399 myPlaylist
->unregisterSong(it
->value());
400 myPlaylist
->main().resizeList(m_playlist_length
);
403 Mpd
.GetPlaylistChanges(previous_version
, [](MPD::Song s
) {
404 size_t pos
= s
.getPosition();
405 if (pos
< myPlaylist
->main().size())
407 // if song's already in playlist, replace it with a new one
408 MPD::Song
&old_s
= myPlaylist
->main()[pos
].value();
409 myPlaylist
->unregisterSong(old_s
);
412 else // otherwise just add it to playlist
413 myPlaylist
->main().addItem(s
);
414 myPlaylist
->registerSong(s
);
418 if (m_player_state
== MPD::psStop
)
419 drawTitle(myPlaylist
->nowPlayingSong());
421 myPlaylist
->reloadTotalLength();
422 myPlaylist
->reloadRemaining();
424 if (isVisible(myBrowser
))
425 markSongsInPlaylist(myBrowser
->proxySongList());
426 if (isVisible(mySearcher
))
427 markSongsInPlaylist(mySearcher
->proxySongList());
428 if (isVisible(myLibrary
))
430 markSongsInPlaylist(myLibrary
->songsProxyList());
431 myLibrary
->Songs
.refresh();
433 if (isVisible(myPlaylistEditor
))
435 markSongsInPlaylist(myPlaylistEditor
->contentProxyList());
436 myPlaylistEditor
->Content
.refresh();
440 void Status::Changes::storedPlaylists()
442 myPlaylistEditor
->requestPlaylistsUpdate();
443 myPlaylistEditor
->requestContentsUpdate();
444 if (myBrowser
->CurrentDir() == "/")
446 myBrowser
->GetDirectory("/");
447 if (isVisible(myBrowser
))
448 myBrowser
->refresh();
452 void Status::Changes::database()
454 if (isVisible(myBrowser
))
455 myBrowser
->GetDirectory(myBrowser
->CurrentDir());
457 myBrowser
->main().clear();
458 # ifdef HAVE_TAGLIB_H
459 myTagEditor
->Dirs
->clear();
460 # endif // HAVE_TAGLIB_H
461 myLibrary
->requestTagsUpdate();
462 myLibrary
->requestAlbumsUpdate();
463 myLibrary
->requestSongsUpdate();
466 void Status::Changes::playerState()
468 switch (m_player_state
)
471 drawTitle(myPlaylist
->nowPlayingSong());
472 myPlaylist
->reloadRemaining();
475 windowTitle("ncmpcpp " VERSION
);
476 if (Progressbar::isUnlocked())
477 Progressbar::draw(0, 0);
478 myPlaylist
->reloadRemaining();
479 if (Config
.design
== Design::Alternative
)
481 *wHeader
<< NC::XY(0, 0) << wclrtoeol
<< NC::XY(0, 1) << wclrtoeol
;
485 # ifdef ENABLE_VISUALIZER
486 if (isVisible(myVisualizer
))
487 myVisualizer
->main().clear();
488 # endif // ENABLE_VISUALIZER
494 std::string state
= playerStateToString(m_player_state
);
495 if (Config
.design
== Design::Alternative
)
497 *wHeader
<< NC::XY(0, 1) << NC::Format::Bold
<< state
<< NC::Format::NoBold
;
500 else if (Statusbar::isUnlocked() && Config
.statusbar_visibility
)
502 *wFooter
<< NC::XY(0, 1);
504 *wFooter
<< wclrtoeol
;
506 *wFooter
<< NC::Format::Bold
<< state
<< NC::Format::NoBold
;
509 // needed for immediate display after starting
510 // player from stopped state or seeking
514 void Status::Changes::songID()
516 // update information about current song
517 myPlaylist
->reloadRemaining();
518 playing_song_scroll_begin
= 0;
519 first_line_scroll_begin
= 0;
520 second_line_scroll_begin
= 0;
521 if (m_player_state
!= MPD::psStop
)
524 if (!Config
.execute_on_song_change
.empty())
525 res
= system(Config
.execute_on_song_change
.c_str());
527 # ifdef HAVE_CURL_CURL_H
528 if (Config
.fetch_lyrics_in_background
)
529 Lyrics::DownloadInBackground(myPlaylist
->nowPlayingSong());
530 # endif // HAVE_CURL_CURL_H
532 drawTitle(myPlaylist
->nowPlayingSong());
534 if (Config
.autocenter_mode
&& !myPlaylist
->main().isFiltered())
535 myPlaylist
->main().highlight(Status::State::currentSongPosition());
537 if (Config
.now_playing_lyrics
&& isVisible(myLyrics
) && myLyrics
->previousScreen() == myPlaylist
)
538 myLyrics
->ReloadNP
= 1;
543 void Status::Changes::elapsedTime(bool update_elapsed
)
547 auto st
= Mpd
.getStatus();
548 m_elapsed_time
= st
.elapsedTime();
552 if (m_player_state
== MPD::psStop
)
554 if (Statusbar::isUnlocked() && Config
.statusbar_visibility
)
555 *wFooter
<< NC::XY(0, 1) << wclrtoeol
;
559 std::string ps
= playerStateToString(m_player_state
);
560 MPD::Song np
= myPlaylist
->nowPlayingSong();
563 std::string tracklength
;
564 switch (Config
.design
)
566 case Design::Classic
:
567 if (Statusbar::isUnlocked() && Config
.statusbar_visibility
)
569 if (Config
.display_bitrate
&& m_kbps
)
572 tracklength
+= boost::lexical_cast
<std::string
>(m_kbps
);
573 tracklength
+= " kbps]";
578 if (Config
.display_remaining_time
)
581 tracklength
+= MPD::Song::ShowTime(m_total_time
-m_elapsed_time
);
584 tracklength
+= MPD::Song::ShowTime(m_elapsed_time
);
586 tracklength
+= MPD::Song::ShowTime(m_total_time
);
591 tracklength
+= MPD::Song::ShowTime(m_elapsed_time
);
595 stringToBuffer(ToWString(Charset::utf8ToLocale(np
.toString(Config
.song_status_format
, Config
.tags_separator
, "$"))), np_song
);
596 *wFooter
<< NC::XY(0, 1) << wclrtoeol
<< NC::Format::Bold
<< ps
<< NC::Format::NoBold
;
597 writeCyclicBuffer(np_song
, *wFooter
, playing_song_scroll_begin
, wFooter
->getWidth()-ps
.length()-tracklength
.length(), L
" ** ");
598 *wFooter
<< NC::Format::Bold
<< NC::XY(wFooter
->getWidth()-tracklength
.length(), 1) << tracklength
<< NC::Format::NoBold
;
601 case Design::Alternative
:
602 if (Config
.display_remaining_time
)
605 tracklength
+= MPD::Song::ShowTime(m_total_time
-m_elapsed_time
);
608 tracklength
= MPD::Song::ShowTime(m_elapsed_time
);
612 tracklength
+= MPD::Song::ShowTime(m_total_time
);
614 // bitrate here doesn't look good, but it can be moved somewhere else later
615 if (Config
.display_bitrate
&& m_kbps
)
618 tracklength
+= boost::lexical_cast
<std::string
>(m_kbps
);
619 tracklength
+= " kbps";
622 NC::WBuffer first
, second
;
623 stringToBuffer(ToWString(Charset::utf8ToLocale(np
.toString(Config
.new_header_first_line
, Config
.tags_separator
, "$"))), first
);
624 stringToBuffer(ToWString(Charset::utf8ToLocale(np
.toString(Config
.new_header_second_line
, Config
.tags_separator
, "$"))), second
);
626 size_t first_len
= wideLength(first
.str());
627 size_t first_margin
= (std::max(tracklength
.length()+1, VolumeState
.length()))*2;
628 size_t first_start
= first_len
< COLS
-first_margin
? (COLS
-first_len
)/2 : tracklength
.length()+1;
630 size_t second_len
= wideLength(second
.str());
631 size_t second_margin
= (std::max(ps
.length(), size_t(8))+1)*2;
632 size_t second_start
= second_len
< COLS
-second_margin
? (COLS
-second_len
)/2 : ps
.length()+1;
634 if (!Global::SeekingInProgress
)
635 *wHeader
<< NC::XY(0, 0) << wclrtoeol
<< tracklength
;
636 *wHeader
<< NC::XY(first_start
, 0);
637 writeCyclicBuffer(first
, *wHeader
, first_line_scroll_begin
, COLS
-tracklength
.length()-VolumeState
.length()-1, L
" ** ");
639 *wHeader
<< NC::XY(0, 1) << wclrtoeol
<< NC::Format::Bold
<< ps
<< NC::Format::NoBold
;
640 *wHeader
<< NC::XY(second_start
, 1);
641 writeCyclicBuffer(second
, *wHeader
, second_line_scroll_begin
, COLS
-ps
.length()-8-2, L
" ** ");
643 *wHeader
<< NC::XY(wHeader
->getWidth()-VolumeState
.length(), 0) << Config
.volume_color
<< VolumeState
<< NC::Color::End
;
647 if (Progressbar::isUnlocked())
648 Progressbar::draw(m_elapsed_time
, m_total_time
);
651 void Status::Changes::flags()
653 if (!Config
.header_visibility
&& Config
.design
== Design::Classic
)
656 std::string switch_state
;
657 switch (Config
.design
)
659 case Design::Classic
:
661 switch_state
+= m_repeat
;
663 switch_state
+= m_random
;
665 switch_state
+= m_single
;
667 switch_state
+= m_consume
;
669 switch_state
+= m_crossfade
;
671 switch_state
+= m_db_updating
;
673 // this is done by raw ncurses because creating another
674 // window only for handling this is quite silly
675 attrset(A_BOLD
|COLOR_PAIR(int(Config
.state_line_color
)));
676 mvhline(1, 0, 0, COLS
);
677 if (!switch_state
.empty())
679 mvprintw(1, COLS
-switch_state
.length()-3, "[");
680 attroff(COLOR_PAIR(int(Config
.state_line_color
)));
681 attron(COLOR_PAIR(int(Config
.state_flags_color
)));
682 mvprintw(1, COLS
-switch_state
.length()-2, "%s", switch_state
.c_str());
683 attroff(COLOR_PAIR(int(Config
.state_flags_color
)));
684 attron(COLOR_PAIR(int(Config
.state_line_color
)));
685 mvprintw(1, COLS
-2, "]");
690 case Design::Alternative
:
692 switch_state
+= m_repeat
? m_repeat
: '-';
693 switch_state
+= m_random
? m_random
: '-';
694 switch_state
+= m_single
? m_single
: '-';
695 switch_state
+= m_consume
? m_consume
: '-';
696 switch_state
+= m_crossfade
? m_crossfade
: '-';
697 switch_state
+= m_db_updating
? m_db_updating
: '-';
699 *wHeader
<< NC::XY(COLS
-switch_state
.length(), 1) << NC::Format::Bold
<< Config
.state_flags_color
<< switch_state
<< NC::Color::End
<< NC::Format::NoBold
;
700 if (!Config
.header_visibility
) // in this case also draw separator
702 *wHeader
<< NC::Format::Bold
<< NC::Color::Black
;
703 mvwhline(wHeader
->raw(), 2, 0, 0, COLS
);
704 *wHeader
<< NC::Color::End
<< NC::Format::NoBold
;
711 void Status::Changes::mixer()
713 if (!Config
.display_volume_level
|| (!Config
.header_visibility
&& Config
.design
== Design::Classic
))
716 switch (Config
.design
)
718 case Design::Classic
:
719 VolumeState
= " " "Volume" ": ";
721 case Design::Alternative
:
722 VolumeState
= " " "Vol" ": ";
726 VolumeState
+= "n/a";
729 VolumeState
+= boost::lexical_cast
<std::string
>(m_volume
);
732 *wHeader
<< Config
.volume_color
;
733 *wHeader
<< NC::XY(wHeader
->getWidth()-VolumeState
.length(), 0) << VolumeState
;
734 *wHeader
<< NC::Color::End
;
738 void Status::Changes::outputs()
740 # ifdef ENABLE_OUTPUTS
741 myOutputs
->FetchList();
742 # endif // ENABLE_OUTPUTS