thumbnail.cpp 24.8 KB
Newer Older
Malte Starostik's avatar
Malte Starostik committed
1
/*  This file is part of the KDE libraries
2
    Copyright (C) 2000 Malte Starostik <malte@kde.org>
3
                  2000 Carsten Pfeiffer <pfeiffer@kde.org>
Malte Starostik's avatar
Malte Starostik committed
4 5 6 7 8 9 10 11 12 13 14 15 16

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
Dirk Mueller's avatar
Dirk Mueller committed
17
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Dirk Mueller's avatar
Dirk Mueller committed
18
    Boston, MA 02110-1301, USA.
Malte Starostik's avatar
Malte Starostik committed
19 20
*/

21
#include "thumbnail.h"
22
#include "thumbnail-logsettings.h"
23

Malte Starostik's avatar
Malte Starostik committed
24
#include <stdlib.h>
Carsten Pfeiffer's avatar
Carsten Pfeiffer committed
25 26 27
#ifdef __FreeBSD__
    #include <machine/param.h>
#endif
Carsten Pfeiffer's avatar
Carsten Pfeiffer committed
28
#include <sys/types.h>
29
#ifndef Q_OS_WIN
Carsten Pfeiffer's avatar
Carsten Pfeiffer committed
30
#include <sys/ipc.h>
31
#include <sys/shm.h>
Kevin Funk's avatar
Kevin Funk committed
32
#include <unistd.h> // nice()
33
#endif
Malte Starostik's avatar
Malte Starostik committed
34

35
#include <QApplication>
36 37 38 39 40 41
#include <QBuffer>
#include <QFile>
#include <QSaveFile>
#include <QBitmap>
#include <QCryptographicHash>
#include <QImage>
42
#include <QIcon>
43 44
#include <QPainter>
#include <QPixmap>
David Faure's avatar
David Faure committed
45
#include <QUrl>
46 47 48 49 50
#include <QMimeType>
#include <QMimeDatabase>
#include <QLibrary>
#include <QDebug>

51
#include <KFileItem>
52 53 54 55 56
#include <KLocalizedString>
#include <KSharedConfig>
#include <KConfigGroup>
#include <KMimeTypeTrader>
#include <KServiceTypeTrader>
57
#include <KPluginLoader>
58

59
#include <kio/thumbcreator.h>
60
#include <kio/thumbsequencecreator.h>
61
#include <kio/previewjob.h>
Malte Starostik's avatar
Malte Starostik committed
62

Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
63
#include <limits>
64
#include <QDirIterator>
65

66 67 68 69
// Fix thumbnail: protocol
#define THUMBNAIL_HACK (1)

#ifdef THUMBNAIL_HACK
David Johnson's avatar
David Johnson committed
70
# include <QFileInfo>
71 72
#endif

73 74
#include "imagefilter.h"

75 76
// Recognized metadata entries:
// mimeType     - the mime type of the file, used for the overlay icon if any
77 78
// width        - maximum width for the thumbnail
// height       - maximum height for the thumbnail
79 80
// iconSize     - the size of the overlay icon to use if any (deprecated, ignored)
// iconAlpha    - the transparency value used for icon overlays (deprecated, ignored)
81
// plugin       - the name of the plugin library to be used for thumbnail creation.
82 83
//                Provided by the application to save an addition KTrader
//                query here.
84 85 86 87
// enabledPlugins - a list of enabled thumbnailer plugins. PreviewJob does not call
//                  this thumbnail slave when a given plugin isn't enabled. However,
//                  for directory thumbnails it doesn't know that the thumbnailer
//                  internally also loads the plugins.
88 89
// shmid        - the shared memory segment id to write the image's data to.
//                The segment is assumed to provide enough space for a 32-bit
90
//                image sized width x height pixels.
91 92 93 94 95
//                If this is given, the data returned by the slave will be:
//                    int width
//                    int height
//                    int depth
//                Otherwise, the data returned is the image in PNG format.
96

