aboutsummaryrefslogtreecommitdiffstats
path: root/CollectionFilter.cpp
blob: e9b930d21a9a309ec4c118800e823fa9d3d79e27 (plain) (blame)
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
/*
 * Copyright 2008 Jason A. Donenfeld <Jason@zx2c4.com>
 */

#include "CollectionFilter.h"
#include "CollectionModel.h"
#include <QStringList>
#include <QDebug>

CollectionFilter::CollectionFilter(QObject *parent, CollectionModel *parentModel)
	: QSortFilterProxyModel(parent)
	, m_parent(parentModel)
	, m_selected(-1)
{
	setSourceModel(parentModel);
}
bool CollectionFilter::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
	if(m_filter.isEmpty())
		return true;
	
	QString artist = sourceModel()->data(sourceModel()->index(sourceRow, 1, sourceParent)).toString();
	QString album = sourceModel()->data(sourceModel()->index(sourceRow, 2, sourceParent)).toString();
	QString title = sourceModel()->data(sourceModel()->index(sourceRow, 3, sourceParent)).toString();
	bool keep = true;
	foreach(QString word, m_filter.split(' ')) {
		keep &= artist.contains(word, Qt::CaseInsensitive) || album.contains(word, Qt::CaseInsensitive) || title.contains(word, Qt::CaseInsensitive);
	}
	return keep;
}
void CollectionFilter::setFilter(QString filter)
{
	if(filter != m_filter)
	{	
		m_filter = filter;
		QModelIndex currentSelected = currentItem();
		invalidateFilter();
		if(currentSelected.isValid())
			m_selected = mapFromSource(currentSelected).row();
		emit filterChanged();
	}
}
QModelIndex CollectionFilter::peekNext() const
{
	if(m_selected + 1 >= rowCount() || rowCount() == 0)
		return QModelIndex();
	return mapToSource(index(m_selected + 1, 0));
}

QModelIndex CollectionFilter::moveNext()
{
	QModelIndex next = peekNext();
	setCurrentItem(next);
	return next;
}

QModelIndex CollectionFilter::peekPrevious() const
{
	if(m_selected <= 0 || rowCount() == 0)
		return QModelIndex();
	return mapToSource(index(m_selected - 1, 0));
}

QModelIndex CollectionFilter::movePrevious()
{
	QModelIndex previous = peekPrevious();
	setCurrentItem(previous);
	return previous;
}
QModelIndex CollectionFilter::currentItem() const
{
	if(m_parent->position() >= 0)
		return m_parent->index(m_parent->position(), 0);
	return QModelIndex();
}
void CollectionFilter::setCurrentItem(const QModelIndex& item)
{
	if(!item.isValid()) {
		m_parent->setPosition(-1);
		m_selected = -1;
		return;
	}
	if(m_selected >= 0)
		emit(dataChanged(index(m_selected, 0), index(m_selected, 3)));
	if(item.model() == this) {
		m_selected = item.row();
		m_parent->setPosition(mapToSource(item).row());
	} else if(item.model() == m_parent) {
		m_selected = mapFromSource(item).row();
		m_parent->setPosition(item.row());
	}		
	emit(dataChanged(index(m_selected, 0), index(m_selected, 3)));
}