filerenamer.cpp 8.55 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
            KListViewItem *i = it.key() != it.data()
58 59
                ? new KListViewItem(lv, it.key(), it.data())
                : new KListViewItem(lv, it.key(), i18n("No Change"));
60 61 62 63
            lvHeight += i->height();
        }

        lvHeight += lv->horizontalScrollBar()->height() + lv->header()->height();
64
        lv->setMinimumHeight(QMIN(lvHeight, 400));
65 66 67
        resize(QMIN(width(), 500), QMIN(minimumHeight(), 400));
    }
};
68

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

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

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

84
QString FileRenamer::Config::getToken(TokenType type) const
85
{
86 87 88 89 90 91 92 93 94
    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);
95
}
96

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

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

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

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

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

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

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

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

147
    if((type == Track) && needValue && (value.toUInt() == 0))
Scott Wheeler's avatar
Scott Wheeler committed
148
        return QString::null;
149

150
    if((needValue) && value.isEmpty())
Scott Wheeler's avatar
Scott Wheeler committed
151
        return QString::null;
152 153

    token.replace("%s", value);
154
    return token;
155 156
}

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

162
    QString newFilename = rename(item->file().absFilePath(), *item->file().tag());
163 164 165 166 167

    // Don't try to rename the file if the name didn't change.
    if(QFileInfo(newFilename).absFilePath() == item->file().absFilePath())
        return;

168
    if(KMessageBox::warningContinueCancel(0,
Jonathan Riddell's avatar
Jonathan Riddell committed
169
        i18n("<qt>You are about to rename the file<br/><br/> '%1'<br/><br/> to <br/><br/>'%2'<br/><br/>Are you sure you "
170
             "want to continue?</qt>").arg(item->file().absFilePath()).arg(newFilename),
171 172
              i18n("Warning"), KStdGuiItem::cont(), "ShowFileRenamerWarning")
       == KMessageBox::Continue) {
173 174
        if(moveFile(item->file().absFilePath(), newFilename))
            item->setFile(FileHandle(newFilename));
175 176 177 178
        else
            KMessageBox::error(0,
                i18n("<qt>Failed to rename the file<br/><br/>'%1'<br/><br/>to<br/><br/>'%2'</qt>")
                    .arg(item->file().absFilePath()).arg(newFilename));
179 180 181 182 183 184
    }
}

void FileRenamer::rename(const PlaylistItemList &items)
{
    QMap<QString, QString> map;
185
    QMap<QString, PlaylistItem *> itemMap;
186
    QStringList errorFiles;
187 188 189

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

193
        const QString oldName = (*it)->file().absFilePath();
194
        map[oldName] = rename(oldName, *(*it)->file().tag());
195
        itemMap[oldName] = *it;
196 197
    }

198 199
    if(ConfirmationDialog(map).exec() == QDialog::Accepted) {

200 201 202 203
        KApplication::setOverrideCursor(Qt::waitCursor);
        int j = 1;
        QMap<QString, QString>::ConstIterator it = map.begin();
        for(; it != map.end(); ++it, ++j) {
204 205 206 207
            // Don't rename a file if the name didn't change.
            if(QFileInfo(it.key()).absFilePath() == QFileInfo(it.data()).absFilePath())
                continue;

208
            if(moveFile(it.key(), it.data()))
209
                itemMap[it.key()]->setFile(FileHandle(it.data()));
210
            else
211
                errorFiles << QString("%1 to %2").arg(it.key()).arg(it.data());
212

213 214 215 216 217
            if(j % 5 == 0)
                kapp->processEvents();
        }
        KApplication::restoreOverrideCursor();
    }
218 219 220

    if(!errorFiles.isEmpty())
        KMessageBox::error(0, i18n("The following rename operations failed:\n") + errorFiles.join("\n"));
221 222 223 224
}

QString FileRenamer::rename(const QString &filename, const Tag &tag) const
{
225
    QString newFilename = m_cfg.filenameScheme();
226 227

    QMap<QChar, QString> substitutions;
228
    substitutions[ 't' ] = expandToken(Title, tag.title());
229 230
    substitutions[ 'a' ] = expandToken(Artist, tag.artist());
    substitutions[ 'A' ] = expandToken(Album, tag.album());
231
    substitutions[ 'T' ] = expandToken(Track, QString::number(tag.track()));
232
    substitutions[ 'c' ] = expandToken(Comment, tag.comment());
233 234 235 236 237

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

    if(QFileInfo(newFilename).isRelative())
238
        newFilename = filename.left( filename.findRev( "/" ) )
239
            + "/" + newFilename;
240
    newFilename += "." + QFileInfo(filename).extension(false);
241

242
    return newFilename;
243 244
}

245
bool FileRenamer::moveFile(const QString &src, const QString &dest)
246
{
Zack Rusin's avatar
Zack Rusin committed
247
    kdDebug(65432) << "Moving file " << src << " to " << dest << endl;
248 249

    if(src == dest)
250
        return false;
251 252 253 254 255 256 257 258 259

    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
260
            kdDebug(65432) << "Checking path " << processedComponents << endl;
261
            QDir dir(processedComponents);
262
            if(!dir.exists()) {
263 264
                if (!dir.mkdir(processedComponents, true))
                    return false;
Zack Rusin's avatar
Zack Rusin committed
265
                kdDebug(65432) << "Need to create " << processedComponents << endl;
266
            }
267 268 269
        }
    }

270
    return KIO::NetAccess::file_move(KURL(src), KURL(dest));
271
}
272 273

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