Malte Starostik's avatar
Malte Starostik committed
97 98
using namespace KIO;

Marco Martin's avatar
Marco Martin committed
99
extern "C" Q_DECL_EXPORT int kdemain( int argc, char **argv )
Malte Starostik's avatar
Malte Starostik committed
100
{
101
#ifdef HAVE_NICE
Malte Starostik's avatar
Malte Starostik committed
102
    nice( 5 );
103 104
#endif

105 106
    QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts);

107
    // creating KApplication in a slave in not a very good idea,
108 109 110
    // as dispatchLoop() doesn't allow it to process its messages,
    // so it for example wouldn't reply to ksmserver - on the other
    // hand, this slave uses QPixmaps for some reason, and they
111
    // need QGuiApplication
112 113
    putenv(strdup("SESSION_MANAGER="));

114
    // Some thumbnail plugins use QWidget classes for the rendering,
115
    // so use QApplication here, not just QGuiApplication
116
    QApplication app(argc, argv);
117

118
    if (argc != 4) {
119
        qCritical() << "Usage: kio_thumbnail protocol domain-socket1 domain-socket2";
Malte Starostik's avatar
Malte Starostik committed
120 121 122 123 124 125 126 127 128
        exit(-1);
    }

    ThumbnailProtocol slave(argv[2], argv[3]);
    slave.dispatchLoop();

    return 0;
}

Marco Martin's avatar
Marco Martin committed
129

Laurent Montel's avatar
Laurent Montel committed
130
ThumbnailProtocol::ThumbnailProtocol(const QByteArray &pool, const QByteArray &app)
131 132
    : SlaveBase("thumbnail", pool, app),
      m_maxFileSize(0)
Malte Starostik's avatar
Malte Starostik committed
133
{
134

Malte Starostik's avatar
Malte Starostik committed
135 136 137 138
}

ThumbnailProtocol::~ThumbnailProtocol()
{
139 140
    qDeleteAll( m_creators );
    m_creators.clear();
Malte Starostik's avatar
Malte Starostik committed
141 142
}

