playlistsplitter.cpp 17.6 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
{
Scott Wheeler's avatar
Scott Wheeler committed
74
    delete m_dirWatch;
75
    saveConfig();
76 77
}

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

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

    int playlistNumber = 1;

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

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

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

109 110 111
    // 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.
112

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

127
    return play(i);
128 129
}

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

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

138
    return play(i);
139 140
}

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

146
    return play(i);
147 148
}

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

153 154 155 156 157 158 159
    if(!m_playingItem)
	return;

    Playlist *p = static_cast<Playlist *>(m_playingItem->listView());

    p->setPlaying(m_playingItem, false);
    m_playingItem = 0;
160 161 162 163
}

QString PlaylistSplitter::playingArtist() const
{
164 165
    if(m_playingItem)
	return m_playingItem->text(PlaylistItem::ArtistColumn);
166
    else
167
	return QString::null;
168 169 170 171
}

QString PlaylistSplitter::playingTrack() const
{
172 173
    if(m_playingItem)
	return m_playingItem->text(PlaylistItem::TrackColumn);
174
    else
175
	return QString::null;
176 177 178 179
}

QString PlaylistSplitter::playingList() const
{
180 181
    if(m_playingItem)
	return static_cast<Playlist *>(m_playingItem->listView())->name();
182
    else
183
	return QString::null;
184 185
}

186
QString PlaylistSplitter::extensionsString(const QStringList &extensions, const QString &type) // static
187
{
188 189 190 191 192 193 194 195 196 197 198 199
    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(", ") + ")";

200
    return s;
201 202
}

203 204
void PlaylistSplitter::open(const QString &file) 
{
205 206 207
    if(file.isEmpty())
	return;

208
    if(visiblePlaylist() == m_collection || 
209 210
       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)
211
	slotAddToPlaylist(file, m_collection);
212
    else
213
	slotAddToPlaylist(file, visiblePlaylist());
214 215 216 217
}

void PlaylistSplitter::open(const QStringList &files) 
{
218 219 220
    if(files.isEmpty())
	return;
    
221
    if(visiblePlaylist() == m_collection || 
222 223
       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)
224
	slotAddToPlaylist(files, m_collection);
225
    else
226
	slotAddToPlaylist(files, visiblePlaylist());
227 228 229 230
}

Playlist *PlaylistSplitter::createPlaylist(const QString &name)
{
231
    Playlist *p = new Playlist(m_playlistStack, name.latin1());
232 233
    setupPlaylist(p, true);
    return p;
234 235
}

236 237 238 239
////////////////////////////////////////////////////////////////////////////////
// public slots
////////////////////////////////////////////////////////////////////////////////

240
void PlaylistSplitter::slotOpen()
241
{
242
    QStringList files = KFileDialog::getOpenFileNames(QString::null, 
243
						      extensionsString((*m_mediaExtensions + *m_listExtensions), i18n("Media Files")));
244 245 246
    open(files);
}

