playlistsplitter.cpp 18.7 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>
Nadeem Hasan's avatar
Nadeem Hasan committed
24
#include <klineeditdlg.h>
25 26
#include <kdebug.h>

27
#include <qtimer.h>
28

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

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

////////////////////////////////////////////////////////////////////////////////
40
// helper functions
41 42
////////////////////////////////////////////////////////////////////////////////

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

51
////////////////////////////////////////////////////////////////////////////////
52
// public methods
53 54
////////////////////////////////////////////////////////////////////////////////

55
PlaylistSplitter::PlaylistSplitter(QWidget *parent, bool restore, const char *name) : QSplitter(Qt::Horizontal, parent, name), 
56
										      m_playingItem(0), m_restore(restore), m_nextPlaylistItem(0)
57
{
58 59 60 61 62 63 64 65
    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");
    }
66 67 68

    setupLayout();
    readConfig();
69 70

    m_editor->slotUpdateCollection();
71
}
72

73
PlaylistSplitter::~PlaylistSplitter()
74
{
Scott Wheeler's avatar
Scott Wheeler committed
75
    delete m_dirWatch;
76
    saveConfig();
77 78
}

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

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

    int playlistNumber = 1;

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

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

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

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

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

130
    return play(i);
131 132
}

133
QString PlaylistSplitter::playPreviousFile(bool random)
134
{
135
    if(!m_playingItem)
136
	return QString::null;
137

138 139
    Playlist *p = static_cast<Playlist *>(m_playingItem->listView());
    PlaylistItem *i = p->previousItem(m_playingItem, random);
140

141
    return play(i);
142 143
}

144 145 146 147 148 149 150 151
QString PlaylistSplitter::playSelectedFile()
{
    if(playlistSelection().isEmpty())
	return QString::null;
    else
	return play(playlistSelection().first());
}

152 153 154 155
QString PlaylistSplitter::playFirstFile()
{
    Playlist *p = visiblePlaylist();
    PlaylistItem *i = static_cast<PlaylistItem *>(p->firstChild());
156

157
    return play(i);
158 159
}

160 161
void PlaylistSplitter::stop()
{
162 163
    m_nextPlaylistItem = 0;

164 165 166 167 168 169 170
    if(!m_playingItem)
	return;

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

    p->setPlaying(m_playingItem, false);
    m_playingItem = 0;
171 172 173 174
}

QString PlaylistSplitter::playingArtist() const
{
175 176
    if(m_playingItem)
	return m_playingItem->text(PlaylistItem::ArtistColumn);
177
    else
178
	return QString::null;
179 180 181 182
}

QString PlaylistSplitter::playingTrack() const
{
183 184
    if(m_playingItem)
	return m_playingItem->text(PlaylistItem::TrackColumn);
185
    else
186
	return QString::null;
187 188 189 190
}

QString PlaylistSplitter::playingList() const
{
191 192
    if(m_playingItem)
	return static_cast<Playlist *>(m_playingItem->listView())->name();
193
    else
194
	return QString::null;
195 196
}

197
QString PlaylistSplitter::extensionsString(const QStringList &extensions, const QString &type) // static
198
{
199 200 201 202 203 204 205 206 207 208 209 210
    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(", ") + ")";

211
    return s;
212 213
}

214 215
void PlaylistSplitter::open(const QString &file) 
{
216 217 218
    if(file.isEmpty())
	return;

219
    if(visiblePlaylist() == m_collection || 
220 221 222 223 224 225
       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)
    {
226
	slotAddToPlaylist(file, m_collection);
227
    }
228
    else
229
	slotAddToPlaylist(file, visiblePlaylist());
230 231 232 233
}

void PlaylistSplitter::open(const QStringList &files) 
{
234 235 236
    if(files.isEmpty())
	return;
    
237
    if(visiblePlaylist() == m_collection || 
238 239 240 241 242 243
       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) 
    {
244
	slotAddToPlaylist(files, m_collection);
245
    }
246
    else
247
	slotAddToPlaylist(files, visiblePlaylist());
248 249 250 251
}

Playlist *PlaylistSplitter::createPlaylist(const QString &name)
{
252
    Playlist *p = new Playlist(m_playlistStack, name.latin1());
253 254
    setupPlaylist(p, true);
    return p;
255 256
}

257 258 259 260
////////////////////////////////////////////////////////////////////////////////
// public slots
////////////////////////////////////////////////////////////////////////////////