Marco Martin's avatar
Marco Martin committed
143
void ThumbnailProtocol::get(const QUrl &url)
Malte Starostik's avatar
Malte Starostik committed
144 145
{
    m_mimeType = metaData("mimeType");
146 147 148 149 150
    m_enabledPlugins = metaData("enabledPlugins").split(QLatin1Char(','), QString::SkipEmptyParts);
    if (m_enabledPlugins.isEmpty()) {
        const KConfigGroup globalConfig(KSharedConfig::openConfig(), "PreviewSettings");
        m_enabledPlugins = globalConfig.readEntry("Plugins", KIO::PreviewJob::defaultPlugins());
    }
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165

    Q_ASSERT(url.scheme() == "thumbnail");
    QFileInfo info(url.path());
    Q_ASSERT(info.isAbsolute());

    if (!info.exists()) {
	// The file does not exist
	error(KIO::ERR_DOES_NOT_EXIST, url.path());
	return;
    } else if (!info.isReadable()) {
	// The file is not readable!
	error(KIO::ERR_CANNOT_READ, url.path());
	return;
    }

166
    //qDebug() << "Wanting MIME Type:" << m_mimeType;
167
#ifdef THUMBNAIL_HACK
168
    // ### HACK
169
    bool direct=false;
170
    if (m_mimeType.isEmpty()) {
171
        //qDebug() << "PATH: " << url.path() << "isDir:" << info.isDir();
172
        if (info.isDir()) {
173
            m_mimeType = "inode/directory";
174
        } else {
175 176
            const QMimeDatabase db;

177
            m_mimeType = db.mimeTypeForFile(info).name();
178
        }
179

180
        //qDebug() << "Guessing MIME Type:" << m_mimeType;
181
        direct=true; // thumbnail: URL was probably typed in Konqueror
182 183 184
    }
#endif

185
    if (m_mimeType.isEmpty()) {
186
        error(KIO::ERR_INTERNAL, i18n("No MIME Type specified."));
Malte Starostik's avatar
Malte Starostik committed
187 188
        return;
    }
189 190 191

    m_width = metaData("width").toInt();
    m_height = metaData("height").toInt();
192

193
    if (m_width < 0 || m_height < 0) {
194
        error(KIO::ERR_INTERNAL, i18n("No or invalid size specified."));
195 196
        return;
    }
197
#ifdef THUMBNAIL_HACK
198
    else if (!m_width || !m_height) {
199
        //qDebug() << "Guessing height, width, icon size!";
200 201
        m_width = 128;
        m_height = 128;
202 203
    }
#endif
204

205 206
    QImage img;

207
    KConfigGroup group( KSharedConfig::openConfig(), "PreviewSettings" );
208
    bool kfmiThumb = false; // TODO Figure out if we can use KFileMetadata as a last resource
209

210
    if (!kfmiThumb) {
211
        QString plugin = metaData("plugin");
212
        if ((plugin.isEmpty() || plugin == "directorythumbnail") && m_mimeType == "inode/directory") {
213
            img = thumbForDirectory(info.canonicalFilePath());
214 215 216 217 218
            if(img.isNull()) {
              error(KIO::ERR_INTERNAL, i18n("Cannot create thumbnail for directory"));
              return;
            }
        } else {
219
#ifdef THUMBNAIL_HACK
220 221 222
            if (plugin.isEmpty()) {
                plugin = pluginForMimeType(m_mimeType);
            }
223

224
            //qDebug() << "Guess plugin: " << plugin;
225
#endif
226 227 228 229
            if (plugin.isEmpty()) {
                error(KIO::ERR_INTERNAL, i18n("No plugin specified."));
                return;
            }
230

231 232 233 234 235
            ThumbCreator* creator = getThumbCreator(plugin);
            if(!creator) {
                error(KIO::ERR_INTERNAL, i18n("Cannot load ThumbCreator %1", plugin));
                return;
            }
236

237 238 239 240
            ThumbSequenceCreator* sequenceCreator = dynamic_cast<ThumbSequenceCreator*>(creator);
            if(sequenceCreator)
                sequenceCreator->setSequenceIndex(sequenceIndex());

241 242
            if (!creator->create(info.canonicalFilePath(), m_width, m_height, img)) {
                error(KIO::ERR_INTERNAL, i18n("Cannot create thumbnail for %1", info.canonicalFilePath()));
243 244
                return;
            }
245
        }
Malte Starostik's avatar
Malte Starostik committed
246
    }
Carsten Pfeiffer's avatar
Carsten Pfeiffer committed
247

248
    scaleDownImage(img, m_width, m_height);
Malte Starostik's avatar
Malte Starostik committed
249

250
    if (img.isNull()) {
251 252 253 254 255
        error(KIO::ERR_INTERNAL, i18n("Failed to create a thumbnail."));
        return;
    }

    const QString shmid = metaData("shmid");
256
    if (shmid.isEmpty()) {
257
#ifdef THUMBNAIL_HACK
258
        if (direct) {
259
            // If thumbnail was called directly from Konqueror, then the image needs to be raw
Sebastian Kügler's avatar
Sebastian Kügler committed
260
            //qDebug() << "RAW IMAGE TO STREAM";
261
            QBuffer buf;
262
            if (!buf.open(QIODevice::WriteOnly)) {
263 264 265 266 267
                error(KIO::ERR_INTERNAL, i18n("Could not write image."));
                return;
            }
            img.save(&buf,"PNG");
            buf.close();
268
            mimeType("image/png");
269
            data(buf.buffer());
270
        }
271
        else
272
#endif
273 274
        {
            QByteArray imgData;
275
            QDataStream stream( &imgData, QIODevice::WriteOnly );
Sebastian Kügler's avatar
Sebastian Kügler committed
276
            //qDebug() << "IMAGE TO STREAM";
277
            stream << img;
278
            mimeType("application/octet-stream");
279 280
            data(imgData);
        }
281
    } else {
282
#ifndef Q_OS_WIN
283
        QByteArray imgData;
284
        QDataStream stream( &imgData, QIODevice::WriteOnly );
Sebastian Kügler's avatar
Sebastian Kügler committed
285
        //qDebug() << "IMAGE TO SHMID";
Kevin Funk's avatar
Kevin Funk committed
286
        void *shmaddr = shmat(shmid.toInt(), nullptr, 0);
287
        if (shmaddr == (void *)-1) {
288
            error(KIO::ERR_INTERNAL, i18n("Failed to attach to shared memory segment %1", shmid));
289 290
            return;
        }
291
        if (img.width() * img.height() > m_width * m_height) {
292
            error(KIO::ERR_INTERNAL, i18n("Image is too big for the shared memory segment"));
293 294 295
            shmdt((char*)shmaddr);
            return;
        }
296 297
        if( img.format() != QImage::Format_ARGB32 ) { // KIO::PreviewJob and this code below completely ignores colortable :-/,
            img = img.convertToFormat(QImage::Format_ARGB32); //  so make sure there is none
298
        }
Pascal Létourneau's avatar
Pascal Létourneau committed
299 300
        // Keep in sync with kdelibs/kio/kio/previewjob.cpp
        stream << img.width() << img.height() << quint8(img.format());
301
        memcpy(shmaddr, img.bits(), img.sizeInBytes());
302
        shmdt((char*)shmaddr);
303
        mimeType("application/octet-stream");
304
        data(imgData);
305
#endif
306
    }
Malte Starostik's avatar
Malte Starostik committed
307 308 309
    finished();
}

