filerenamer.cpp 30.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/***************************************************************************
    begin                : Thu Oct 28 2004
    copyright            : (C) 2004 by Michael Pyne
                         : (c) 2003 Frerich Raabe <raabe@kde.org>
    email                : michael.pyne@kdemail.net
***************************************************************************/

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

#include <algorithm>
18

Scott Wheeler's avatar
build  
Scott Wheeler committed
19
#include <kdebug.h>
20 21 22
#include <kcombobox.h>
#include <kurl.h>
#include <kurlrequester.h>
23
#include <kiconloader.h>
24 25
#include <knuminput.h>
#include <kstandarddirs.h>
26
#include <kio/netaccess.h>
27 28 29 30
#include <kconfigbase.h>
#include <kconfig.h>
#include <kglobal.h>
#include <klineedit.h>
31
#include <klocale.h>
32
#include <kpushbutton.h>
33 34
#include <kapplication.h>
#include <kmessagebox.h>
35
#include <ksimpleconfig.h>
36

37
#include <qfile.h>
Laurent Montel's avatar
Laurent Montel committed
38 39 40 41
#include <q3hbox.h>
#include <q3vbox.h>
#include <q3scrollview.h>
#include <qobject.h>
42 43 44 45 46 47 48
#include <qtimer.h>
#include <qregexp.h>
#include <qcheckbox.h>
#include <qdir.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qsignalmapper.h>
Laurent Montel's avatar
Laurent Montel committed
49
#include <q3header.h>
Scott Wheeler's avatar
Scott Wheeler committed
50

Laurent Montel's avatar
Laurent Montel committed
51 52 53
#include <QPixmap>
#include <Q3Frame>
#include <Q3ValueList>
54
#include <Q3HBoxLayout>
55

56 57 58 59 60
#include "tag.h"
#include "filehandle.h"
#include "filerenamer.h"
#include "exampleoptions.h"
#include "playlistitem.h"
61
#include "playlist.h"
62
#include "coverinfo.h"
63 64 65 66 67 68 69 70

class ConfirmationDialog : public KDialogBase
{
public:
    ConfirmationDialog(const QMap<QString, QString> &files,
                       QWidget *parent = 0, const char *name = 0)
        : KDialogBase(parent, name, true, i18n("Warning"), Ok | Cancel)
    {
Scott Wheeler's avatar
Scott Wheeler committed
71 72
        KVBox *vbox = makeVBoxMainWidget();
        KVBox *hbox = new KVBox(vbox);
73 74 75 76 77 78 79 80

        QLabel *l = new QLabel(hbox);
        l->setPixmap(SmallIcon("messagebox_warning", 32));

        l = new QLabel(i18n("You are about to rename the following files. "
                            "Are you sure you want to continue?"), hbox);
        hbox->setStretchFactor(l, 1);

Laurent Montel's avatar
Laurent Montel committed
81
        K3ListView *lv = new K3ListView(vbox);
82 83 84 85 86 87 88 89

        lv->addColumn(i18n("Original Name"));
        lv->addColumn(i18n("New Name"));

        int lvHeight = 0;

        QMap<QString, QString>::ConstIterator it = files.begin();
        for(; it != files.end(); ++it) {
Laurent Montel's avatar
Laurent Montel committed
90 91 92
            K3ListViewItem *i = it.key() != it.data()
                ? new K3ListViewItem(lv, it.key(), it.data())
                : new K3ListViewItem(lv, it.key(), i18n("No Change"));
93 94 95 96 97 98 99 100
            lvHeight += i->height();
        }

        lvHeight += lv->horizontalScrollBar()->height() + lv->header()->height();
        lv->setMinimumHeight(QMIN(lvHeight, 400));
        resize(QMIN(width(), 500), QMIN(minimumHeight(), 400));
    }
};
101 102 103 104 105 106 107

//
// Implementation of ConfigCategoryReader
//

ConfigCategoryReader::ConfigCategoryReader() : CategoryReaderInterface(),
    m_currentItem(0)
108
{
109
    KConfigGroup config(KGlobal::config(), "FileRenamer");
110

Scott Wheeler's avatar
Scott Wheeler committed
111 112
    QList<int> categoryOrder = config.readEntry("CategoryOrder", QList<int>());
    int categoryCount[NumTypes] = { 0 }; // Keep track of each category encountered.
113

114
    // Set a default:
115

116 117
    if(categoryOrder.isEmpty())
        categoryOrder << Artist << Album << Title << Track;
118

Scott Wheeler's avatar
Scott Wheeler committed
119
    QList<int>::ConstIterator catIt = categoryOrder.constBegin();
120 121
    for(; catIt != categoryOrder.constEnd(); ++catIt)
    {
Scott Wheeler's avatar
Scott Wheeler committed
122
        int catCount = categoryCount[*catIt]++;
123 124
        TagType category = static_cast<TagType>(*catIt);
        CategoryID catId(category, catCount);
125

126 127 128
        m_options[catId] = TagRenamerOptions(catId);
        m_categoryOrder << catId;
    }
129

130
    m_folderSeparators.resize(m_categoryOrder.count() - 1, false);
131

Scott Wheeler's avatar
Scott Wheeler committed
132
    QList<int> checkedSeparators = config.readEntry("CheckedDirSeparators", QList<int>());
133

Scott Wheeler's avatar
Scott Wheeler committed
134
    QList<int>::ConstIterator it = checkedSeparators.constBegin();
135
    for(; it != checkedSeparators.constEnd(); ++it) {
Scott Wheeler's avatar
Scott Wheeler committed
136 137
        if(*it < m_folderSeparators.count())
            m_folderSeparators[*it] = true;
138
    }
139

140
    m_musicFolder = config.readEntry("MusicFolder", "${HOME}/music");
141
    m_separator = config.readEntry("Separator", " - ");
142
}
143

