status: make idle events handling independent of the order of their arrival
[ncmpcpp.git] / src / ncmpcpp.cpp
blob789a13fa1541dbe4f86394f27e63077226654b1a
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 <cerrno>
22 #include <clocale>
23 #include <csignal>
24 #include <cstring>
25 #include <netinet/tcp.h>
26 #include <netinet/in.h>
28 #include <boost/date_time/posix_time/posix_time.hpp>
29 #include <boost/locale.hpp>
30 #include <iostream>
31 #include <fstream>
32 #include <stdexcept>
34 #include "mpdpp.h"
36 #include "actions.h"
37 #include "bindings.h"
38 #include "browser.h"
39 #include "charset.h"
40 #include "configuration.h"
41 #include "global.h"
42 #include "error.h"
43 #include "helpers.h"
44 #include "lyrics.h"
45 #include "outputs.h"
46 #include "playlist.h"
47 #include "settings.h"
48 #include "status.h"
49 #include "statusbar.h"
50 #include "visualizer.h"
51 #include "title.h"
52 #include "utility/conversion.h"
54 namespace
56 std::ofstream errorlog;
57 std::streambuf *cerr_buffer;
58 bool run_resize_screen = false;
60 # if !defined(WIN32)
61 void sighandler(int sig)
63 if (sig == SIGPIPE)
65 Statusbar::print("SIGPIPE (broken pipe signal) received");
67 else if (sig == SIGWINCH)
69 run_resize_screen = true;
71 # if defined(__sun) && defined(__SVR4)
72 // in solaris it is needed to reinstall the handler each time it's executed
73 signal(sig, sighandler);
74 # endif // __sun && __SVR4
76 # endif // !WIN32
78 void do_at_exit()
80 // restore old cerr buffer
81 std::cerr.rdbuf(cerr_buffer);
82 errorlog.close();
83 Mpd.Disconnect();
84 # ifndef USE_PDCURSES // destroying screen somehow crashes pdcurses
85 NC::destroyScreen();
86 # endif // USE_PDCURSES
87 windowTitle("");
91 int main(int argc, char **argv)
93 using Global::myScreen;
95 using Global::wHeader;
96 using Global::wFooter;
98 using Global::VolumeState;
99 using Global::Timer;
101 srand(time(nullptr));
102 std::setlocale(LC_ALL, "");
103 std::locale::global(Charset::internalLocale());
105 if (!configure(argc, argv))
106 return 0;
108 // always execute these commands, even if ncmpcpp use exit function
109 atexit(do_at_exit);
111 // redirect std::cerr output to ~/.ncmpcpp/error.log file
112 errorlog.open((Config.ncmpcpp_directory + "error.log").c_str(), std::ios::app);
113 cerr_buffer = std::cerr.rdbuf();
114 std::cerr.rdbuf(errorlog.rdbuf());
116 NC::initScreen("ncmpcpp ver. " VERSION, Config.colors_enabled);
118 Actions::OriginalStatusbarVisibility = Config.statusbar_visibility;
120 if (Config.design == Design::Alternative)
121 Config.statusbar_visibility = 0;
123 Actions::setWindowsDimensions();
124 Actions::validateScreenSize();
125 Actions::initializeScreens();
127 wHeader = new NC::Window(0, 0, COLS, Actions::HeaderHeight, "", Config.header_color, NC::Border::None);
128 if (Config.header_visibility || Config.design == Design::Alternative)
129 wHeader->display();
131 wFooter = new NC::Window(0, Actions::FooterStartY, COLS, Actions::FooterHeight, "", Config.statusbar_color, NC::Border::None);
132 wFooter->setGetStringHelper(Statusbar::Helpers::getString);
134 // initialize global timer
135 Timer = boost::posix_time::microsec_clock::local_time();
137 // initialize playlist
138 myPlaylist->switchTo();
140 // local variables
141 bool key_pressed = false;
142 Key input = Key::noOp;
143 auto past = boost::posix_time::from_time_t(0);
145 /// enable mouse
146 mouseinterval(0);
147 if (Config.mouse_support)
148 mousemask(ALL_MOUSE_EVENTS, 0);
150 # ifndef WIN32
151 signal(SIGPIPE, sighandler);
152 signal(SIGWINCH, sighandler);
153 // ignore Ctrl-C
154 sigignore(SIGINT);
155 # endif // !WIN32
157 while (!Actions::ExitMainLoop)
161 if (!Mpd.Connected())
163 wFooter->clearFDCallbacksList();
166 Mpd.Connect();
167 if (Mpd.Version() < 16)
169 Mpd.Disconnect();
170 throw MPD::ClientError(MPD_ERROR_STATE, "MPD < 0.16.0 is not supported", false);
172 wFooter->addFDCallback(Mpd.GetFD(), Statusbar::Helpers::mpd);
173 Status::clear(); // reset local status info
174 Status::update(-1); // we need info about new connection
176 if (Config.jump_to_now_playing_song_at_start)
178 int curr_pos = Status::get().currentSongPosition();
179 if (curr_pos >= 0)
180 myPlaylist->main().highlight(curr_pos);
183 // Set TCP_NODELAY on the tcp socket as we are using write-write-read pattern
184 // a lot (idle - write, noidle - write, then read the result of noidle), which
185 // kills the performance.
186 int flag = 1;
187 setsockopt(Mpd.GetFD(), IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(flag));
189 // go to startup screen
190 if (Config.startup_screen_type != myScreen->type())
191 toScreen(Config.startup_screen_type)->switchTo();
192 myScreen->refresh();
194 myBrowser->fetchSupportedExtensions();
195 # ifdef ENABLE_OUTPUTS
196 myOutputs->FetchList();
197 # endif // ENABLE_OUTPUTS
198 # ifdef ENABLE_VISUALIZER
199 myVisualizer->ResetFD();
200 if (myScreen == myVisualizer)
201 myVisualizer->SetFD();
202 myVisualizer->FindOutputID();
203 # endif // ENABLE_VISUALIZER
205 Statusbar::printf("Connected to %1%", Mpd.GetHostname());
207 catch (MPD::ClientError &e)
209 Status::handleClientError(e);
213 // update timer, status if necessary etc.
214 Status::trace(!key_pressed, true);
216 if (run_resize_screen)
218 Actions::resizeScreen(true);
219 run_resize_screen = false;
222 // header stuff
223 if ((myScreen == myPlaylist || myScreen == myBrowser || myScreen == myLyrics)
224 && (Timer - past > boost::posix_time::milliseconds(500))
227 drawHeader();
228 past = Timer;
231 if (key_pressed)
232 myScreen->refreshWindow();
233 input = Key::read(*wFooter);
234 key_pressed = input != Key::noOp;
236 if (!key_pressed)
237 continue;
239 // The reason we want to update timer here is that if the timer is updated
240 // in Status::trace, then Key::read usually blocks for 500ms and if key is
241 // pressed 400ms after Key::read was called, we end up with Timer that is
242 // ~400ms inaccurate. On the other hand, if keys are being pressed, we don't
243 // want to update timer in both Status::trace and here. Therefore we update
244 // timer in Status::trace only if there was no recent input.
245 Timer = boost::posix_time::microsec_clock::local_time();
249 auto k = Bindings.get(input);
250 std::any_of(k.first, k.second, boost::bind(&Binding::execute, _1));
252 catch (ConversionError &e)
254 Statusbar::printf("Couldn't convert value \"%1%\" to target type", e.value());
256 catch (OutOfBounds &e)
258 Statusbar::printf("Error: %1%", e.errorMessage());
261 if (myScreen == myPlaylist)
262 myPlaylist->EnableHighlighting();
264 catch (MPD::ClientError &e)
266 Status::handleClientError(e);
268 catch (MPD::ServerError &e)
270 Status::handleServerError(e);
272 catch (std::exception &e)
274 Statusbar::printf("Unexpected error: %1%", e.what());
277 return 0;