1 /***************************************************************************
2  *   Copyright (C) 2008-2021 by Andrzej Rybczak                            *
3  *   andrzej@rybczak.net                                                   *
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  ***************************************************************************/
20 
21 #include <algorithm>
22 #include <boost/date_time/posix_time/posix_time.hpp>
23 #include <sstream>
24 
25 #include "curses/menu_impl.h"
26 #include "display.h"
27 #include "global.h"
28 #include "helpers.h"
29 #include "screens/playlist.h"
30 #include "screens/screen_switcher.h"
31 #include "song.h"
32 #include "status.h"
33 #include "statusbar.h"
34 #include "format_impl.h"
35 #include "helpers/song_iterator_maker.h"
36 #include "utility/comparators.h"
37 #include "utility/functional.h"
38 #include "title.h"
39 
40 using Global::MainHeight;
41 using Global::MainStartY;
42 
43 namespace ph = std::placeholders;
44 
45 Playlist *myPlaylist;
46 
47 namespace {
48 
49 std::string songToString(const MPD::Song &s);
50 bool playlistEntryMatcher(const Regex::Regex &rx, const MPD::Song &s);
51 
52 }
53 
Playlist()54 Playlist::Playlist()
55 : m_total_length(0), m_remaining_time(0), m_scroll_begin(0)
56 , m_timer(boost::posix_time::from_time_t(0))
57 , m_reload_total_length(false), m_reload_remaining(false)
58 {
59 	w = NC::Menu<MPD::Song>(0, MainStartY, COLS, MainHeight, Config.playlist_display_mode == DisplayMode::Columns && Config.titles_visibility ? Display::Columns(COLS) : "", Config.main_color, NC::Border());
60 	w.cyclicScrolling(Config.use_cyclic_scrolling);
61 	w.centeredCursor(Config.centered_cursor);
62 	setHighlightFixes(w);
63 	w.setSelectedPrefix(Config.selected_item_prefix);
64 	w.setSelectedSuffix(Config.selected_item_suffix);
65 	switch (Config.playlist_display_mode)
66 	{
67 		case DisplayMode::Classic:
68 			w.setItemDisplayer(std::bind(
69 				Display::Songs, ph::_1, std::cref(w), std::cref(Config.song_list_format)
70 			));
71 			break;
72 		case DisplayMode::Columns:
73 			w.setItemDisplayer(std::bind(
74 				Display::SongsInColumns, ph::_1, std::cref(w)
75 			));
76 			break;
77 	}
78 }
79 
switchTo()80 void Playlist::switchTo()
81 {
82 	SwitchTo::execute(this);
83 	m_scroll_begin = 0;
84 	drawHeader();
85 }
86 
resize()87 void Playlist::resize()
88 {
89 	size_t x_offset, width;
90 	getWindowResizeParams(x_offset, width);
91 	w.resize(width, MainHeight);
92 	w.moveTo(x_offset, MainStartY);
93 
94 	switch (Config.playlist_display_mode)
95 	{
96 		case DisplayMode::Columns:
97 			if (Config.titles_visibility)
98 				w.setTitle(Display::Columns(w.getWidth()));
99 			break;
100 		case DisplayMode::Classic:
101 			w.setTitle("");
102 			break;
103 	}
104 
105 	hasToBeResized = 0;
106 }
107 
title()108 std::wstring Playlist::title()
109 {
110 	std::wstring result = L"Playlist ";
111 	if (Config.playlist_show_mpd_host)
112 	{
113 		result += L"on ";
114 		result += ToWString(Mpd.GetHostname());
115 		result += L" ";
116 	}
117 	if (m_reload_total_length || m_reload_remaining)
118 		m_stats = getTotalLength();
119 	result += Scroller(ToWString(m_stats), m_scroll_begin, COLS-result.length()-(Config.design == Design::Alternative ? 2 : Global::VolumeState.length()));
120 	return result;
121 }
122 
update()123 void Playlist::update()
124 {
125 	if (w.isHighlighted()
126 	&&  Config.playlist_disable_highlight_delay.time_duration::seconds() > 0
127 	&&  Global::Timer - m_timer > Config.playlist_disable_highlight_delay)
128 	{
129 		w.setHighlighting(false);
130 		w.refresh();
131 	}
132 }
133 
mouseButtonPressed(MEVENT me)134 void Playlist::mouseButtonPressed(MEVENT me)
135 {
136 	if (!w.empty() && w.hasCoords(me.x, me.y))
137 	{
138 		if (size_t(me.y) < w.size() && (me.bstate & (BUTTON1_PRESSED | BUTTON3_PRESSED)))
139 		{
140 			w.Goto(me.y);
141 			if (me.bstate & BUTTON3_PRESSED)
142 				addItemToPlaylist(true);
143 		}
144 		else
145 			Screen<WindowType>::mouseButtonPressed(me);
146 	}
147 }
148 
149 /***********************************************************************/
150 
allowsSearching()151 bool Playlist::allowsSearching()
152 {
153 	return true;
154 }
155 
searchConstraint()156 const std::string &Playlist::searchConstraint()
157 {
158 	return m_search_predicate.constraint();
159 }
160 
setSearchConstraint(const std::string & constraint)161 void Playlist::setSearchConstraint(const std::string &constraint)
162 {
163 	m_search_predicate = Regex::Filter<MPD::Song>(
164 		constraint,
165 		Config.regex_type,
166 		playlistEntryMatcher);
167 }
168 
clearSearchConstraint()169 void Playlist::clearSearchConstraint()
170 {
171 	m_search_predicate.clear();
172 }
173 
search(SearchDirection direction,bool wrap,bool skip_current)174 bool Playlist::search(SearchDirection direction, bool wrap, bool skip_current)
175 {
176 	return ::search(w, m_search_predicate, direction, wrap, skip_current);
177 }
178 
179 /***********************************************************************/
180 
allowsFiltering()181 bool Playlist::allowsFiltering()
182 {
183 	return allowsSearching();
184 }
185 
currentFilter()186 std::string Playlist::currentFilter()
187 {
188 	std::string result;
189 	if (auto pred = w.filterPredicate<Regex::Filter<MPD::Song>>())
190 		result = pred->constraint();
191 	return result;
192 }
193 
applyFilter(const std::string & constraint)194 void Playlist::applyFilter(const std::string &constraint)
195 {
196 	if (!constraint.empty())
197 	{
198 		w.applyFilter(Regex::Filter<MPD::Song>(
199 			              constraint,
200 			              Config.regex_type,
201 			              playlistEntryMatcher));
202 	}
203 	else
204 		w.clearFilter();
205 }
206 
207 /***********************************************************************/
208 
itemAvailable()209 bool Playlist::itemAvailable()
210 {
211 	return !w.empty();
212 }
213 
addItemToPlaylist(bool play)214 bool Playlist::addItemToPlaylist(bool play)
215 {
216 	if (play)
217 		Mpd.PlayID(w.currentV()->getID());
218 	return true;
219 }
220 
getSelectedSongs()221 std::vector<MPD::Song> Playlist::getSelectedSongs()
222 {
223 	return w.getSelectedSongs();
224 }
225 
226 /***********************************************************************/
227 
nowPlayingSong()228 MPD::Song Playlist::nowPlayingSong()
229 {
230 	MPD::Song s;
231 	if (Status::State::player() != MPD::psUnknown)
232 	{
233 		ScopedUnfilteredMenu<MPD::Song> sunfilter(ReapplyFilter::No, w);
234 		auto sp = Status::State::currentSongPosition();
235 		if (sp >= 0 && size_t(sp) < w.size())
236 			s = w.at(sp).value();
237 	}
238 	return s;
239 }
240 
locateSong(const MPD::Song & s)241 void Playlist::locateSong(const MPD::Song &s)
242 {
243 	if (!w.isFiltered())
244 		w.highlight(s.getPosition());
245 	else
246 	{
247 		auto cmp = [](const MPD::Song &a, const MPD::Song &b) {
248 			return a.getPosition() < b.getPosition();
249 		};
250 		auto first = w.beginV(), last = w.endV();
251 		auto it = std::lower_bound(first, last, s, cmp);
252 		if (it != last && it->getPosition() == s.getPosition())
253 			w.highlight(it - first);
254 		else
255 			Statusbar::print("Song is filtered out");
256 	}
257 }
258 
enableHighlighting()259 void Playlist::enableHighlighting()
260 {
261 	w.setHighlighting(true);
262 	m_timer = Global::Timer;
263 }
264 
getTotalLength()265 std::string Playlist::getTotalLength()
266 {
267 	std::ostringstream result;
268 
269 	if (m_reload_total_length)
270 	{
271 		m_total_length = 0;
272 		for (const auto &s : w)
273 			m_total_length += s.value().getDuration();
274 		m_reload_total_length = false;
275 	}
276 	if (Config.playlist_show_remaining_time && m_reload_remaining)
277 	{
278 		ScopedUnfilteredMenu<MPD::Song> sunfilter(ReapplyFilter::No, w);
279 		m_remaining_time = 0;
280 		for (size_t i = Status::State::currentSongPosition(); i < w.size(); ++i)
281 			m_remaining_time += w[i].value().getDuration();
282 		m_reload_remaining = false;
283 	}
284 
285 	result << '(' << w.size() << (w.size() == 1 ? " item" : " items");
286 
287 	if (w.isFiltered())
288 	{
289 		ScopedUnfilteredMenu<MPD::Song> sunfilter(ReapplyFilter::No, w);
290 		result << " (out of " << w.size() << ")";
291 	}
292 
293 	if (m_total_length)
294 	{
295 		result << ", length: ";
296 		ShowTime(result, m_total_length, Config.playlist_shorten_total_times);
297 	}
298 	if (Config.playlist_show_remaining_time && m_remaining_time && w.size() > 1)
299 	{
300 		result << ", remaining: ";
301 		ShowTime(result, m_remaining_time, Config.playlist_shorten_total_times);
302 	}
303 	result << ')';
304 	return result.str();
305 }
306 
setSelectedItemsPriority(int prio)307 void Playlist::setSelectedItemsPriority(int prio)
308 {
309 	auto list = getSelectedOrCurrent(w.begin(), w.end(), w.current());
310 	Mpd.StartCommandsList();
311 	for (auto it = list.begin(); it != list.end(); ++it)
312 		Mpd.SetPriority((*it)->value(), prio);
313 	Mpd.CommitCommandsList();
314 	Statusbar::print("Priority set");
315 }
316 
checkForSong(const MPD::Song & s)317 bool Playlist::checkForSong(const MPD::Song &s)
318 {
319 	return m_song_refs.find(s) != m_song_refs.end();
320 }
321 
registerSong(const MPD::Song & s)322 void Playlist::registerSong(const MPD::Song &s)
323 {
324 	++m_song_refs[s];
325 }
326 
unregisterSong(const MPD::Song & s)327 void Playlist::unregisterSong(const MPD::Song &s)
328 {
329 	auto it = m_song_refs.find(s);
330 	assert(it != m_song_refs.end());
331 	if (it->second == 1)
332 		m_song_refs.erase(it);
333 	else
334 		--it->second;
335 }
336 
337 namespace {
338 
songToString(const MPD::Song & s)339 std::string songToString(const MPD::Song &s)
340 {
341 	std::string result;
342 	switch (Config.playlist_display_mode)
343 	{
344 		case DisplayMode::Classic:
345 			result = Format::stringify<char>(Config.song_list_format, &s);
346 			break;
347 		case DisplayMode::Columns:
348 			result = Format::stringify<char>(Config.song_columns_mode_format, &s);
349 	}
350 	return result;
351 }
352 
playlistEntryMatcher(const Regex::Regex & rx,const MPD::Song & s)353 bool playlistEntryMatcher(const Regex::Regex &rx, const MPD::Song &s)
354 {
355 	return Regex::search(songToString(s), rx, Config.ignore_diacritics);
356 }
357 
358 }
359