247
void PlaylistSplitter::slotOpenDirectory()
248
{ 
249
    DirectoryList *l = new DirectoryList(m_directoryList, this, "directoryList");
250

251
    m_directoryQueue.clear();
252
    m_directoryQueueRemove.clear();
253

254 255
    connect(l, SIGNAL(signalDirectoryAdded(const QString &)), this, SLOT(slotQueueDirectory(const QString &)));
    connect(l, SIGNAL(signalDirectoryRemoved(const QString &)), this, SLOT(slotQueueDirectoryRemove(const QString &)));
256 257

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

277
Playlist *PlaylistSplitter::slotCreatePlaylist()
278 279 280
{
    bool ok;

281
    // If this text is changed, please also change it in PlaylistBox::duplicate().
282 283 284 285

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

291
void PlaylistSplitter::slotSelectPlaying()
292
{
293
    if(!m_playingItem)
294 295
	return;

296
    Playlist *l = static_cast<Playlist *>(m_playingItem->listView());
297
	
298 299
    if(!l)
	return;
300

301
    l->clearSelection();
302 303
    l->setSelected(m_playingItem, true);
    l->ensureItemVisible(m_playingItem);
304
    
305
    m_playlistBox->raise(l);
306 307
}

308
void PlaylistSplitter::slotDeleteSelectedItems()
309 310 311
{
    Playlist *p = visiblePlaylist();
    if(p)
312
	p->slotDeleteSelectedItems();
313 314
}

315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
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();
}

336
void PlaylistSplitter::slotToggleColumnVisible(int column)
337
{
338 339 340
    m_visibleColumns[column] = ! m_visibleColumns[column];
    if(visiblePlaylist())
	setupColumns(visiblePlaylist());
341 342
}

343 344 345 346 347 348
////////////////////////////////////////////////////////////////////////////////
// private members
////////////////////////////////////////////////////////////////////////////////

void PlaylistSplitter::setupLayout()
{
349
    m_playlistBox = new PlaylistBox(this, "playlistBox");
350 351 352 353 354 355 356

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

357 358
    m_playlistStack = new QWidgetStack(editorSplitter, "playlistStack");
    m_editor = new TagEditor(editorSplitter, "tagEditor");
359 360 361

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

362
    editorSplitter->setResizeMode(m_editor, QSplitter::FollowSizeHint);
363 364 365 366

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

367 368
    connect(m_playlistBox, SIGNAL(signalCurrentChanged(Playlist *)), 
	    this, SLOT(slotChangePlaylist(Playlist *)));
369

370
    connect(m_playlistBox, SIGNAL(signalDoubleClicked()), this, SIGNAL(signalListBoxDoubleClicked()));
371 372 373 374

    // 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 
375
    // slotCreatePlaylist().
376

377
    CollectionList::initialize(m_playlistStack, m_restore);
378 379
    m_collection = CollectionList::instance();
    setupPlaylist(m_collection, true, "folder_sound");
380
    connect(m_collection, SIGNAL(signalCollectionChanged()), m_editor, SLOT(slotUpdateCollection()));
381 382

    // Show the collection on startup.
383
    m_playlistBox->setSelected(0, true);
384 385 386 387
}

void PlaylistSplitter::readConfig()
{
388 389 390 391
    KConfig *config = KGlobal::config();
    { // block for Playlists group
	KConfigGroupSaver saver(config, "Playlists");

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

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

	    QFile f(playlistsFile);
404
	    
405 406 407
	    if(f.open(IO_ReadOnly)) {
		QDataStream s(&f);
		while(!s.atEnd()) {
408
		    Playlist *p = new Playlist(m_playlistStack);
409 410 411 412
		    s >> *p;

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

413
		    if(p->fileName().isEmpty() || !m_playlistFiles.insert(p->fileName()))
414 415 416 417
			setupPlaylist(p);
		    else
			delete p;
		}
418
	    }
419

420
	    m_directoryList = config->readListEntry("DirectoryList");
421
	    QTimer::singleShot(0, this, SLOT(slotScanDirectories()));
422 423 424 425 426 427 428 429

	    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();
430
	}
431 432 433

	// restore the list of hidden and shown columns

434
	if(m_collection) {
435
	    // the last column is just a filler
436
	    m_visibleColumns.resize(m_collection->columns() - 1, true);
437
	    QValueList<int> l = config->readIntListEntry("VisibleColumns");
438
	    m_collection->setSorting( config->readNumEntry("SortColumn", 1) );
439 440 441 442

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

447
		// while we're looping go ahead and populate m_columnNames
448
		
449
		m_columnNames.append(m_collection->columnText(i));
450

451 452
		i++;
	    }
453
	    setupColumns(m_collection);
454
	}
455
    }
456
}
457 458 459 460

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

462 463
    // Save the list of open playlists.
    
464
    if(m_restore && m_playlistBox) {
465 466 467

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

468 469 470 471 472 473 474
	QString playlistsFile = KGlobal::dirs()->saveLocation("appdata") + "playlists";
	QFile f(playlistsFile);
	
	if(f.open(IO_WriteOnly)) {

	    QDataStream s(&f);

475
	    QPtrList<Playlist> l = m_playlistBox->playlists();
476

477 478
	    for(Playlist *p = l.first(); p; p = l.next())
		s << *p;
479

480
	    f.close();
481 482 483
	}
	{ // block for Playlists group
	    KConfigGroupSaver saver(config, "Playlists");
484
	    config->writeEntry("DirectoryList", m_directoryList);
485 486

	    QValueList<int> l;
487 488
	    for(uint i = 0; i < m_visibleColumns.size(); i++)
		l.append(int(m_visibleColumns[i]));
489 490
	    
	    config->writeEntry("VisibleColumns", l);
491
	    config->writeEntry("SortColumn", m_collection->sortColumn());
492 493

	    config->writeEntry("PlaylistSplitterSizes", sizes());
494 495
	}
    }
