/* * Copyright 2008, 2011 Jason A. Donenfeld */ #include "CollectionFilter.h" #include "CollectionModel.h" #include #include 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))); }