261
void PlaylistSplitter::slotOpen()
262
{
263 264
    QStringList files = KFileDialog::getOpenFileNames(
	QString::null, extensionsString((*m_mediaExtensions + *m_listExtensions), i18n("Media Files")));
265 266 267
    open(files);
}

268
void PlaylistSplitter::slotOpenDirectory()
269
{ 
270
    DirectoryList *l = new DirectoryList(m_directoryList, this, "directoryList");
271

272
    m_directoryQueue.clear();
273
    m_directoryQueueRemove.clear();
274

275 276 277 278
    connect(l, SIGNAL(signalDirectoryAdded(const QString &)), 
	    this, SLOT(slotQueueDirectory(const QString &)));
    connect(l, SIGNAL(signalDirectoryRemoved(const QString &)), 
	    this, SLOT(slotQueueDirectoryRemove(const QString &)));
279 280

    if(l->exec() == QDialog::Accepted) {
281
	open(m_directoryQueue);
282 283 284
	for(QStringList::Iterator it = m_directoryQueue.begin(); it !=  m_directoryQueue.end(); it++)
	    m_dirWatch->addDir(*it, false, true);
	    
285
	m_directoryList += m_directoryQueue;
286 287 288

	QStringList::Iterator it = m_directoryQueueRemove.begin();
	for(; it !=  m_directoryQueueRemove.end(); it++) {
289
	    m_dirWatch->removeDir(*it);
290
	    m_directoryList.remove(*it);
291
	}
292 293
    }
}
294

295
Playlist *PlaylistSplitter::slotCreatePlaylist()
296 297 298
{
    bool ok;

299
    // If this text is changed, please also change it in PlaylistBox::duplicate().
300

Nadeem Hasan's avatar
Nadeem Hasan committed
301 302 303
    QString name = KLineEditDlg::getText(i18n("Create New Playlist"), 
	i18n("Please enter a name for the new playlist:"),
	uniquePlaylistName(), &ok);
304
    if(ok)
305
	return createPlaylist(name);
306
    else
307
	return 0;
308 309
}

310
void PlaylistSplitter::slotSelectPlaying()
311
{
312
    if(!m_playingItem)
313 314
	return;

315
    Playlist *l = static_cast<Playlist *>(m_playingItem->listView());
316
	
317 318
    if(!l)
	return;
319

320
    l->clearSelection();
321 322
    l->setSelected(m_playingItem, true);
    l->ensureItemVisible(m_playingItem);
Nadeem Hasan's avatar
Nadeem Hasan committed
323

324
    m_playlistBox->raise(l);
325 326
}

327
void PlaylistSplitter::slotDeleteSelectedItems()
328 329 330
{
    Playlist *p = visiblePlaylist();
    if(p)
331
	p->slotDeleteSelectedItems();
332 333
}

334 335 336 337 338
void PlaylistSplitter::slotAddToPlaylist(const QString &file, Playlist *list)
{
    KApplication::setOverrideCursor(Qt::waitCursor);
    addImpl(file, list);
    KApplication::restoreOverrideCursor();
Nadeem Hasan's avatar
Nadeem Hasan committed
339

340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
    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();
}

355 356 357 358 359 360 361
void PlaylistSplitter::slotGuessTagInfo()
{
    visiblePlaylist()->slotGuessTagInfo();
    if(m_editor)
        m_editor->slotRefresh();
}

362 363 364 365 366 367
////////////////////////////////////////////////////////////////////////////////
// private members
////////////////////////////////////////////////////////////////////////////////

