filerenamer.cpp 6.21 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
    const bool needValue = m_cfg.tokenNeedsValue(type);
    if(needValue && value.isEmpty())
        return QString();

    QString token = m_cfg.getToken(type);
    token.replace("%s", value);
87 88 89 90
    if(token.find(QDir::separator()) > -1) {
        kdWarning() << "Found token value with dir separators!" << endl;
        token.replace(QDir::separator(), "");
    }
91
    return token;
92 93
}

94

95 96 97 98 99
void FileRenamer::rename(const PlaylistItem *item)
{
    if(item == 0 || item->tag() == 0)
        return;

100
    QString newFilename = rename(item->absFilePath(), *item->tag());
101
    if(KMessageBox::warningContinueCancel(0,
102 103
        i18n("<qt>You're about to rename the file<br/><br/> '%1'<br/><br/> to <br/><br/>'%2'<br/><br/>Are you sure you "
             "want to continue?</qt>").arg(item->absFilePath()).arg(newFilename),
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 133 134 135 136
              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();
    }
137 138 139 140
}

QString FileRenamer::rename(const QString &filename, const Tag &tag) const
{
141
    QString newFilename = m_cfg.filenameScheme();
142 143

    QMap<QChar, QString> substitutions;
144 145 146 147 148
    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());
149 150 151 152 153

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

    if(QFileInfo(newFilename).isRelative())
154
        newFilename = filename.left( filename.findRev( "/" ) )
155
            + "/" + newFilename;
156
    newFilename += "." + QFileInfo(filename).extension();
157

158
    return newFilename;
159 160 161 162
}

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

    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
176
            kdDebug(65432) << "Checking path " << processedComponents << endl;
177
            QDir dir(processedComponents);
178 179
            if(!dir.exists()) {
                dir.mkdir(processedComponents, true);
Zack Rusin's avatar
Zack Rusin committed
180
                kdDebug(65432) << "Need to create " << processedComponents << endl;
181
            }
182 183 184 185 186
        }
    }

    QFile srcFile(src);
    if(!srcFile.open(IO_ReadOnly)) {
187
        KMessageBox::error(0, i18n("Could not open %1 for reading.").arg(src));
188 189 190 191 192
        return;
    }

    QFile destFile(dest);
    if(!destFile.open(IO_WriteOnly)) {
193
        KMessageBox::error(0, i18n("Could not open %1 for writing.").arg(dest));
194 195 196 197 198 199
        return;
    }

    destFile.writeBlock(srcFile.readAll());

    if(!srcFile.remove())
200 201 202
        KMessageBox::sorry(0, i18n("Renamed the file, but failed the source "
                                      "file %1. You might want to do so by "
                                      "hand.").arg(src));
203
}
204 205

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