move code responsible for screen resize to SIGWINCH handler
[ncmpcpp.git] / src / browser.cpp
blob989f4dee81880b91c462ecd50b36e28833817a2a
1 /***************************************************************************
2 * Copyright (C) 2008-2009 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 <dirent.h>
22 #include <sys/stat.h>
23 #include <cerrno>
24 #include <cstring>
25 #include <algorithm>
27 #include "browser.h"
28 #include "charset.h"
29 #include "display.h"
30 #include "global.h"
31 #include "helpers.h"
32 #include "playlist.h"
33 #include "settings.h"
34 #include "status.h"
35 #ifdef HAVE_TAGLIB_H
36 # include "tag_editor.h"
37 #endif // HAVE_TAGLIB_H
39 using namespace Global;
40 using namespace MPD;
42 Browser *myBrowser = new Browser;
44 const char *Browser::SupportedExtensions[] =
46 "wma", "asf", "rm", "mp1", "mp2", "mp3",
47 "mp4", "m4a", "flac", "ogg", "wav", "au",
48 "aiff", "aif", "ac3", "aac", "mpc", "it",
49 "mod", "s3m", "xm", "wv", 0
52 void Browser::Init()
54 w = new Menu<Item>(0, MainStartY, COLS, MainHeight, Config.columns_in_browser ? Display::Columns() : "", Config.main_color, brNone);
55 w->HighlightColor(Config.main_highlight_color);
56 w->CyclicScrolling(Config.use_cyclic_scrolling);
57 w->SetSelectPrefix(&Config.selected_item_prefix);
58 w->SetSelectSuffix(&Config.selected_item_suffix);
59 w->SetItemDisplayer(Display::Items);
60 w->SetGetStringFunction(ItemToString);
61 isInitialized = 1;
64 void Browser::Resize()
66 w->Resize(COLS, MainHeight);
67 w->MoveTo(0, MainStartY);
68 hasToBeResized = 0;
71 void Browser::SwitchTo()
73 if (myScreen == this)
75 # ifndef WIN32
76 myBrowser->ChangeBrowseMode();
77 # endif // !WIN32
80 if (!isInitialized)
81 Init();
83 if (hasToBeResized)
84 Resize();
86 if (isLocal()) // local browser doesn't support sorting by mtime
87 Config.browser_sort_by_mtime = 0;
89 w->Empty() ? myBrowser->GetDirectory(itsBrowsedDir) : myBrowser->UpdateItemList();
90 myScreen = this;
91 RedrawHeader = 1;
94 std::basic_string<my_char_t> Browser::Title()
96 std::basic_string<my_char_t> result = U("Browse: ");
97 result += Scroller(TO_WSTRING(itsBrowsedDir), itsScrollBeginning, w->GetWidth()-result.length()-(Config.new_design ? 2 : VolumeState.length()));
98 return result;
101 void Browser::EnterPressed()
103 if (w->Empty())
104 return;
106 const Item &item = w->Current();
107 switch (item.type)
109 case itDirectory:
111 GetDirectory(item.name, itsBrowsedDir);
112 RedrawHeader = 1;
113 break;
115 case itSong:
117 w->Bold(w->Choice(), myPlaylist->Add(*item.song, w->isBold(), 1));
118 break;
120 case itPlaylist:
122 SongList list;
123 Mpd.GetPlaylistContent(locale_to_utf_cpy(item.name), list);
124 if (myPlaylist->Add(list, 1))
125 ShowMessage("Loading and playing playlist %s...", item.name.c_str());
126 FreeSongList(list);
127 break;
132 void Browser::SpacePressed()
134 if (w->Empty())
135 return;
137 if (Config.space_selects && w->Choice() >= (itsBrowsedDir != "/" ? 1 : 0))
139 w->Select(w->Choice(), !w->isSelected());
140 w->Scroll(wDown);
141 return;
144 if (itsBrowsedDir != "/" && w->Choice() == 0 /* parent dir */)
145 return;
147 const Item &item = w->Current();
148 switch (item.type)
150 case itDirectory:
152 if (itsBrowsedDir != "/" && !w->Choice())
153 break; // do not let add parent dir.
155 SongList list;
156 # ifndef WIN32
157 if (isLocal())
159 ItemList items;
160 ShowMessage("Scanning \"%s\"...", item.name.c_str());
161 myBrowser->GetLocalDirectory(items, item.name, 1);
162 list.reserve(items.size());
163 for (MPD::ItemList::const_iterator it = items.begin(); it != items.end(); ++it)
164 list.push_back(it->song);
166 else
167 # endif // !WIN32
168 Mpd.GetDirectoryRecursive(locale_to_utf_cpy(item.name), list);
170 if (myPlaylist->Add(list, 0))
171 ShowMessage("Added folder: %s", item.name.c_str());
173 FreeSongList(list);
174 break;
176 case itSong:
178 w->Bold(w->Choice(), myPlaylist->Add(*item.song, w->isBold(), 0));
179 break;
181 case itPlaylist:
183 SongList list;
184 Mpd.GetPlaylistContent(locale_to_utf_cpy(item.name), list);
185 if (myPlaylist->Add(list, 0))
186 ShowMessage("Loading playlist %s...", item.name.c_str());
187 FreeSongList(list);
188 break;
191 w->Scroll(wDown);
194 void Browser::MouseButtonPressed(MEVENT me)
196 if (w->Empty() || !w->hasCoords(me.x, me.y) || size_t(me.y) >= w->Size())
197 return;
198 if (me.bstate & (BUTTON1_PRESSED | BUTTON3_PRESSED))
200 w->Goto(me.y);
201 switch (w->Current().type)
203 case itDirectory:
204 if (me.bstate & BUTTON1_PRESSED)
206 GetDirectory(w->Current().name);
207 RedrawHeader = 1;
209 else
211 size_t pos = w->Choice();
212 SpacePressed();
213 if (pos < w->Size()-1)
214 w->Scroll(wUp);
216 break;
217 case itPlaylist:
218 case itSong:
219 if (me.bstate & BUTTON1_PRESSED)
221 size_t pos = w->Choice();
222 SpacePressed();
223 if (pos < w->Size()-1)
224 w->Scroll(wUp);
226 else
227 EnterPressed();
228 break;
231 else
232 Screen< Menu<MPD::Item> >::MouseButtonPressed(me);
235 MPD::Song *Browser::CurrentSong()
237 return !w->Empty() && w->Current().type == itSong ? w->Current().song : 0;
240 void Browser::ReverseSelection()
242 w->ReverseSelection(itsBrowsedDir == "/" ? 0 : 1);
245 void Browser::GetSelectedSongs(MPD::SongList &v)
247 std::vector<size_t> selected;
248 w->GetSelected(selected);
249 for (std::vector<size_t>::const_iterator it = selected.begin(); it != selected.end(); ++it)
251 const Item &item = w->at(*it);
252 switch (item.type)
254 case itDirectory:
256 Mpd.GetDirectoryRecursive(locale_to_utf_cpy(item.name), v);
257 break;
259 case itSong:
261 v.push_back(new Song(*item.song));
262 break;
264 case itPlaylist:
266 Mpd.GetPlaylistContent(locale_to_utf_cpy(item.name), v);
267 break;
273 void Browser::ApplyFilter(const std::string &s)
275 w->ApplyFilter(s, itsBrowsedDir == "/" ? 0 : 1, REG_ICASE | Config.regex_type);
278 bool Browser::hasSupportedExtension(const std::string &file)
280 size_t last_dot = file.rfind(".");
281 if (last_dot > file.length())
282 return false;
284 std::string ext = file.substr(last_dot+1);
285 ToLower(ext);
286 for (int i = 0; SupportedExtensions[i]; ++i)
287 if (strcmp(ext.c_str(), SupportedExtensions[i]) == 0)
288 return true;
290 return false;
293 void Browser::LocateSong(const MPD::Song &s)
295 if (s.GetDirectory().empty())
296 return;
298 itsBrowseLocally = !s.isFromDB();
300 if (myScreen != this)
301 SwitchTo();
303 std::string option = s.toString(Config.song_status_format);
304 locale_to_utf(option);
305 if (itsBrowsedDir != s.GetDirectory())
306 GetDirectory(s.GetDirectory());
307 for (size_t i = 0; i < w->Size(); ++i)
309 if (w->at(i).type == itSong && option == w->at(i).song->toString(Config.song_status_format))
311 w->Highlight(i);
312 break;
317 void Browser::GetDirectory(std::string dir, std::string subdir)
319 if (dir.empty())
320 dir = "/";
322 int highlightme = -1;
323 itsScrollBeginning = 0;
324 if (itsBrowsedDir != dir)
325 w->Reset();
326 itsBrowsedDir = dir;
328 locale_to_utf(dir);
330 for (size_t i = 0; i < w->Size(); ++i)
331 if (w->at(i).type == itSong)
332 delete w->at(i).song;
334 w->Clear(0);
336 if (dir != "/")
338 Item parent;
339 size_t slash = dir.rfind("/");
340 parent.song = reinterpret_cast<Song *>(1); // in that way we assume that's really parent dir
341 parent.name = slash != std::string::npos ? dir.substr(0, slash) : "/";
342 parent.type = itDirectory;
343 utf_to_locale(parent.name);
344 w->AddOption(parent);
347 ItemList list;
348 # ifndef WIN32
349 isLocal() ? GetLocalDirectory(list) : Mpd.GetDirectory(dir, list);
350 # else
351 Mpd.GetDirectory(dir, list);
352 # endif // !WIN32
353 if (!isLocal()) // local directory is already sorted
354 sort(list.begin(), list.end(), CaseInsensitiveSorting());
356 for (ItemList::iterator it = list.begin(); it != list.end(); ++it)
358 switch (it->type)
360 case itPlaylist:
362 utf_to_locale(it->name);
363 w->AddOption(*it);
364 break;
366 case itDirectory:
368 utf_to_locale(it->name);
369 if (it->name == subdir)
370 highlightme = w->Size();
371 w->AddOption(*it);
372 break;
374 case itSong:
376 bool bold = 0;
377 for (size_t i = 0; i < myPlaylist->Items->Size(); ++i)
379 if (myPlaylist->Items->at(i).GetHash() == it->song->GetHash())
381 bold = 1;
382 break;
385 w->AddOption(*it, bold);
386 break;
390 if (highlightme >= 0)
391 w->Highlight(highlightme);
394 #ifndef WIN32
395 void Browser::GetLocalDirectory(ItemList &v, const std::string &directory, bool recursively) const
397 DIR *dir = opendir((directory.empty() ? itsBrowsedDir : directory).c_str());
399 if (!dir)
400 return;
402 dirent *file;
404 struct stat file_stat;
405 std::string full_path;
407 // omit . and ..
408 for (int i = 0; i < 2; ++i)
410 file = readdir(dir);
411 if (!file)
413 closedir(dir);
414 return;
418 size_t old_size = v.size();
419 while ((file = readdir(dir)))
421 if (!Config.local_browser_show_hidden_files && file->d_name[0] == '.')
422 continue;
423 Item new_item;
424 full_path = directory.empty() ? itsBrowsedDir : directory;
425 if (itsBrowsedDir != "/")
426 full_path += "/";
427 full_path += file->d_name;
428 stat(full_path.c_str(), &file_stat);
429 if (S_ISDIR(file_stat.st_mode))
431 if (recursively)
433 GetLocalDirectory(v, full_path, 1);
434 old_size = v.size();
436 else
438 new_item.type = itDirectory;
439 new_item.name = full_path;
440 v.push_back(new_item);
443 else if (hasSupportedExtension(file->d_name))
445 new_item.type = itSong;
446 mpd_pair file_pair = { "file", full_path.c_str() };
447 new_item.song = new Song(mpd_song_begin(&file_pair));
448 # ifdef HAVE_TAGLIB_H
449 if (!recursively)
450 TagEditor::ReadTags(*new_item.song);
451 # endif // HAVE_TAGLIB_H
452 v.push_back(new_item);
455 closedir(dir);
456 std::sort(v.begin()+old_size, v.end(), CaseInsensitiveSorting());
459 void Browser::ClearDirectory(const std::string &path) const
461 DIR *dir = opendir(path.c_str());
462 if (!dir)
463 return;
465 dirent *file;
466 struct stat file_stat;
467 std::string full_path;
469 // omit . and ..
470 for (int i = 0; i < 2; ++i)
472 file = readdir(dir);
473 if (!file)
475 closedir(dir);
476 return;
480 while ((file = readdir(dir)))
482 full_path = path;
483 if (*full_path.rbegin() != '/')
484 full_path += '/';
485 full_path += file->d_name;
486 lstat(full_path.c_str(), &file_stat);
487 if (S_ISDIR(file_stat.st_mode))
488 ClearDirectory(full_path);
489 if (remove(full_path.c_str()) == 0)
491 static const char msg[] = "Deleting \"%s\"...";
492 ShowMessage(msg, Shorten(TO_WSTRING(full_path), COLS-static_strlen(msg)).c_str());
494 else
496 static const char msg[] = "Couldn't remove \"%s\": %s";
497 ShowMessage(msg, Shorten(TO_WSTRING(full_path), COLS-static_strlen(msg)-25).c_str(), strerror(errno));
500 closedir(dir);
503 void Browser::ChangeBrowseMode()
505 if (Mpd.GetHostname()[0] != '/')
506 return;
508 itsBrowseLocally = !itsBrowseLocally;
509 ShowMessage("Browse mode: %s", itsBrowseLocally ? "Local filesystem" : "MPD music dir");
510 itsBrowsedDir = itsBrowseLocally ? home_path : "/";
511 w->Reset();
512 GetDirectory(itsBrowsedDir);
513 RedrawHeader = 1;
515 #endif // !WIN32
517 void Browser::UpdateItemList()
519 bool bold = 0;
520 for (size_t i = 0; i < w->Size(); ++i)
522 if (w->at(i).type == itSong)
524 for (size_t j = 0; j < myPlaylist->Items->Size(); ++j)
526 if (myPlaylist->Items->at(j).GetHash() == w->at(i).song->GetHash())
528 bold = 1;
529 break;
532 w->Bold(i, bold);
533 bold = 0;
536 w->Refresh();
539 std::string Browser::ItemToString(const MPD::Item &item, void *)
541 switch (item.type)
543 case MPD::itDirectory:
545 if (item.song)
546 return "[..]";
547 return "[" + ExtractTopDirectory(item.name) + "]";
549 case MPD::itSong:
551 if (!Config.columns_in_browser)
552 return item.song->toString(Config.song_list_format);
553 else
554 return Playlist::SongInColumnsToString(*item.song, 0);
556 case MPD::itPlaylist:
558 return Config.browser_playlist_prefix.Str() + item.name;
560 default:
562 return "";