310
QString ThumbnailProtocol::pluginForMimeType(const QString& mimeType) {
311 312
    KService::List offers = KMimeTypeTrader::self()->query( mimeType, QLatin1String("ThumbCreator"));
    if (!offers.isEmpty()) {
313 314 315 316
        KService::Ptr serv;
        serv = offers.first();
        return serv->library();
    }
317

318 319 320
    //Match group mimetypes
    ///@todo Move this into some central location together with the related matching code in previewjob.cpp. This doesn't handle inheritance and such
    const KService::List plugins = KServiceTypeTrader::self()->query("ThumbCreator");
321
    for (const KService::Ptr& plugin : plugins) {
David Nolden's avatar
David Nolden committed
322
        const QStringList mimeTypes = plugin->serviceTypes();
323
        for (const QString& mime : mimeTypes) {
David Nolden's avatar
David Nolden committed
324
            if(mime.endsWith('*')) {
325 326
                const auto mimeGroup = mime.leftRef(mime.length()-1);
                if(mimeType.startsWith(mimeGroup))
David Nolden's avatar
David Nolden committed
327 328
                    return plugin->library();
            }
329 330 331
        }
    }

332 333 334
    return QString();
}

335 336 337 338
float ThumbnailProtocol::sequenceIndex() const {
    return metaData("sequence-index").toFloat();
}

339 340 341 342 343 344 345 346 347
bool ThumbnailProtocol::isOpaque(const QImage &image) const
{
    // Test the corner pixels
    return qAlpha(image.pixel(QPoint(0, 0))) == 255 &&
           qAlpha(image.pixel(QPoint(image.width()-1, 0))) == 255 &&
           qAlpha(image.pixel(QPoint(0, image.height()-1))) == 255 &&
           qAlpha(image.pixel(QPoint(image.width()-1, image.height()-1))) == 255;
}

348
void ThumbnailProtocol::drawPictureFrame(QPainter *painter, const QPoint &centerPos,
349
                                         const QImage &image, int frameWidth, QSize imageTargetSize) const
