1 /***************************************************************************
2 * Copyright (C) 2008-2014 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>
33 #include "menu_impl.h"
34 #include "screen_switcher.h"
37 #include "statusbar.h"
38 #include "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(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
);
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
85 if (item
.value().type() == MPD::Item::Type::Song
)
86 ptr
= const_cast<Song
*>(&item
.value().song());
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()
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);
169 markSongsInPlaylist(w
);
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()));
180 void Browser::update()
182 if (m_update_request
)
184 m_update_request
= false;
185 bool directory_changed
= false;
190 getDirectory(m_current_directory
);
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;
206 while (w
.empty() && !inRootDirectory());
207 if (directory_changed
)
212 void Browser::mouseButtonPressed(MEVENT me
)
214 if (w
.empty() || !w
.hasCoords(me
.x
, me
.y
) || size_t(me
.y
) >= w
.size())
216 if (me
.bstate
& (BUTTON1_PRESSED
| BUTTON3_PRESSED
))
219 switch (w
.current()->value().type())
221 case MPD::Item::Type::Directory
:
222 if (me
.bstate
& BUTTON1_PRESSED
)
225 addItemToPlaylist(false);
227 case MPD::Item::Type::Playlist
:
228 case MPD::Item::Type::Song
:
230 bool play
= me
.bstate
& BUTTON3_PRESSED
;
231 addItemToPlaylist(play
);
237 Screen
<WindowType
>::mouseButtonPressed(me
);
240 /***********************************************************************/
242 bool Browser::allowsSearching()
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()
270 // ignore parent directory
271 && !isParentDirectory(w
.current()->value());
274 bool Browser::addItemToPlaylist(bool play
)
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
)
296 const MPD::Item
&item
= w
.current()->value();
299 case MPD::Item::Type::Directory
:
303 std::vector
<MPD::Song
> songs
;
304 getLocalDirectoryRecursively(songs
, item
.directory().path());
305 result
= addSongsToPlaylist(songs
.begin(), songs
.end(), play
, -1);
309 Mpd
.Add(item
.directory().path());
314 Statusbar::printf("Directory \"%1%\" added%2%",
315 item
.directory().path(), withErrors(result
));
318 case MPD::Item::Type::Song
:
319 result
= addSongToPlaylist(item
.song(), play
);
321 case MPD::Item::Type::Playlist
:
322 Mpd
.LoadPlaylist(item
.playlist().path());
325 Statusbar::printf("Playlist \"%1%\" loaded", item
.playlist().path());
332 std::vector
<MPD::Song
> Browser::getSelectedSongs()
334 std::vector
<MPD::Song
> songs
;
335 auto item_handler
= [this, &songs
](const MPD::Item
&item
) {
338 case MPD::Item::Type::Directory
:
340 getLocalDirectoryRecursively(songs
, item
.directory().path());
344 std::make_move_iterator(Mpd
.GetDirectoryRecursive(item
.directory().path())),
345 std::make_move_iterator(MPD::SongIterator()),
346 std::back_inserter(songs
)
350 case MPD::Item::Type::Song
:
351 songs
.push_back(item
.song());
353 case MPD::Item::Type::Playlist
:
355 std::make_move_iterator(Mpd
.GetPlaylistContent(item
.playlist().path())),
356 std::make_move_iterator(MPD::SongIterator()),
357 std::back_inserter(songs
)
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());
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)
398 // change to relevant directory
399 if (m_current_directory
!= s
.getDirectory())
401 getDirectory(s
.getDirectory());
405 // highlight the item
406 auto begin
= w
.beginV(), end
= w
.endV();
407 auto it
= std::find(begin
, end
, MPD::Item(s
));
409 w
.highlight(it
-begin
);
412 bool Browser::enterDirectory()
417 const auto &item
= w
.current()->value();
418 if (item
.type() == MPD::Item::Type::Directory
)
420 getDirectory(item
.directory().path());
428 void Browser::getDirectory(std::string directory
)
430 m_scroll_beginning
= 0;
433 // reset the position if we change directories
434 if (m_current_directory
!= directory
)
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())
447 std::vector
<MPD::Item
> items
;
449 getLocalDirectory(items
, directory
);
453 std::make_move_iterator(Mpd
.GetDirectory(directory
)),
454 std::make_move_iterator(MPD::ItemIterator()),
455 std::back_inserter(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
)
478 case MPD::Item::Type::Playlist
:
480 w
.addItem(std::move(item
));
483 case MPD::Item::Type::Directory
:
485 bool is_current
= item
.directory().path() == m_current_directory
;
486 w
.addItem(std::move(item
));
488 w
.highlight(w
.size()-1);
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
);
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");
512 m_local_browser
= !m_local_browser
;
513 Statusbar::printf("Browse mode: %1%",
514 m_local_browser
? "local filesystem" : "MPD database"
518 m_current_directory
= "~";
519 expand_home(m_current_directory
);
522 m_current_directory
= "/";
524 getDirectory(m_current_directory
);
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");
538 case MPD::Item::Type::Directory
:
539 path
= realPath(m_local_browser
, item
.directory().path());
540 clearDirectory(path
);
543 case MPD::Item::Type::Song
:
544 path
= realPath(m_local_browser
, item
.song().getURI());
547 case MPD::Item::Type::Playlist
:
548 path
= item
.playlist().path();
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
));
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 /***********************************************************************/
579 std::string
realPath(bool local_browser
, std::string path
)
582 path
= Config
.mpd_music_dir
+ 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
);
618 throw std::runtime_error("invalid path: " + entry
.path().native());
622 Tags::setAttribute(s
, "Last-Modified",
623 timeFormat("%Y-%m-%dT%H:%M:%SZ", fs::last_write_time(entry
.path()))
627 #endif // HAVE_TAGLIB_H
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
))
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
))
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
)
695 case MPD::Item::Type::Directory
:
696 result
= "[" + getBasename(item
.directory().path()) + "]";
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());
704 case DisplayMode::Columns
:
705 result
= Format::stringify
<char>(Config
.song_columns_mode_format
, &item
.song());
709 case MPD::Item::Type::Playlist
:
710 result
= Config
.browser_playlist_prefix
.str();
711 result
+= getBasename(item
.playlist().path());
717 bool browserEntryMatcher(const Regex::Regex
&rx
, const MPD::Item
&item
, bool filter
)
719 if (isItemParentDirectory(item
))
721 return Regex::search(itemToString(item
), rx
);