filerenamer.cpp 8.1 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 <klocale.h>
18
#include <kmacroexpander.h>
19
#include <kmessagebox.h>
20 21

#include <qdir.h>
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
#include <qhbox.h>
#include <qheader.h>
#include <qlabel.h>
#include <qvbox.h>

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));
        
        l = new QLabel(i18n("You're about to rename the following files. "
                            "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;
        
        QMap<QString, QString>::ConstIterator it = files.begin();
        for(; it != files.end(); ++it) {
            KListViewItem *i = new KListViewItem(lv, it.key(), it.data());
            lvHeight += i->height();
        }

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

63 64
FileRenamer::Config::Config(KConfigBase *cfg)
    : m_grp(cfg, "FileRenamer")
65 66 67
{
}

68
QString FileRenamer::Config::filenameScheme() const
69
{
70
    return m_grp.readEntry("FilenameScheme", QDir::homeDirPath() + "/Music/%a%A%T%t%c");
71 72
}

73
void FileRenamer::Config::setFilenameScheme(const QString &scheme)
74
{
75
    m_grp.writeEntry("FilenameScheme", scheme);
76 77
}

78
QString FileRenamer::Config::getToken(TokenType type) const
79
{
80 81 82 83 84 85 86 87 88
    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);
89
}
90

91 92 93 94
void FileRenamer::Config::setToken(TokenType type, const QString &value)
{
    m_grp.writeEntry(tokenToString(type) + "Token", value);
}
95

96 97
bool FileRenamer::Config::tokenNeedsValue(TokenType type) const
{
98 99
    bool fallback = type != Title ? true : false;
    return m_grp.readBoolEntry("Need" + tokenToString(type) + "Value", fallback);
100 101
}

102
void FileRenamer::Config::setTokenNeedsValue(TokenType type, bool needsValue)
103
{
104
    m_grp.writeEntry("Need" + tokenToString(type) + "Value", needsValue);
105 106
}

107
QString FileRenamer::tokenToString(TokenType type)
108
{
109 110 111 112 113 114 115 116
    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;
117 118
}

119 120
FileRenamer::FileRenamer()
    : m_cfg(kapp->config())
121 122 123
{
}

124
FileRenamer::FileRenamer(PlaylistItem *item)
125
    : m_cfg(kapp->config())
126
{
127
    rename(item);
128 129
}

130
QString FileRenamer::expandToken(TokenType type, const QString &value_) const
131
{
132 133
    const bool needValue = m_cfg.tokenNeedsValue(type);

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

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

    token.replace("%s", value);
145
    return token;
146 147
}

148
void FileRenamer::rename(PlaylistItem *item)
149 150 151 152
{
    if(item == 0 || item->tag() == 0)
        return;

153
    QString newFilename = rename(item->absFilePath(), *item->tag());
154
    if(KMessageBox::warningContinueCancel(0,
155 156
        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),
157 158
              i18n("Warning"), KStdGuiItem::cont(), "ShowFileRenamerWarning")
       == KMessageBox::Continue) {
159 160
        if(moveFile(item->absFilePath(), newFilename))
            item->setFile(newFilename);
161 162 163 164 165 166
    }
}

void FileRenamer::rename(const PlaylistItemList &items)
{
    QMap<QString, QString> map;
167
    QMap<QString, PlaylistItem *> itemMap;
168 169 170 171
    QStringList filenames;

    PlaylistItemList::ConstIterator it = items.begin();
    for(; it != items.end(); ++it) {
172 173 174 175 176 177 178 179
	if(*it && (*it)->tag()) {
            const QString oldName = (*it)->absFilePath();
            const QString newName = rename(oldName, *(*it)->tag());
            filenames += oldName;
            filenames += " => " + newName;
            map[oldName] = newName;
            itemMap[oldName] = *it;
        }
180 181
    }

182 183
    if(ConfirmationDialog(map).exec() == QDialog::Accepted) {

184 185 186 187
        KApplication::setOverrideCursor(Qt::waitCursor);
        int j = 1;
        QMap<QString, QString>::ConstIterator it = map.begin();
        for(; it != map.end(); ++it, ++j) {
188 189 190
            if(moveFile(it.key(), it.data()))
                itemMap[it.key()]->setFile(it.data());
                
191 192 193 194 195
            if(j % 5 == 0)
                kapp->processEvents();
        }
        KApplication::restoreOverrideCursor();
    }
196 197 198 199
}

QString FileRenamer::rename(const QString &filename, const Tag &tag) const
{
200
    QString newFilename = m_cfg.filenameScheme();
201 202

    QMap<QChar, QString> substitutions;
203 204 205 206 207
    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());
208 209 210 211 212

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

    if(QFileInfo(newFilename).isRelative())
213
        newFilename = filename.left( filename.findRev( "/" ) )
214
            + "/" + newFilename;
215
    newFilename += "." + QFileInfo(filename).extension();
216

217
    return newFilename;
218 219
}

220
bool FileRenamer::moveFile(const QString &src, const QString &dest)
221
{
Zack Rusin's avatar
Zack Rusin committed
222
    kdDebug(65432) << "Moving file " << src << " to " << dest << endl;
223 224

    if(src == dest)
225
        return false;
226 227 228 229 230 231 232 233 234

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

    QFile srcFile(src);
    if(!srcFile.open(IO_ReadOnly)) {
246
        KMessageBox::error(0, i18n("Could not open %1 for reading.").arg(src));
247
        return false;
248 249 250 251
    }

    QFile destFile(dest);
    if(!destFile.open(IO_WriteOnly)) {
252
        KMessageBox::error(0, i18n("Could not open %1 for writing.").arg(dest));
253
        return false;
254 255 256 257
    }

    destFile.writeBlock(srcFile.readAll());

258
    if(!srcFile.remove()) {
259 260 261
        KMessageBox::sorry(0, i18n("Renamed the file, but failed the source "
                                      "file %1. You might want to do so by "
                                      "hand.").arg(src));
262 263 264 265
        return false;
    }

    return true;
266
}
267 268

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