filerenamer.cpp 5.93 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
/*
 * filerenamer.cpp - (c) 2003 Frerich Raabe <raabe@kde.org>
 *
 * 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 "filerenamer.h"
#include "playlistitem.h"

#include <kapplication.h>
#include <kconfig.h>
Scott Wheeler's avatar
build  
Scott Wheeler committed
14
#include <kdebug.h>
15
#include <klocale.h>
16
#include <kmacroexpander.h>
17
#include <kmessagebox.h>
18 19 20

#include <qdir.h>

21 22
FileRenamer::Config::Config(KConfigBase *cfg)
    : m_grp(cfg, "FileRenamer")
23 24 25
{
}

26
QString FileRenamer::Config::filenameScheme() const
27
{
28
    return m_grp.readEntry("FilenameScheme");
29 30
}

31
void FileRenamer::Config::setFilenameScheme(const QString &scheme)
32
{
33
    m_grp.writeEntry("FilenameScheme", scheme);
34 35
}

36
QString FileRenamer::Config::getToken(TokenType type) const
37
{
38 39
    return m_grp.readEntry(tokenToString(type) + "Token");
}
40

41 42 43 44
void FileRenamer::Config::setToken(TokenType type, const QString &value)
{
    m_grp.writeEntry(tokenToString(type) + "Token", value);
}
45

46 47 48
bool FileRenamer::Config::tokenNeedsValue(TokenType type) const
{
    return m_grp.readBoolEntry("Need" + tokenToString(type) + "Value");
49 50
}

51
void FileRenamer::Config::setTokenNeedsValue(TokenType type, bool needsValue)
52
{
53
    m_grp.writeEntry("Need" + tokenToString(type) + "Value", needsValue);
54 55
}

56
QString FileRenamer::tokenToString(TokenType type)
57
{
58 59 60 61 62 63 64 65
    switch(type) {
        case Title: return "Title";
        case Artist: return "Artist";
        case Album: return "Album";
        case Track: return "Track";
        case Comment: return "Comment";
    }
    return QString::null;
66 67
}

68 69
FileRenamer::FileRenamer()
    : m_cfg(kapp->config())
70 71 72
{
}

73 74
FileRenamer::FileRenamer(const PlaylistItem *item)
    : m_cfg(kapp->config())
75
{
76
    rename(item);
77 78
}

79
QString FileRenamer::expandToken(TokenType type, const QString &value) const
80
{
81 82 83 84 85 86 87
    const bool needValue = m_cfg.tokenNeedsValue(type);
    if(needValue && value.isEmpty())
        return QString();

    QString token = m_cfg.getToken(type);
    token.replace("%s", value);
    return token;
88 89
}

90

91 92 93 94 95
void FileRenamer::rename(const PlaylistItem *item)
{
    if(item == 0 || item->tag() == 0)
        return;

96
    QString newFilename = rename(item->absFilePath(), *item->tag());
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    if(KMessageBox::warningContinueCancel(0,
        i18n("You're about to rename the file '%1' to '%2'. Are you sure you "
             "want to continue?").arg(item->absFilePath()).arg(newFilename),
              i18n("Warning"), KStdGuiItem::cont(), "ShowFileRenamerWarning")
       == KMessageBox::Continue) {
        moveFile(item->absFilePath(), newFilename);
    }
}

void FileRenamer::rename(const PlaylistItemList &items)
{
    QMap<QString, QString> map;
    QStringList filenames;

    PlaylistItemList::ConstIterator it = items.begin();
    for(; it != items.end(); ++it) {
        const QString oldName = (*it)->absFilePath();
        const QString newName = rename(oldName, *(*it)->tag());
        filenames += oldName + "=>" + newName;
        map[oldName] = newName;
    }

    if(KMessageBox::warningContinueCancelList(0, i18n("You're about to "
       "rename the following files. Are you sure you want to continue?"),
       filenames, i18n("Warning"), KStdGuiItem::cont(), "ShowFileRenamerWarning")
       == KMessageBox::Continue) {
        KApplication::setOverrideCursor(Qt::waitCursor);
        int j = 1;
        QMap<QString, QString>::ConstIterator it = map.begin();
        for(; it != map.end(); ++it, ++j) {
            moveFile(it.key(), it.data());
            if(j % 5 == 0)
                kapp->processEvents();
        }
        KApplication::restoreOverrideCursor();
    }
133 134 135 136
}

QString FileRenamer::rename(const QString &filename, const Tag &tag) const
{
137
    QString newFilename = m_cfg.filenameScheme();
138 139

    QMap<QChar, QString> substitutions;
140 141 142 143 144
    substitutions[ 't' ] = expandToken(Title, tag.track());
    substitutions[ 'a' ] = expandToken(Artist, tag.artist());
    substitutions[ 'A' ] = expandToken(Album, tag.album());
    substitutions[ 'T' ] = expandToken(Track, tag.trackNumberString());
    substitutions[ 'c' ] = expandToken(Comment, tag.comment());
145 146 147 148 149

    newFilename = KMacroExpander::expandMacros(newFilename, substitutions);
    newFilename = newFilename.stripWhiteSpace();

    if(QFileInfo(newFilename).isRelative())
150
        newFilename = filename.left( filename.findRev( "/" ) )
151
            + "/" + newFilename;
152
    newFilename += "." + QFileInfo(filename).extension();
153

154
    return newFilename;
155 156 157 158
}

void FileRenamer::moveFile(const QString &src, const QString &dest)
{
Zack Rusin's avatar
Zack Rusin committed
159
    kdDebug(65432) << "Moving file " << src << " to " << dest << endl;
160 161 162 163 164 165 166 167 168 169 170 171

    if(src == dest)
        return;

    QString dest_ = dest.mid(1); // strip the leading "/"
    if(dest_.find("/") > 0) {
        const QStringList components = QStringList::split("/", dest_.left( dest.findRev("/")));
        QStringList::ConstIterator it = components.begin();
        QStringList::ConstIterator end = components.end();
        QString processedComponents;
        for(; it != end; ++it) {
            processedComponents += "/" + *it;
Zack Rusin's avatar
Zack Rusin committed
172
            kdDebug(65432) << "Checking path " << processedComponents << endl;
173 174
            QDir dir(processedComponents);
            if (!dir.exists())
Zack Rusin's avatar
Zack Rusin committed
175
                kdDebug(65432) << "Need to create " << processedComponents << endl;
176 177 178 179 180
        }
    }

    QFile srcFile(src);
    if(!srcFile.open(IO_ReadOnly)) {
181
        KMessageBox::error(0, i18n("Could not open %1 for reading.").arg(src));
182 183 184 185 186
        return;
    }

    QFile destFile(dest);
    if(!destFile.open(IO_WriteOnly)) {
187
        KMessageBox::error(0, i18n("Could not open %1 for writing.").arg(dest));
188 189 190 191 192 193
        return;
    }

    destFile.writeBlock(srcFile.readAll());

    if(!srcFile.remove())
194 195 196
        KMessageBox::sorry(0, i18n("Renamed the file, but failed the source "
                                      "file %1. You might want to do so by "
                                      "hand.").arg(src));
197
}
198 199

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