playlistsplitter.cpp 17.5 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 155 156 157 158
    if(!m_playingItem)
	return;

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

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

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

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

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

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

199
    return s;
200 201
}

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

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

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

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

235 236 237 238
////////////////////////////////////////////////////////////////////////////////
// public slots
////////////////////////////////////////////////////////////////////////////////

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	// restore the list of hidden and shown columns

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

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

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

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

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

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

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

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

	    QDataStream s(&f);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    if(!item)
	return QString::null;

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

    p->setPlaying(item, true);

573 574 575 576 577
    m_playingItem = item;

    return item->absFilePath();
}

578 579 580 581
////////////////////////////////////////////////////////////////////////////////
// private slots
////////////////////////////////////////////////////////////////////////////////

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

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

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

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

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

609
#include "playlistsplitter.moc"