summaryrefslogtreecommitdiff
path: root/src/browser.cpp
blob: b36644e8ab0771306cdf3f25062c5a6933e5bb02 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
/***************************************************************************
 *   Copyright (C) 2008-2013 by Andrzej Rybczak                            *
 *   electricityispower@gmail.com                                          *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.              *
 ***************************************************************************/

#include <dirent.h>
#include <sys/stat.h>
#include <cerrno>
#include <cstring>
#include <boost/filesystem.hpp>
#include <boost/locale/conversion.hpp>
#include <algorithm>

#include "browser.h"
#include "charset.h"
#include "display.h"
#include "error.h"
#include "global.h"
#include "helpers.h"
#include "playlist.h"
#include "regex_filter.h"
#include "screen_switcher.h"
#include "settings.h"
#include "status.h"
#include "statusbar.h"
#include "tag_editor.h"
#include "title.h"
#include "tags.h"
#include "utility/comparators.h"
#include "utility/string.h"

using namespace std::placeholders;

using Global::MainHeight;
using Global::MainStartY;
using Global::myScreen;

using MPD::itDirectory;
using MPD::itSong;
using MPD::itPlaylist;

Browser *myBrowser;

namespace {//

std::set<std::string> SupportedExtensions;
bool hasSupportedExtension(const std::string &file);

std::string ItemToString(const MPD::Item &item);
bool BrowserEntryMatcher(const boost::regex &rx, const MPD::Item &item, bool filter);

}

Browser::Browser() : itsBrowseLocally(0), itsScrollBeginning(0), itsBrowsedDir("/")
{
	w = NC::Menu<MPD::Item>(0, MainStartY, COLS, MainHeight, Config.columns_in_browser && Config.titles_visibility ? Display::Columns(COLS) : "", Config.main_color, NC::Border::None);
	w.setHighlightColor(Config.main_highlight_color);
	w.cyclicScrolling(Config.use_cyclic_scrolling);
	w.centeredCursor(Config.centered_cursor);
	w.setSelectedPrefix(Config.selected_item_prefix);
	w.setSelectedSuffix(Config.selected_item_suffix);
	w.setItemDisplayer(std::bind(Display::Items, _1, proxySongList()));
}

void Browser::resize()
{
	size_t x_offset, width;
	getWindowResizeParams(x_offset, width);
	w.resize(width, MainHeight);
	w.moveTo(x_offset, MainStartY);
	w.setTitle(Config.columns_in_browser && Config.titles_visibility ? Display::Columns(w.getWidth()) : "");
	hasToBeResized = 0;
}

void Browser::switchTo()
{
	SwitchTo::execute(this);
	
	if (w.empty())
		GetDirectory(itsBrowsedDir);
	else
		markSongsInPlaylist(proxySongList());
	
	drawHeader();
}

std::wstring Browser::title()
{
	std::wstring result = L"Browse: ";
	result += Scroller(ToWString(itsBrowsedDir), itsScrollBeginning, COLS-result.length()-(Config.new_design ? 2 : Global::VolumeState.length()));
	return result;
}

void Browser::enterPressed()
{
	if (w.empty())
		return;
	
	const MPD::Item &item = w.current().value();
	switch (item.type)
	{
		case itDirectory:
		{
			if (isParentDirectory(item))
				GetDirectory(getParentDirectory(itsBrowsedDir), itsBrowsedDir);
			else
				GetDirectory(item.name, itsBrowsedDir);
			drawHeader();
			break;
		}
		case itSong:
		{
			addSongToPlaylist(*item.song, true, -1);
			break;
		}
		case itPlaylist:
		{
			Mpd.LoadPlaylist(item.name);
			Statusbar::msg("Playlist \"%s\" loaded", item.name.c_str());
			myPlaylist->PlayNewlyAddedSongs();
		}
	}
}

