filerenamer.cpp 25.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 50 51 52 53 54 55
#include <q3header.h>
//Added by qt3to4:
#include <QPixmap>
#include <Q3Frame>
#include <QHBoxLayout>
#include <QBoxLayout>
#include <Q3ValueList>
56

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

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)
    {
Laurent Montel's avatar
Laurent Montel committed
72
        KVBox *vbox = makeVBoxMainWidget();
Laurent Montel's avatar
Laurent Montel committed
73
        Q3HBox *hbox = new Q3HBox(vbox);
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101

        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);

        KListView *lv = new KListView(vbox);

        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) {
            KListViewItem *i = it.key() != it.data()
                ? new KListViewItem(lv, it.key(), it.data())
                : new KListViewItem(lv, it.key(), i18n("No Change"));
            lvHeight += i->height();
        }

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

//
// Implementation of ConfigCategoryReader
//

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

112 113
    for(unsigned i = StartTag; i < NumTypes; ++i)
        m_options[i] = TagRenamerOptions(static_cast<TagType>(i));
114

115 116
    for(unsigned i = 0; i < (NumTypes - 1); ++i)
        m_folderSeparators[i] = false;
117

Laurent Montel's avatar
Laurent Montel committed
118 119
    Q3ValueList<int> checkedSeparators = config.readIntListEntry("CheckedDirSeparators");
    Q3ValueList<int>::ConstIterator it = checkedSeparators.begin();
120
    for(; it != checkedSeparators.end(); ++it)
121
        if(*it >= 0 && *it < (NumTypes - 1))
122
            m_folderSeparators[*it] = true;
123

Scott Wheeler's avatar
Scott Wheeler committed
124
    m_musicFolder = config.readPathEntry("MusicFolder", "${HOME}/music");
125
    m_separator = config.readEntry("Separator", " - ");
126

127
    checkedSeparators = config.readIntListEntry("CategoryOrder");
128 129 130 131 132 133 134

    // Set a default:

    if(checkedSeparators.isEmpty())
        checkedSeparators << Artist << Album << Title << Track;


135 136 137
    for(it = checkedSeparators.begin(); it != checkedSeparators.end(); ++it)
        m_categoryOrder.append(static_cast<TagType>(*it));
}
138

139 140 141
QString ConfigCategoryReader::categoryValue(TagType type) const
{
    if(!m_currentItem)
142
        return QString::null;
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

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

    switch(type) {
    case Track:
        return FileRenamer::fixupTrack(QString::number(tag->track()), *this);

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

    case Title:
        return tag->title();

    case Artist:
        return tag->artist();

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

162 163 164 165
    case Genre:
        return tag->genre();

    default:
166
        return QString::null;
167
    }
168
}
169

170
QString ConfigCategoryReader::prefix(TagType category) const
171
{
172
    return m_options[category].prefix();
173 174
}

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

180
TagRenamerOptions::EmptyActions ConfigCategoryReader::emptyAction(TagType category) const
181
{
182
    return m_options[category].emptyAction();
183 184
}

185
QString ConfigCategoryReader::emptyText(TagType category) const
186
{
187 188 189
    return m_options[category].emptyText();
}

Laurent Montel's avatar
Laurent Montel committed
190
Q3ValueList<TagType> ConfigCategoryReader::categoryOrder() const
191 192 193 194 195 196 197 198 199
{
    return m_categoryOrder;
}

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

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

int ConfigCategoryReader::trackWidth() const
{
    return m_options[Track].trackWidth();
}

Scott Wheeler's avatar
Scott Wheeler committed
210
bool ConfigCategoryReader::hasFolderSeparator(int index) const
211 212 213 214 215 216 217 218 219 220 221
{
    return m_folderSeparators[index];
}

bool ConfigCategoryReader::isDisabled(TagType category) const
{
    return m_options[category].disabled();
}

FileRenamerWidget::FileRenamerWidget(QWidget *parent) :
    FileRenamerBase(parent), CategoryReaderInterface(),
222
    m_exampleFromFile(false)
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
{
    QLabel *temp = new QLabel(0);
    m_exampleText->setPaletteBackgroundColor(temp->paletteBackgroundColor());
    delete temp;

    layout()->setMargin(0); // We'll be wrapped by KDialogBase
    
    // This must be created before createTagRows() is called.

    m_exampleDialog = new ExampleOptionsDialog(this);

    createTagRows();
    loadConfig();

    for(unsigned i = 0; i < NumTypes; ++i) {
        setCategoryEnabled(m_rows[i].category, !m_rows[i].options.disabled());
        m_rows[i].enableButton->setChecked(!m_rows[i].options.disabled());
240
    }
241 242 243 244 245 246 247 248

    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();
249
}
250