350
{
351
    // Scale the image down so it matches the aspect ratio
352
    float scaling = 1.0;
353 354

    if ((image.size().width() > imageTargetSize.width()) && (imageTargetSize.width() != 0)) {
355
        scaling = float(imageTargetSize.width()) / float(image.size().width());
356 357
    } else if ((image.size().height() > imageTargetSize.height()) && (imageTargetSize.height() != 0)) {
        scaling = float(imageTargetSize.height()) / float(image.size().height());
358 359
    }

360
    QImage frame(imageTargetSize + QSize(frameWidth * 2, frameWidth * 2),
361
                 QImage::Format_ARGB32);
362 363
    frame.fill(0);

364
    float scaledFrameWidth = frameWidth / scaling;
365

366
    QTransform m;
367
    m.rotate(qrand() % 17 - 8); // Random rotation ±8°
368
    m.scale(scaling, scaling);
369

370
    QRectF frameRect(QPointF(0, 0), QPointF(image.width() + scaledFrameWidth*2, image.height() + scaledFrameWidth*2));
371

372
    QRect r = m.mapRect(QRectF(frameRect)).toAlignedRect();
373

374
    QImage transformed(r.size(), QImage::Format_ARGB32);
375
    transformed.fill(0);
376
    QPainter p(&transformed);
377
    p.setRenderHint(QPainter::SmoothPixmapTransform);
378
    p.setCompositionMode(QPainter::CompositionMode_Source);
379

380 381
    p.translate(-r.topLeft());
    p.setWorldTransform(m, true);
382

383 384 385 386 387 388
    if (isOpaque(image)) {
        p.setRenderHint(QPainter::Antialiasing);
        p.setPen(Qt::NoPen);
        p.setBrush(Qt::white);
        p.drawRoundedRect(frameRect, scaledFrameWidth / 2, scaledFrameWidth / 2);
    }
389
    p.drawImage(scaledFrameWidth, scaledFrameWidth, image);
390 391 392 393
    p.end();

    int radius = qMax(frameWidth, 1);

394
    QImage shadow(r.size() + QSize(radius * 2, radius * 2), QImage::Format_ARGB32);
395 396 397 398 399 400 401
    shadow.fill(0);

    p.begin(&shadow);
    p.setCompositionMode(QPainter::CompositionMode_Source);
    p.drawImage(radius, radius, transformed);
    p.end();

402
    ImageFilter::shadowBlur(shadow, radius, QColor(0, 0, 0, 128));
403 404 405 406 407 408 409

    r.moveCenter(centerPos);

    painter->drawImage(r.topLeft() - QPoint(radius / 2, radius / 2), shadow);
    painter->drawImage(r.topLeft(), transformed);
}