void Browser::spacePressed()
{
	if (w.empty())
		return;
	
	size_t i = itsBrowsedDir != "/" ? 1 : 0;
	if (Config.space_selects && w.choice() >= i)
	{
		i = w.choice();
		w.at(i).setSelected(!w.at(i).isSelected());
		w.scroll(NC::Scroll::Down);
		return;
	}
	
	const MPD::Item &item = w.current().value();
	
	if (isParentDirectory(item))
		return;
	
	switch (item.type)
	{
		case itDirectory:
		{
#			ifndef WIN32
			if (isLocal())
			{
				MPD::SongList list;
				MPD::ItemList items;
				Statusbar::msg("Scanning directory \"%s\"...", item.name.c_str());
				myBrowser->GetLocalDirectory(items, item.name, 1);
				list.reserve(items.size());
				for (MPD::ItemList::const_iterator it = items.begin(); it != items.end(); ++it)
					list.push_back(*it->song);
				addSongsToPlaylist(list, false, -1);
			}
			else
#			endif // !WIN32
				Mpd.Add(item.name);
			Statusbar::msg("Directory \"%s\" added", item.name.c_str());
			break;
		}
		case itSong:
		{
			addSongToPlaylist(*item.song, false);
			break;
		}
		case itPlaylist:
		{
			Mpd.LoadPlaylist(item.name);
			Statusbar::msg("Playlist \"%s\" loaded", item.name.c_str());
			break;
		}
	}
	w.scroll(NC::Scroll::Down);
}

void Browser::mouseButtonPressed(MEVENT me)
{
	if (w.empty() || !w.hasCoords(me.x, me.y) || size_t(me.y) >= w.size())
		return;
	if (me.bstate & (BUTTON1_PRESSED | BUTTON3_PRESSED))
	{
		w.Goto(me.y);
		switch (w.current().value().type)
		{
			case itDirectory:
				if (me.bstate & BUTTON1_PRESSED)
				{
					GetDirectory(w.current().value().name);
					drawHeader();
				}
				else
				{
					size_t pos = w.choice();
					spacePressed();
					if (pos < w.size()-1)
						w.scroll(NC::Scroll::Up);
				}
				break;
			case itPlaylist:
			case itSong:
				if (me.bstate & BUTTON1_PRESSED)
				{
					size_t pos = w.choice();
					spacePressed();
					if (pos < w.size()-1)
						w.scroll(NC::Scroll::Up);
				}
				else
					enterPressed();
				break;
		}
	}
	else
		Screen<WindowType>::mouseButtonPressed(me);
}

/***********************************************************************/

bool Browser::allowsFiltering()
{
	return true;
}

std::string Browser::currentFilter()
{
	return RegexFilter<MPD::Item>::currentFilter(w);
}

void Browser::applyFilter(const std::string &filter)
{
	if (filter.empty())
	{
		w.clearFilter();
		w.clearFilterResults();
		return;
	}
	try
	{
		w.showAll();
		auto fun = std::bind(BrowserEntryMatcher, _1, _2, true);
		auto rx = RegexFilter<MPD::Item>(
			boost::regex(filter, Config.regex_type), fun);
		w.filter(w.begin(), w.end(), rx);
	}
	catch (boost::bad_expression &) { }
}

/***********************************************************************/

bool Browser::allowsSearching()
{
	return true;
}

bool Browser::search(const std::string &constraint)
{
	if (constraint.empty())
	{
		w.clearSearchResults();
		return false;
	}
	try
	{
		auto fun = std::bind(BrowserEntryMatcher, _1, _2, false);
		auto rx = RegexFilter<MPD::Item>(
			boost::regex(constraint, Config.regex_type), fun);
		return w.search(w.begin(), w.end(), rx);
	}
	catch (boost::bad_expression &)
	{
		return false;
	}
}

void Browser::nextFound(bool wrap)
{
	w.nextFound(wrap);
}

void Browser::prevFound(bool wrap)
{
	w.prevFound(wrap);
}

/***********************************************************************/

ProxySongList Browser::proxySongList()
{
	return ProxySongList(w, [](NC::Menu<MPD::Item>::Item &item) -> MPD::Song * {
		MPD::Song *ptr = 0;
		if (item.value().type == itSong)
			ptr = item.value().song.get();
		return ptr;
	});
}

bool Browser::allowsSelection()
{
	return true;
}

void Browser::reverseSelection()
{
	reverseSelectionHelper(w.begin()+(itsBrowsedDir == "/" ? 0 : 1), w.end());
}

