filerenamer.cpp 7.64 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>
14
#include <kdialogbase.h>
Scott Wheeler's avatar
build  
Scott Wheeler committed
15
#include <kdebug.h>
16
#include <kiconloader.h>
17
#include <kio/netaccess.h>
18
#include <klocale.h>
19
#include <kmacroexpander.h>
20
#include <kmessagebox.h>
21 22

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

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

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

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

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

        lvHeight += lv->horizontalScrollBar()->height() + lv->header()->height();
        lv->setFixedHeight(QMIN(lvHeight, 400));
        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 148 149 150

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

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

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

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

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

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

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

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

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

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

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

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

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

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

221
    return newFilename;
222 223
}

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

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

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

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

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