filerenamer.cpp 7.66 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/*
 * 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"
11
#include "tag.h"
12 13 14

#include <kapplication.h>
#include <kconfig.h>
15
#include <kdialogbase.h>
Scott Wheeler's avatar
build  
Scott Wheeler committed
16
#include <kdebug.h>
17
#include <kiconloader.h>
18
#include <kio/netaccess.h>
19
#include <klocale.h>
20
#include <kmacroexpander.h>
21
#include <kmessagebox.h>
22 23

#include <qdir.h>
24 25 26 27
#include <qhbox.h>
#include <qheader.h>
#include <qlabel.h>
#include <qvbox.h>
28 29
#include <qpainter.h>
#include <qsimplerichtext.h>
30 31 32 33 34 35 36 37 38 39 40 41 42

class FileRenamer::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)
    {
        QVBox *vbox = makeVBoxMainWidget();
        QHBox *hbox = new QHBox(vbox);

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

Jonathan Riddell's avatar
Jonathan Riddell committed
44
        l = new QLabel(i18n("You are about to rename the following files. "
45 46 47 48 49 50 51 52 53
                            "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;
54

55 56
        QMap<QString, QString>::ConstIterator it = files.begin();
        for(; it != files.end(); ++it) {
57 58 59 60

            KListViewItem *i = it.key() == it.data()
                ? new KListViewItem(lv, it.key(), it.data())
                : new KListViewItem(lv, it.key(), i18n("No Change"));
61 62 63 64 65 66 67 68
            lvHeight += i->height();
        }

        lvHeight += lv->horizontalScrollBar()->height() + lv->header()->height();
        lv->setFixedHeight(QMIN(lvHeight, 400));
        resize(QMIN(width(), 500), QMIN(minimumHeight(), 400));
    }
};
69

70 71
FileRenamer::Config::Config(KConfigBase *cfg)
    : m_grp(cfg, "FileRenamer")
72 73 74
{
}

75
QString FileRenamer::Config::filenameScheme() const
76
{
77
    return m_grp.readEntry("FilenameScheme", QDir::homeDirPath() + "/Music/%a%A%T%t%c");
78 79
}

80
void FileRenamer::Config::setFilenameScheme(const QString &scheme)
81
{
82
    m_grp.writeEntry("FilenameScheme", scheme);
83 84
}

85
QString FileRenamer::Config::getToken(TokenType type) const
86
{
87 88 89 90 91 92 93 94 95
    QString fallback;
    switch(type) {
        case Title: fallback = "%s"; break;
        case Artist: fallback = "%s/"; break;
        case Album: fallback = "%s/"; break;
        case Track: fallback = "[%s] "; break;
        case Comment: fallback = " (%s)"; break;
    }
    return m_grp.readEntry(tokenToString(type) + "Token", fallback);
96
}
97

98 99 100 101
void FileRenamer::Config::setToken(TokenType type, const QString &value)
{
    m_grp.writeEntry(tokenToString(type) + "Token", value);
}
102

103 104
bool FileRenamer::Config::tokenNeedsValue(TokenType type) const
{
105 106
    bool fallback = type != Title ? true : false;
    return m_grp.readBoolEntry("Need" + tokenToString(type) + "Value", fallback);
107 108
}

109
void FileRenamer::Config::setTokenNeedsValue(TokenType type, bool needsValue)
110
{
111
    m_grp.writeEntry("Need" + tokenToString(type) + "Value", needsValue);
112 113
}

114
QString FileRenamer::tokenToString(TokenType type)
115
{
116 117 118 119 120 121 122 123
    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;
124 125
}

126 127
FileRenamer::FileRenamer()
    : m_cfg(kapp->config())
128 129 130
{
}

131
FileRenamer::FileRenamer(PlaylistItem *item)
132
    : m_cfg(kapp->config())
133
{
134
    rename(item);
135 136
}

137
QString FileRenamer::expandToken(TokenType type, const QString &value_) const
138
{
139 140
    const bool needValue = m_cfg.tokenNeedsValue(type);

141
    QString value = value_;
142
    QString token = m_cfg.getToken(type);
143
    if(value.find(QDir::separator()) > -1) {
144
        kdWarning() << "Found token value with dir separators!" << endl;
145
        value.replace(QDir::separator(), "");
146
    }
147 148 149 150 151

    if((needValue) && value.isEmpty())
        return QString();

    token.replace("%s", value);
152
    return token;
153 154
}

155
void FileRenamer::rename(PlaylistItem *item)
156
{
157
    if(item == 0 || item->file().tag() == 0)
158 159
        return;

160
    QString newFilename = rename(item->file().absFilePath(), *item->file().tag());
161
    if(KMessageBox::warningContinueCancel(0,
Jonathan Riddell's avatar
Jonathan Riddell committed
162
        i18n("<qt>You are about to rename the file<br/><br/> '%1'<br/><br/> to <br/><br/>'%2'<br/><br/>Are you sure you "
163
             "want to continue?</qt>").arg(item->file().absFilePath()).arg(newFilename),
164 165
              i18n("Warning"), KStdGuiItem::cont(), "ShowFileRenamerWarning")
       == KMessageBox::Continue) {
166 167
        if(moveFile(item->file().absFilePath(), newFilename))
            item->setFile(FileHandle(newFilename));
168 169 170 171 172 173
    }
}

void FileRenamer::rename(const PlaylistItemList &items)
{
    QMap<QString, QString> map;
174
    QMap<QString, PlaylistItem *> itemMap;
175 176 177

    PlaylistItemList::ConstIterator it = items.begin();
    for(; it != items.end(); ++it) {
178
        if(!*it || !(*it)->file().tag())
179 180
            continue;

181 182 183 184
        const QString oldName = (*it)->file().absFilePath();
        const QString newName = rename(oldName, *(*it)->file().tag());
        map[oldName] = newName;
        itemMap[oldName] = *it;
185 186
    }

187 188
    if(ConfirmationDialog(map).exec() == QDialog::Accepted) {

189 190 191 192
        KApplication::setOverrideCursor(Qt::waitCursor);
        int j = 1;
        QMap<QString, QString>::ConstIterator it = map.begin();
        for(; it != map.end(); ++it, ++j) {
193
            if(moveFile(it.key(), it.data()))
194
                itemMap[it.key()]->setFile(FileHandle(it.data()));
195

196 197 198 199 200
            if(j % 5 == 0)
                kapp->processEvents();
        }
        KApplication::restoreOverrideCursor();
    }
201 202 203 204
}

QString FileRenamer::rename(const QString &filename, const Tag &tag) const
{
205
    QString newFilename = m_cfg.filenameScheme();
206 207

    QMap<QChar, QString> substitutions;
208
    substitutions[ 't' ] = expandToken(Title, tag.title());
209 210
    substitutions[ 'a' ] = expandToken(Artist, tag.artist());
    substitutions[ 'A' ] = expandToken(Album, tag.album());
211
    substitutions[ 'T' ] = expandToken(Track, QString::number(tag.track()));
212
    substitutions[ 'c' ] = expandToken(Comment, tag.comment());
213 214 215 216 217

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

    if(QFileInfo(newFilename).isRelative())
218
        newFilename = filename.left( filename.findRev( "/" ) )
219
            + "/" + newFilename;
220
    newFilename += "." + QFileInfo(filename).extension(false);
221

222
    return newFilename;
223 224
}

225
bool FileRenamer::moveFile(const QString &src, const QString &dest)
226
{
Zack Rusin's avatar
Zack Rusin committed
227
    kdDebug(65432) << "Moving file " << src << " to " << dest << endl;
228 229

    if(src == dest)
230
        return false;
231 232 233 234 235 236 237 238 239

    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
240
            kdDebug(65432) << "Checking path " << processedComponents << endl;
241
            QDir dir(processedComponents);
242 243
            if(!dir.exists()) {
                dir.mkdir(processedComponents, true);
Zack Rusin's avatar
Zack Rusin committed
244
                kdDebug(65432) << "Need to create " << processedComponents << endl;
245
            }
246 247 248
        }
    }

249
    return KIO::NetAccess::file_move(KURL(src), KURL(dest));
250
}
251 252

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