1 /***************************************************************************
2 * Copyright (C) 2008-2017 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 ***************************************************************************/
22 #include <boost/algorithm/string/predicate.hpp>
23 #include <boost/filesystem.hpp>
24 #include <boost/locale/conversion.hpp>
27 #include "screens/browser.h"
32 #include "screens/playlist.h"
33 #include "curses/menu_impl.h"
34 #include "screens/screen_switcher.h"
37 #include "statusbar.h"
38 #include "screens/tag_editor.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
;
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
);
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()
85 m_cache
.assign(&item
.properties(), s
);
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()
128 /**********************************************************************/
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()));
159 case DisplayMode::Classic
:
166 void Browser::switchTo()
168 SwitchTo::execute(this);
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()));
179 void Browser::update()
181 if (m_update_request
)
183 m_update_request
= false;
184 bool directory_changed
= false;
189 getDirectory(m_current_directory
);
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;
205 while (w
.empty() && !inRootDirectory());
206 if (directory_changed
)
211 void Browser::mouseButtonPressed(MEVENT me
)
213 if (w
.empty() || !w
.hasCoords(me
.x
, me
.y
) || size_t(me
.y
) >= w
.size())
215 if (me
.bstate
& (BUTTON1_PRESSED
| BUTTON3_PRESSED
))
218 switch (w
.current()->value().type())
220 case MPD::Item::Type::Directory
:
221 if (me
.bstate
& BUTTON1_PRESSED
)
224 addItemToPlaylist(false);
226 case MPD::Item::Type::Playlist
:
227 case MPD::Item::Type::Song
:
229 bool play
= me
.bstate
& BUTTON3_PRESSED
;
230 addItemToPlaylist(play
);
236 Screen
<WindowType
>::mouseButtonPressed(me
);
239 /***********************************************************************/
241 bool Browser::allowsSearching()
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
>(
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()
279 if (auto pred
= w
.filterPredicate
<Regex::Filter
<MPD::Item
>>())
280 result
= pred
->constraint();
284 void Browser::applyFilter(const std::string
&constraint
)
286 if (!constraint
.empty())
288 w
.applyFilter(Regex::Filter
<MPD::Item
>(
291 std::bind(browserEntryMatcher
, ph::_1
, ph::_2
, true)));
298 /***********************************************************************/
300 bool Browser::itemAvailable()
303 // ignore parent directory
304 && !isParentDirectory(w
.current()->value());
307 bool Browser::addItemToPlaylist(bool play
)
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
)
329 const MPD::Item
&item
= w
.current()->value();
332 case MPD::Item::Type::Directory
:
336 std::vector
<MPD::Song
> songs
;
337 getLocalDirectoryRecursively(songs
, item
.directory().path());
338 result
= addSongsToPlaylist(songs
.begin(), songs
.end(), play
, -1);
342 Mpd
.Add(item
.directory().path());
347 Statusbar::printf("Directory \"%1%\" added%2%",
348 item
.directory().path(), withErrors(result
));
351 case MPD::Item::Type::Song
:
352 result
= addSongToPlaylist(item
.song(), play
);
354 case MPD::Item::Type::Playlist
:
355 Mpd
.LoadPlaylist(item
.playlist().path());
358 Statusbar::printf("Playlist \"%1%\" loaded", item
.playlist().path());
365 std::vector
<MPD::Song
> Browser::getSelectedSongs()
367 std::vector
<MPD::Song
> songs
;
368 auto item_handler
= [this, &songs
](const MPD::Item
&item
) {
371 case MPD::Item::Type::Directory
:
373 getLocalDirectoryRecursively(songs
, item
.directory().path());
377 std::make_move_iterator(Mpd
.GetDirectoryRecursive(item
.directory().path())),
378 std::make_move_iterator(MPD::SongIterator()),
379 std::back_inserter(songs
)
383 case MPD::Item::Type::Song
:
384 songs
.push_back(item
.song());
386 case MPD::Item::Type::Playlist
:
388 std::make_move_iterator(Mpd
.GetPlaylistContent(item
.playlist().path())),
389 std::make_move_iterator(MPD::SongIterator()),
390 std::back_inserter(songs
)
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());
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)
433 // change to relevant directory
434 if (m_current_directory
!= s
.getDirectory())
436 getDirectory(s
.getDirectory());
440 // highlight the item
441 auto begin
= w
.beginV(), end
= w
.endV();
442 auto it
= std::find(begin
, end
, MPD::Item(s
));
444 w
.highlight(it
-begin
);
447 bool Browser::enterDirectory()
452 const auto &item
= w
.current()->value();
453 if (item
.type() == MPD::Item::Type::Directory
)
455 getDirectory(item
.directory().path());
463 void Browser::getDirectory(std::string directory
)
466 ScopedUnfilteredMenu
<MPD::Item
> sunfilter(ReapplyFilter::Yes
, w
);
468 m_scroll_beginning
= 0;
471 // Reset the position if we change directories.
472 if (m_current_directory
!= directory
)
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())
485 bool is_root
= isRootDirectory(directory
);
486 // If the requested directory is not root, add parent directory.
489 // Make it so that display function doesn't have to handle special cases.
490 w
.addItem(MPD::Directory(directory
+ "/.."), NC::List::Properties::None
);
494 getLocalDirectory(w
, directory
);
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
)
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");
529 m_local_browser
= !m_local_browser
;
530 Statusbar::printf("Browse mode: %1%",
531 m_local_browser
? "local filesystem" : "MPD database"
535 m_current_directory
= "~";
536 expand_home(m_current_directory
);
539 m_current_directory
= "/";
541 getDirectory(m_current_directory
);
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");
555 case MPD::Item::Type::Directory
:
556 path
= realPath(m_local_browser
, item
.directory().path());
557 clearDirectory(path
);
560 case MPD::Item::Type::Song
:
561 path
= realPath(m_local_browser
, item
.song().getURI());
564 case MPD::Item::Type::Playlist
:
565 path
= item
.playlist().path();
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
));
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 /***********************************************************************/
596 std::string
realPath(bool local_browser
, std::string path
)
599 path
= Config
.mpd_music_dir
+ 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
);
635 throw std::runtime_error("invalid path: " + entry
.path().native());
639 Tags::setAttribute(s
, "Last-Modified",
640 timeFormat("%Y-%m-%dT%H:%M:%SZ", fs::last_write_time(entry
.path()))
644 #endif // HAVE_TAGLIB_H
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
))
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
))
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
)
710 case MPD::Item::Type::Directory
:
711 result
= "[" + getBasename(item
.directory().path()) + "]";
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());
719 case DisplayMode::Columns
:
720 result
= Format::stringify
<char>(Config
.song_columns_mode_format
, &item
.song());
724 case MPD::Item::Type::Playlist
:
725 result
= Config
.browser_playlist_prefix
.str();
726 result
+= getBasename(item
.playlist().path());
732 bool browserEntryMatcher(const Regex::Regex
&rx
, const MPD::Item
&item
, bool filter
)
734 if (isItemParentDirectory(item
))
736 return Regex::search(itemToString(item
), rx
);