144 145 146
QString ConfigCategoryReader::categoryValue(TagType type) const
{
    if(!m_currentItem)
147
        return QString::null;
148 149 150 151 152

    Tag *tag = m_currentItem->file().tag();

    switch(type) {
    case Track:
153
        return QString::number(tag->track());
154 155 156 157 158 159 160 161 162 163 164 165

    case Year:
        return QString::number(tag->year());

    case Title:
        return tag->title();

    case Artist:
        return tag->artist();

    case Album:
        return tag->album();
166

167 168 169 170
    case Genre:
        return tag->genre();

    default:
171
        return QString::null;
172
    }
173
}
174

175
QString ConfigCategoryReader::prefix(const CategoryID &category) const
176
{
177
    return m_options[category].prefix();
178 179
}

180
QString ConfigCategoryReader::suffix(const CategoryID &category) const
181
{
182
    return m_options[category].suffix();
183 184
}

185
TagRenamerOptions::EmptyActions ConfigCategoryReader::emptyAction(const CategoryID &category) const
186
{
187
    return m_options[category].emptyAction();
188 189
}

190
QString ConfigCategoryReader::emptyText(const CategoryID &category) const
191
{
192 193 194
    return m_options[category].emptyText();
}

195
Q3ValueList<CategoryID> ConfigCategoryReader::categoryOrder() const
196 197 198 199 200 201 202 203 204
{
    return m_categoryOrder;
}

QString ConfigCategoryReader::separator() const
{
    return m_separator;
}

Scott Wheeler's avatar
Scott Wheeler committed
205
QString ConfigCategoryReader::musicFolder() const
206
{
Scott Wheeler's avatar
Scott Wheeler committed
207
    return m_musicFolder;
208 209
}

Scott Wheeler's avatar
Scott Wheeler committed
210
int ConfigCategoryReader::trackWidth(int categoryNum) const
211
{
212
    return m_options[CategoryID(Track, categoryNum)].trackWidth();
213 214
}

Scott Wheeler's avatar
Scott Wheeler committed
215
bool ConfigCategoryReader::hasFolderSeparator(int index) const
216
{
217 218
    if(index >= m_folderSeparators.count())
        return false;
219 220 221
    return m_folderSeparators[index];
}

222
bool ConfigCategoryReader::isDisabled(const CategoryID &category) const
223 224 225 226
{
    return m_options[category].disabled();
}

227 228 229 230
//
// Implementation of FileRenamerWidget
//

231
FileRenamerWidget::FileRenamerWidget(QWidget *parent) :
Scott Wheeler's avatar
Scott Wheeler committed
232 233 234
    QWidget(parent),
    Ui::FileRenamerBase(),
    CategoryReaderInterface(),
235
    m_exampleFromFile(false)
236 237 238 239 240
{
    QLabel *temp = new QLabel(0);
    m_exampleText->setPaletteBackgroundColor(temp->paletteBackgroundColor());
    delete temp;

Scott Wheeler's avatar
Scott Wheeler committed
241 242
    #warning Repair this.
    /* layout()->setMargin(0); */ // We'll be wrapped by KDialogBase
243

244 245 246 247 248 249 250
    // This must be created before createTagRows() is called.

    m_exampleDialog = new ExampleOptionsDialog(this);

    createTagRows();
    loadConfig();

251 252
    // Add correct text to combo box.
    m_category->clear();
Scott Wheeler's avatar
Scott Wheeler committed
253
    for(int i = StartTag; i < NumTypes; ++i) {
254 255
        QString category = TagRenamerOptions::tagTypeText(static_cast<TagType>(i));
        m_category->insertItem(category);
256
    }
257 258 259 260 261 262 263 264

    connect(m_exampleDialog, SIGNAL(signalShown()), SLOT(exampleDialogShown()));
    connect(m_exampleDialog, SIGNAL(signalHidden()), SLOT(exampleDialogHidden()));
    connect(m_exampleDialog, SIGNAL(dataChanged()), SLOT(dataSelected()));
    connect(m_exampleDialog, SIGNAL(fileChanged(const QString &)),
            this,            SLOT(fileSelected(const QString &)));

    exampleTextChanged();
265
}
266