MPD::SongList Browser::getSelectedSongs()
{
	MPD::SongList result;
	auto item_handler = [this, &result](const MPD::Item &item) {
		if (item.type == itDirectory)
		{
#			ifndef WIN32
			if (isLocal())
			{
				MPD::ItemList list;
				GetLocalDirectory(list, item.name, true);
				for (auto it = list.begin(); it != list.end(); ++it)
					result.push_back(*it->song);
			}
			else
#			endif // !WIN32
			{
				Mpd.GetDirectoryRecursive(item.name, [&result](MPD::Song &&s) {
					result.push_back(s);
				});
			}
		}
		else if (item.type == itSong)
			result.push_back(*item.song);
		else if (item.type == itPlaylist)
		{
			Mpd.GetPlaylistContent(item.name, [&result](MPD::Song &&s) {
				result.push_back(s);
			});
		}
	};
	for (auto it = w.begin(); it != w.end(); ++it)
		if (it->isSelected())
			item_handler(it->value());
	// if no item is selected, add current one
	if (result.empty() && !w.empty())
		item_handler(w.current().value());
	return result;
}

void Browser::fetchSupportedExtensions()
{
	SupportedExtensions.clear();
	Mpd.GetSupportedExtensions(SupportedExtensions);
}

void Browser::LocateSong(const MPD::Song &s)
{
	if (s.getDirectory().empty())
		return;
	
	itsBrowseLocally = !s.isFromDatabase();
	
	if (myScreen != this)
		switchTo();
	
	if (itsBrowsedDir != s.getDirectory())
		GetDirectory(s.getDirectory());
	for (size_t i = 0; i < w.size(); ++i)
	{
		if (w[i].value().type == itSong && s.getHash() == w[i].value().song->getHash())
		{
			w.highlight(i);
			break;
		}
	}
	drawHeader();
}

void Browser::GetDirectory(std::string dir, std::string subdir)
{
	if (dir.empty())
		dir = "/";
	
	int highlightme = -1;
	itsScrollBeginning = 0;
	if (itsBrowsedDir != dir)
		w.reset();
	itsBrowsedDir = dir;
	
	w.clear();
	
	if (dir != "/")
	{
		MPD::Item parent;
		parent.name = "..";
		parent.type = itDirectory;
		w.addItem(parent);
	}
	
	MPD::ItemList list;
#	ifndef WIN32
	if (isLocal())
		GetLocalDirectory(list, itsBrowsedDir, false);
	else
		Mpd.GetDirectory(dir, [&list](MPD::Item &&item) {
			list.push_back(item);
		});
#	else
	list = Mpd.GetDirectory(dir);
#	endif // !WIN32
	if (!isLocal()) // local directory is already sorted
		std::sort(list.begin(), list.end(),
			LocaleBasedItemSorting(std::locale(), Config.ignore_leading_the, Config.browser_sort_mode));
	
	for (MPD::ItemList::iterator it = list.begin(); it != list.end(); ++it)
	{
		switch (it->type)
		{
			case itPlaylist:
			{
				w.addItem(*it);
				break;
			}
			case itDirectory:
			{
				if (it->name == subdir)
					highlightme = w.size();
				w.addItem(*it);
				break;
			}
			case itSong:
			{
				bool bold = 0;
				for (size_t i = 0; i < myPlaylist->main().size(); ++i)
				{
					if (myPlaylist->main().at(i).value().getHash() == it->song->getHash())
					{
						bold = 1;
						break;
					}
				}
				w.addItem(*it, bold);
				break;
			}
		}
	}
	if (highlightme >= 0)
		w.highlight(highlightme);
}

#ifndef WIN32
void Browser::GetLocalDirectory(MPD::ItemList &v, const std::string &directory, bool recursively) const
{
	namespace fs = boost::filesystem;
	
	size_t start_size = v.size();
	fs::path dir(directory);
	std::for_each(fs::directory_iterator(dir), fs::directory_iterator(), [&](fs::directory_entry &e) {
		if (!Config.local_browser_show_hidden_files && e.path().filename().native()[0] == '.')
			return;
		MPD::Item item;
		if (fs::is_directory(e))
		{
			if (recursively)
			{
				GetLocalDirectory(v, e.path().native(), true);
				start_size = v.size();
			}
			else
			{
				item.type = itDirectory;
				item.name = e.path().native();
				v.push_back(item);
			}
		}
		else if (hasSupportedExtension(e.path().native()))
		{
			item.type = itSong;
			mpd_pair file_pair = { "file", e.path().native().c_str() };
			MPD::MutableSong *s = new MPD::MutableSong(mpd_song_begin(&file_pair));
			item.song = std::shared_ptr<MPD::Song>(s);
#			ifdef HAVE_TAGLIB_H
			if (!recursively)
				Tags::read(*s);
#			endif // HAVE_TAGLIB_H
			v.push_back(item);
		}
	});
	
	std::sort(v.begin()+start_size, v.end(), LocaleBasedItemSorting(std::locale(),
		Config.ignore_leading_the, Config.browser_sort_mode));
}

