change version to 0.7.3
[ncmpcpp.git] / src / browser.cpp
blob00d1e4d58424633d2bdfd629544b90a4160cec98
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 <algorithm>
22 #include <boost/algorithm/string/predicate.hpp>
23 #include <boost/filesystem.hpp>
24 #include <boost/locale/conversion.hpp>
25 #include <time.h>
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 "menu_impl.h"
34 #include "screen_switcher.h"
35 #include "settings.h"
36 #include "status.h"
37 #include "statusbar.h"
38 #include "tag_editor.h"
39 #include "title.h"
40 #include "tags.h"
41 #include "helpers/song_iterator_maker.h"
42 #include "utility/comparators.h"
43 #include "utility/string.h"
44 #include "configuration.h"
46 using Global::MainHeight;
47 using Global::MainStartY;
48 using Global::myScreen;
50 namespace fs = boost::filesystem;
51 namespace ph = std::placeholders;
53 Browser *myBrowser;
55 namespace {
57 std::set<std::string> lm_supported_extensions;
59 std::string realPath(bool local_browser, std::string path);
60 bool isStringParentDirectory(const std::string &directory);
61 bool isItemParentDirectory(const MPD::Item &item);
62 bool isRootDirectory(const std::string &directory);
63 bool isHidden(const fs::directory_iterator &entry);
64 bool hasSupportedExtension(const fs::directory_entry &entry);
65 MPD::Song getLocalSong(const fs::directory_entry &entry, bool read_tags);
66 void getLocalDirectory(std::vector<MPD::Item> &items, const std::string &directory);
67 void getLocalDirectoryRecursively(std::vector<MPD::Song> &songs, const std::string &directory);
68 void clearDirectory(const std::string &directory);
70 std::string itemToString(const MPD::Item &item);
71 bool browserEntryMatcher(const Regex::Regex &rx, const MPD::Item &item, bool filter);
73 template <bool Const>
74 struct SongExtractor
76 typedef SongExtractor type;
78 typedef typename NC::Menu<MPD::Item>::Item MenuItem;
79 typedef typename std::conditional<Const, const MenuItem, MenuItem>::type Item;
80 typedef typename std::conditional<Const, const MPD::Song, MPD::Song>::type Song;
82 Song *operator()(Item &item) const
84 Song *ptr = nullptr;
85 if (item.value().type() == MPD::Item::Type::Song)
86 ptr = const_cast<Song *>(&item.value().song());
87 return ptr;
93 SongIterator BrowserWindow::currentS()
95 return makeSongIterator_<MPD::Item>(current(), SongExtractor<false>());
98 ConstSongIterator BrowserWindow::currentS() const
100 return makeConstSongIterator_<MPD::Item>(current(), SongExtractor<true>());
103 SongIterator BrowserWindow::beginS()
105 return makeSongIterator_<MPD::Item>(begin(), SongExtractor<false>());
108 ConstSongIterator BrowserWindow::beginS() const
110 return makeConstSongIterator_<MPD::Item>(begin(), SongExtractor<true>());
113 SongIterator BrowserWindow::endS()
115 return makeSongIterator_<MPD::Item>(end(), SongExtractor<false>());
118 ConstSongIterator BrowserWindow::endS() const
120 return makeConstSongIterator_<MPD::Item>(end(), SongExtractor<true>());
123 std::vector<MPD::Song> BrowserWindow::getSelectedSongs()
125 return {}; // TODO
128 /**********************************************************************/
130 Browser::Browser()
131 : m_update_request(true)
132 , m_local_browser(false)
133 , m_scroll_beginning(0)
134 , m_current_directory("/")
136 w = NC::Menu<MPD::Item>(0, MainStartY, COLS, MainHeight, Config.browser_display_mode == DisplayMode::Columns && Config.titles_visibility ? Display::Columns(COLS) : "", Config.main_color, NC::Border());
137 w.setHighlightColor(Config.main_highlight_color);
138 w.cyclicScrolling(Config.use_cyclic_scrolling);
139 w.centeredCursor(Config.centered_cursor);
140 w.setSelectedPrefix(Config.selected_item_prefix);
141 w.setSelectedSuffix(Config.selected_item_suffix);
142 w.setItemDisplayer(std::bind(Display::Items, ph::_1, std::cref(w)));
145 void Browser::resize()
147 size_t x_offset, width;
148 getWindowResizeParams(x_offset, width);
149 w.resize(width, MainHeight);
150 w.moveTo(x_offset, MainStartY);
151 switch (Config.browser_display_mode)
153 case DisplayMode::Columns:
154 if (Config.titles_visibility)
156 w.setTitle(Display::Columns(w.getWidth()));
157 break;
159 case DisplayMode::Classic:
160 w.setTitle("");
161 break;
163 hasToBeResized = 0;
166 void Browser::switchTo()
168 SwitchTo::execute(this);
169 markSongsInPlaylist(w);
170 drawHeader();
173 std::wstring Browser::title()
175 std::wstring result = L"Browse: ";
176 result += Scroller(ToWString(m_current_directory), m_scroll_beginning, COLS-result.length()-(Config.design == Design::Alternative ? 2 : Global::VolumeState.length()));
177 return result;
180 void Browser::update()
182 if (m_update_request)
184 m_update_request = false;
185 bool directory_changed = false;
190 getDirectory(m_current_directory);
191 w.refresh();
193 catch (MPD::ServerError &err)
195 // If current directory doesn't exist, try getting its
196 // parent until we either succeed or reach the root.
197 if (err.code() == MPD_SERVER_ERROR_NO_EXIST)
199 m_current_directory = getParentDirectory(m_current_directory);
200 directory_changed = true;
202 else
203 throw;
206 while (w.empty() && !inRootDirectory());
207 if (directory_changed)
208 drawHeader();
212 void Browser::mouseButtonPressed(MEVENT me)
214 if (w.empty() || !w.hasCoords(me.x, me.y) || size_t(me.y) >= w.size())
215 return;
216 if (me.bstate & (BUTTON1_PRESSED | BUTTON3_PRESSED))
218 w.Goto(me.y);
219 switch (w.current()->value().type())
221 case MPD::Item::Type::Directory:
222 if (me.bstate & BUTTON1_PRESSED)
223 enterDirectory();
224 else
225 addItemToPlaylist(false);
226 break;
227 case MPD::Item::Type::Playlist:
228 case MPD::Item::Type::Song:
230 bool play = me.bstate & BUTTON3_PRESSED;
231 addItemToPlaylist(play);
232 break;
236 else
237 Screen<WindowType>::mouseButtonPressed(me);
240 /***********************************************************************/
242 bool Browser::allowsSearching()
244 return true;
247 void Browser::setSearchConstraint(const std::string &constraint)
249 m_search_predicate = Regex::Filter<MPD::Item>(
250 Regex::make(constraint, Config.regex_type),
251 std::bind(browserEntryMatcher, ph::_1, ph::_2, false)
255 void Browser::clearConstraint()
257 m_search_predicate.clear();
260 bool Browser::find(SearchDirection direction, bool wrap, bool skip_current)
262 return search(w, m_search_predicate, direction, wrap, skip_current);
265 /***********************************************************************/
267 bool Browser::itemAvailable()
269 return !w.empty()
270 // ignore parent directory
271 && !isParentDirectory(w.current()->value());
274 bool Browser::addItemToPlaylist(bool play)
276 bool result = false;
278 auto tryToPlay = [] {
279 // Cheap trick that might fail in presence of multiple
280 // clients modifying the playlist at the same time, but
281 // oh well, this approach correctly loads cue playlists
282 // and is much faster in general as it doesn't require
283 // fetching song data.
286 Mpd.Play(Status::State::playlistLength());
288 catch (MPD::ServerError &e)
290 // If not bad index, rethrow.
291 if (e.code() != MPD_SERVER_ERROR_ARG)
292 throw;
296 const MPD::Item &item = w.current()->value();
297 switch (item.type())
299 case MPD::Item::Type::Directory:
301 if (m_local_browser)
303 std::vector<MPD::Song> songs;
304 getLocalDirectoryRecursively(songs, item.directory().path());
305 result = addSongsToPlaylist(songs.begin(), songs.end(), play, -1);
307 else
309 Mpd.Add(item.directory().path());
310 if (play)
311 tryToPlay();
312 result = true;
314 Statusbar::printf("Directory \"%1%\" added%2%",
315 item.directory().path(), withErrors(result));
316 break;
318 case MPD::Item::Type::Song:
319 result = addSongToPlaylist(item.song(), play);
320 break;
321 case MPD::Item::Type::Playlist:
322 Mpd.LoadPlaylist(item.playlist().path());
323 if (play)
324 tryToPlay();
325 Statusbar::printf("Playlist \"%1%\" loaded", item.playlist().path());
326 result = true;
327 break;
329 return result;
332 std::vector<MPD::Song> Browser::getSelectedSongs()
334 std::vector<MPD::Song> songs;
335 auto item_handler = [this, &songs](const MPD::Item &item) {
336 switch (item.type())
338 case MPD::Item::Type::Directory:
339 if (m_local_browser)
340 getLocalDirectoryRecursively(songs, item.directory().path());
341 else
343 std::copy(
344 std::make_move_iterator(Mpd.GetDirectoryRecursive(item.directory().path())),
345 std::make_move_iterator(MPD::SongIterator()),
346 std::back_inserter(songs)
349 break;
350 case MPD::Item::Type::Song:
351 songs.push_back(item.song());
352 break;
353 case MPD::Item::Type::Playlist:
354 std::copy(
355 std::make_move_iterator(Mpd.GetPlaylistContent(item.playlist().path())),
356 std::make_move_iterator(MPD::SongIterator()),
357 std::back_inserter(songs)
359 break;
362 for (const auto &item : w)
363 if (item.isSelected())
364 item_handler(item.value());
365 // if no item is selected, add current one
366 if (songs.empty() && !w.empty())
367 item_handler(w.current()->value());
368 return songs;
371 /***********************************************************************/
373 bool Browser::inRootDirectory()
375 return isRootDirectory(m_current_directory);
378 bool Browser::isParentDirectory(const MPD::Item &item)
380 return isItemParentDirectory(item);
383 const std::string& Browser::currentDirectory()
385 return m_current_directory;
388 void Browser::locateSong(const MPD::Song &s)
390 if (s.getDirectory().empty())
391 throw std::runtime_error("Song's directory is empty");
393 m_local_browser = !s.isFromDatabase();
395 if (myScreen != this)
396 switchTo();
398 // change to relevant directory
399 if (m_current_directory != s.getDirectory())
401 getDirectory(s.getDirectory());
402 drawHeader();
405 // highlight the item
406 auto begin = w.beginV(), end = w.endV();
407 auto it = std::find(begin, end, MPD::Item(s));
408 if (it != end)
409 w.highlight(it-begin);
412 bool Browser::enterDirectory()
414 bool result = false;
415 if (!w.empty())
417 const auto &item = w.current()->value();
418 if (item.type() == MPD::Item::Type::Directory)
420 getDirectory(item.directory().path());
421 drawHeader();
422 result = true;
425 return result;
428 void Browser::getDirectory(std::string directory)
430 m_scroll_beginning = 0;
431 w.clear();
433 // reset the position if we change directories
434 if (m_current_directory != directory)
435 w.reset();
437 // check if it's a parent directory
438 if (isStringParentDirectory(directory))
440 directory.resize(directory.length()-3);
441 directory = getParentDirectory(directory);
443 // when we go down to root, it can be empty
444 if (directory.empty())
445 directory = "/";
447 std::vector<MPD::Item> items;
448 if (m_local_browser)
449 getLocalDirectory(items, directory);
450 else
452 std::copy(
453 std::make_move_iterator(Mpd.GetDirectory(directory)),
454 std::make_move_iterator(MPD::ItemIterator()),
455 std::back_inserter(items)
459 // sort items
460 if (Config.browser_sort_mode != SortMode::NoOp)
462 std::sort(items.begin(), items.end(),
463 LocaleBasedItemSorting(std::locale(), Config.ignore_leading_the, Config.browser_sort_mode)
467 // if the requested directory is not root, add parent directory
468 if (!isRootDirectory(directory))
470 // make it so that display function doesn't have to handle special cases
471 w.addItem(MPD::Directory(directory + "/.."), NC::List::Properties::None);
474 for (const auto &item : items)
476 switch (item.type())
478 case MPD::Item::Type::Playlist:
480 w.addItem(std::move(item));
481 break;
483 case MPD::Item::Type::Directory:
485 bool is_current = item.directory().path() == m_current_directory;
486 w.addItem(std::move(item));
487 if (is_current)
488 w.highlight(w.size()-1);
489 break;
491 case MPD::Item::Type::Song:
493 auto properties = NC::List::Properties::Selectable;
494 if (myPlaylist->checkForSong(item.song()))
495 properties |= NC::List::Properties::Bold;
496 w.addItem(std::move(item), properties);
497 break;
501 m_current_directory = directory;
504 void Browser::changeBrowseMode()
506 if (Mpd.GetHostname()[0] != '/')
508 Statusbar::print("For browsing local filesystem connection to MPD via UNIX Socket is required");
509 return;
512 m_local_browser = !m_local_browser;
513 Statusbar::printf("Browse mode: %1%",
514 m_local_browser ? "local filesystem" : "MPD database"
516 if (m_local_browser)
518 m_current_directory = "~";
519 expand_home(m_current_directory);
521 else
522 m_current_directory = "/";
523 w.reset();
524 getDirectory(m_current_directory);
525 drawHeader();
528 void Browser::remove(const MPD::Item &item)
530 if (!Config.allow_for_physical_item_deletion)
531 throw std::runtime_error("physical deletion is forbidden");
532 if (isParentDirectory((item)))
533 throw std::runtime_error("deletion of parent directory is forbidden");
535 std::string path;
536 switch (item.type())
538 case MPD::Item::Type::Directory:
539 path = realPath(m_local_browser, item.directory().path());
540 clearDirectory(path);
541 fs::remove(path);
542 break;
543 case MPD::Item::Type::Song:
544 path = realPath(m_local_browser, item.song().getURI());
545 fs::remove(path);
546 break;
547 case MPD::Item::Type::Playlist:
548 path = item.playlist().path();
549 try {
550 Mpd.DeletePlaylist(path);
551 } catch (MPD::ServerError &e) {
552 // if there is no such mpd playlist, it's a local one
553 if (e.code() == MPD_SERVER_ERROR_NO_EXIST)
555 path = realPath(m_local_browser, std::move(path));
556 fs::remove(path);
558 else
559 throw;
561 break;
565 /***********************************************************************/
567 void Browser::fetchSupportedExtensions()
569 lm_supported_extensions.clear();
570 MPD::StringIterator extension = Mpd.GetSupportedExtensions(), end;
571 for (; extension != end; ++extension)
572 lm_supported_extensions.insert("." + std::move(*extension));
575 /***********************************************************************/
577 namespace {
579 std::string realPath(bool local_browser, std::string path)
581 if (!local_browser)
582 path = Config.mpd_music_dir + path;
583 return path;
586 bool isStringParentDirectory(const std::string &directory)
588 return boost::algorithm::ends_with(directory, "/..");
591 bool isItemParentDirectory(const MPD::Item &item)
593 return item.type() == MPD::Item::Type::Directory
594 && isStringParentDirectory(item.directory().path());
597 bool isRootDirectory(const std::string &directory)
599 return directory == "/";
602 bool isHidden(const fs::directory_iterator &entry)
604 return entry->path().filename().native()[0] == '.';
607 bool hasSupportedExtension(const fs::directory_entry &entry)
609 return lm_supported_extensions.find(entry.path().extension().native())
610 != lm_supported_extensions.end();
613 MPD::Song getLocalSong(const fs::directory_entry &entry, bool read_tags)
615 mpd_pair pair = { "file", entry.path().c_str() };
616 mpd_song *s = mpd_song_begin(&pair);
617 if (s == nullptr)
618 throw std::runtime_error("invalid path: " + entry.path().native());
619 if (read_tags)
621 #ifdef HAVE_TAGLIB_H
622 Tags::setAttribute(s, "Last-Modified",
623 timeFormat("%Y-%m-%dT%H:%M:%SZ", fs::last_write_time(entry.path()))
625 // read tags
626 Tags::read(s);
627 #endif // HAVE_TAGLIB_H
629 return s;
632 void getLocalDirectory(std::vector<MPD::Item> &items, const std::string &directory)
634 for (fs::directory_iterator entry(directory), end; entry != end; ++entry)
636 if (!Config.local_browser_show_hidden_files && isHidden(entry))
637 continue;
639 if (fs::is_directory(*entry))
641 items.push_back(MPD::Directory(
642 entry->path().native(),
643 fs::last_write_time(entry->path())
646 else if (hasSupportedExtension(*entry))
647 items.push_back(getLocalSong(*entry, true));
651 void getLocalDirectoryRecursively(std::vector<MPD::Song> &songs, const std::string &directory)
653 size_t sort_offset = songs.size();
654 for (fs::directory_iterator entry(directory), end; entry != end; ++entry)
656 if (!Config.local_browser_show_hidden_files && isHidden(entry))
657 continue;
659 if (fs::is_directory(*entry))
661 getLocalDirectoryRecursively(songs, entry->path().native());
662 sort_offset = songs.size();
664 else if (hasSupportedExtension(*entry))
665 songs.push_back(getLocalSong(*entry, false));
668 if (Config.browser_sort_mode != SortMode::NoOp)
670 std::sort(songs.begin()+sort_offset, songs.end(),
671 LocaleBasedSorting(std::locale(), Config.ignore_leading_the)
676 void clearDirectory(const std::string &directory)
678 for (fs::directory_iterator entry(directory), end; entry != end; ++entry)
680 if (!fs::is_symlink(*entry) && fs::is_directory(*entry))
681 clearDirectory(entry->path().native());
682 const char msg[] = "Deleting \"%1%\"...";
683 Statusbar::printf(msg, wideShorten(entry->path().native(), COLS-const_strlen(msg)));
684 fs::remove(entry->path());
688 /***********************************************************************/
690 std::string itemToString(const MPD::Item &item)
692 std::string result;
693 switch (item.type())
695 case MPD::Item::Type::Directory:
696 result = "[" + getBasename(item.directory().path()) + "]";
697 break;
698 case MPD::Item::Type::Song:
699 switch (Config.browser_display_mode)
701 case DisplayMode::Classic:
702 result = Format::stringify<char>(Config.song_list_format, &item.song());
703 break;
704 case DisplayMode::Columns:
705 result = Format::stringify<char>(Config.song_columns_mode_format, &item.song());
706 break;
708 break;
709 case MPD::Item::Type::Playlist:
710 result = Config.browser_playlist_prefix.str();
711 result += getBasename(item.playlist().path());
712 break;
714 return result;
717 bool browserEntryMatcher(const Regex::Regex &rx, const MPD::Item &item, bool filter)
719 if (isItemParentDirectory(item))
720 return filter;
721 return Regex::search(itemToString(item), rx);