267
void FileRenamerWidget::loadConfig()
268
{
Scott Wheeler's avatar
Scott Wheeler committed
269
    QList<int> checkedSeparators;
270 271
    KConfigGroup config(KGlobal::config(), "FileRenamer");

Scott Wheeler's avatar
Scott Wheeler committed
272
    for(int i = 0; i < m_rows.count(); ++i)
273 274
        m_rows[i].options = TagRenamerOptions(m_rows[i].category);

Scott Wheeler's avatar
Scott Wheeler committed
275
    checkedSeparators = config.readEntry("CheckedDirSeparators", QList<int>());
276

Scott Wheeler's avatar
Scott Wheeler committed
277 278 279 280 281
    
    for(QList<int>::ConstIterator it = checkedSeparators.begin();
        it != checkedSeparators.end(); ++it)
    {
        int separator = *it;
282 283
        if(separator < m_folderSwitches.count())
            m_folderSwitches[separator]->setChecked(true);
284 285
    }

286
    QString url = config.readEntry("MusicFolder", "${HOME}/music");
Scott Wheeler's avatar
Scott Wheeler committed
287
    m_musicFolder->setURL(url);
288 289

    m_separator->setCurrentText(config.readEntry("Separator", " - "));
290
}
291

292
void FileRenamerWidget::saveConfig()
293
{
294
    KConfigGroup config(KGlobal::config(), "FileRenamer");
Scott Wheeler's avatar
Scott Wheeler committed
295 296
    QList<int> checkedSeparators;
    QList<int> categoryOrder;
297

Scott Wheeler's avatar
Scott Wheeler committed
298 299
    for(int i = 0; i < m_rows.count(); ++i) {
        int rowId = idOfPosition(i); // Write out in GUI order, not m_rows order
300 301 302
        m_rows[rowId].options.saveConfig(m_rows[rowId].category.categoryNumber);
        categoryOrder += m_rows[rowId].category.category;
    }
303

Scott Wheeler's avatar
Scott Wheeler committed
304
    for(int i = 0; i < m_folderSwitches.count(); ++i)
305 306 307 308 309
        if(m_folderSwitches[i]->isChecked() == true)
            checkedSeparators += i;

    config.writeEntry("CheckedDirSeparators", checkedSeparators);
    config.writeEntry("CategoryOrder", categoryOrder);
310
    config.writePathEntry("MusicFolder", m_musicFolder->url());
311 312 313
    config.writeEntry("Separator", m_separator->currentText());

    config.sync();
314 315
}

316
FileRenamerWidget::~FileRenamerWidget()
317 318 319
{
}

Scott Wheeler's avatar
Scott Wheeler committed
320
int FileRenamerWidget::addRowCategory(TagType category)
321 322 323 324 325
{
    static QPixmap up   = SmallIcon("up");
    static QPixmap down = SmallIcon("down");

    // Find number of categories already of this type.
Scott Wheeler's avatar
Scott Wheeler committed
326 327
    int categoryCount = 0;
    for(int i = 0; i < m_rows.count(); ++i)
328 329 330 331 332 333 334
        if(m_rows[i].category.category == category)
            ++categoryCount;

    Row row;

    row.category = CategoryID(category, categoryCount);
    row.position = m_rows.count();
Scott Wheeler's avatar
Scott Wheeler committed
335
    int id = row.position;
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

    Q3HBox *frame = new Q3HBox(m_mainFrame);
    frame->setPaletteBackgroundColor(frame->paletteBackgroundColor().dark(110));

    row.widget = frame;
    frame->setFrameShape(Q3Frame::Box);
    frame->setLineWidth(1);
    frame->setMargin(3);

    m_mainFrame->setStretchFactor(frame, 1);

    Q3VBox *buttons = new Q3VBox(frame);
    buttons->setFrameStyle(Q3Frame::Plain | Q3Frame::Box);
    buttons->setLineWidth(1);

    row.upButton = new KPushButton(buttons);
    row.downButton = new KPushButton(buttons);

    row.upButton->setPixmap(up);
    row.downButton->setPixmap(down);
    row.upButton->setFlat(true);
    row.downButton->setFlat(true);

    upMapper->connect(row.upButton, SIGNAL(clicked()), SLOT(map()));
    upMapper->setMapping(row.upButton, id);
    downMapper->connect(row.downButton, SIGNAL(clicked()), SLOT(map()));
    downMapper->setMapping(row.downButton, id);

    QString labelText = QString("<b>%1</b>").arg(TagRenamerOptions::tagTypeText(category));
    QLabel *label = new QLabel(labelText, frame);
    frame->setStretchFactor(label, 1);
Scott Wheeler's avatar
Scott Wheeler committed
367
    label->setAlignment(Qt::AlignCenter);
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387

    Q3VBox *options = new Q3VBox(frame);
    row.enableButton = new KPushButton(i18n("Remove"), options);
    toggleMapper->connect(row.enableButton, SIGNAL(clicked()), SLOT(map()));
    toggleMapper->setMapping(row.enableButton, id);

    row.optionsButton = new KPushButton(i18n("Options"), options);
    mapper->connect(row.optionsButton, SIGNAL(clicked()), SLOT(map()));
    mapper->setMapping(row.optionsButton, id);

    row.widget->show();
    m_rows.append(row);

    // Disable add button if there's too many rows.
    if(m_rows.count() == MAX_CATEGORIES)
        m_insertCategory->setEnabled(false);

    return id;
}