void PlaylistSplitter::setupLayout()
{
368
    m_playlistBox = new PlaylistBox(this, "playlistBox");
369 370 371 372 373 374

    // 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.
375
    
376 377
    m_playlistStack = new QWidgetStack(editorSplitter, "playlistStack");
    m_editor = new TagEditor(editorSplitter, "tagEditor");
378 379 380

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

381
    editorSplitter->setResizeMode(m_editor, QSplitter::FollowSizeHint);
382 383 384 385

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

386 387
    connect(m_playlistBox, SIGNAL(signalCurrentChanged(const PlaylistList &)), 
	    this, SLOT(slotChangePlaylist(const PlaylistList &)));
388

389
    connect(m_playlistBox, SIGNAL(signalDoubleClicked()), this, SIGNAL(signalListBoxDoubleClicked()));
390 391 392 393

    // 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 
394
    // slotCreatePlaylist().
395

396
    CollectionList::initialize(m_playlistStack, m_restore);
397 398
    m_collection = CollectionList::instance();
    setupPlaylist(m_collection, true, "folder_sound");
399
    connect(m_collection, SIGNAL(signalCollectionChanged()), m_editor, SLOT(slotUpdateCollection()));
400 401
    connect(m_collection, SIGNAL(signalRequestPlaylistCreation(const QValueList<QFileInfo> &)), 
	    this, SLOT(slotCreatePlaylist(const QValueList<QFileInfo> &)));
402

403 404 405 406 407 408 409 410 411

    // Create the search widget -- this must be done after the CollectionList is created.
    m_searchWidget = new SearchWidget(editorSplitter, CollectionList::instance(), "searchWidget");
    editorSplitter->moveToFirst(m_searchWidget);
    connect(m_searchWidget, SIGNAL(signalQueryChanged(const QString &, bool)),
	    this, SLOT(slotShowSearchResults(const QString &, bool)));
    connect(CollectionList::instance(), SIGNAL(signalVisibleColumnsChanged()),
	    this, SLOT(slotVisibleColumnsChanged()));

412
    // Show the collection on startup.
413
    m_playlistBox->setSelected(0, true);
414 415 416 417
}

void PlaylistSplitter::readConfig()
{
418 419 420 421
    KConfig *config = KGlobal::config();
    { // block for Playlists group
	KConfigGroupSaver saver(config, "Playlists");

422 423 424 425 426 427 428
	QValueList<int> splitterSizes = config->readIntListEntry("PlaylistSplitterSizes");
	if(splitterSizes.isEmpty()) {
	    splitterSizes.append(100);
	    splitterSizes.append(640);
	}
	setSizes(splitterSizes);
	
429
	if(m_restore) {
430 431 432 433

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

	    QFile f(playlistsFile);
Nadeem Hasan's avatar
Nadeem Hasan committed
434

435 436 437
	    if(f.open(IO_ReadOnly)) {
		QDataStream s(&f);
		while(!s.atEnd()) {
438
		    Playlist *p = new Playlist(m_playlistStack);
439 440 441 442
		    s >> *p;

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

443
		    if(p->fileName().isEmpty() || !m_playlistFiles.insert(p->fileName()))
444 445 446 447
			setupPlaylist(p);
		    else
			delete p;
		}
448
	    }
449

450
	    m_directoryList = config->readListEntry("DirectoryList");
451
	    QTimer::singleShot(0, this, SLOT(slotScanDirectories()));
452 453

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

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

	    m_dirWatch->startScan();
462
	}
463 464 465

	// restore the list of hidden and shown columns

466
	if(m_collection) {
467
	    for(int i = 0; i < m_collection->columns(); i++)
468
		m_columnNames.append(m_collection->columnText(i));
469
	}
470

471
    }
472
}
473 474 475 476

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

478
    // Save the list of open playlists.
Nadeem Hasan's avatar
Nadeem Hasan committed
479

480
    if(m_restore && m_playlistBox) {
481 482 483

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

484 485 486 487 488 489 490
	QString playlistsFile = KGlobal::dirs()->saveLocation("appdata") + "playlists";
	QFile f(playlistsFile);
	
	if(f.open(IO_WriteOnly)) {

	    QDataStream s(&f);

491
	    PlaylistList l = m_playlistBox->playlists();
492

493 494
	    for(PlaylistList::Iterator it = l.begin(); it != l.end(); it++)
		s << *(*it);
495

496
	    f.close();
497 498 499
	}
	{ // block for Playlists group
	    KConfigGroupSaver saver(config, "Playlists");
500
	    config->writeEntry("DirectoryList", m_directoryList);
501
	    config->writeEntry("SortColumn", m_collection->sortColumn());
502
	    config->writeEntry("PlaylistSplitterSizes", sizes());
503 504
	}
    }
505 506
}

507 508 509 510 511 512 513 514 515 516 517 518 519
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 {
520
            QString extension = fileInfo.extension(false).lower();
521
            if(m_mediaExtensions->contains(extension) > 0)
522
		list->createItem(fileInfo);
523
	    else if(m_listExtensions->contains(extension) > 0)
524 525
		openPlaylist(fileInfo.absFilePath());
        }
Nadeem Hasan's avatar
Nadeem Hasan committed
526
    }
527 528
}