void Browser::ClearDirectory(const std::string &path) const
{
	DIR *dir = opendir(path.c_str());
	if (!dir)
		return;
	
	dirent *file;
	struct stat file_stat;
	std::string full_path;
	
	while ((file = readdir(dir)))
	{
		// omit . and ..
		if (file->d_name[0] == '.' && (file->d_name[1] == '\0' || (file->d_name[1] == '.' && file->d_name[2] == '\0')))
			continue;
		
		full_path = path;
		if (*full_path.rbegin() != '/')
			full_path += '/';
		full_path += file->d_name;
		lstat(full_path.c_str(), &file_stat);
		if (S_ISDIR(file_stat.st_mode))
			ClearDirectory(full_path);
		if (remove(full_path.c_str()) == 0)
		{
			const char msg[] = "Deleting \"%ls\"...";
			Statusbar::msg(msg, wideShorten(ToWString(full_path), COLS-const_strlen(msg)).c_str());
		}
		else
		{
			const char msg[] = "Couldn't remove \"%ls\": %s";
			Statusbar::msg(msg, wideShorten(ToWString(full_path), COLS-const_strlen(msg)-25).c_str(), strerror(errno));
		}
	}
	closedir(dir);
}

void Browser::ChangeBrowseMode()
{
	if (Mpd.GetHostname()[0] != '/')
	{
		Statusbar::msg("For browsing local filesystem connection to MPD via UNIX Socket is required");
		return;
	}
	
	itsBrowseLocally = !itsBrowseLocally;
	Statusbar::msg("Browse mode: %s", itsBrowseLocally ? "Local filesystem" : "MPD database");
	itsBrowsedDir = itsBrowseLocally ? Config.GetHomeDirectory() : "/";
	if (itsBrowseLocally && *itsBrowsedDir.rbegin() == '/')
		itsBrowsedDir.resize(itsBrowsedDir.length()-1);
	w.reset();
	GetDirectory(itsBrowsedDir);
	drawHeader();
}

bool Browser::deleteItem(const MPD::Item &item)
{
	if (isParentDirectory((item)))
		FatalError("Parent directory passed to Browser::deleteItem");
	
	// playlist created by mpd
	if (!isLocal() && item.type == itPlaylist && CurrentDir() == "/")
		Mpd.DeletePlaylist(item.name);
	
	std::string path;
	if (!isLocal())
		path = Config.mpd_music_dir;
	path += item.type == itSong ? item.song->getURI() : item.name;
	
	if (item.type == itDirectory)
		ClearDirectory(path);
	
	return std::remove(path.c_str()) == 0;
}
#endif // !WIN32

namespace {//

bool hasSupportedExtension(const std::string &file)
{
	size_t last_dot = file.rfind(".");
	if (last_dot > file.length())
		return false;
	
	std::string ext = boost::locale::to_lower(file.substr(last_dot+1));
	return SupportedExtensions.find(ext) != SupportedExtensions.end();
}

std::string ItemToString(const MPD::Item &item)
{
	std::string result;
	switch (item.type)
	{
		case MPD::itDirectory:
			result = "[" + getBasename(item.name) + "]";
			break;
		case MPD::itSong:
			if (Config.columns_in_browser)
				result = item.song->toString(Config.song_in_columns_to_string_format, Config.tags_separator);
			else
				result = item.song->toString(Config.song_list_format_dollar_free, Config.tags_separator);
			break;
		case MPD::itPlaylist:
			result = Config.browser_playlist_prefix.str() + getBasename(item.name);
			break;
	}
	return result;
}

bool BrowserEntryMatcher(const boost::regex &rx, const MPD::Item &item, bool filter)
{
	if (Browser::isParentDirectory(item))
		return filter;
	return boost::regex_search(ItemToString(item), rx);
}

}