Scott Wheeler's avatar
Scott Wheeler committed
388
void FileRenamerWidget::moveSignalMappings(int oldId, int newId)
389 390 391 392 393 394 395
{
    mapper->setMapping(m_rows[oldId].optionsButton, newId);
    downMapper->setMapping(m_rows[oldId].downButton, newId);
    upMapper->setMapping(m_rows[oldId].upButton, newId);
    toggleMapper->setMapping(m_rows[oldId].enableButton, newId);
}

Scott Wheeler's avatar
Scott Wheeler committed
396
bool FileRenamerWidget::removeRow(int id)
397 398
{
    if(id >= m_rows.count()) {
Scott Wheeler's avatar
Scott Wheeler committed
399
        kWarning(65432) << "Trying to remove row, but " << id << " is out-of-range.\n";
400 401 402 403
        return false;
    }

    if(m_rows.count() == 1) {
404
        kError(65432) << "Can't remove last row of File Renamer.\n";
405 406 407 408 409 410 411 412 413 414 415
        return false;
    }

    // Remove widget.  Don't delete it since it appears QSignalMapper may still need it.
    m_rows[id].widget->deleteLater();
    m_rows[id].widget = 0;
    m_rows[id].enableButton = 0;
    m_rows[id].upButton = 0;
    m_rows[id].optionsButton = 0;
    m_rows[id].downButton = 0;

Scott Wheeler's avatar
Scott Wheeler committed
416
    int checkboxPosition = 0; // Remove first checkbox.
417 418 419 420 421 422 423 424 425 426 427 428 429

    // If not the first row, remove the checkbox before it.
    if(m_rows[id].position > 0)
        checkboxPosition = m_rows[id].position - 1;

    // The checkbox is contained within a layout widget, so the layout
    // widget is the one the needs to die.
    delete m_folderSwitches[checkboxPosition]->parent();
    m_folderSwitches.erase(&m_folderSwitches[checkboxPosition]);

    // Go through all the rows and if they have the same category and a
    // higher categoryNumber, decrement the number.  Also update the
    // position identifier.
Scott Wheeler's avatar
Scott Wheeler committed
430
    for(int i = 0; i < m_rows.count(); ++i) {
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
        if(i == id)
            continue; // Don't mess with ourself.

        if((m_rows[id].category.category == m_rows[i].category.category) &&
           (m_rows[id].category.categoryNumber < m_rows[i].category.categoryNumber))
        {
            --m_rows[i].category.categoryNumber;
        }

        // Items are moving up.
        if(m_rows[id].position < m_rows[i].position)
            --m_rows[i].position;
    }

    // Every row after the one we delete will have a different identifier, since
    // the identifier is simply its index into m_rows.  So we need to re-do the
    // signal mappings for the affected rows.
Scott Wheeler's avatar
Scott Wheeler committed
448
    for(int i = id + 1; i < m_rows.count(); ++i)
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
        moveSignalMappings(i, i - 1);

    m_rows.erase(&m_rows[id]);

    // Make sure we update the buttons of affected rows.
    m_rows[idOfPosition(0)].upButton->setEnabled(false);
    m_rows[idOfPosition(m_rows.count() - 1)].downButton->setEnabled(false);

    // We can insert another row now, make sure GUI is updated to match.
    m_insertCategory->setEnabled(true);

    QTimer::singleShot(0, this, SLOT(exampleTextChanged()));
    return true;
}

void FileRenamerWidget::addFolderSeparatorCheckbox()
{
    QWidget *temp = new QWidget(m_mainFrame);
    Q3HBoxLayout *l = new Q3HBoxLayout(temp);

    QCheckBox *cb = new QCheckBox(i18n("Insert folder separator"), temp);
    m_folderSwitches.append(cb);
Scott Wheeler's avatar
Scott Wheeler committed
471
    l->addWidget(cb, 0, Qt::AlignCenter);
472 473 474 475 476 477 478 479
    cb->setChecked(false);

    connect(cb, SIGNAL(toggled(bool)),
            SLOT(exampleTextChanged()));

    temp->show();
}

