playlistsplitter.cpp 17.2 KB
Newer Older
1 2 3 4 5
/***************************************************************************
                          playlistsplitter.cpp  -  description
                             -------------------
    begin                : Fri Sep 13 2002
    copyright            : (C) 2002 by Scott Wheeler
6
    email                : wheeler@kde.org
7 8 9 10 11 12 13 14 15 16 17
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

18
#include <klocale.h>
19
#include <kiconloader.h>
20
#include <kapplication.h>
21
#include <kstandarddirs.h>
22
#include <kmessagebox.h>
23
#include <kdirwatch.h>
24 25
#include <kdebug.h>

26
#include <qinputdialog.h>
27
#include <qtimer.h>
28

29
#include "playlistitem.h"
30
#include "playlistsplitter.h"
31
#include "collectionlist.h"
32
#include "directorylist.h"
33 34
#include "playlist.h"

35 36
QStringList *PlaylistSplitter::m_mediaExtensions = 0;
QStringList *PlaylistSplitter::m_listExtensions = 0;
37 38

////////////////////////////////////////////////////////////////////////////////
39
// helper functions
40 41
////////////////////////////////////////////////////////////////////////////////

42
void processEvents()
43
{
44 45 46
    static int processed = 0;
    if(processed == 0)
        kapp->processEvents();
47
    processed = (processed + 1) % 5;
48 49
}

50
////////////////////////////////////////////////////////////////////////////////
51
// public methods
52 53
////////////////////////////////////////////////////////////////////////////////

54
PlaylistSplitter::PlaylistSplitter(QWidget *parent, bool restore, const char *name) : QSplitter(Qt::Horizontal, parent, name), 
55
										      m_playingItem(0), m_restore(restore), m_nextPlaylistItem(0)
56
{
57 58 59 60 61 62 63 64
    if(!m_mediaExtensions && !m_listExtensions) {
	m_mediaExtensions = new QStringList();
	m_listExtensions = new QStringList();

	m_mediaExtensions->append("mp3");
	m_mediaExtensions->append("ogg");
	m_listExtensions->append("m3u");
    }
65 66 67

    setupLayout();
    readConfig();
68 69

    m_editor->slotUpdateCollection();
70
}
71

72
PlaylistSplitter::~PlaylistSplitter()
73
{
74
    saveConfig();
75 76
}

77
QString PlaylistSplitter::uniquePlaylistName(const QString &startingWith, bool useParenthesis)
78
{
79
    if(!m_playlistBox)
80
	return QString::null;
81

82
    QStringList names = m_playlistBox->names();
83 84 85 86 87 88

    int playlistNumber = 1;

    // while the list contains more than zero instances of the generated 
    // string...

89 90 91 92
    if(useParenthesis) {
	while(names.contains(startingWith + " (" + QString::number(playlistNumber) + ")") != 0)
	    playlistNumber++;
	
93
	return startingWith + " (" + QString::number(playlistNumber) + ")";	
94 95 96 97 98 99
    }
    else
    {
	while(names.contains(startingWith + ' ' + QString::number(playlistNumber)) != 0)
	    playlistNumber++;
	
100
	return startingWith + " " + QString::number(playlistNumber);
101
    }
102 103
}

104
QString PlaylistSplitter::playNextFile(bool random)
105
{
106 107
    PlaylistItem *i;

108 109 110
    // Four basic cases here:  (1) We've asked for a specific next item, (2) play
    // the item that's after the currently playing item, (3) play the selected 
    // item or (4) play the first item in the list.
111

112
    if(m_nextPlaylistItem && m_nextPlaylistItem != m_playingItem) {
113 114 115 116 117
	i = m_nextPlaylistItem;
	m_nextPlaylistItem = 0;
    }  
    else if(m_playingItem) {
	Playlist *p = static_cast<Playlist *>(m_playingItem->listView());
118
	i = p->nextItem(m_playingItem, random);
119 120
    }
    else {
121 122 123
	i = playlistSelection().getFirst();
	if(!i)
	    i = static_cast<PlaylistItem *>(visiblePlaylist()->firstChild());
124 125
    }

126
    return play(i);
127 128
}

129
QString PlaylistSplitter::playPreviousFile(bool random)
130
{
131
    if(!m_playingItem)
132
	return QString::null;
133

134 135
    Playlist *p = static_cast<Playlist *>(m_playingItem->listView());
    PlaylistItem *i = p->previousItem(m_playingItem, random);
136

137
    return play(i);
138 139
}

140 141 142 143
QString PlaylistSplitter::playFirstFile()
{
    Playlist *p = visiblePlaylist();
    PlaylistItem *i = static_cast<PlaylistItem *>(p->firstChild());
144

145
    return play(i);
146 147
}

148 149
void PlaylistSplitter::stop()
{
150 151
    m_nextPlaylistItem = 0;

152 153 154
    if(m_playingItem) {
	m_playingItem->setPixmap(0, 0);
	m_playingItem = 0;
155 156 157 158 159
    }
}

QString PlaylistSplitter::playingArtist() const
{
160 161
    if(m_playingItem)
	return m_playingItem->text(PlaylistItem::ArtistColumn);
162
    else
163
	return QString::null;
164 165 166 167
}

QString PlaylistSplitter::playingTrack() const
{
168 169
    if(m_playingItem)
	return m_playingItem->text(PlaylistItem::TrackColumn);
170
    else
171
	return QString::null;
172 173 174 175
}

QString PlaylistSplitter::playingList() const
{
176 177
    if(m_playingItem)
	return static_cast<Playlist *>(m_playingItem->listView())->name();
178
    else
179
	return QString::null;
180 181
}

182
QString PlaylistSplitter::extensionsString(const QStringList &extensions, const QString &type) // static
183
{
184 185 186 187 188 189 190 191 192 193 194 195
    QStringList l;

    for(QStringList::ConstIterator it = extensions.begin(); it != extensions.end(); ++it)
	l.append(QString("*." + (*it)));

    // i.e. "*.m3u, *.mp3|Media Files"

    QString s = l.join(" ");

    if(type != QString::null)
	s += "|" + type + " (" + l.join(", ") + ")";

196
    return s;
197 198
}

199 200
void PlaylistSplitter::open(const QString &file) 
{
201 202 203
    if(file.isEmpty())
	return;

204
    if(visiblePlaylist() == m_collection || 
205 206
       KMessageBox::questionYesNo(this, i18n("Do you want to add this item to the current list or to the collection list?"), 
				  QString::null, KGuiItem(i18n("Current")), KGuiItem(i18n("Collection"))) == KMessageBox::No)
207
	slotAddToPlaylist(file, m_collection);
208
    else
209
	slotAddToPlaylist(file, visiblePlaylist());
210 211 212 213
}

void PlaylistSplitter::open(const QStringList &files) 
{
214 215 216
    if(files.isEmpty())
	return;
    
217
    if(visiblePlaylist() == m_collection || 
218 219
       KMessageBox::questionYesNo(this, i18n("Do you want to add these items to the current list or to the collection list?"), 
				  QString::null, KGuiItem(i18n("Current")), KGuiItem(i18n("Collection"))) == KMessageBox::No)
220
	slotAddToPlaylist(files, m_collection);
221
    else
222
	slotAddToPlaylist(files, visiblePlaylist());
223 224 225 226
}

Playlist *PlaylistSplitter::createPlaylist(const QString &name)
{
227
    Playlist *p = new Playlist(m_playlistStack, name.latin1());
228 229
    setupPlaylist(p, true);
    return p;
230 231
}

232 233 234 235
////////////////////////////////////////////////////////////////////////////////
// public slots
////////////////////////////////////////////////////////////////////////////////

236
void PlaylistSplitter::slotOpen()
237
{
238
    QStringList files = KFileDialog::getOpenFileNames(QString::null, 
239
						      extensionsString((*m_mediaExtensions + *m_listExtensions), i18n("Media Files")));
240 241 242
    open(files);
}

243
void PlaylistSplitter::slotOpenDirectory()
244
{ 
245
    DirectoryList *l = new DirectoryList(m_directoryList, this, "directoryList");
246

247
    m_directoryQueue.clear();
248
    m_directoryQueueRemove.clear();
249

250 251
    connect(l, SIGNAL(signalDirectoryAdded(const QString &)), this, SLOT(slotQueueDirectory(const QString &)));
    connect(l, SIGNAL(signalDirectoryRemoved(const QString &)), this, SLOT(slotQueueDirectoryRemove(const QString &)));
252 253

    if(l->exec() == QDialog::Accepted) {
254
	open(m_directoryQueue);
255 256 257
	for(QStringList::Iterator it = m_directoryQueue.begin(); it !=  m_directoryQueue.end(); it++)
	    m_dirWatch->addDir(*it, false, true);
	    
258
	m_directoryList += m_directoryQueue;
259 260
	for(QStringList::Iterator it = m_directoryQueueRemove.begin(); it !=  m_directoryQueueRemove.end(); it++) {
	    m_dirWatch->removeDir(*it);
261
	    m_directoryList.remove(*it);
262
	}
263 264
    }
}
265
void PlaylistSplitter::slotSetEditorVisible(bool visible)
266 267
{
    if(visible)
268
	m_editor->show();
269
    else
270
	m_editor->hide();
271 272
}

273
Playlist *PlaylistSplitter::slotCreatePlaylist()
274 275 276
{
    bool ok;

277
    // If this text is changed, please also change it in PlaylistBox::duplicate().
278 279 280 281

    QString name = QInputDialog::getText(i18n("New Playlist..."), i18n("Please enter a name for the new playlist:"),
					 QLineEdit::Normal, uniquePlaylistName(), &ok);
    if(ok)
282
	return createPlaylist(name);
283
    else
284
	return 0;
285 286
}

287
void PlaylistSplitter::slotSelectPlaying()
288
{
289
    if(!m_playingItem)
290 291
	return;

292
    Playlist *l = static_cast<Playlist *>(m_playingItem->listView());
293
	
294 295
    if(!l)
	return;
296

297
    l->clearSelection();
298 299
    l->setSelected(m_playingItem, true);
    l->ensureItemVisible(m_playingItem);
300
    
301
    m_playlistBox->raise(l);
302 303
}

304
void PlaylistSplitter::slotDeleteSelectedItems()
305 306 307
{
    Playlist *p = visiblePlaylist();
    if(p)
308
	p->slotDeleteSelectedItems();
309 310
}

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
void PlaylistSplitter::slotAddToPlaylist(const QString &file, Playlist *list)
{
    KApplication::setOverrideCursor(Qt::waitCursor);
    addImpl(file, list);
    KApplication::restoreOverrideCursor();
    
    if(m_editor)
	m_editor->slotUpdateCollection();
}

void PlaylistSplitter::slotAddToPlaylist(const QStringList &files, Playlist *list)
{
    KApplication::setOverrideCursor(Qt::waitCursor);
    for(QStringList::ConstIterator it = files.begin(); it != files.end(); ++it)
        addImpl(*it, list);
    KApplication::restoreOverrideCursor();

    if(m_editor)
	m_editor->slotUpdateCollection();
}

332
void PlaylistSplitter::slotToggleColumnVisible(int column)
333
{
334 335 336
    m_visibleColumns[column] = ! m_visibleColumns[column];
    if(visiblePlaylist())
	setupColumns(visiblePlaylist());
337 338
}

339 340 341 342 343 344
////////////////////////////////////////////////////////////////////////////////
// private members
////////////////////////////////////////////////////////////////////////////////

void PlaylistSplitter::setupLayout()
{
345
    m_playlistBox = new PlaylistBox(this, "playlistBox");
346 347 348 349 350 351 352

    // Create a splitter to go between the playlists and the editor.

    QSplitter *editorSplitter = new QSplitter(Qt::Vertical, this, "editorSplitter");

    // Create the playlist and the editor.

353 354
    m_playlistStack = new QWidgetStack(editorSplitter, "playlistStack");
    m_editor = new TagEditor(editorSplitter, "tagEditor");
355 356 357

    // Make the editor as small as possible (or at least as small as recommended)

358
    editorSplitter->setResizeMode(m_editor, QSplitter::FollowSizeHint);
359 360 361 362

    // Make the connection that will update the selected playlist when a 
    // selection is made in the playlist box.

363 364
    connect(m_playlistBox, SIGNAL(signalCurrentChanged(Playlist *)), 
	    this, SLOT(slotChangePlaylist(Playlist *)));
365

366
    connect(m_playlistBox, SIGNAL(signalDoubleClicked()), this, SIGNAL(signalListBoxDoubleClicked()));
367 368 369 370

    // Create the collection list; this should always exist.  This has a 
    // slightly different creation process than normal playlists (since it in
    // fact is a subclass) so it is created here rather than by using 
371
    // slotCreatePlaylist().
372

373
    CollectionList::initialize(m_playlistStack, m_restore);
374 375
    m_collection = CollectionList::instance();
    setupPlaylist(m_collection, true, "folder_sound");
376
    connect(m_collection, SIGNAL(signalCollectionChanged()), m_editor, SLOT(slotUpdateCollection()));
377 378

    // Show the collection on startup.
379
    m_playlistBox->setSelected(0, true);
380 381 382 383
}

void PlaylistSplitter::readConfig()
{
384 385 386 387
    KConfig *config = KGlobal::config();
    { // block for Playlists group
	KConfigGroupSaver saver(config, "Playlists");

388 389 390 391 392 393 394
	QValueList<int> splitterSizes = config->readIntListEntry("PlaylistSplitterSizes");
	if(splitterSizes.isEmpty()) {
	    splitterSizes.append(100);
	    splitterSizes.append(640);
	}
	setSizes(splitterSizes);
	
395
	if(m_restore) {
396 397 398 399

	    QString playlistsFile = KGlobal::dirs()->saveLocation("appdata") + "playlists";

	    QFile f(playlistsFile);
400
	    
401 402 403
	    if(f.open(IO_ReadOnly)) {
		QDataStream s(&f);
		while(!s.atEnd()) {
404
		    Playlist *p = new Playlist(m_playlistStack);
405 406 407 408
		    s >> *p;

		    // check to see if we've alredy loaded this item before continuing

409
		    if(p->fileName().isEmpty() || !m_playlistFiles.insert(p->fileName()))
410 411 412 413
			setupPlaylist(p);
		    else
			delete p;
		}
414
	    }
415

416
	    m_directoryList = config->readListEntry("DirectoryList");
417
	    QTimer::singleShot(0, this, SLOT(slotScanDirectories()));
418 419 420 421 422 423 424 425

	    m_dirWatch = new KDirWatch();
	    connect(m_dirWatch, SIGNAL(dirty(const QString &)), this, SLOT(slotDirChanged(const QString &)));

            for(QStringList::Iterator it = m_directoryList.begin(); it != m_directoryList.end(); ++it)
		m_dirWatch->addDir(*it, false, true);

	    m_dirWatch->startScan();
426
	}
427 428 429

	// restore the list of hidden and shown columns

430
	if(m_collection) {
431
	    // the last column is just a filler
432
	    m_visibleColumns.resize(m_collection->columns() - 1, true);
433 434 435 436 437
	    QValueList<int> l = config->readIntListEntry("VisibleColumns");

	    uint i = 0;
	    for(QValueList<int>::Iterator it = l.begin(); it != l.end(); ++it) {
		if(! bool(*it)) {
438
		    m_visibleColumns[i] = bool(*it);
439
		    m_collection->hideColumn(i);
440
		}
441

442
		// while we're looping go ahead and populate m_columnNames
443
		
444
		m_columnNames.append(m_collection->columnText(i));
445

446 447
		i++;
	    }
448
	    setupColumns(m_collection);
449
	}
450
    }
451
}
452 453 454 455

void PlaylistSplitter::saveConfig()
{
    KConfig *config = KGlobal::config();
456

457 458
    // Save the list of open playlists.
    
459
    if(m_restore && m_playlistBox) {
460 461 462

	// Start at item 1.  We want to skip the collection list.

463 464 465 466 467 468 469
	QString playlistsFile = KGlobal::dirs()->saveLocation("appdata") + "playlists";
	QFile f(playlistsFile);
	
	if(f.open(IO_WriteOnly)) {

	    QDataStream s(&f);

470
	    QPtrList<Playlist> l = m_playlistBox->playlists();
471

472 473
	    for(Playlist *p = l.first(); p; p = l.next())
		s << *p;
474

475
	    f.close();
476 477 478
	}
	{ // block for Playlists group
	    KConfigGroupSaver saver(config, "Playlists");
479
	    config->writeEntry("DirectoryList", m_directoryList);
480 481

	    QValueList<int> l;
482 483
	    for(uint i = 0; i < m_visibleColumns.size(); i++)
		l.append(int(m_visibleColumns[i]));
484 485
	    
	    config->writeEntry("VisibleColumns", l);
486 487

	    config->writeEntry("PlaylistSplitterSizes", sizes());
488 489
	}
    }
490 491
}

492 493 494 495 496 497 498 499 500 501 502 503 504 505
void PlaylistSplitter::addImpl(const QString &file, Playlist *list)
{
    processEvents();
    QFileInfo fileInfo(QDir::cleanDirPath(file));
    if(fileInfo.exists()) {
        if(fileInfo.isDir()) {
            QDir dir(fileInfo.filePath());
            QStringList dirContents=dir.entryList();
            for(QStringList::Iterator it = dirContents.begin(); it != dirContents.end(); ++it)
                if(*it != "." && *it != "..")
                    addImpl(fileInfo.filePath() + QDir::separator() + *it, list);
        }
        else {
            QString extension = fileInfo.extension(false);
506
            if(m_mediaExtensions->contains(extension) > 0)
507
		list->createItem(fileInfo);
508
	    else if(m_listExtensions->contains(extension) > 0)
509 510 511 512 513
		openPlaylist(fileInfo.absFilePath());
        }
    }    
}

514
void PlaylistSplitter::setupPlaylist(Playlist *p, bool raise, const char *icon)
515
{
516 517 518 519
    connect(p, SIGNAL(signalSelectionChanged(const PlaylistItemList &)), m_editor, SLOT(slotSetItems(const PlaylistItemList &)));
    connect(p, SIGNAL(signalDoubleClicked()), this, SIGNAL(signalDoubleClicked()));
    connect(p, SIGNAL(signalNumberOfItemsChanged(Playlist *)), this, SLOT(slotPlaylistCountChanged(Playlist *)));
    connect(p, SIGNAL(signalAboutToRemove(PlaylistItem *)), this, SLOT(slotPlaylistItemRemoved(PlaylistItem *)));
520 521
    connect(p, SIGNAL(signalFilesDropped(const QStringList &, Playlist *)), this, SLOT(slotAddToPlaylist(const QStringList &, Playlist *)));
    connect(p, SIGNAL(signalSetNext(PlaylistItem *)), this, SLOT(slotSetNextItem(PlaylistItem *)));
522

523 524
    connect(p, SIGNAL(signalToggleColumnVisible(int)), this, SLOT(slotToggleColumnVisible(int)));

525
    m_playlistBox->createItem(p, icon, raise);
526

527
    if(raise) {
528
	m_playlistStack->raiseWidget(p);
529
	setupColumns(p);
530
    }
531 532
}

533 534 535
Playlist *PlaylistSplitter::openPlaylist(const QString &file)
{
    QFileInfo fileInfo(file);
536
    if(!fileInfo.exists() || !fileInfo.isFile() || !fileInfo.isReadable() || m_playlistFiles.insert(fileInfo.absFilePath()))
537
	return 0;
538

539
    Playlist *p = new Playlist(file, m_playlistStack, fileInfo.baseName(true).latin1());
540
    setupPlaylist(p);
541
    return p;
542 543
}

544 545 546 547 548
void PlaylistSplitter::setupColumns(Playlist *p)
{
    if(!p)
	return;
    
549 550
    for(uint i = 0; i < m_visibleColumns.size(); i++) {
	if(m_visibleColumns[i] && ! p->isColumnVisible(i))
551
	    p->showColumn(i);
552
	else if(! m_visibleColumns[i] && p->isColumnVisible(i))
553 554 555 556
	    p->hideColumn(i);
    }
}

557 558 559 560 561 562 563 564 565 566 567 568 569
QString PlaylistSplitter::play(PlaylistItem *item)
{
    stop();

    if(!item)
	return QString::null;

    item->setPixmap(0, QPixmap(UserIcon("playing")));
    m_playingItem = item;

    return item->absFilePath();
}

570 571 572 573
////////////////////////////////////////////////////////////////////////////////
// private slots
////////////////////////////////////////////////////////////////////////////////

574
void PlaylistSplitter::slotChangePlaylist(Playlist *p)
575
{
576 577
    if(!p)
	return;
578 579

    m_nextPlaylistItem = 0; 
580
    m_playlistStack->raiseWidget(p);
581
    m_editor->slotSetItems(playlistSelection());
582
    setupColumns(p);
583
    emit signalPlaylistChanged();
584 585
}

586
void PlaylistSplitter::slotPlaylistCountChanged(Playlist *p)
587
{
588 589
    if(p && p == m_playlistStack->visibleWidget())
	emit signalSelectedPlaylistCountChanged(p->childCount());
590 591
}

592
void PlaylistSplitter::slotPlaylistItemRemoved(PlaylistItem *item)
593
{
594 595
    if(item == m_playingItem)
	m_playingItem = 0;
596 597 598

    if(item == m_nextPlaylistItem)
	m_nextPlaylistItem = 0;
599 600
}

601
#include "playlistsplitter.moc"