Config: reformat all descriptions to fill 80 columns
[ncmpcpp.git] / src / screens / browser.cpp
blobcbdb4a0b6b405e34799169c447c7bffe808de143
1 /***************************************************************************
2 * Copyright (C) 2008-2017 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 "screens/browser.h"
28 #include "charset.h"
29 #include "display.h"
30 #include "global.h"
31 #include "helpers.h"
32 #include "screens/playlist.h"
33 #include "curses/menu_impl.h"
34 #include "screens/screen_switcher.h"
35 #include "settings.h"
36 #include "status.h"
37 #include "statusbar.h"
38 #include "screens/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(NC::Menu<MPD::Item> &menu, const std::string &directory);
67 void getLocalDirectoryRecursively(std::vector<MPD::Song> &songs,
68 const std::string &directory);
69 void clearDirectory(const std::string &directory);
71 std::string itemToString(const MPD::Item &item);
72 bool browserEntryMatcher(const Regex::Regex &rx, const MPD::Item &item, bool filter);
76 template <>
77 struct SongPropertiesExtractor<MPD::Item>
79 template <typename ItemT>
80 auto &operator()(ItemT &item) const
82 auto s = item.value().type() == MPD::Item::Type::Song
83 ? &item.value().song()
84 : nullptr;
85 m_cache.assign(&item.properties(), s);
86 return m_cache;
89 private:
90 mutable SongProperties m_cache;
93 SongIterator BrowserWindow::currentS()
95 return makeSongIterator(current());
98 ConstSongIterator BrowserWindow::currentS() const
100 return makeConstSongIterator(current());
103 SongIterator BrowserWindow::beginS()
105 return makeSongIterator(begin());
108 ConstSongIterator BrowserWindow::beginS() const
110 return makeConstSongIterator(begin());
113 SongIterator BrowserWindow::endS()
115 return makeSongIterator(end());
118 ConstSongIterator BrowserWindow::endS() const
120 return makeConstSongIterator(end());
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 drawHeader();
172 std::wstring Browser::title()
174 std::wstring result = L"Browse: ";
175 result += Scroller(ToWString(m_current_directory), m_scroll_beginning, COLS-result.length()-(Config.design == Design::Alternative ? 2 : Global::VolumeState.length()));
176 return result;
179 void Browser::update()
181 if (m_update_request)
183 m_update_request = false;
184 bool directory_changed = false;
189 getDirectory(m_current_directory);
190 w.refresh();
192 catch (MPD::ServerError &err)
194 // If current directory doesn't exist, try getting its
195 // parent until we either succeed or reach the root.
196 if (err.code() == MPD_SERVER_ERROR_NO_EXIST)
198 m_current_directory = getParentDirectory(m_current_directory);
199 directory_changed = true;
201 else
202 throw;
205 while (w.empty() && !inRootDirectory());
206 if (directory_changed)
207 drawHeader();
211 void Browser::mouseButtonPressed(MEVENT me)
213 if (w.empty() || !w.hasCoords(me.x, me.y) || size_t(me.y) >= w.size())
214 return;
215 if (me.bstate & (BUTTON1_PRESSED | BUTTON3_PRESSED))
217 w.Goto(me.y);
218 switch (w.current()->value().type())
220 case MPD::Item::Type::Directory:
221 if (me.bstate & BUTTON1_PRESSED)
222 enterDirectory();
223 else
224 addItemToPlaylist(false);
225 break;
226 case MPD::Item::Type::Playlist:
227 case MPD::Item::Type::Song:
229 bool play = me.bstate & BUTTON3_PRESSED;
230 addItemToPlaylist(play);
231 break;
235 else
236 Screen<WindowType>::mouseButtonPressed(me);
239 /***********************************************************************/
241 bool Browser::allowsSearching()
243 return true;
246 const std::string &Browser::searchConstraint()
248 return m_search_predicate.constraint();
251 void Browser::setSearchConstraint(const std::string &constraint)
253 m_search_predicate = Regex::Filter<MPD::Item>(
254 constraint,
255 Config.regex_type,
256 std::bind(browserEntryMatcher, ph::_1, ph::_2, false));
259 void Browser::clearSearchConstraint()
261 m_search_predicate.clear();
264 bool Browser::search(SearchDirection direction, bool wrap, bool skip_current)
266 return ::search(w, m_search_predicate, direction, wrap, skip_current);
269 /***********************************************************************/
271 bool Browser::allowsFiltering()
273 return allowsSearching();
276 std::string Browser::currentFilter()
278 std::string result;
279 if (auto pred = w.filterPredicate<Regex::Filter<MPD::Item>>())
280 result = pred->constraint();
281 return result;
284 void Browser::applyFilter(const std::string &constraint)
286 if (!constraint.empty())
288 w.applyFilter(Regex::Filter<MPD::Item>(
289 constraint,
290 Config.regex_type,
291 std::bind(browserEntryMatcher, ph::_1, ph::_2, true)));
293 else
294 w.clearFilter();
298 /***********************************************************************/
300 bool Browser::itemAvailable()
302 return !w.empty()
303 // ignore parent directory
304 && !isParentDirectory(w.current()->value());
307 bool Browser::addItemToPlaylist(bool play)
309 bool result = false;
311 auto tryToPlay = [] {
312 // Cheap trick that might fail in presence of multiple
313 // clients modifying the playlist at the same time, but
314 // oh well, this approach correctly loads cue playlists
315 // and is much faster in general as it doesn't require
316 // fetching song data.
319 Mpd.Play(Status::State::playlistLength());
321 catch (MPD::ServerError &e)
323 // If not bad index, rethrow.
324 if (e.code() != MPD_SERVER_ERROR_ARG)
325 throw;
329 const MPD::Item &item = w.current()->value();
330 switch (item.type())
332 case MPD::Item::Type::Directory:
334 if (m_local_browser)
336 std::vector<MPD::Song> songs;
337 getLocalDirectoryRecursively(songs, item.directory().path());
338 result = addSongsToPlaylist(songs.begin(), songs.end(), play, -1);
340 else
342 Mpd.Add(item.directory().path());
343 if (play)
344 tryToPlay();
345 result = true;
347 Statusbar::printf("Directory \"%1%\" added%2%",
348 item.directory().path(), withErrors(result));
349 break;
351 case MPD::Item::Type::Song:
352 result = addSongToPlaylist(item.song(), play);
353 break;
354 case MPD::Item::Type::Playlist:
355 Mpd.LoadPlaylist(item.playlist().path());
356 if (play)
357 tryToPlay();
358 Statusbar::printf("Playlist \"%1%\" loaded", item.playlist().path());
359 result = true;
360 break;
362 return result;
365 std::vector<MPD::Song> Browser::getSelectedSongs()
367 std::vector<MPD::Song> songs;
368 auto item_handler = [this, &songs](const MPD::Item &item) {
369 switch (item.type())
371 case MPD::Item::Type::Directory:
372 if (m_local_browser)
373 getLocalDirectoryRecursively(songs, item.directory().path());
374 else
376 std::copy(
377 std::make_move_iterator(Mpd.GetDirectoryRecursive(item.directory().path())),
378 std::make_move_iterator(MPD::SongIterator()),
379 std::back_inserter(songs)
382 break;
383 case MPD::Item::Type::Song:
384 songs.push_back(item.song());
385 break;
386 case MPD::Item::Type::Playlist:
387 std::copy(
388 std::make_move_iterator(Mpd.GetPlaylistContent(item.playlist().path())),
389 std::make_move_iterator(MPD::SongIterator()),
390 std::back_inserter(songs)
392 break;
395 for (const auto &item : w)
396 if (item.isSelected())
397 item_handler(item.value());
398 // if no item is selected, add current one
399 if (songs.empty() && !w.empty())
400 item_handler(w.current()->value());
401 return songs;
404 /***********************************************************************/
406 bool Browser::inRootDirectory()
408 return isRootDirectory(m_current_directory);
411 bool Browser::isParentDirectory(const MPD::Item &item)
413 return isItemParentDirectory(item);
416 const std::string& Browser::currentDirectory()
418 return m_current_directory;
421 void Browser::locateSong(const MPD::Song &s)
423 if (s.getDirectory().empty())
424 throw std::runtime_error("Song's directory is empty");
426 m_local_browser = !s.isFromDatabase();
428 if (myScreen != this)
429 switchTo();
431 w.clearFilter();
433 // change to relevant directory
434 if (m_current_directory != s.getDirectory())
436 getDirectory(s.getDirectory());
437 drawHeader();
440 // highlight the item
441 auto begin = w.beginV(), end = w.endV();
442 auto it = std::find(begin, end, MPD::Item(s));
443 if (it != end)
444 w.highlight(it-begin);
447 bool Browser::enterDirectory()
449 bool result = false;
450 if (!w.empty())
452 const auto &item = w.current()->value();
453 if (item.type() == MPD::Item::Type::Directory)
455 getDirectory(item.directory().path());
456 drawHeader();
457 result = true;
460 return result;
463 void Browser::getDirectory(std::string directory)
466 ScopedUnfilteredMenu<MPD::Item> sunfilter(ReapplyFilter::Yes, w);
468 m_scroll_beginning = 0;
469 w.clear();
471 // Reset the position if we change directories.
472 if (m_current_directory != directory)
473 w.reset();
475 // Check if it's a parent directory.
476 if (isStringParentDirectory(directory))
478 directory.resize(directory.length()-3);
479 directory = getParentDirectory(directory);
481 // When we go down to root, it can be empty.
482 if (directory.empty())
483 directory = "/";
485 bool is_root = isRootDirectory(directory);
486 // If the requested directory is not root, add parent directory.
487 if (!is_root)
489 // Make it so that display function doesn't have to handle special cases.
490 w.addItem(MPD::Directory(directory + "/.."), NC::List::Properties::None);
493 if (m_local_browser)
494 getLocalDirectory(w, directory);
495 else
497 MPD::ItemIterator end;
498 for (auto dir = Mpd.GetDirectory(directory); dir != end; ++dir)
499 w.addItem(std::move(*dir));
502 if (Config.browser_sort_mode != SortMode::NoOp)
504 std::sort(w.begin() + (is_root ? 0 : 1), w.end(),
505 LocaleBasedItemSorting(std::locale(), Config.ignore_leading_the, Config.browser_sort_mode));
509 for (size_t i = 0; i < w.size(); ++i)
511 if (w[i].value().type() == MPD::Item::Type::Directory
512 && w[i].value().directory().path() == m_current_directory)
514 w.highlight(i);
515 break;
518 m_current_directory = directory;
521 void Browser::changeBrowseMode()
523 if (Mpd.GetHostname()[0] != '/')
525 Statusbar::print("For browsing local filesystem connection to MPD via UNIX Socket is required");
526 return;
529 m_local_browser = !m_local_browser;
530 Statusbar::printf("Browse mode: %1%",
531 m_local_browser ? "local filesystem" : "MPD database"
533 if (m_local_browser)
535 m_current_directory = "~";
536 expand_home(m_current_directory);
538 else
539 m_current_directory = "/";
540 w.reset();
541 getDirectory(m_current_directory);
542 drawHeader();
545 void Browser::remove(const MPD::Item &item)
547 if (!Config.allow_for_physical_item_deletion)
548 throw std::runtime_error("physical deletion is forbidden");
549 if (isParentDirectory((item)))
550 throw std::runtime_error("deletion of parent directory is forbidden");
552 std::string path;
553 switch (item.type())
555 case MPD::Item::Type::Directory:
556 path = realPath(m_local_browser, item.directory().path());
557 clearDirectory(path);
558 fs::remove(path);
559 break;
560 case MPD::Item::Type::Song:
561 path = realPath(m_local_browser, item.song().getURI());
562 fs::remove(path);
563 break;
564 case MPD::Item::Type::Playlist:
565 path = item.playlist().path();
566 try {
567 Mpd.DeletePlaylist(path);
568 } catch (MPD::ServerError &e) {
569 // if there is no such mpd playlist, it's a local one
570 if (e.code() == MPD_SERVER_ERROR_NO_EXIST)
572 path = realPath(m_local_browser, std::move(path));
573 fs::remove(path);
575 else
576 throw;
578 break;
582 /***********************************************************************/
584 void Browser::fetchSupportedExtensions()
586 lm_supported_extensions.clear();
587 MPD::StringIterator extension = Mpd.GetSupportedExtensions(), end;
588 for (; extension != end; ++extension)
589 lm_supported_extensions.insert("." + std::move(*extension));
592 /***********************************************************************/
594 namespace {
596 std::string realPath(bool local_browser, std::string path)
598 if (!local_browser)
599 path = Config.mpd_music_dir + path;
600 return path;
603 bool isStringParentDirectory(const std::string &directory)
605 return boost::algorithm::ends_with(directory, "/..");
608 bool isItemParentDirectory(const MPD::Item &item)
610 return item.type() == MPD::Item::Type::Directory
611 && isStringParentDirectory(item.directory().path());
614 bool isRootDirectory(const std::string &directory)
616 return directory == "/";
619 bool isHidden(const fs::directory_iterator &entry)
621 return entry->path().filename().native()[0] == '.';
624 bool hasSupportedExtension(const fs::directory_entry &entry)
626 return lm_supported_extensions.find(entry.path().extension().native())
627 != lm_supported_extensions.end();
630 MPD::Song getLocalSong(const fs::directory_entry &entry, bool read_tags)
632 mpd_pair pair = { "file", entry.path().c_str() };
633 mpd_song *s = mpd_song_begin(&pair);
634 if (s == nullptr)
635 throw std::runtime_error("invalid path: " + entry.path().native());
636 if (read_tags)
638 #ifdef HAVE_TAGLIB_H
639 Tags::setAttribute(s, "Last-Modified",
640 timeFormat("%Y-%m-%dT%H:%M:%SZ", fs::last_write_time(entry.path()))
642 // read tags
643 Tags::read(s);
644 #endif // HAVE_TAGLIB_H
646 return s;
649 void getLocalDirectory(NC::Menu<MPD::Item> &menu, const std::string &directory)
651 for (fs::directory_iterator entry(directory), end; entry != end; ++entry)
653 if (!Config.local_browser_show_hidden_files && isHidden(entry))
654 continue;
656 if (fs::is_directory(*entry))
658 menu.addItem(MPD::Directory(entry->path().native(),
659 fs::last_write_time(entry->path())));
661 else if (hasSupportedExtension(*entry))
662 menu.addItem(getLocalSong(*entry, true));
666 void getLocalDirectoryRecursively(std::vector<MPD::Song> &songs, const std::string &directory)
668 size_t sort_offset = songs.size();
669 for (fs::directory_iterator entry(directory), end; entry != end; ++entry)
671 if (!Config.local_browser_show_hidden_files && isHidden(entry))
672 continue;
674 if (fs::is_directory(*entry))
676 getLocalDirectoryRecursively(songs, entry->path().native());
677 sort_offset = songs.size();
679 else if (hasSupportedExtension(*entry))
680 songs.push_back(getLocalSong(*entry, false));
683 if (Config.browser_sort_mode != SortMode::NoOp)
685 std::sort(songs.begin()+sort_offset, songs.end(),
686 LocaleBasedSorting(std::locale(), Config.ignore_leading_the)
691 void clearDirectory(const std::string &directory)
693 for (fs::directory_iterator entry(directory), end; entry != end; ++entry)
695 if (!fs::is_symlink(*entry) && fs::is_directory(*entry))
696 clearDirectory(entry->path().native());
697 const char msg[] = "Deleting \"%1%\"...";
698 Statusbar::printf(msg, wideShorten(entry->path().native(), COLS-const_strlen(msg)));
699 fs::remove(entry->path());
703 /***********************************************************************/
705 std::string itemToString(const MPD::Item &item)
707 std::string result;
708 switch (item.type())
710 case MPD::Item::Type::Directory:
711 result = "[" + getBasename(item.directory().path()) + "]";
712 break;
713 case MPD::Item::Type::Song:
714 switch (Config.browser_display_mode)
716 case DisplayMode::Classic:
717 result = Format::stringify<char>(Config.song_list_format, &item.song());
718 break;
719 case DisplayMode::Columns:
720 result = Format::stringify<char>(Config.song_columns_mode_format, &item.song());
721 break;
723 break;
724 case MPD::Item::Type::Playlist:
725 result = Config.browser_playlist_prefix.str();
726 result += getBasename(item.playlist().path());
727 break;
729 return result;
732 bool browserEntryMatcher(const Regex::Regex &rx, const MPD::Item &item, bool filter)
734 if (isItemParentDirectory(item))
735 return filter;
736 return Regex::search(itemToString(item), rx);