480
void FileRenamerWidget::createTagRows()
481
{
482
    KConfigGroup config(KGlobal::config(), "FileRenamer");
Scott Wheeler's avatar
Scott Wheeler committed
483
    QList<int> categoryOrder = config.readEntry("CategoryOrder", QList<int>());
484

485
    if(categoryOrder.isEmpty())
486
        categoryOrder << Artist << Album << Artist << Title << Track;
487

488 489 490
    // Setup arrays.
    m_rows.reserve(categoryOrder.count());
    m_folderSwitches.reserve(categoryOrder.count() - 1);
491

492 493 494 495
    mapper       = new QSignalMapper(this, "signal mapper");
    toggleMapper = new QSignalMapper(this, "toggle mapper");
    upMapper     = new QSignalMapper(this, "up button mapper");
    downMapper   = new QSignalMapper(this, "down button mapper");
496 497

    connect(mapper,       SIGNAL(mapped(int)), SLOT(showCategoryOption(int)));
498
    connect(toggleMapper, SIGNAL(mapped(int)), SLOT(slotRemoveRow(int)));
499 500 501
    connect(upMapper,     SIGNAL(mapped(int)), SLOT(moveItemUp(int)));
    connect(downMapper,   SIGNAL(mapped(int)), SLOT(moveItemDown(int)));

Laurent Montel's avatar
Laurent Montel committed
502
    m_mainFrame = new Q3VBox(m_mainView->viewport());
Scott Wheeler's avatar
Scott Wheeler committed
503 504 505
    m_mainFrame->setMargin(10);
    m_mainFrame->setSpacing(5);

506
    m_mainView->addChild(m_mainFrame);
Laurent Montel's avatar
Laurent Montel committed
507
    m_mainView->setResizePolicy(Q3ScrollView::AutoOneFit);
508 509

    // OK, the deal with the categoryOrder variable is that we need to create
510 511 512 513
    // the rows in the order that they were saved in (the order given by categoryOrder).
    // The signal mappers operate according to the row identifier.  To find the position of
    // a row given the identifier, use m_rows[id].position.  To find the id of a given
    // position, use idOfPosition(position).
514

Scott Wheeler's avatar
Scott Wheeler committed
515
    QList<int>::ConstIterator it = categoryOrder.constBegin();
516

517 518
    for(; it != categoryOrder.constEnd(); ++it) {
        if(*it < StartTag || *it >= NumTypes) {
519
            kError(65432) << "Invalid category encountered in file renamer configuration.\n";
520 521
            continue;
        }
522

523
        if(m_rows.count() == MAX_CATEGORIES) {
524
            kError(65432) << "Maximum number of File Renamer tags reached, bailing.\n";
525
            break;
526 527
        }

528 529 530
        TagType i = static_cast<TagType>(*it);

        addRowCategory(i);
531

532 533 534
        // Insert the directory separator checkbox if this isn't the last
        // item.

Scott Wheeler's avatar
Scott Wheeler committed
535
        QList<int>::ConstIterator dup(it);
536 537 538 539

        // Check for last item
        if(++dup != categoryOrder.constEnd())
            addFolderSeparatorCheckbox();
540
    }
541

542 543 544 545 546 547 548
    m_rows.first().upButton->setEnabled(false);
    m_rows.last().downButton->setEnabled(false);

    // If we have maximum number of categories already, don't let the user
    // add more.
    if(m_rows.count() >= MAX_CATEGORIES)
        m_insertCategory->setEnabled(false);
549 550
}

551
void FileRenamerWidget::exampleTextChanged()
552
{
553 554
    // Just use .mp3 as an example

555
    if(m_exampleFromFile && (m_exampleFile.isEmpty() ||
556 557
                             !FileHandle(m_exampleFile).tag()->isValid()))
    {
558 559 560 561
        m_exampleText->setText(i18n("No file selected, or selected file has no tags."));
        return;
    }

562
    m_exampleText->setText(FileRenamer::fileName(*this) + ".mp3");
563 564
}

565
QString FileRenamerWidget::fileCategoryValue(TagType category) const
566
{
567 568
    FileHandle file(m_exampleFile);
    Tag *tag = file.tag();
569 570 571

    switch(category) {
    case Track:
572
        return QString::number(tag->track());
573 574 575 576 577

    case Year:
        return QString::number(tag->year());

    case Title:
578
        return tag->title();
579 580

    case Artist:
581
        return tag->artist();
582 583

    case Album:
584
        return tag->album();
585 586

    case Genre:
587
        return tag->genre();
588 589

    default:
590
        return QString::null;
591
    }
592 593
}

594
QString FileRenamerWidget::categoryValue(TagType category) const
595
{
596 597 598 599
    if(m_exampleFromFile)
        return fileCategoryValue(category);

    const ExampleOptions *example = m_exampleDialog->widget();
600

601 602
    switch (category) {
    case Track:
603
        return example->m_exampleTrack->text();
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620

    case Year:
        return example->m_exampleYear->text();

    case Title:
        return example->m_exampleTitle->text();

    case Artist:
        return example->m_exampleArtist->text();

    case Album:
        return example->m_exampleAlbum->text();

    case Genre:
        return example->m_exampleGenre->text();

    default:
621
        return QString::null;
622
    }
623
}
624

625
Q3ValueList<CategoryID> FileRenamerWidget::categoryOrder() const
626
{
627 628 629
    Q3ValueList<CategoryID> list;

    // Iterate in GUI row order.
Scott Wheeler's avatar
Scott Wheeler committed
630 631
    for(int i = 0; i < m_rows.count(); ++i) {
        int rowId = idOfPosition(i);
632 633
        list += m_rows[rowId].category;
    }
634

635
    return list;
636 637
}

Scott Wheeler's avatar
Scott Wheeler committed
638
bool FileRenamerWidget::hasFolderSeparator(int index) const
639
{
640 641
    if(index >= m_folderSwitches.count())
        return false;
642 643
    return m_folderSwitches[index]->isChecked();
}
644

