File: comiccreator.cpp

package info (click to toggle)
kio-extras 4%3A16.08.3-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 2,720 kB
  • ctags: 3,303
  • sloc: cpp: 26,172; ansic: 5,034; perl: 1,056; xml: 460; python: 28; sh: 20; makefile: 6
file content (314 lines) | stat: -rw-r--r-- 9,385 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/**
 * This file is part of the KDE libraries
 *
 * Comic Book Thumbnailer for KDE 4 v0.1
 * Creates cover page previews for comic-book files (.cbr/z/t).
 * Copyright (c) 2009 Harsh J <harsh@harshj.com>
 *
 * Some code borrowed from Okular's comicbook generators,
 * by Tobias Koenig <tokoe@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) version 3 or any later version
 * accepted by the membership of KDE e.V. (or its successor approved
 * by the membership of KDE e.V.), which shall act as a proxy
 * defined in Section 14 of version 3 of the license.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

// comiccreator.cpp

#include "comiccreator.h"

#include <kzip.h>
#include <ktar.h>
#include <QDebug>
#include <kprocess.h>

#include <memory>

#include <QtCore/QFile>
#include <QtCore/QEventLoop>
#include <QMimeDatabase>
#include <QMimeType>
#include <QStandardPaths>
#include <QTemporaryDir>

// For KIO-Thumbnail debug outputs
// TODO KF5 qCDebug
#define KIO_THUMB 11371

extern "C"
{
    Q_DECL_EXPORT ThumbCreator *new_creator()
    {
        return new ComicCreator;
    }
}

ComicCreator::ComicCreator() : m_loop(0) {}

bool ComicCreator::create(const QString& path, int width, int height, QImage& img)
{
    Q_UNUSED(width);
    Q_UNUSED(height);

    QImage cover;

    // Detect mime type.
    QMimeDatabase db;
    db.mimeTypeForFile(path, QMimeDatabase::MatchContent);
    const QMimeType mime = db.mimeTypeForFile(path, QMimeDatabase::MatchContent);

    if (mime.inherits("application/x-cbz") || mime.inherits("application/zip")) {
        // ZIP archive.
        cover = extractArchiveImage(path, ZIP);
    } else if (mime.inherits("application/x-cbt") ||
                mime.inherits("application/x-gzip") ||
                mime.inherits("application/x-tar")) {
        // TAR archive
        cover = extractArchiveImage(path, TAR);
    } else if (mime.inherits("application/x-cbr") || mime.inherits("application/x-rar")) {
        // RAR archive.
        cover = extractRARImage(path);
    }

    if (cover.isNull()) {
        qDebug()<<"Error creating the comic book thumbnail.";
        return false;
    }

    // Copy the extracted cover to KIO::ThumbCreator's img reference.
    img = cover;

    return true;
}

void ComicCreator::filterImages(QStringList& entries)
{
    /// Sort case-insensitive, then remove non-image entries.
    QMap<QString, QString> entryMap;
    Q_FOREACH(const QString& entry, entries) {
        if (entry.endsWith(QLatin1String(".gif"), Qt::CaseInsensitive) ||
                entry.endsWith(QLatin1String(".jpg"), Qt::CaseInsensitive) ||
                entry.endsWith(QLatin1String(".jpeg"), Qt::CaseInsensitive) ||
                entry.endsWith(QLatin1String(".png"), Qt::CaseInsensitive)) {
            entryMap.insert(entry.toLower(), entry);
        }
    }
    entries = entryMap.values();
}

QImage ComicCreator::extractArchiveImage(const QString& path, const ComicCreator::Type type)
{
    /// Extracts the cover image out of the .cbz or .cbt file.
    QScopedPointer<KArchive> cArchive;

    if (type==ZIP) {
        // Open the ZIP archive.
        cArchive.reset(new KZip(path));
    } else if (type==TAR) {
        // Open the TAR archive.
        cArchive.reset(new KTar(path));
    } else {
        // Reject all other types for this method.
        return QImage();
    }

    // Can our archive be opened?
    if (!cArchive->open(QIODevice::ReadOnly)) {
            return QImage();
    }

    // Get the archive's directory.
    const KArchiveDirectory* cArchiveDir = 0;
    cArchiveDir = cArchive->directory();
    if (!cArchiveDir) {
        return QImage();
    }

    QStringList entries;

    // Get and filter the entries from the archive.
    getArchiveFileList(entries, QString(), cArchiveDir);
    filterImages(entries);
    if (entries.isEmpty()) {
        return QImage();
    }

    // Extract the cover file.
    const KArchiveFile *coverFile = static_cast<const KArchiveFile*>
        (cArchiveDir->entry(entries[0]));
    if (!coverFile) {
        return QImage();
    }

    return QImage::fromData(coverFile->data());
}



void ComicCreator::getArchiveFileList(QStringList& entries, const QString& prefix,
    const KArchiveDirectory *dir)
{
    /// Recursively list all files in the ZIP archive into 'entries'.
    Q_FOREACH (const QString& entry, dir->entries()) {
        const KArchiveEntry *e = dir->entry(entry);
        if (e->isDirectory()) {
        getArchiveFileList(entries, prefix + entry + '/',
            static_cast<const KArchiveDirectory*>(e));
        } else if (e->isFile()) {
            entries.append(prefix + entry);
        }
    }
}

QImage ComicCreator::extractRARImage(const QString& path)
{
    /// Extracts the cover image out of the .cbr file.

    // Check if unrar is available. Get its path in 'unrarPath'.
    QString unrar = unrarPath();
    if (unrar.isEmpty()) {
        qDebug()<<"A suitable version of unrar is not available.";
        return QImage();
    }

    // Get the files and filter the images out.
    QStringList entries = getRARFileList(path, unrar);
    filterImages(entries);
    if (entries.isEmpty()) {
        return QImage();
    }

    // Clear previously used data arrays.
    m_stdOut.clear();
    m_stdErr.clear();

    // Extract the cover file alone. Use verbose paths.
    // unrar x -n<file> path/to/archive /path/to/temp
    QTemporaryDir cUnrarTempDir;
    startProcess(unrar, QStringList() << "x" << "-n" + entries[0] << path << cUnrarTempDir.path());

    // Load cover file data into image.
    QImage cover;
    cover.load(cUnrarTempDir.path() + QDir::separator() + entries[0]);

    return cover;
}

QStringList ComicCreator::getRARFileList(const QString& path,
    const QString& unrarPath)
{
    /// Get a verbose unrar listing so we can extract a single file later.
    // CMD: unrar vb /path/to/archive
    QStringList entries;
    startProcess(unrarPath, QStringList() << "vb" << path);
    entries = QString::fromLocal8Bit(m_stdOut).split('\n', QString::SkipEmptyParts);
    return entries;
}

QString ComicCreator::unrarPath() const
{
    /// Check the standard paths to see if a suitable unrar is available.
    QString unrar = QStandardPaths::findExecutable("unrar");
    if (unrar.isEmpty()) {
        unrar = QStandardPaths::findExecutable("unrar-nonfree");
    }
    if (unrar.isEmpty()) {
        unrar = QStandardPaths::findExecutable("rar");
    }
    if (!unrar.isEmpty()) {
        QProcess proc;
        proc.start(unrar, QStringList() << "--version");
        proc.waitForFinished(-1);
        const QStringList lines = QString::fromLocal8Bit(proc.readAllStandardOutput()).split
            ('\n', QString::SkipEmptyParts);
        if (!lines.isEmpty()) {
            if (lines.first().startsWith("RAR ") || lines.first().startsWith("UNRAR ")) {
                return unrar;
            }
        }
    }
    return QString();
}

void ComicCreator::readProcessOut()
{
    /// Read all std::out data and store to the data array.
    if (!m_process)
        return;

    m_stdOut += m_process->readAllStandardOutput();
}

void ComicCreator::readProcessErr()
{
    /// Read available std:err data and kill process if there is any.
    if (!m_process)
        return;

    m_stdErr += m_process->readAllStandardError();
    if (!m_stdErr.isEmpty())
    {
        m_process->kill();
        return;
    }
}

void ComicCreator::finishedProcess(int exitCode, QProcess::ExitStatus exitStatus)
{
    /// Run when process finishes.
    Q_UNUSED(exitCode)
    if (m_loop)
    {
        m_loop->exit(exitStatus == QProcess::CrashExit ? 1 : 0);
    }
}

int ComicCreator::startProcess(const QString& processPath, const QStringList& args)
{
    /// Run a process and store std::out, std::err data in their respective buffers.
    int ret = 0;

#if defined(Q_OS_WIN)
    m_process.reset(new QProcess(this));
#else
    m_process.reset(new KPtyProcess(this));
    m_process->setOutputChannelMode(KProcess::SeparateChannels);
#endif

    connect(m_process.data(), SIGNAL(readyReadStandardOutput()), SLOT(readProcessOut()));
    connect(m_process.data(), SIGNAL(readyReadStandardError()), SLOT(readProcessErr()));
    connect(m_process.data(), SIGNAL(finished(int, QProcess::ExitStatus)),
        SLOT(finishedProcess(int, QProcess::ExitStatus)));

#if defined(Q_OS_WIN)
    m_process->start(processPath, args, QIODevice::ReadWrite | QIODevice::Unbuffered);
    ret = m_process->waitForFinished(-1) ? 0 : 1;
#else
    m_process->setProgram(processPath, args);
    m_process->setNextOpenMode(QIODevice::ReadWrite | QIODevice::Unbuffered);
    m_process->start();
    QEventLoop loop;
    m_loop = &loop;
    ret = loop.exec(QEventLoop::WaitForMoreEvents);
    m_loop = 0;
#endif

    return ret;
}

ThumbCreator::Flags ComicCreator::flags() const
{
    return DrawFrame;
}