496 497
}

498 499 500 501 502 503 504 505 506 507 508 509 510 511
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);
512
            if(m_mediaExtensions->contains(extension) > 0)
513
		list->createItem(fileInfo);
514
	    else if(m_listExtensions->contains(extension) > 0)
515 516 517 518 519
		openPlaylist(fileInfo.absFilePath());
        }
    }    
}

520
void PlaylistSplitter::setupPlaylist(Playlist *p, bool raise, const char *icon)
521
{
522 523 524 525
    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 *)));
526 527
    connect(p, SIGNAL(signalFilesDropped(const QStringList &, Playlist *)), this, SLOT(slotAddToPlaylist(const QStringList &, Playlist *)));
    connect(p, SIGNAL(signalSetNext(PlaylistItem *)), this, SLOT(slotSetNextItem(PlaylistItem *)));
528

529 530
    connect(p, SIGNAL(signalToggleColumnVisible(int)), this, SLOT(slotToggleColumnVisible(int)));

531
    m_playlistBox->createItem(p, icon, raise);
532

533
    if(raise) {
534
	m_playlistStack->raiseWidget(p);
535
	setupColumns(p);
536
    }
537 538
}

539 540 541
Playlist *PlaylistSplitter::openPlaylist(const QString &file)
{
    QFileInfo fileInfo(file);
542
    if(!fileInfo.exists() || !fileInfo.isFile() || !fileInfo.isReadable() || m_playlistFiles.insert(fileInfo.absFilePath()))
543
	return 0;
544

545
    Playlist *p = new Playlist(file, m_playlistStack, fileInfo.baseName(true).latin1());
546
    setupPlaylist(p);
547
    return p;
548 549
}

550 551 552 553 554
void PlaylistSplitter::setupColumns(Playlist *p)
{
    if(!p)
	return;
    
555 556
    for(uint i = 0; i < m_visibleColumns.size(); i++) {
	if(m_visibleColumns[i] && ! p->isColumnVisible(i))
557
	    p->showColumn(i);
558
	else if(! m_visibleColumns[i] && p->isColumnVisible(i))
559 560 561 562
	    p->hideColumn(i);
    }
}

563 564 565 566 567 568 569
QString PlaylistSplitter::play(PlaylistItem *item)
{
    stop();

    if(!item)
	return QString::null;

570 571 572 573
    Playlist *p = static_cast<Playlist *>(item->listView());

    p->setPlaying(item, true);

574 575 576 577 578
    m_playingItem = item;

    return item->absFilePath();
}

579 580 581 582
////////////////////////////////////////////////////////////////////////////////
// private slots
////////////////////////////////////////////////////////////////////////////////

583
void PlaylistSplitter::slotChangePlaylist(Playlist *p)
584
{
585 586
    if(!p)
	return;
587 588

    m_nextPlaylistItem = 0; 
589
    m_playlistStack->raiseWidget(p);
590
    m_editor->slotSetItems(playlistSelection());
591
    setupColumns(p);
592
    emit signalPlaylistChanged();
593 594
}

595
void PlaylistSplitter::slotPlaylistCountChanged(Playlist *p)
596
{
597 598
    if(p && p == m_playlistStack->visibleWidget())
	emit signalSelectedPlaylistCountChanged(p->childCount());
599 600
}

601
void PlaylistSplitter::slotPlaylistItemRemoved(PlaylistItem *item)
602
{
603 604
    if(item == m_playingItem)
	m_playingItem = 0;
605 606 607

    if(item == m_nextPlaylistItem)
	m_nextPlaylistItem = 0;
608 609
}

610
#include "playlistsplitter.moc"