Scott Wheeler's avatar
Scott Wheeler committed
645
void FileRenamerWidget::moveItem(int id, MovementDirection direction)
646
{
647
    QWidget *l = m_rows[id].widget;
Scott Wheeler's avatar
Scott Wheeler committed
648 649 650
    int bottom = m_rows.count() - 1;
    int pos = m_rows[id].position;
    int newPos = (direction == MoveUp) ? pos - 1 : pos + 1;
651

652 653
    // Item we're moving can't go further down after this.

654 655
    if((pos == (bottom - 1) && direction == MoveDown) ||
       (pos == bottom && direction == MoveUp))
656
    {
Scott Wheeler's avatar
Scott Wheeler committed
657 658
        int idBottomRow = idOfPosition(bottom);
        int idAboveBottomRow = idOfPosition(bottom - 1);
659 660 661

        m_rows[idBottomRow].downButton->setEnabled(true);
        m_rows[idAboveBottomRow].downButton->setEnabled(false);
662 663 664 665 666
    }

    // We're moving the top item, do some button switching.

    if((pos == 0 && direction == MoveDown) || (pos == 1 && direction == MoveUp)) {
Scott Wheeler's avatar
Scott Wheeler committed
667 668
        int idTopItem = idOfPosition(0);
        int idBelowTopItem = idOfPosition(1);
669 670 671

        m_rows[idTopItem].upButton->setEnabled(true);
        m_rows[idBelowTopItem].upButton->setEnabled(false);
672 673 674 675
    }

    // This is the item we're swapping with.

Scott Wheeler's avatar
Scott Wheeler committed
676
    int idSwitchWith = idOfPosition(newPos);
677
    QWidget *w = m_rows[idSwitchWith].widget;
678 679 680

    // Update the table of widget rows.

681
    std::swap(m_rows[id].position, m_rows[idSwitchWith].position);
682 683 684 685

    // Move the item two spaces above/below its previous position.  It has to
    // be 2 spaces because of the checkbox.

686
    Q3BoxLayout *layout = dynamic_cast<Q3BoxLayout *>(m_mainFrame->layout());
687 688

    layout->remove(l);
689
    layout->insertWidget(2 * newPos, l);
690 691 692 693 694

    // Move the top item two spaces in the opposite direction, for a similar
    // reason.

    layout->remove(w);
695
    layout->insertWidget(2 * pos, w);
696 697 698 699 700
    layout->invalidate();

    QTimer::singleShot(0, this, SLOT(exampleTextChanged()));
}

Scott Wheeler's avatar
Scott Wheeler committed
701
int FileRenamerWidget::idOfPosition(int position) const
702
{
703
    if(position >= m_rows.count()) {
704
        kError(65432) << "Search for position " << position << " out-of-range.\n";
Scott Wheeler's avatar
Scott Wheeler committed
705
        return -1;
706 707
    }

Scott Wheeler's avatar
Scott Wheeler committed
708
    for(int i = 0; i < m_rows.count(); ++i)
709 710
        if(m_rows[i].position == position)
            return i;
711

712
    kError(65432) << "Unable to find identifier for position " << position << endl;
Scott Wheeler's avatar
Scott Wheeler committed
713
    return -1;
714 715
}

Scott Wheeler's avatar
Scott Wheeler committed
716
int FileRenamerWidget::findIdentifier(const CategoryID &category) const
717
{
Scott Wheeler's avatar
Scott Wheeler committed
718
    for(int index = 0; index < m_rows.count(); ++index)
719
        if(m_rows[index].category == category)
720 721
            return index;

722
    kError(65432) << "Unable to find match for category " <<
723 724 725 726
        TagRenamerOptions::tagTypeText(category.category) <<
        ", number " << category.categoryNumber << endl;

    return MAX_CATEGORIES;
727 728 729 730
}

void FileRenamerWidget::enableAllUpButtons()
{
Scott Wheeler's avatar
Scott Wheeler committed
731
    for(int i = 0; i < m_rows.count(); ++i)
732 733 734 735 736
        m_rows[i].upButton->setEnabled(true);
}

void FileRenamerWidget::enableAllDownButtons()
{
Scott Wheeler's avatar
Scott Wheeler committed
737
    for(int i = 0; i < m_rows.count(); ++i)
738 739 740
        m_rows[i].downButton->setEnabled(true);
}

741
void FileRenamerWidget::showCategoryOption(int id)
742
{
743
    TagOptionsDialog *dialog = new TagOptionsDialog(this, m_rows[id].options, m_rows[id].category.categoryNumber);
744 745

    if(dialog->exec() == QDialog::Accepted) {
746
        m_rows[id].options = dialog->options();
747
        exampleTextChanged();
748
    }
749 750

    delete dialog;
751 752
}

753
void FileRenamerWidget::moveItemUp(int id)
754
{
Scott Wheeler's avatar
Scott Wheeler committed
755
    moveItem(id, MoveUp);
756 757
}

758
void FileRenamerWidget::moveItemDown(int id)
759
{
Scott Wheeler's avatar
Scott Wheeler committed
760
    moveItem(id, MoveDown);
761 762
}

763
void FileRenamerWidget::toggleExampleDialog()
764
{
765
    m_exampleDialog->setShown(!m_exampleDialog->isShown());
766 767
}