251
void FileRenamerWidget::loadConfig()
252
{
Laurent Montel's avatar
Laurent Montel committed
253
    Q3ValueList<int> checkedSeparators;
254 255 256 257 258 259 260
    KConfigGroup config(KGlobal::config(), "FileRenamer");

    for(unsigned i = StartTag; i < NumTypes; ++i)
        m_rows[i].options = TagRenamerOptions(m_rows[i].category);

    checkedSeparators = config.readIntListEntry("CheckedDirSeparators");

Laurent Montel's avatar
Laurent Montel committed
261
    Q3ValueList<int>::ConstIterator it = checkedSeparators.begin();
262 263 264 265 266
    for(; it != checkedSeparators.end(); ++it) {
        if(*it < (NumTypes - 1) && *it >= 0)
            m_folderSwitches[*it]->setChecked(true);
    }

267
    QString url = config.readPathEntry("MusicFolder", "${HOME}/music");
Scott Wheeler's avatar
Scott Wheeler committed
268
    m_musicFolder->setURL(url);
269 270

    m_separator->setCurrentText(config.readEntry("Separator", " - "));
271
}
272

273
void FileRenamerWidget::saveConfig()
274
{
275
    KConfigGroup config(KGlobal::config(), "FileRenamer");
Laurent Montel's avatar
Laurent Montel committed
276 277
    Q3ValueList<int> checkedSeparators;
    Q3ValueList<int> categoryOrder;
278 279 280 281 282 283 284 285 286 287 288 289 290 291

    for(unsigned i = StartTag; i < NumTypes; ++i)
        m_rows[i].options.saveConfig();

    for(int i = 0; i < NumTypes - 1; ++i)
        if(m_folderSwitches[i]->isChecked() == true)
            checkedSeparators += i;

    config.writeEntry("CheckedDirSeparators", checkedSeparators);

    for(int i = 0; i < NumTypes; ++i)
        categoryOrder += m_rows[i].category;

    config.writeEntry("CategoryOrder", categoryOrder);
292
    config.writePathEntry("MusicFolder", m_musicFolder->url());
293 294 295
    config.writeEntry("Separator", m_separator->currentText());

    config.sync();
296 297
}

298
FileRenamerWidget::~FileRenamerWidget()
299 300 301
{
}