529
void PlaylistSplitter::setupPlaylist(Playlist *p, bool raise, const char *icon)
530
{
531 532 533 534 535 536 537 538 539 540 541 542
    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 *)));
    connect(p, SIGNAL(signalFilesDropped(const QStringList &, Playlist *)), 
	    this, SLOT(slotAddToPlaylist(const QStringList &, Playlist *)));
    connect(p, SIGNAL(signalSetNext(PlaylistItem *)),
	    this, SLOT(slotSetNextItem(PlaylistItem *)));
543

544
    m_playlistBox->createItem(p, icon, raise);
545

546
    if(raise)
547
	m_playlistStack->raiseWidget(p);
548 549
}

550 551 552
Playlist *PlaylistSplitter::openPlaylist(const QString &file)
{
    QFileInfo fileInfo(file);
553 554 555 556 557
    if(!fileInfo.exists() || 
       !fileInfo.isFile() || 
       !fileInfo.isReadable() || 
       m_playlistFiles.insert(fileInfo.absFilePath()))
    {
558
	return 0;
559
    }
560

561
    Playlist *p = new Playlist(file, m_playlistStack, fileInfo.baseName(true).latin1());
562
    setupPlaylist(p);
563
    return p;
564 565
}

566 567 568 569 570 571 572
QString PlaylistSplitter::play(PlaylistItem *item)
{
    stop();

    if(!item)
	return QString::null;

573 574 575 576
    Playlist *p = static_cast<Playlist *>(item->listView());

    p->setPlaying(item, true);

577 578 579 580 581
    m_playingItem = item;

    return item->absFilePath();
}

582 583 584 585
////////////////////////////////////////////////////////////////////////////////
// private slots
////////////////////////////////////////////////////////////////////////////////

586
void PlaylistSplitter::slotChangePlaylist(const PlaylistList &l)
587
{
588
    if(l.isEmpty())
589
	return;
590

591 592 593
    m_searchWidget->clear();

    m_nextPlaylistItem = 0;
594
    m_playlistStack->raiseWidget(l.first());
595
    m_editor->slotSetItems(playlistSelection());
596
    emit signalPlaylistChanged();    
597 598
}

599
void PlaylistSplitter::slotPlaylistCountChanged(Playlist *p)
600
{
601 602
    if(p && p == m_playlistStack->visibleWidget())
	emit signalSelectedPlaylistCountChanged(p->childCount());
603 604
}

605
void PlaylistSplitter::slotPlaylistItemRemoved(PlaylistItem *item)
606
{
607 608
    if(item == m_playingItem)
	m_playingItem = 0;
609 610 611

    if(item == m_nextPlaylistItem)
	m_nextPlaylistItem = 0;
612 613
}

614 615 616
void PlaylistSplitter::slotCreatePlaylist(const QValueList<QFileInfo> &fileInfos)
{
    Playlist *playlist = slotCreatePlaylist();
617
    if(!playlist)
618
        return;
619

620 621 622 623 624 625
    QValueList<QFileInfo>::ConstIterator it = fileInfos.begin();
    QValueList<QFileInfo>::ConstIterator end = fileInfos.end();
    for(; it != end; ++it)
        playlist->createItem(*it);
}

626 627 628 629 630 631 632 633 634 635
void PlaylistSplitter::slotShowSearchResults(const QString &query, bool caseSensitive)
{
    if(query.isEmpty()) {
	visiblePlaylist()->setItemsVisible(visiblePlaylist()->items(), true);
	return;
    }

    PlaylistList playlists;
    playlists.append(visiblePlaylist());

636
    PlaylistSearch::Component component(query, caseSensitive, m_searchWidget->searchedColumns(0));
637 638 639 640 641 642 643 644 645
    PlaylistSearch::ComponentList components;
    components.append(&component);

    PlaylistSearch search(playlists, components);

    Playlist::setItemsVisible(search.matchedItems(), true);    
    Playlist::setItemsVisible(search.unmatchedItems(), false);
}

646 647 648 649 650 651 652 653
void PlaylistSplitter::slotVisibleColumnsChanged()
{
    m_searchWidget->slotUpdateColumns();
    m_searchWidget->slotQueryChanged();
    if(m_searchWidget->searchedColumns(0).count() > 1)
	slotShowSearchResults(m_searchWidget->query(), m_searchWidget->caseSensitive());
}

654
#include "playlistsplitter.moc"
Nadeem Hasan's avatar
Nadeem Hasan committed
655 656

// vim:ts=8