768
void FileRenamerWidget::insertCategory()
769
{
770 771
    TagType category = TagRenamerOptions::tagFromCategoryText(m_category->currentText());
    if(category == Unknown) {
772
        kError(65432) << "Trying to add unknown category somehow.\n";
773 774 775 776 777
        return;
    }

    // We need to enable the down button of the current bottom row since it
    // can now move down.
Scott Wheeler's avatar
Scott Wheeler committed
778
    int idBottom = idOfPosition(m_rows.count() - 1);
779 780 781 782 783
    m_rows[idBottom].downButton->setEnabled(true);

    addFolderSeparatorCheckbox();

    // Identifier of new row.
Scott Wheeler's avatar
Scott Wheeler committed
784
    int id = addRowCategory(category);
785 786 787 788 789 790 791 792 793 794

    // Set its down button to be disabled.
    m_rows[id].downButton->setEnabled(false);

    m_mainFrame->layout()->invalidate();
    m_mainView->update();

    // Now update according to the code in loadConfig().
    m_rows[id].options = TagRenamerOptions(m_rows[id].category);
    exampleTextChanged();
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
}

void FileRenamerWidget::exampleDialogShown()
{
    m_showExample->setText(i18n("Hide Renamer Test Dialog"));
}

void FileRenamerWidget::exampleDialogHidden()
{
    m_showExample->setText(i18n("Show Renamer Test Dialog"));
}

void FileRenamerWidget::fileSelected(const QString &file)
{
    m_exampleFromFile = true;
810
    m_exampleFile = file;
811 812 813 814 815 816 817 818 819 820 821 822 823
    exampleTextChanged();
}

void FileRenamerWidget::dataSelected()
{
    m_exampleFromFile = false;
    exampleTextChanged();
}

QString FileRenamerWidget::separator() const
{
    return m_separator->currentText();
}
824

Scott Wheeler's avatar
Scott Wheeler committed
825
QString FileRenamerWidget::musicFolder() const
826
{
Scott Wheeler's avatar
Scott Wheeler committed
827
    return m_musicFolder->url();
828 829
}

830
void FileRenamerWidget::slotRemoveRow(int id)
831
{
832 833
    // Remove the given identified row.
    if(!removeRow(id))
834
        kError(65432) << "Unable to remove row " << id << endl;
835 836
}

837 838 839
//
// Implementation of FileRenamer
//
840 841

FileRenamer::FileRenamer()
842
{
843
}
844

845 846 847 848 849 850 851
void FileRenamer::rename(PlaylistItem *item)
{
    PlaylistItemList list;
    list.append(item);

    rename(list);
}
852

853 854 855
void FileRenamer::rename(const PlaylistItemList &items)
{
    ConfigCategoryReader reader;
856 857 858
    QStringList errorFiles;
    QMap<QString, QString> map;
    QMap<QString, PlaylistItem *> itemMap;
859

860 861
    for(PlaylistItemList::ConstIterator it = items.begin(); it != items.end(); ++it) {
        reader.setPlaylistItem(*it);
862 863 864 865 866 867 868 869 870
        QString oldFile = (*it)->file().absFilePath();
        QString extension = (*it)->file().fileInfo().extension(false);
        QString newFile = fileName(reader) + "." + extension;

        if(oldFile != newFile) {
            map[oldFile] = newFile;
            itemMap[oldFile] = *it;
        }
    }
871

872
    if(itemMap.isEmpty() || ConfirmationDialog(map).exec() != QDialog::Accepted)
873 874
        return;

875
    KApplication::setOverrideCursor(Qt::waitCursor);
876 877 878
    for(QMap<QString, QString>::ConstIterator it = map.begin();
        it != map.end(); ++it)
    {
879 880 881
        if(moveFile(it.key(), it.data())) {
            itemMap[it.key()]->setFile(it.data());
            itemMap[it.key()]->refresh();
882 883

            setFolderIcon(it.data(), itemMap[it.key()]);
884
        }
885 886 887 888
        else
            errorFiles << i18n("%1 to %2").arg(it.key()).arg(it.data());

        processEvents();
889
    }
890 891 892
    KApplication::restoreOverrideCursor();

    if(!errorFiles.isEmpty())
893
        KMessageBox::errorList(0, i18n("The following rename operations failed:\n"), errorFiles);
894 895
}

896
bool FileRenamer::moveFile(const QString &src, const QString &dest)
897
{
Scott Wheeler's avatar
Scott Wheeler committed
898
    kDebug(65432) << "Moving file " << src << " to " << dest << endl;
899 900

    if(src == dest)
901
        return false;
902

903
    // Escape URL.
Scott Wheeler's avatar
Scott Wheeler committed
904 905
    KUrl srcURL = KUrl::fromPathOrURL(src);
    KUrl dstURL = KUrl::fromPathOrURL(dest);
906 907 908 909 910 911 912 913 914 915

    // Clean it.
    srcURL.cleanPath();
    dstURL.cleanPath();

    // Make sure it is valid.
    if(!srcURL.isValid() || !dstURL.isValid())
        return false;

    // Get just the directory.
Scott Wheeler's avatar
Scott Wheeler committed
916
    KUrl dir = dstURL;
917 918 919 920
    dir.setFileName(QString::null);

    // Create the directory.
    if(!KStandardDirs::exists(dir.path()))
921
        if(!KStandardDirs::makeDir(dir.path())) {
922
            kError() << "Unable to create directory " << dir.path() << endl;
923
            return false;
924
        }
925

926 927
    // Move the file.
    return KIO::NetAccess::file_move(srcURL, dstURL);
928
}
929