410
QImage ThumbnailProtocol::thumbForDirectory(const QString& directory)
411 412
{
    QImage img;
413 414
    if (m_propagationDirectories.isEmpty()) {
        // Directories that the directory preview will be propagated into if there is no direct sub-directories
415
        const KConfigGroup globalConfig(KSharedConfig::openConfig(), "PreviewSettings");
416
        m_propagationDirectories = globalConfig.readEntry("PropagationDirectories", QStringList() << "VIDEO_TS").toSet();
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
417
        m_maxFileSize = globalConfig.readEntry("MaximumSize", std::numeric_limits<qint64>::max());
418
    }
419

420
    const int tiles = 2; //Count of items shown on each dimension
421
    const int spacing = 1;
422
    const int visibleCount = tiles * tiles;
423 424 425 426

    // TODO: the margins are optimized for the Oxygen iconset
    // Provide a fallback solution for other iconsets (e. g. draw folder
    // only as small overlay, use no margins)
427

428
    KFileItem item(QUrl::fromLocalFile(directory));
429 430 431 432 433 434 435 436
    const int extent = qMin(m_width, m_height);
    QPixmap folder = QIcon::fromTheme(item.iconName()).pixmap(extent);

    // Scale up base icon to ensure overlays are rendered with
    // the best quality possible even for low-res custom folder icons
    if (qMax(folder.width(), folder.height()) < extent) {
        folder = folder.scaled(extent, extent, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    }
437

438 439 440 441 442 443
    const int folderWidth  = folder.width();
    const int folderHeight = folder.height();

    const int topMargin = folderHeight * 30 / 100;
    const int bottomMargin = folderHeight / 6;
    const int leftMargin = folderWidth / 13;
444 445
    const int rightMargin = leftMargin;

446 447
    const int segmentWidth  = (folderWidth  - leftMargin - rightMargin  + spacing) / tiles - spacing;
    const int segmentHeight = (folderHeight - topMargin  - bottomMargin + spacing) / tiles - spacing;
448 449 450 451
    if ((segmentWidth < 5) || (segmentHeight <  5)) {
        // the segment size is too small for a useful preview
        return img;
    }
452

453 454
    // Advance to the next tile page each second
    int skipValidItems = ((int)sequenceIndex()) * visibleCount;
455

456
    img = QImage(QSize(folderWidth, folderHeight), QImage::Format_ARGB32);
457
    img.fill(0);
458

459 460 461
    QPainter p;
    p.begin(&img);

462
    p.setCompositionMode(QPainter::CompositionMode_Source);
463
    p.drawPixmap(0, 0, folder);
464
    p.setCompositionMode(QPainter::CompositionMode_SourceOver);
465

466 467
    int xPos = leftMargin;
    int yPos = topMargin;
468

469 470
    int frameWidth = qRound(folderWidth / 85.);

471
    int iterations = 0;
472
    QString hadFirstThumbnail;
473
    QImage firstThumbnail;
474

475 476
    int validThumbnails = 0;

477
    while (true) {
478
        QDirIterator dir(directory, QDir::Files | QDir::Readable);
479
        int skipped = 0;
480

481 482 483 484
        // Seed the random number generator so that it always returns the same result
        // for the same directory and sequence-item
        qsrand(qHash(directory) + skipValidItems);

Stefan Brüns's avatar
Stefan Brüns committed
485
        while (dir.hasNext()) {
486 487 488 489 490
            ++iterations;
            if (iterations > 500) {
                skipValidItems = skipped = 0;
                break;
            }
491

492
            dir.next();
493

494 495
            auto fileSize = dir.fileInfo().size();
            if ((fileSize == 0) || (fileSize > m_maxFileSize)) {
496
                // don't create thumbnails for files that exceed
497
                // the maximum set file size or are empty
498 499 500
                continue;
            }

501 502
            QImage subThumbnail;
            if (!createSubThumbnail(subThumbnail, dir.filePath(), segmentWidth, segmentHeight)) {
503 504
                continue;
            }
505

506 507 508 509
            if (skipped < skipValidItems) {
                ++skipped;
                continue;
            }
510

511 512 513 514
            if (!drawSubThumbnail(p, subThumbnail, segmentWidth, segmentHeight, xPos, yPos, frameWidth)) {
                continue;
            }

515
            if (hadFirstThumbnail.isEmpty()) {
516
                hadFirstThumbnail = dir.filePath();
517
                firstThumbnail = subThumbnail;
518
            }
519

520
            ++validThumbnails;
Stefan Brüns's avatar
Stefan Brüns committed
521 522 523
            if (validThumbnails >= visibleCount) {
                break;
            }
524

525 526 527 528 529
            xPos += segmentWidth + spacing;
            if (xPos > folderWidth - rightMargin - segmentWidth) {
                xPos = leftMargin;
                yPos += segmentHeight + spacing;
            }
530
        }
531

Stefan Brüns's avatar
Stefan Brüns committed
532 533 534 535
        if (validThumbnails > 0) {
            break;
        }

536 537 538
        if (skipped == 0) {
            break; // No valid items were found
        }
539

540 541
        // Calculate number of (partial) pages for all valid items in the directory
        auto skippedPages = (skipped + visibleCount - 1) / visibleCount;
542

543 544
        // The sequence is continously repeated after all valid items, calculate remainder
        skipValidItems = (((int)sequenceIndex()) % skippedPages) * visibleCount;
545
    }
546

547
    p.end();
548

549
    if (validThumbnails == 0) {
550
        // Eventually propagate the contained items from a sub-directory
551
        QDirIterator dir(directory, QDir::Dirs);
552
        int max = 50;
553
        while (dir.hasNext() && max > 0) {
554 555
            --max;
            dir.next();
556
            if (m_propagationDirectories.contains(dir.fileName())) {
557
                return thumbForDirectory(dir.filePath());
558
            }
559
        }
560 561 562 563

        // If no thumbnail could be found, return an empty image which indicates
        // that no preview for the directory is available.
        img = QImage();
564
    }
565

566
    // If only for one file a thumbnail could be generated then paint an image with only one tile
567
    if (validThumbnails == 1) {
568 569 570 571 572 573 574 575 576 577 578
        QImage oneTileImg(folder.size(), QImage::Format_ARGB32);
        oneTileImg.fill(0);

        QPainter oneTilePainter(&oneTileImg);
        oneTilePainter.setCompositionMode(QPainter::CompositionMode_Source);
        oneTilePainter.drawPixmap(0, 0, folder);
        oneTilePainter.setCompositionMode(QPainter::CompositionMode_SourceOver);

        const int oneTileWidth = folderWidth - leftMargin - rightMargin;
        const int oneTileHeight = folderHeight - topMargin - bottomMargin;

579 580 581 582
        if (firstThumbnail.width() < oneTileWidth && firstThumbnail.height() < oneTileHeight) {
            createSubThumbnail(firstThumbnail, hadFirstThumbnail, oneTileWidth, oneTileHeight);
        }
        drawSubThumbnail(oneTilePainter, firstThumbnail, oneTileWidth, oneTileHeight, leftMargin, topMargin, frameWidth);
583 584 585
        return oneTileImg;
    }

586
    return img;
587 588 589 590
}

ThumbCreator* ThumbnailProtocol::getThumbCreator(const QString& plugin)
{
591 592 593 594
    auto it = m_creators.constFind(plugin);
    if (it != m_creators.constEnd()) {
	return *it;
    }
595

596 597 598 599 600 601 602 603 604 605 606 607
    ThumbCreator *creator = nullptr;
    // Don't use KPluginFactory here, this is not a QObject and
    // neither is ThumbCreator
    QLibrary library(KPluginLoader::findPlugin((plugin)));
    if (library.load()) {
	auto createFn = (newCreator)library.resolve("new_creator");
	if (createFn) {
	    creator = createFn();
	}
    }
    if (!creator) {
	qCWarning(KIO_THUMBNAIL_LOG) << "Failed to load" << plugin << library.errorString();
608 609
    }

610 611
    m_creators.insert(plugin, creator);

612 613 614
    return creator;
}

615 616 617
bool ThumbnailProtocol::createSubThumbnail(QImage& thumbnail, const QString& filePath,
                                           int segmentWidth, int segmentHeight)
{
618
    auto getSubCreator = [&filePath, this]() -> ThumbCreator* {
619
        const QMimeDatabase db;
620
        const QString subPlugin = pluginForMimeType(db.mimeTypeForFile(filePath).name());
621 622 623 624 625
        if (subPlugin.isEmpty() || !m_enabledPlugins.contains(subPlugin)) {
            return nullptr;
        }
        return getThumbCreator(subPlugin);
    };
626 627 628 629 630

    if ((segmentWidth <= 256) && (segmentHeight <= 256)) {
        // check whether a cached version of the file is available for
        // 128 x 128 or 256 x 256 pixels
        int cacheSize = 0;
Sebastian Kügler's avatar
Sebastian Kügler committed
631
        QCryptographicHash md5(QCryptographicHash::Md5);
632 633 634
        const QByteArray fileUrl = QUrl::fromLocalFile(filePath).toEncoded();
        md5.addData(fileUrl);
        const QString thumbName = QString::fromLatin1(md5.result().toHex()).append(".png");
Sebastian Kügler's avatar
Sebastian Kügler committed
635

636
        if (m_thumbBasePath.isEmpty()) {
637
            m_thumbBasePath = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QLatin1String("/thumbnails/");
638 639 640 641 642
            QDir basePath(m_thumbBasePath);
            basePath.mkpath("normal/");
            QFile::setPermissions(basePath.absoluteFilePath("normal"), QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner);
            basePath.mkpath("large/");
            QFile::setPermissions(basePath.absoluteFilePath("large"), QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner);
643 644
        }

645
        QDir thumbPath(m_thumbBasePath);
646 647
        if ((segmentWidth <= 128) && (segmentHeight <= 128)) {
            cacheSize = 128;
648
            thumbPath.cd("normal");
649 650
        } else {
            cacheSize = 256;
651
            thumbPath.cd("large");
652
        }
653

654 655
        QFile thumbFile(thumbPath.absoluteFilePath(thumbName));
        if (thumbFile.open(QIODevice::ReadOnly) && thumbnail.load(&thumbFile, "png")) {
656 657 658 659
            return true;
        } else if (cacheSize == 128) {
            QDir fallbackPath(m_thumbBasePath);
            fallbackPath.cd("large");
660 661
            QFile fallbackThumbFile(fallbackPath.absoluteFilePath(thumbName));
            if (fallbackThumbFile.open(QIODevice::ReadOnly) && thumbnail.load(&fallbackThumbFile, "png")) {
662 663 664 665
                return true;
            }
        }

666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
        // no cached version is available, a new thumbnail must be created
        ThumbCreator* subCreator = getSubCreator();
        if (subCreator && subCreator->create(filePath, cacheSize, cacheSize, thumbnail)) {
            scaleDownImage(thumbnail, cacheSize, cacheSize);

            // The thumbnail has been created successfully. Store the thumbnail
            // to the cache for future access.
            QSaveFile thumbnailfile(thumbPath.absoluteFilePath(thumbName));
            if (thumbnailfile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
                QFileInfo fi(filePath);
                thumbnail.setText(QStringLiteral("Thumb::URI"), QString::fromUtf8(fileUrl));
                thumbnail.setText(QStringLiteral("Thumb::MTime"), QString::number(fi.lastModified().toSecsSinceEpoch()));
                thumbnail.setText(QStringLiteral("Thumb::Size"), QString::number(fi.size()));

                if (thumbnail.save(&thumbnailfile, "png")) {
                    thumbnailfile.commit();
682 683
                }
            }
684 685
        } else {
            return false;
686
        }
687 688 689
    } else {
        ThumbCreator* subCreator = getSubCreator();
        return subCreator && subCreator->create(filePath, segmentWidth, segmentHeight, thumbnail);
690 691 692 693
    }
    return true;
}

694 695 696
void ThumbnailProtocol::scaleDownImage(QImage& img, int maxWidth, int maxHeight)
{
    if (img.width() > maxWidth || img.height() > maxHeight) {
697
        img = img.scaled(maxWidth, maxHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);
698 699 700
    }
}

701
bool ThumbnailProtocol::drawSubThumbnail(QPainter& p, QImage subThumbnail, int width, int height, int xPos, int yPos, int frameWidth)
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
{
    // Apply fake smooth scaling, as seen on several blogs
    if (subThumbnail.width() > width * 4 || subThumbnail.height() > height * 4) {
        subThumbnail = subThumbnail.scaled(width*4, height*4, Qt::KeepAspectRatio, Qt::FastTransformation);
    }

    QSize targetSize(subThumbnail.size());
    targetSize.scale(width, height, Qt::KeepAspectRatio);

    // center the image inside the segment boundaries
    const QPoint centerPos(xPos + (width/ 2), yPos + (height / 2));
    drawPictureFrame(&p, centerPos, subThumbnail, frameWidth, targetSize);

    return true;
}