302
void FileRenamerWidget::createTagRows()
303
{
304
    KConfigGroup config(KGlobal::config(), "FileRenamer");
Laurent Montel's avatar
Laurent Montel committed
305
    Q3ValueList<int> categoryOrder = config.readIntListEntry("CategoryOrder");
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
    if(categoryOrder.isEmpty())
        for(int i = 0; i < NumTypes; ++i)
            categoryOrder += i;
    
    QPixmap up   = SmallIcon("up");
    QPixmap down = SmallIcon("down");

    QSignalMapper *mapper       = new QSignalMapper(this, "signal mapper");
    QSignalMapper *toggleMapper = new QSignalMapper(this, "toggle mapper");
    QSignalMapper *upMapper     = new QSignalMapper(this, "up button mapper");
    QSignalMapper *downMapper   = new QSignalMapper(this, "down button mapper");

    connect(mapper,       SIGNAL(mapped(int)), SLOT(showCategoryOption(int)));
    connect(toggleMapper, SIGNAL(mapped(int)), SLOT(toggleCategory(int)));
    connect(upMapper,     SIGNAL(mapped(int)), SLOT(moveItemUp(int)));
    connect(downMapper,   SIGNAL(mapped(int)), SLOT(moveItemDown(int)));

Laurent Montel's avatar
Laurent Montel committed
323
    m_mainFrame = new Q3VBox(m_mainView->viewport());
Scott Wheeler's avatar
Scott Wheeler committed
324 325 326
    m_mainFrame->setMargin(10);
    m_mainFrame->setSpacing(5);

327
    m_mainView->addChild(m_mainFrame);
Laurent Montel's avatar
Laurent Montel committed
328
    m_mainView->setResizePolicy(Q3ScrollView::AutoOneFit);
329 330 331 332 333 334 335 336 337 338 339 340

    // OK, the deal with the categoryOrder variable is that we need to create
    // the rows in the order that they were saved in.  Or at least, this is
    // the easiest way to handle it.  The signal mappers operate according to
    // the category value, whereas most of the other variables (including
    // m_rows) operate on the current position, where 0 is the top.  To get
    // the category value, use m_rows[i].category

    for(TagType i = StartTag; i < NumTypes; /* Empty */) {
        m_rows[i].category = static_cast<TagType>(categoryOrder.front());
        categoryOrder.pop_front();

Laurent Montel's avatar
Laurent Montel committed
341
        Q3HBox *frame = new Q3HBox(m_mainFrame);
Scott Wheeler's avatar
Scott Wheeler committed
342 343
        frame->setPaletteBackgroundColor(frame->paletteBackgroundColor().dark(110));

344
        m_rows[i].widget = frame;
Laurent Montel's avatar
Laurent Montel committed
345
        frame->setFrameShape(Q3Frame::Box);
346 347 348 349 350
        frame->setLineWidth(1);
        frame->setMargin(3);

        m_mainFrame->setStretchFactor(frame, 1);

Laurent Montel's avatar
Laurent Montel committed
351 352
        Q3VBox *buttons = new Q3VBox(frame);
        buttons->setFrameStyle(Q3Frame::Plain | Q3Frame::Box);
Scott Wheeler's avatar
Scott Wheeler committed
353
        buttons->setLineWidth(1);
354 355 356 357 358 359 360 361 362 363 364 365 366 367

        m_rows[i].upButton = new KPushButton(buttons);
        m_rows[i].downButton = new KPushButton(buttons);

        m_rows[i].upButton->setPixmap(up);
        m_rows[i].downButton->setPixmap(down);
        m_rows[i].upButton->setFlat(true);
        m_rows[i].downButton->setFlat(true);

        upMapper->connect(m_rows[i].upButton, SIGNAL(clicked()), SLOT(map()));
        upMapper->setMapping(m_rows[i].upButton, m_rows[i].category);
        downMapper->connect(m_rows[i].downButton, SIGNAL(clicked()), SLOT(map()));
        downMapper->setMapping(m_rows[i].downButton, m_rows[i].category);

Scott Wheeler's avatar
Scott Wheeler committed
368
        QString labelText = QString("<b>%1</b>").arg(TagRenamerOptions::tagTypeText(m_rows[i].category));
369 370 371 372
        QLabel *label = new QLabel(labelText, frame);
        frame->setStretchFactor(label, 1);
        label->setAlignment(AlignCenter);

Laurent Montel's avatar
Laurent Montel committed
373
        Q3VBox *options = new Q3VBox(frame);
374 375 376 377 378
        m_rows[i].enableButton = new QCheckBox(i18n("Enabled"), options);
        m_rows[i].enableButton->setChecked(true);
        toggleMapper->connect(m_rows[i].enableButton, SIGNAL(toggled(bool)), SLOT(map()));
        toggleMapper->setMapping(m_rows[i].enableButton, m_rows[i].category);

379
        KPushButton *optionsButton = new KPushButton(i18n("Options"), options);
380 381 382 383 384 385 386 387 388 389
        mapper->connect(optionsButton, SIGNAL(clicked()), SLOT(map()));
        mapper->setMapping(optionsButton, m_rows[i].category);

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

        if(i < (NumTypes - 1)) {
            QWidget *temp = new QWidget(m_mainFrame);
            QHBoxLayout *l = new QHBoxLayout(temp);

390
            m_folderSwitches[i] = new QCheckBox(i18n("Insert folder separator"), temp);
391 392 393 394 395 396 397 398 399 400
            l->addWidget(m_folderSwitches[i], 0, AlignCenter);

            connect(m_folderSwitches[i], SIGNAL(toggled(bool)),
                    SLOT(exampleTextChanged()));
        }

        // Yes, this is a hack

        int destroyerOfWorlds = i;
        i = static_cast<TagType>(++destroyerOfWorlds);
401
    }
402 403 404

    m_rows[0].upButton->setEnabled(false);
    m_rows[NumTypes - 1].downButton->setEnabled(false);
405 406
}

407
void FileRenamerWidget::exampleTextChanged()
408
{
Laurent Montel's avatar
Laurent Montel committed
409
    kDebug(65432) << k_funcinfo << endl;
410

411 412
    // Just use .mp3 as an example

413 414 415
    if(m_exampleFromFile && (m_exampleFile.isEmpty() || 
                             !FileHandle(m_exampleFile).tag()->isValid()))
    {
416 417 418 419
        m_exampleText->setText(i18n("No file selected, or selected file has no tags."));
        return;
    }

420
    m_exampleText->setText(FileRenamer::fileName(*this) + ".mp3");
421 422
}

423
QString FileRenamerWidget::fileCategoryValue(TagType category) const
424
{
425 426
    FileHandle file(m_exampleFile);
    Tag *tag = file.tag();
427 428 429 430 431 432 433 434 435

    switch(category) {
    case Track:
        return FileRenamer::fixupTrack(QString::number(tag->track()), *this);

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

    case Title:
436
        return tag->title();
437 438

    case Artist:
439
        return tag->artist();
440 441

    case Album:
442
        return tag->album();
443 444

    case Genre:
445
        return tag->genre();
446 447

    default:
448
        return QString::null;
449
    }
450 451
}

452
QString FileRenamerWidget::categoryValue(TagType category) const
453
{
454 455 456 457
    if(m_exampleFromFile)
        return fileCategoryValue(category);

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

459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
    switch (category) {
    case Track:
        return FileRenamer::fixupTrack(example->m_exampleTrack->text(), *this);

    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:
479
        return QString::null;
480
    }
481
}
482

Laurent Montel's avatar
Laurent Montel committed
483
Q3ValueList<TagType> FileRenamerWidget::categoryOrder() const
484
{
Laurent Montel's avatar
Laurent Montel committed
485
    Q3ValueList<TagType> list;
486

487 488
    for(unsigned i = 0; i < NumTypes; ++i)
        list.append(m_rows[i].category);
489

490
    return list;
491 492
}

Scott Wheeler's avatar
Scott Wheeler committed
493
bool FileRenamerWidget::hasFolderSeparator(int index) const
494
{
495 496
    return m_folderSwitches[index]->isChecked();
}
497

498 499 500
void FileRenamerWidget::moveItem(QWidget *l, MovementDirection direction)
{
    int pos = findIndex(l);
501

502
    if(pos < 0) {
Laurent Montel's avatar
Laurent Montel committed
503
        kError() << "Unable to find index for " << l << endl;
504
        return;
505 506 507
    }

    int delta = 1;
508

509 510 511 512 513
    // This is used to make the following code more or less
    // direction-independant.
    
    if(direction == MoveUp)
        delta = -1;
514

515 516 517 518
    // Item we're moving can't go further down after this.

    if((pos == (NumTypes - 2) && direction == MoveDown) ||
       (pos == (NumTypes - 1) && direction == MoveUp))
519
    {
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
        m_rows[NumTypes - 1].downButton->setEnabled(true);
        m_rows[NumTypes - 2].downButton->setEnabled(false);
    }

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

    if((pos == 0 && direction == MoveDown) || (pos == 1 && direction == MoveUp)) {
        m_rows[0].upButton->setEnabled(true);
        m_rows[1].upButton->setEnabled(false);
    }

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

    QWidget *w = m_rows[pos + delta].widget;

    // Update the table of widget rows.

    std::swap(m_rows[pos], m_rows[pos + delta]);

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

    QBoxLayout *layout = dynamic_cast<QBoxLayout *>(m_mainFrame->layout());

    layout->remove(l);
    layout->insertWidget(2 * (pos + delta), l);

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

    layout->remove(w);
    layout->insertWidget(pos * 2, w);
    layout->invalidate();

    setCategoryEnabled(pos + delta, !m_rows[pos + delta].options.disabled());
    setCategoryEnabled(pos, !m_rows[pos].options.disabled());

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

int FileRenamerWidget::findIndex(TagType category) const
{
    for(int index = 0; index < NumTypes; ++index)
        if(m_rows[index].category == category)
            return index;

    return -1;
}

int FileRenamerWidget::findIndex(QWidget *item) const
{
    for(int index = 0; index < NumTypes; ++index)
        if(m_rows[index].widget == item)
            return index;

    return -1;
}

void FileRenamerWidget::enableAllUpButtons()
{
    for(unsigned i = 0; i < NumTypes; ++i)
        m_rows[i].upButton->setEnabled(true);
}

void FileRenamerWidget::enableAllDownButtons()
{
    for(unsigned i = 0; i < NumTypes; ++i)
        m_rows[i].downButton->setEnabled(true);
}

void FileRenamerWidget::showCategoryOption(int category)
{
    showCategoryOptions(static_cast<TagType>(category));
}

void FileRenamerWidget::showCategoryOptions(TagType category)
{
    TagOptionsDialog *dialog = new TagOptionsDialog(this, m_rows[findIndex(category)].options);

    if(dialog->exec() == QDialog::Accepted) {
        m_rows[findIndex(category)].options = dialog->options();
        exampleTextChanged();
602
    }
603 604

    delete dialog;
605 606
}

607
void FileRenamerWidget::setCategoryEnabled(int index, bool enable)
608
{
609
    bool changed = m_rows[index].options.disabled() == enable;
610

611
    m_rows[index].options.setDisabled(!enable);
612

613 614 615
    if(index < (NumTypes - 1)) {
        changed = changed || m_folderSwitches[index]->isChecked() != enable;
        m_folderSwitches[index]->setEnabled(enable);
616 617
    }

618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
    // Only call this if we actually changed something, since it sorta
    // takes some time to process, and we want to avoid flicker if possible.

    if(changed)
        exampleTextChanged();
}

void FileRenamerWidget::moveItemUp(int category)
{
    TagType tag = static_cast<TagType>(category);

    moveItem(widgetForCategory(tag), MoveUp);
}

void FileRenamerWidget::moveItemDown(int category)
{
    TagType tag = static_cast<TagType>(category);

    moveItem(widgetForCategory(tag), MoveDown);
}

void FileRenamerWidget::toggleExampleDialog()
{
    m_exampleDialog->setShown(!m_exampleDialog->isShown());
}

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;
657
    m_exampleFile = file;
658 659 660 661 662 663 664 665 666 667 668 669 670
    exampleTextChanged();
}

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

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

Scott Wheeler's avatar
Scott Wheeler committed
672
QString FileRenamerWidget::musicFolder() const
673
{
Scott Wheeler's avatar
Scott Wheeler committed
674
    return m_musicFolder->url();
675 676 677 678 679
}

void FileRenamerWidget::toggleCategory(int category)
{
    QCheckBox *b = 0;
680

681
    // Find checkbox that matches this category
682

683 684 685 686
    for(unsigned i = 0; i < NumTypes; ++i) {
        if(m_rows[i].category == category) {
            b = m_rows[i].enableButton;
            break;
687 688
        }
    }
689

690
    if(!b) {
Laurent Montel's avatar
Laurent Montel committed
691
        kError() << "Unable to match category " << category << " to a check box!\n";
692 693 694 695
        return;
    }

    setCategoryEnabled(findIndex(static_cast<TagType>(category)), b->isChecked());
696 697
}

698 699

FileRenamer::FileRenamer()
700
{
701
}
702

703 704 705 706 707 708 709
void FileRenamer::rename(PlaylistItem *item)
{
    PlaylistItemList list;
    list.append(item);

    rename(list);
}
710

711 712 713
void FileRenamer::rename(const PlaylistItemList &items)
{
    ConfigCategoryReader reader;
714 715 716
    QStringList errorFiles;
    QMap<QString, QString> map;
    QMap<QString, PlaylistItem *> itemMap;
717

718 719
    for(PlaylistItemList::ConstIterator it = items.begin(); it != items.end(); ++it) {
        reader.setPlaylistItem(*it);
720 721 722 723 724 725 726 727 728
        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;
        }
    }
729

730
    if(itemMap.isEmpty() || ConfirmationDialog(map).exec() != QDialog::Accepted)
731 732
        return;

Laurent Montel's avatar
Laurent Montel committed
733
    KApplication::setOverrideCursor(Qt::WaitCursor);
734 735 736
    for(QMap<QString, QString>::ConstIterator it = map.begin();
        it != map.end(); ++it)
    {
737 738 739
        if(moveFile(it.key(), it.data())) {
            itemMap[it.key()]->setFile(it.data());
            itemMap[it.key()]->refresh();
740 741

            setFolderIcon(it.data(), itemMap[it.key()]);
742
        }
743 744 745 746
        else
            errorFiles << i18n("%1 to %2").arg(it.key()).arg(it.data());

        processEvents();
747
    }
748 749 750
    KApplication::restoreOverrideCursor();

    if(!errorFiles.isEmpty())