Scott Wheeler's avatar
Scott Wheeler committed
930
void FileRenamer::setFolderIcon(const KUrl &dst, const PlaylistItem *item)
931 932 933 934 935 936 937
{
    if(item->file().tag()->album().isEmpty() ||
       !item->file().coverInfo()->hasCover())
    {
        return;
    }

Scott Wheeler's avatar
Scott Wheeler committed
938
    KUrl dstURL = dst;
939 940 941 942 943 944 945 946 947 948
    dstURL.cleanPath();

    // Split path, and go through each path element.  If a path element has
    // the album information, set its folder icon.
    QStringList elements = QStringList::split("/", dstURL.directory());
    QString path;

    for(QStringList::ConstIterator it = elements.begin(); it != elements.end(); ++it) {
        path.append("/" + (*it));

Scott Wheeler's avatar
Scott Wheeler committed
949
        kDebug() << "Checking path: " << path << endl;
950 951 952 953 954
        if((*it).find(item->file().tag()->album()) != -1 &&
           !QFile::exists(path + "/.directory"))
        {
            // Seems to be a match, let's set the folder icon for the current
            // path.  First we should write out the file.
955

956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
            QPixmap thumb = item->file().coverInfo()->pixmap(CoverInfo::Thumbnail);
            thumb.save(path + "/.juk-thumbnail.png", "PNG");

            KSimpleConfig config(path + "/.directory");
            config.setGroup("Desktop Entry");

            if(!config.hasKey("Icon")) {
                config.writeEntry("Icon", QString("%1/.juk-thumbnail.png").arg(path));
                config.sync();
            }

            return;
        }
    }
}

972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
/**
 * Returns iterator pointing to the last item enabled in the given list with
 * a non-empty value (or is required to be included).
 */
Q3ValueList<CategoryID>::ConstIterator lastEnabledItem(const Q3ValueList<CategoryID> &list,
                                                   const CategoryReaderInterface &interface)
{
    Q3ValueList<CategoryID>::ConstIterator it = list.constBegin();
    Q3ValueList<CategoryID>::ConstIterator last = list.constEnd();

    for(; it != list.constEnd(); ++it) {
        if(interface.isRequired(*it) || (!interface.isDisabled(*it) &&
              !interface.categoryValue((*it).category).isEmpty()))
        {
            last = it;
        }
    }

    return last;
}

993
QString FileRenamer::fileName(const CategoryReaderInterface &interface)
994
{
995
    const Q3ValueList<CategoryID> categoryOrder = interface.categoryOrder();
996
    const QString separator = interface.separator();
Scott Wheeler's avatar
Scott Wheeler committed
997
    const QString folder = interface.musicFolder();
998
    Q3ValueList<CategoryID>::ConstIterator lastEnabled;
Scott Wheeler's avatar
Scott Wheeler committed
999
    int i = 0;
1000
    QStringList list;
1001
    QChar dirSeparator = QChar(QDir::separator());
1002

1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
    // Use lastEnabled to properly handle folder separators.
    lastEnabled = lastEnabledItem(categoryOrder, interface);
    bool pastLast = false; // Toggles to true once we've passed lastEnabled.

    for(Q3ValueList<CategoryID>::ConstIterator it = categoryOrder.begin();
            it != categoryOrder.end();
            ++it, ++i)
    {
        if(it == lastEnabled)
            pastLast = true;
1013

1014
        if(interface.isDisabled(*it))
1015
            continue;
1016

1017 1018 1019 1020 1021 1022
        QString value = interface.value(*it);

        // The user can use the folder separator checkbox to add folders, so don't allow
        // slashes that slip in to accidentally create new folders.  Should we filter this
        // back out when showing it in the GUI?
        value.replace('/', "%2f");
1023

1024 1025
        if(!pastLast && interface.hasFolderSeparator(i))
            value.append(dirSeparator);
1026

1027
        if(interface.isRequired(*it) || !value.isEmpty())
1028 1029 1030 1031 1032 1033 1034
            list.append(value);
    }

    // Construct a single string representation, handling strings ending in
    // '/' specially

    QString result;
1035

1036
    for(QStringList::ConstIterator it = list.constBegin(); it != list.constEnd(); /* Empty */) {
1037 1038
        result += *it;

1039 1040 1041 1042 1043 1044
        ++it; // Manually advance iterator to check for end-of-list.

        // Add separator unless at a directory boundary
        if(it != list.constEnd() &&
           !(*it).startsWith(dirSeparator) && // Check beginning of next item.
           !result.endsWith(dirSeparator))
1045 1046 1047 1048
        {
            result += separator;
        }
    }
1049

1050
    return QString(folder + dirSeparator + result);
1051 1052 1053 1054
}

#include "filerenamer.moc"

1055
// vim: set et sw=4 tw=0 sta: