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
|
/**
* Copyright (C) 2002-2004 Scott Wheeler <wheeler@kde.org>
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "collectionlist.h"
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <kmenu.h>
#include <kconfig.h>
#include <kconfiggroup.h>
#include <kglobal.h>
#include <kactioncollection.h>
#include <ksavefile.h>
#include <kstandarddirs.h>
#include <ktoolbarpopupaction.h>
#include <kdirwatch.h>
#include <QStringBuilder>
#include <QList>
#include <QDragMoveEvent>
#include <QDropEvent>
#include <QApplication>
#include <QTimer>
#include <QTime>
#include <QClipboard>
#include <QFileInfo>
#include "playlistcollection.h"
#include "splashscreen.h"
#include "stringshare.h"
#include "cache.h"
#include "actioncollection.h"
#include "tag.h"
#include "viewmode.h"
using ActionCollection::action;
////////////////////////////////////////////////////////////////////////////////
// static methods
////////////////////////////////////////////////////////////////////////////////
CollectionList *CollectionList::m_list = 0;
CollectionList *CollectionList::instance()
{
return m_list;
}
static QTime stopwatch;
void CollectionList::startLoadingCachedItems()
{
if(!m_list)
return;
kDebug() << "Starting to load cached items";
stopwatch.start();
if(!Cache::instance()->prepareToLoadCachedItems()) {
kError() << "Unable to setup to load cache... perhaps it doesn't exist?";
completedLoadingCachedItems();
return;
}
kDebug() << "Kicked off first batch";
QTimer::singleShot(0, this, SLOT(loadNextBatchCachedItems()));
}
void CollectionList::loadNextBatchCachedItems()
{
Cache *cache = Cache::instance();
bool done = false;
for(int i = 0; i < 20; ++i) {
FileHandle cachedItem(cache->loadNextCachedItem());
if(cachedItem.isNull()) {
done = true;
break;
}
// This may have already been created via a loaded playlist.
if(!m_itemsDict.contains(cachedItem.absFilePath())) {
CollectionListItem *newItem = new CollectionListItem(this, cachedItem);
setupItem(newItem);
}
}
SplashScreen::update();
if(!done) {
QTimer::singleShot(0, this, SLOT(loadNextBatchCachedItems()));
}
else {
completedLoadingCachedItems();
}
}
void CollectionList::completedLoadingCachedItems()
{
// The CollectionList is created with sorting disabled for speed. Re-enable
// it here, and perform the sort.
KConfigGroup config(KGlobal::config(), "Playlists");
Qt::SortOrder order = Qt::DescendingOrder;
if(config.readEntry("CollectionListSortAscending", true))
order = Qt::AscendingOrder;
m_list->setSortOrder(order);
m_list->setSortColumn(config.readEntry("CollectionListSortColumn", 1));
m_list->sort();
SplashScreen::finishedLoading();
kDebug() << "Finished loading cached items, took" << stopwatch.elapsed() << "ms";
kDebug() << m_itemsDict.size() << "items are in the CollectionList";
emit cachedItemsLoaded();
}
void CollectionList::initialize(PlaylistCollection *collection)
{
if(m_list)
return;
// We have to delay initialization here because dynamic_cast or comparing to
// the collection instance won't work in the PlaylistBox::Item initialization
// won't work until the CollectionList is fully constructed.
m_list = new CollectionList(collection);
m_list->setName(i18n("Collection List"));
collection->setupPlaylist(m_list, "folder-sound");
}
////////////////////////////////////////////////////////////////////////////////
// public methods
////////////////////////////////////////////////////////////////////////////////
CollectionListItem *CollectionList::createItem(const FileHandle &file, Q3ListViewItem *, bool)
{
// It's probably possible to optimize the line below away, but, well, right
// now it's more important to not load duplicate items.
if(m_itemsDict.contains(file.absFilePath()))
return 0;
CollectionListItem *item = new CollectionListItem(this, file);
if(!item->isValid()) {
kError() << "CollectionList::createItem() -- A valid tag was not created for \""
<< file.absFilePath() << "\"" << endl;
delete item;
return 0;
}
setupItem(item);
return item;
}
void CollectionList::clearItems(const PlaylistItemList &items)
{
foreach(PlaylistItem *item, items) {
delete item;
}
dataChanged();
}
void CollectionList::setupTreeViewEntries(ViewMode *viewMode) const
{
TreeViewMode *treeViewMode = dynamic_cast<TreeViewMode *>(viewMode);
if(!treeViewMode) {
kWarning() << "Can't setup entries on a non-tree-view mode!\n";
return;
}
QList<int> columnList;
columnList << PlaylistItem::ArtistColumn;
columnList << PlaylistItem::GenreColumn;
columnList << PlaylistItem::AlbumColumn;
foreach(int column, columnList)
treeViewMode->addItems(m_columnTags[column]->keys(), column);
}
void CollectionList::slotNewItems(const KFileItemList &items)
{
QStringList files;
for(KFileItemList::ConstIterator it = items.constBegin(); it != items.constEnd(); ++it)
files.append((*it).url().path());
addFiles(files);
update();
}
void CollectionList::slotRefreshItems(const QList<QPair<KFileItem, KFileItem> > &items)
{
for(int i = 0; i < items.count(); ++i) {
const KFileItem fileItem = items[i].second;
CollectionListItem *item = lookup(fileItem.url().path());
if(item) {
item->refreshFromDisk();
// If the item is no longer on disk, remove it from the collection.
if(item->file().fileInfo().exists())
item->repaint();
else
delete item;
}
}
update();
}
void CollectionList::slotDeleteItem(const KFileItem &item)
{
delete lookup(item.url().path());
}
void CollectionList::saveItemsToCache() const
{
kDebug() << "Saving collection list to cache";
QString cacheFileName =
KGlobal::dirs()->saveLocation("appdata") % QLatin1String("cache");
KSaveFile f(cacheFileName);
if(!f.open(QIODevice::WriteOnly)) {
kError() << "Error saving cache:" << f.errorString();
return;
}
QByteArray data;
QDataStream s(&data, QIODevice::WriteOnly);
s.setVersion(QDataStream::Qt_4_3);
QHash<QString, CollectionListItem *>::const_iterator it;
for(it = m_itemsDict.begin(); it != m_itemsDict.end(); ++it) {
s << it.key();
s << (*it)->file();
}
QDataStream fs(&f);
qint32 checksum = qChecksum(data.data(), data.size());
fs << qint32(Cache::playlistItemsCacheVersion)
<< checksum
<< data;
f.close();
if(!f.finalize())
kError() << "Error saving cache:" << f.errorString();
}
////////////////////////////////////////////////////////////////////////////////
// public slots
////////////////////////////////////////////////////////////////////////////////
void CollectionList::paste()
{
decode(QApplication::clipboard()->mimeData());
}
void CollectionList::clear()
{
int result = KMessageBox::warningContinueCancel(this,
i18n("Removing an item from the collection will also remove it from "
"all of your playlists. Are you sure you want to continue?\n\n"
"Note, however, that if the directory that these files are in is in "
"your \"scan on startup\" list, they will be readded on startup."));
if(result == KMessageBox::Continue) {
Playlist::clear();
emit signalCollectionChanged();
}
}
void CollectionList::slotCheckCache()
{
PlaylistItemList invalidItems;
kDebug() << "Starting to check cached items for consistency";
stopwatch.start();
int i = 0;
foreach(CollectionListItem *item, m_itemsDict) {
if(!item->checkCurrent())
invalidItems.append(item);
if(++i == (m_itemsDict.size() / 2))
kDebug() << "Checkpoint";
}
clearItems(invalidItems);
kDebug() << "Finished consistency check, took" << stopwatch.elapsed() << "ms";
}
void CollectionList::slotRemoveItem(const QString &file)
{
delete m_itemsDict[file];
}
void CollectionList::slotRefreshItem(const QString &file)
{
if(m_itemsDict[file])
m_itemsDict[file]->refresh();
}
////////////////////////////////////////////////////////////////////////////////
// protected methods
////////////////////////////////////////////////////////////////////////////////
CollectionList::CollectionList(PlaylistCollection *collection) :
Playlist(collection, true),
m_columnTags(15, 0)
{
QAction *spaction = ActionCollection::actions()->addAction("showPlaying");
spaction->setText(i18n("Show Playing"));
connect(spaction, SIGNAL(triggered(bool)), SLOT(slotShowPlaying()));
connect(action<KToolBarPopupAction>("back")->menu(), SIGNAL(aboutToShow()),
this, SLOT(slotPopulateBackMenu()));
connect(action<KToolBarPopupAction>("back")->menu(), SIGNAL(triggered(QAction*)),
this, SLOT(slotPlayFromBackMenu(QAction*)));
setSorting(-1); // Temporarily disable sorting to add items faster.
m_columnTags[PlaylistItem::ArtistColumn] = new TagCountDict;
m_columnTags[PlaylistItem::AlbumColumn] = new TagCountDict;
m_columnTags[PlaylistItem::GenreColumn] = new TagCountDict;
}
CollectionList::~CollectionList()
{
KConfigGroup config(KGlobal::config(), "Playlists");
config.writeEntry("CollectionListSortColumn", sortColumn());
config.writeEntry("CollectionListSortAscending", sortOrder() == Qt::AscendingOrder);
// In some situations the dataChanged signal from clearItems will cause observers to
// subsequently try to access a deleted item. Since we're going away just remove all
// observers.
clearObservers();
// The CollectionListItems will try to remove themselves from the
// m_columnTags member, so we must make sure they're gone before we
// are.
clearItems(items());
qDeleteAll(m_columnTags);
m_columnTags.clear();
}
void CollectionList::contentsDropEvent(QDropEvent *e)
{
if(e->source() == this)
return; // Don't rearrange in the CollectionList.
else
Playlist::contentsDropEvent(e);
}
void CollectionList::contentsDragMoveEvent(QDragMoveEvent *e)
{
if(e->source() != this)
Playlist::contentsDragMoveEvent(e);
else
e->setAccepted(false);
}
QString CollectionList::addStringToDict(const QString &value, int column)
{
if(column > m_columnTags.count() || value.trimmed().isEmpty())
return QString();
if(m_columnTags[column]->contains(value))
++((*m_columnTags[column])[value]);
else {
m_columnTags[column]->insert(value, 1);
emit signalNewTag(value, column);
}
return value;
}
QStringList CollectionList::uniqueSet(UniqueSetType t) const
{
int column;
switch(t)
{
case Artists:
column = PlaylistItem::ArtistColumn;
break;
case Albums:
column = PlaylistItem::AlbumColumn;
break;
case Genres:
column = PlaylistItem::GenreColumn;
break;
default:
return QStringList();
}
return m_columnTags[column]->keys();
}
CollectionListItem *CollectionList::lookup(const QString &file) const
{
return m_itemsDict.value(file, 0);
}
void CollectionList::removeStringFromDict(const QString &value, int column)
{
if(column > m_columnTags.count() || value.trimmed().isEmpty())
return;
if(m_columnTags[column]->contains(value) &&
--((*m_columnTags[column])[value])) // If the decrement goes to 0...
{
emit signalRemovedTag(value, column);
m_columnTags[column]->remove(value);
}
}
void CollectionList::addWatched(const QString &file)
{
m_dirWatch->addFile(file);
}
void CollectionList::removeWatched(const QString &file)
{
m_dirWatch->removeFile(file);
}
////////////////////////////////////////////////////////////////////////////////
// CollectionListItem public methods
////////////////////////////////////////////////////////////////////////////////
void CollectionListItem::refresh()
{
int offset = CollectionList::instance()->columnOffset();
int columns = lastColumn() + offset + 1;
data()->metadata.resize(columns);
data()->cachedWidths.resize(columns);
for(int i = offset; i < columns; i++) {
int id = i - offset;
if(id != TrackNumberColumn && id != LengthColumn) {
// All columns other than track num and length need local-encoded data for sorting
QString toLower = text(i).toLower();
// For some columns, we may be able to share some strings
if((id == ArtistColumn) || (id == AlbumColumn) ||
(id == GenreColumn) || (id == YearColumn) ||
(id == CommentColumn))
{
toLower = StringShare::tryShare(toLower);
if(id != YearColumn && id != CommentColumn && data()->metadata[id] != toLower) {
CollectionList::instance()->removeStringFromDict(data()->metadata[id], id);
CollectionList::instance()->addStringToDict(text(i), id);
}
}
data()->metadata[id] = toLower;
}
int newWidth = width(listView()->fontMetrics(), listView(), i);
if(newWidth != data()->cachedWidths[i])
playlist()->slotWeightDirty(i);
data()->cachedWidths[i] = newWidth;
}
if(listView()->isVisible())
repaint();
for(PlaylistItemList::Iterator it = m_children.begin(); it != m_children.end(); ++it) {
(*it)->playlist()->update();
(*it)->playlist()->dataChanged();
if((*it)->listView()->isVisible())
(*it)->repaint();
}
CollectionList::instance()->dataChanged();
emit CollectionList::instance()->signalCollectionChanged();
}
PlaylistItem *CollectionListItem::itemForPlaylist(const Playlist *playlist)
{
if(playlist == CollectionList::instance())
return this;
PlaylistItemList::ConstIterator it;
for(it = m_children.constBegin(); it != m_children.constEnd(); ++it)
if((*it)->playlist() == playlist)
return *it;
return 0;
}
void CollectionListItem::updateCollectionDict(const QString &oldPath, const QString &newPath)
{
CollectionList *collection = CollectionList::instance();
if(!collection)
return;
collection->removeFromDict(oldPath);
collection->addToDict(newPath, this);
}
void CollectionListItem::repaint() const
{
Q3ListViewItem::repaint();
for(PlaylistItemList::ConstIterator it = m_children.constBegin(); it != m_children.constEnd(); ++it)
(*it)->repaint();
}
////////////////////////////////////////////////////////////////////////////////
// CollectionListItem protected methods
////////////////////////////////////////////////////////////////////////////////
CollectionListItem::CollectionListItem(CollectionList *parent, const FileHandle &file) :
PlaylistItem(parent),
m_shuttingDown(false)
{
parent->addToDict(file.absFilePath(), this);
data()->fileHandle = file;
if(file.tag()) {
refresh();
parent->dataChanged();
}
else {
kError() << "CollectionListItem::CollectionListItem() -- Tag() could not be created." << endl;
}
SplashScreen::increment();
}
CollectionListItem::~CollectionListItem()
{
m_shuttingDown = true;
foreach(PlaylistItem *item, m_children)
delete item;
CollectionList *l = CollectionList::instance();
if(l) {
l->removeFromDict(file().absFilePath());
l->removeStringFromDict(file().tag()->album(), AlbumColumn);
l->removeStringFromDict(file().tag()->artist(), ArtistColumn);
l->removeStringFromDict(file().tag()->genre(), GenreColumn);
}
}
void CollectionListItem::addChildItem(PlaylistItem *child)
{
m_children.append(child);
}
void CollectionListItem::removeChildItem(PlaylistItem *child)
{
if(!m_shuttingDown)
m_children.removeAll(child);
}
bool CollectionListItem::checkCurrent()
{
if(!file().fileInfo().exists() || !file().fileInfo().isFile())
return false;
if(!file().current()) {
file().refresh();
refresh();
}
return true;
}
#include "collectionlist.moc"
// vim: set et sw=4 tw=0 sta:
|