751
        KMessageBox::errorList(0, i18n("The following rename operations failed:\n"), errorFiles);
752 753
}

754
bool FileRenamer::moveFile(const QString &src, const QString &dest)
755
{
Laurent Montel's avatar
Laurent Montel committed
756
    kDebug(65432) << "Moving file " << src << " to " << dest << endl;
757 758

    if(src == dest)
759
        return false;
760

761
    // Escape URL.
Laurent Montel's avatar
Laurent Montel committed
762 763
    KUrl srcURL = KUrl::fromPathOrURL(src);
    KUrl dstURL = KUrl::fromPathOrURL(dest);
764 765 766 767 768 769 770 771 772 773

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

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

    // Get just the directory.
Laurent Montel's avatar
Laurent Montel committed
774
    KUrl dir = dstURL;
775 776 777 778
    dir.setFileName(QString::null);

    // Create the directory.
    if(!KStandardDirs::exists(dir.path()))
779
        if(!KStandardDirs::makeDir(dir.path())) {
Laurent Montel's avatar
Laurent Montel committed
780
            kError() << "Unable to create directory " << dir.path() << endl;
781
            return false;
782
        }
783

784 785
    // Move the file.
    return KIO::NetAccess::file_move(srcURL, dstURL);
786
}
787

Laurent Montel's avatar
Laurent Montel committed
788
void FileRenamer::setFolderIcon(const KUrl &dst, const PlaylistItem *item)
789 790 791 792 793 794 795
{
    if(item->file().tag()->album().isEmpty() ||
       !item->file().coverInfo()->hasCover())
    {
        return;
    }

Laurent Montel's avatar
Laurent Montel committed
796
    KUrl dstURL = dst;
797 798 799 800 801 802 803 804 805 806
    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));

Laurent Montel's avatar
Laurent Montel committed
807
        kDebug() << "Checking path: " << path << endl;
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
        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.
            
            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;
        }
    }
}

830
QString FileRenamer::fileName(const CategoryReaderInterface &interface)
831
{
Laurent Montel's avatar
Laurent Montel committed
832
    const Q3ValueList<TagType> categoryOrder = interface.categoryOrder();
833
    const QString separator = interface.separator();
Scott Wheeler's avatar
Scott Wheeler committed
834
    const QString folder = interface.musicFolder();
835 836 837 838 839 840
    const QRegExp closeBracket("[])}]\\s*$");
    const QRegExp openBracket("^\\s*[[({]");

    unsigned i = 0;
    QStringList list;

Laurent Montel's avatar
Laurent Montel committed
841
    for(Q3ValueList<TagType>::ConstIterator it = categoryOrder.begin(); it != categoryOrder.end(); ++it) {
842 843

        TagType category = static_cast<TagType>(*it);
844 845 846 847
        if(interface.isDisabled(category)) {
            ++i;
            continue;
        }
848 849

        QString value = interface.value(category);
850

Scott Wheeler's avatar
Scott Wheeler committed
851
        if(i < (NumTypes - 1) && interface.hasFolderSeparator(i))
852 853 854 855 856 857 858 859 860 861 862
            value.append("/");
        ++i;

        if(interface.isRequired(category) || !interface.isEmpty(category))
            list.append(value);
    }

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

    QString result;
863

864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
    for(QStringList::ConstIterator it = list.begin(); it != list.end(); /* Empty */) {
        result += *it;
        if((*it).find(closeBracket) != -1) {
            ++it;
            continue;
        }

        ++it;
        if(it != list.end() &&
           !result.endsWith(QChar(QDir::separator())) &&
           (*it).find(openBracket) == -1)
        {
            result += separator;
        }
    }
879

Scott Wheeler's avatar
Scott Wheeler committed
880
    return QString(folder + QDir::separator() + result);
881 882 883 884 885 886 887 888 889 890
}

QString FileRenamer::fixupTrack(const QString &track, const CategoryReaderInterface &interface)
{
    QString str(track);

    if(track == "0") {
        if(interface.emptyAction(Track) == TagRenamerOptions::UseReplacementValue)
            str = interface.emptyText(Track);
        else
891
            return QString::null;
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
    }

    unsigned minimumWidth = interface.trackWidth();

    if(str.length() < minimumWidth) {
        QString prefix;
        prefix.fill('0', minimumWidth - str.length());
        return prefix + str;
    }

    return str;
}

#include "filerenamer.moc"

// vim: set et sw=4 ts=8: