~ubuntu-branches/ubuntu/precise/gwenview/precise-proposed

« back to all changes in this revision

Viewing changes to lib/document/loadingdocumentimpl.cpp

  • Committer: Package Import Robot
  • Author(s): Jonathan Riddell
  • Date: 2011-12-15 14:17:54 UTC
  • mto: This revision was merged to the branch mainline in revision 12.
  • Revision ID: package-import@ubuntu.com-20111215141754-z043hyx69dulbggf
Tags: upstream-4.7.90
ImportĀ upstreamĀ versionĀ 4.7.90

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
// vim: set tabstop=4 shiftwidth=4 noexpandtab:
 
1
// vim: set tabstop=4 shiftwidth=4 expandtab:
2
2
/*
3
3
Gwenview: an image viewer
4
4
Copyright 2007 AurĆ©lien GĆ¢teau <agateau@kde.org>
58
58
#include "urlutils.h"
59
59
#include "videodocumentloadedimpl.h"
60
60
 
61
 
namespace Gwenview {
 
61
namespace Gwenview
 
62
{
62
63
 
63
64
#undef ENABLE_LOG
64
65
#undef LOG
72
73
const int HEADER_SIZE = 256;
73
74
 
74
75
struct LoadingDocumentImplPrivate {
75
 
        LoadingDocumentImpl* mImpl;
76
 
        QPointer<KIO::TransferJob> mTransferJob;
77
 
        QFuture<bool> mMetaInfoFuture;
78
 
        QFutureWatcher<bool> mMetaInfoFutureWatcher;
79
 
        QFuture<void> mImageDataFuture;
80
 
        QFutureWatcher<void> mImageDataFutureWatcher;
81
 
 
82
 
        // If != 0, this means we need to load an image at zoom =
83
 
        // 1/mImageDataInvertedZoom
84
 
        int mImageDataInvertedZoom;
85
 
 
86
 
        bool mMetaInfoLoaded;
87
 
        bool mAnimated;
88
 
        bool mDownSampledImageLoaded;
89
 
        QByteArray mData;
90
 
        QByteArray mFormat;
91
 
        QSize mImageSize;
92
 
        Exiv2::Image::AutoPtr mExiv2Image;
93
 
        std::auto_ptr<JpegContent> mJpegContent;
94
 
        QImage mImage;
95
 
 
96
 
 
97
 
        /**
98
 
         * Determine kind of document and switch to an implementation if it is not
99
 
         * necessary to download more data.
100
 
         * @return true if switched to another implementation.
101
 
         */
102
 
        bool determineKind() {
103
 
                QString mimeType;
104
 
                const KUrl& url = mImpl->document()->url();
105
 
                if (KProtocolInfo::determineMimetypeFromExtension(url.protocol())) {
106
 
                        mimeType = KMimeType::findByNameAndContent(url.fileName(), mData)->name();
107
 
                } else {
108
 
                        mimeType = KMimeType::findByContent(mData)->name();
109
 
                }
110
 
                MimeTypeUtils::Kind kind = MimeTypeUtils::mimeTypeKind(mimeType);
111
 
                LOG("mimeType:" << mimeType);
112
 
                LOG("kind:" << kind);
113
 
                mImpl->setDocumentKind(kind);
114
 
 
115
 
                switch (kind) {
116
 
                case MimeTypeUtils::KIND_RASTER_IMAGE:
117
 
                case MimeTypeUtils::KIND_SVG_IMAGE:
118
 
                        return false;
119
 
 
120
 
                case MimeTypeUtils::KIND_VIDEO:
121
 
                        mImpl->switchToImpl(new VideoDocumentLoadedImpl(mImpl->document()));
122
 
                        return true;
123
 
 
124
 
                default:
125
 
                        mImpl->setDocumentErrorString(
126
 
                                i18nc("@info", "Gwenview cannot display documents of type %1.", mimeType)
127
 
                                );
128
 
                        emit mImpl->loadingFailed();
129
 
                        mImpl->switchToImpl(new EmptyDocumentImpl(mImpl->document()));
130
 
                        return true;
131
 
                }
132
 
        }
133
 
 
134
 
 
135
 
        void startLoading() {
136
 
                Q_ASSERT(!mMetaInfoLoaded);
137
 
 
138
 
                switch (mImpl->document()->kind()) {
139
 
                case MimeTypeUtils::KIND_RASTER_IMAGE:
140
 
                        mMetaInfoFuture = QtConcurrent::run(this, &LoadingDocumentImplPrivate::loadMetaInfo);
141
 
                        mMetaInfoFutureWatcher.setFuture(mMetaInfoFuture);
142
 
                        break;
143
 
 
144
 
                case MimeTypeUtils::KIND_SVG_IMAGE:
145
 
                        mImpl->switchToImpl(new SvgDocumentLoadedImpl(mImpl->document(), mData));
146
 
                        break;
147
 
 
148
 
                case MimeTypeUtils::KIND_VIDEO:
149
 
                        break;
150
 
 
151
 
                default:
152
 
                        kWarning() << "We should not reach this point!";
153
 
                        break;
154
 
                }
155
 
        }
156
 
 
157
 
        void startImageDataLoading() {
158
 
                LOG("");
159
 
                Q_ASSERT(mMetaInfoLoaded);
160
 
                Q_ASSERT(mImageDataInvertedZoom != 0);
161
 
                Q_ASSERT(!mImageDataFuture.isRunning());
162
 
                mImageDataFuture = QtConcurrent::run(this, &LoadingDocumentImplPrivate::loadImageData);
163
 
                mImageDataFutureWatcher.setFuture(mImageDataFuture);
164
 
        }
165
 
 
166
 
        bool loadMetaInfo() {
167
 
                QBuffer buffer;
168
 
                buffer.setBuffer(&mData);
169
 
                buffer.open(QIODevice::ReadOnly);
170
 
                QImageReader reader(&buffer);
171
 
                mFormat = reader.format();
172
 
                if (mFormat.isEmpty()) {
173
 
                        return false;
174
 
                }
175
 
 
176
 
                Exiv2ImageLoader loader;
177
 
                if (loader.load(mData)) {
178
 
                        mExiv2Image = loader.popImage();
179
 
                }
180
 
 
181
 
                if (mFormat == "jpeg" && mExiv2Image.get()) {
182
 
                        mJpegContent.reset(new JpegContent());
183
 
                        if (!mJpegContent->loadFromData(mData, mExiv2Image.get())) {
184
 
                                return false;
185
 
                        }
186
 
 
187
 
                        // Use the size from JpegContent, as its correctly transposed if the
188
 
                        // image has been rotated
189
 
                        mImageSize = mJpegContent->size();
190
 
                } else {
191
 
                        mImageSize = reader.size();
192
 
                }
193
 
                LOG("mImageSize" << mImageSize);
194
 
 
195
 
                return true;
196
 
        }
197
 
 
198
 
        void loadImageData() {
199
 
                QBuffer buffer;
200
 
                buffer.setBuffer(&mData);
201
 
                buffer.open(QIODevice::ReadOnly);
202
 
                QImageReader reader(&buffer);
203
 
 
204
 
                LOG("mImageDataInvertedZoom=" << mImageDataInvertedZoom);
205
 
                if (mImageSize.isValid()
206
 
                        && mImageDataInvertedZoom != 1
207
 
                        && reader.supportsOption(QImageIOHandler::ScaledSize)
208
 
                        )
209
 
                {
210
 
                        // Do not use mImageSize here: QImageReader needs a non-transposed
211
 
                        // image size
212
 
                        QSize size = reader.size() / mImageDataInvertedZoom;
213
 
                        if (!size.isEmpty()) {
214
 
                                LOG("Setting scaled size to" << size);
215
 
                                reader.setScaledSize(size);
216
 
                        } else {
217
 
                                LOG("Not setting scaled size as it is empty" << size);
218
 
                        }
219
 
                }
220
 
 
221
 
                bool ok = reader.read(&mImage);
222
 
                if (!ok) {
223
 
                        LOG("QImageReader::read() failed");
224
 
                        return;
225
 
                }
226
 
 
227
 
                if (mJpegContent.get()) {
228
 
                        Gwenview::Orientation orientation = mJpegContent->orientation();
229
 
                        QMatrix matrix = ImageUtils::transformMatrix(orientation);
230
 
                        mImage = mImage.transformed(matrix);
231
 
                }
232
 
 
233
 
                if (reader.supportsAnimation()
234
 
                        && reader.nextImageDelay() > 0 // Assume delay == 0 <=> only one frame
235
 
                ) {
236
 
                        /*
237
 
                         * QImageReader is not really helpful to detect animated gif:
238
 
                         * - QImageReader::imageCount() returns 0
239
 
                         * - QImageReader::nextImageDelay() may return something > 0 if the
240
 
                         *   image consists of only one frame but includes a "Graphic
241
 
                         *   Control Extension" (usually only present if we have an
242
 
                         *   animation) (Bug #185523)
243
 
                         *
244
 
                         * Decoding the next frame is the only reliable way I found to
245
 
                         * detect an animated gif
246
 
                         */
247
 
                        LOG("May be an animated image. delay:" << reader.nextImageDelay());
248
 
                        QImage nextImage;
249
 
                        if (reader.read(&nextImage)) {
250
 
                                LOG("Really an animated image (more than one frame)");
251
 
                                mAnimated = true;
252
 
                        } else {
253
 
                                kWarning() << mImpl->document()->url() << "is not really an animated image (only one frame)";
254
 
                        }
255
 
                }
256
 
        }
 
76
    LoadingDocumentImpl* q;
 
77
    QPointer<KIO::TransferJob> mTransferJob;
 
78
    QFuture<bool> mMetaInfoFuture;
 
79
    QFutureWatcher<bool> mMetaInfoFutureWatcher;
 
80
    QFuture<void> mImageDataFuture;
 
81
    QFutureWatcher<void> mImageDataFutureWatcher;
 
82
 
 
83
    // If != 0, this means we need to load an image at zoom =
 
84
    // 1/mImageDataInvertedZoom
 
85
    int mImageDataInvertedZoom;
 
86
 
 
87
    bool mMetaInfoLoaded;
 
88
    bool mAnimated;
 
89
    bool mDownSampledImageLoaded;
 
90
    QByteArray mData;
 
91
    QByteArray mFormat;
 
92
    QSize mImageSize;
 
93
    Exiv2::Image::AutoPtr mExiv2Image;
 
94
    std::auto_ptr<JpegContent> mJpegContent;
 
95
    QImage mImage;
 
96
 
 
97
    /**
 
98
     * Determine kind of document and switch to an implementation if it is not
 
99
     * necessary to download more data.
 
100
     * @return true if switched to another implementation.
 
101
     */
 
102
    bool determineKind()
 
103
    {
 
104
        QString mimeType;
 
105
        const KUrl& url = q->document()->url();
 
106
        if (KProtocolInfo::determineMimetypeFromExtension(url.protocol())) {
 
107
            mimeType = KMimeType::findByNameAndContent(url.fileName(), mData)->name();
 
108
        } else {
 
109
            mimeType = KMimeType::findByContent(mData)->name();
 
110
        }
 
111
        MimeTypeUtils::Kind kind = MimeTypeUtils::mimeTypeKind(mimeType);
 
112
        LOG("mimeType:" << mimeType);
 
113
        LOG("kind:" << kind);
 
114
        q->setDocumentKind(kind);
 
115
 
 
116
        switch (kind) {
 
117
        case MimeTypeUtils::KIND_RASTER_IMAGE:
 
118
        case MimeTypeUtils::KIND_SVG_IMAGE:
 
119
            return false;
 
120
 
 
121
        case MimeTypeUtils::KIND_VIDEO:
 
122
            q->switchToImpl(new VideoDocumentLoadedImpl(q->document()));
 
123
            return true;
 
124
 
 
125
        default:
 
126
            q->setDocumentErrorString(
 
127
                i18nc("@info", "Gwenview cannot display documents of type %1.", mimeType)
 
128
            );
 
129
            emit q->loadingFailed();
 
130
            q->switchToImpl(new EmptyDocumentImpl(q->document()));
 
131
            return true;
 
132
        }
 
133
    }
 
134
 
 
135
    void startLoading()
 
136
    {
 
137
        Q_ASSERT(!mMetaInfoLoaded);
 
138
 
 
139
        switch (q->document()->kind()) {
 
140
        case MimeTypeUtils::KIND_RASTER_IMAGE:
 
141
            mMetaInfoFuture = QtConcurrent::run(this, &LoadingDocumentImplPrivate::loadMetaInfo);
 
142
            mMetaInfoFutureWatcher.setFuture(mMetaInfoFuture);
 
143
            break;
 
144
 
 
145
        case MimeTypeUtils::KIND_SVG_IMAGE:
 
146
            q->switchToImpl(new SvgDocumentLoadedImpl(q->document(), mData));
 
147
            break;
 
148
 
 
149
        case MimeTypeUtils::KIND_VIDEO:
 
150
            break;
 
151
 
 
152
        default:
 
153
            kWarning() << "We should not reach this point!";
 
154
            break;
 
155
        }
 
156
    }
 
157
 
 
158
    void startImageDataLoading()
 
159
    {
 
160
        LOG("");
 
161
        Q_ASSERT(mMetaInfoLoaded);
 
162
        Q_ASSERT(mImageDataInvertedZoom != 0);
 
163
        Q_ASSERT(!mImageDataFuture.isRunning());
 
164
        mImageDataFuture = QtConcurrent::run(this, &LoadingDocumentImplPrivate::loadImageData);
 
165
        mImageDataFutureWatcher.setFuture(mImageDataFuture);
 
166
    }
 
167
 
 
168
    bool loadMetaInfo()
 
169
    {
 
170
        QBuffer buffer;
 
171
        buffer.setBuffer(&mData);
 
172
        buffer.open(QIODevice::ReadOnly);
 
173
        QImageReader reader(&buffer);
 
174
        mFormat = reader.format();
 
175
        if (mFormat.isEmpty()) {
 
176
            return false;
 
177
        }
 
178
 
 
179
        Exiv2ImageLoader loader;
 
180
        if (loader.load(mData)) {
 
181
            mExiv2Image = loader.popImage();
 
182
        }
 
183
 
 
184
        if (mFormat == "jpeg" && mExiv2Image.get()) {
 
185
            mJpegContent.reset(new JpegContent());
 
186
            if (!mJpegContent->loadFromData(mData, mExiv2Image.get())) {
 
187
                return false;
 
188
            }
 
189
 
 
190
            // Use the size from JpegContent, as its correctly transposed if the
 
191
            // image has been rotated
 
192
            mImageSize = mJpegContent->size();
 
193
        } else {
 
194
            mImageSize = reader.size();
 
195
        }
 
196
        LOG("mImageSize" << mImageSize);
 
197
 
 
198
        return true;
 
199
    }
 
200
 
 
201
    void loadImageData()
 
202
    {
 
203
        QBuffer buffer;
 
204
        buffer.setBuffer(&mData);
 
205
        buffer.open(QIODevice::ReadOnly);
 
206
        QImageReader reader(&buffer);
 
207
 
 
208
        LOG("mImageDataInvertedZoom=" << mImageDataInvertedZoom);
 
209
        if (mImageSize.isValid()
 
210
                && mImageDataInvertedZoom != 1
 
211
                && reader.supportsOption(QImageIOHandler::ScaledSize)
 
212
           ) {
 
213
            // Do not use mImageSize here: QImageReader needs a non-transposed
 
214
            // image size
 
215
            QSize size = reader.size() / mImageDataInvertedZoom;
 
216
            if (!size.isEmpty()) {
 
217
                LOG("Setting scaled size to" << size);
 
218
                reader.setScaledSize(size);
 
219
            } else {
 
220
                LOG("Not setting scaled size as it is empty" << size);
 
221
            }
 
222
        }
 
223
 
 
224
        bool ok = reader.read(&mImage);
 
225
        if (!ok) {
 
226
            LOG("QImageReader::read() failed");
 
227
            return;
 
228
        }
 
229
 
 
230
        if (mJpegContent.get()) {
 
231
            Gwenview::Orientation orientation = mJpegContent->orientation();
 
232
            QMatrix matrix = ImageUtils::transformMatrix(orientation);
 
233
            mImage = mImage.transformed(matrix);
 
234
        }
 
235
 
 
236
        if (reader.supportsAnimation()
 
237
                && reader.nextImageDelay() > 0 // Assume delay == 0 <=> only one frame
 
238
           ) {
 
239
            /*
 
240
             * QImageReader is not really helpful to detect animated gif:
 
241
             * - QImageReader::imageCount() returns 0
 
242
             * - QImageReader::nextImageDelay() may return something > 0 if the
 
243
             *   image consists of only one frame but includes a "Graphic
 
244
             *   Control Extension" (usually only present if we have an
 
245
             *   animation) (Bug #185523)
 
246
             *
 
247
             * Decoding the next frame is the only reliable way I found to
 
248
             * detect an animated gif
 
249
             */
 
250
            LOG("May be an animated image. delay:" << reader.nextImageDelay());
 
251
            QImage nextImage;
 
252
            if (reader.read(&nextImage)) {
 
253
                LOG("Really an animated image (more than one frame)");
 
254
                mAnimated = true;
 
255
            } else {
 
256
                kWarning() << q->document()->url() << "is not really an animated image (only one frame)";
 
257
            }
 
258
        }
 
259
    }
257
260
};
258
261
 
259
 
 
260
262
LoadingDocumentImpl::LoadingDocumentImpl(Document* document)
261
263
: AbstractDocumentImpl(document)
262
 
, d(new LoadingDocumentImplPrivate) {
263
 
        d->mImpl = this;
264
 
        d->mMetaInfoLoaded = false;
265
 
        d->mAnimated = false;
266
 
        d->mDownSampledImageLoaded = false;
267
 
        d->mImageDataInvertedZoom = 0;
268
 
 
269
 
        connect(&d->mMetaInfoFutureWatcher, SIGNAL(finished()),
270
 
                SLOT(slotMetaInfoLoaded()) );
271
 
 
272
 
        connect(&d->mImageDataFutureWatcher, SIGNAL(finished()),
273
 
                SLOT(slotImageLoaded()) );
274
 
}
275
 
 
276
 
 
277
 
LoadingDocumentImpl::~LoadingDocumentImpl() {
278
 
        LOG("");
279
 
        // Disconnect watchers to make sure they do not trigger further work
280
 
        d->mMetaInfoFutureWatcher.disconnect();
281
 
        d->mImageDataFutureWatcher.disconnect();
282
 
 
283
 
        d->mMetaInfoFutureWatcher.waitForFinished();
284
 
        d->mImageDataFutureWatcher.waitForFinished();
285
 
 
286
 
        if (d->mTransferJob) {
287
 
                d->mTransferJob->kill();
288
 
        }
289
 
        delete d;
290
 
}
291
 
 
292
 
void LoadingDocumentImpl::init() {
293
 
        KUrl url = document()->url();
294
 
 
295
 
        if (UrlUtils::urlIsFastLocalFile(url)) {
296
 
                // Load file content directly
297
 
                QFile file(url.toLocalFile());
298
 
                if (!file.open(QIODevice::ReadOnly)) {
299
 
                        setDocumentErrorString(i18nc("@info", "Could not open file %1", url.toLocalFile()));
300
 
                        emit loadingFailed();
301
 
                        switchToImpl(new EmptyDocumentImpl(document()));
302
 
                        return;
303
 
                }
304
 
                d->mData = file.read(HEADER_SIZE);
305
 
                if (d->determineKind()) {
306
 
                        return;
307
 
                }
308
 
                d->mData += file.readAll();
309
 
                d->startLoading();
310
 
        } else {
311
 
                // Transfer file via KIO
312
 
                d->mTransferJob = KIO::get(document()->url());
313
 
                connect(d->mTransferJob, SIGNAL(data(KIO::Job*, const QByteArray&)),
314
 
                        SLOT(slotDataReceived(KIO::Job*, const QByteArray&)) );
315
 
                connect(d->mTransferJob, SIGNAL(result(KJob*)),
316
 
                        SLOT(slotTransferFinished(KJob*)) );
317
 
                d->mTransferJob->start();
318
 
        }
319
 
}
320
 
 
321
 
 
322
 
void LoadingDocumentImpl::loadImage(int invertedZoom) {
323
 
        if (d->mImageDataInvertedZoom == invertedZoom) {
324
 
                LOG("Already loading an image at invertedZoom=" << invertedZoom);
325
 
                return;
326
 
        }
327
 
        if (d->mImageDataInvertedZoom == 1) {
328
 
                LOG("Ignoring request: we are loading a full image");
329
 
                return;
330
 
        }
331
 
        d->mImageDataFutureWatcher.waitForFinished();
332
 
        d->mImageDataInvertedZoom = invertedZoom;
333
 
 
334
 
        if (d->mMetaInfoLoaded) {
335
 
                // Do not test on mMetaInfoFuture.isRunning() here: it might not have
336
 
                // started if we are downloading the image from a remote url
337
 
                d->startImageDataLoading();
338
 
        }
339
 
}
340
 
 
341
 
 
342
 
void LoadingDocumentImpl::slotDataReceived(KIO::Job* job, const QByteArray& chunk) {
343
 
        d->mData.append(chunk);
344
 
        if (document()->kind() == MimeTypeUtils::KIND_UNKNOWN && d->mData.length() >= HEADER_SIZE) {
345
 
                if (d->determineKind()) {
346
 
                        job->kill();
347
 
                        return;
348
 
                }
349
 
        }
350
 
}
351
 
 
352
 
 
353
 
void LoadingDocumentImpl::slotTransferFinished(KJob* job) {
354
 
        if (job->error()) {
355
 
                setDocumentErrorString(job->errorString());
356
 
                emit loadingFailed();
357
 
                switchToImpl(new EmptyDocumentImpl(document()));
358
 
                return;
359
 
        }
360
 
        d->startLoading();
361
 
}
362
 
 
363
 
 
364
 
bool LoadingDocumentImpl::isEditable() const {
365
 
        return d->mDownSampledImageLoaded;
366
 
}
367
 
 
368
 
 
369
 
Document::LoadingState LoadingDocumentImpl::loadingState() const {
370
 
        if (!document()->image().isNull()) {
371
 
                return Document::Loaded;
372
 
        } else if (d->mMetaInfoLoaded) {
373
 
                return Document::MetaInfoLoaded;
374
 
        } else if (document()->kind() != MimeTypeUtils::KIND_UNKNOWN) {
375
 
                return Document::KindDetermined;
376
 
        } else {
377
 
                return Document::Loading;
378
 
        }
379
 
}
380
 
 
381
 
 
382
 
void LoadingDocumentImpl::slotMetaInfoLoaded() {
383
 
        LOG("");
384
 
        Q_ASSERT(!d->mMetaInfoFuture.isRunning());
385
 
        if (!d->mMetaInfoFuture.result()) {
386
 
                setDocumentErrorString(
387
 
                        i18nc("@info", "Loading meta information failed.")
388
 
                        );
389
 
                emit loadingFailed();
390
 
                switchToImpl(new EmptyDocumentImpl(document()));
391
 
                return;
392
 
        }
393
 
 
394
 
        setDocumentFormat(d->mFormat);
395
 
        setDocumentImageSize(d->mImageSize);
396
 
        setDocumentExiv2Image(d->mExiv2Image);
397
 
 
398
 
        d->mMetaInfoLoaded = true;
399
 
        emit metaInfoLoaded();
400
 
 
401
 
        // Start image loading if necessary
402
 
        // We test if mImageDataFuture is not already running because code connected to
403
 
        // metaInfoLoaded() signal could have called loadImage()
404
 
        if (!d->mImageDataFuture.isRunning() && d->mImageDataInvertedZoom != 0) {
405
 
                d->startImageDataLoading();
406
 
        }
407
 
}
408
 
 
409
 
 
410
 
void LoadingDocumentImpl::slotImageLoaded() {
411
 
        LOG("");
412
 
        if (d->mImage.isNull()) {
413
 
                setDocumentErrorString(
414
 
                        i18nc("@info", "Loading image failed.")
415
 
                        );
416
 
                emit loadingFailed();
417
 
                switchToImpl(new EmptyDocumentImpl(document()));
418
 
                return;
419
 
        }
420
 
 
421
 
        if (d->mAnimated) {
422
 
                if (d->mImage.size() == d->mImageSize) {
423
 
                        // We already decoded the first frame at the right size, let's show
424
 
                        // it
425
 
                        setDocumentImage(d->mImage);
426
 
                }
427
 
 
428
 
                switchToImpl(new AnimatedDocumentLoadedImpl(
429
 
                        document(),
430
 
                        d->mData));
431
 
 
432
 
                return;
433
 
        }
434
 
 
435
 
        if (d->mImageDataInvertedZoom != 1 && d->mImage.size() != d->mImageSize) {
436
 
                LOG("Loaded a down sampled image");
437
 
                d->mDownSampledImageLoaded = true;
438
 
                // We loaded a down sampled image
439
 
                setDocumentDownSampledImage(d->mImage, d->mImageDataInvertedZoom);
440
 
                return;
441
 
        }
442
 
 
443
 
        LOG("Loaded a full image");
444
 
        setDocumentImage(d->mImage);
445
 
        DocumentLoadedImpl* impl;
446
 
        if (d->mJpegContent.get()) {
447
 
                impl = new JpegDocumentLoadedImpl(
448
 
                        document(),
449
 
                        d->mJpegContent.release());
450
 
        } else {
451
 
                impl = new DocumentLoadedImpl(
452
 
                        document(),
453
 
                        d->mData);
454
 
        }
455
 
        switchToImpl(impl);
456
 
}
457
 
 
 
264
, d(new LoadingDocumentImplPrivate)
 
265
{
 
266
    d->q = this;
 
267
    d->mMetaInfoLoaded = false;
 
268
    d->mAnimated = false;
 
269
    d->mDownSampledImageLoaded = false;
 
270
    d->mImageDataInvertedZoom = 0;
 
271
 
 
272
    connect(&d->mMetaInfoFutureWatcher, SIGNAL(finished()),
 
273
            SLOT(slotMetaInfoLoaded()));
 
274
 
 
275
    connect(&d->mImageDataFutureWatcher, SIGNAL(finished()),
 
276
            SLOT(slotImageLoaded()));
 
277
}
 
278
 
 
279
LoadingDocumentImpl::~LoadingDocumentImpl()
 
280
{
 
281
    LOG("");
 
282
    // Disconnect watchers to make sure they do not trigger further work
 
283
    d->mMetaInfoFutureWatcher.disconnect();
 
284
    d->mImageDataFutureWatcher.disconnect();
 
285
 
 
286
    d->mMetaInfoFutureWatcher.waitForFinished();
 
287
    d->mImageDataFutureWatcher.waitForFinished();
 
288
 
 
289
    if (d->mTransferJob) {
 
290
        d->mTransferJob->kill();
 
291
    }
 
292
    delete d;
 
293
}
 
294
 
 
295
void LoadingDocumentImpl::init()
 
296
{
 
297
    KUrl url = document()->url();
 
298
 
 
299
    if (UrlUtils::urlIsFastLocalFile(url)) {
 
300
        // Load file content directly
 
301
        QFile file(url.toLocalFile());
 
302
        if (!file.open(QIODevice::ReadOnly)) {
 
303
            setDocumentErrorString(i18nc("@info", "Could not open file %1", url.toLocalFile()));
 
304
            emit loadingFailed();
 
305
            switchToImpl(new EmptyDocumentImpl(document()));
 
306
            return;
 
307
        }
 
308
        d->mData = file.read(HEADER_SIZE);
 
309
        if (d->determineKind()) {
 
310
            return;
 
311
        }
 
312
        d->mData += file.readAll();
 
313
        d->startLoading();
 
314
    } else {
 
315
        // Transfer file via KIO
 
316
        d->mTransferJob = KIO::get(document()->url());
 
317
        connect(d->mTransferJob, SIGNAL(data(KIO::Job*, QByteArray)),
 
318
                SLOT(slotDataReceived(KIO::Job*, QByteArray)));
 
319
        connect(d->mTransferJob, SIGNAL(result(KJob*)),
 
320
                SLOT(slotTransferFinished(KJob*)));
 
321
        d->mTransferJob->start();
 
322
    }
 
323
}
 
324
 
 
325
void LoadingDocumentImpl::loadImage(int invertedZoom)
 
326
{
 
327
    if (d->mImageDataInvertedZoom == invertedZoom) {
 
328
        LOG("Already loading an image at invertedZoom=" << invertedZoom);
 
329
        return;
 
330
    }
 
331
    if (d->mImageDataInvertedZoom == 1) {
 
332
        LOG("Ignoring request: we are loading a full image");
 
333
        return;
 
334
    }
 
335
    d->mImageDataFutureWatcher.waitForFinished();
 
336
    d->mImageDataInvertedZoom = invertedZoom;
 
337
 
 
338
    if (d->mMetaInfoLoaded) {
 
339
        // Do not test on mMetaInfoFuture.isRunning() here: it might not have
 
340
        // started if we are downloading the image from a remote url
 
341
        d->startImageDataLoading();
 
342
    }
 
343
}
 
344
 
 
345
void LoadingDocumentImpl::slotDataReceived(KIO::Job* job, const QByteArray& chunk)
 
346
{
 
347
    d->mData.append(chunk);
 
348
    if (document()->kind() == MimeTypeUtils::KIND_UNKNOWN && d->mData.length() >= HEADER_SIZE) {
 
349
        if (d->determineKind()) {
 
350
            job->kill();
 
351
            return;
 
352
        }
 
353
    }
 
354
}
 
355
 
 
356
void LoadingDocumentImpl::slotTransferFinished(KJob* job)
 
357
{
 
358
    if (job->error()) {
 
359
        setDocumentErrorString(job->errorString());
 
360
        emit loadingFailed();
 
361
        switchToImpl(new EmptyDocumentImpl(document()));
 
362
        return;
 
363
    }
 
364
    d->startLoading();
 
365
}
 
366
 
 
367
bool LoadingDocumentImpl::isEditable() const
 
368
{
 
369
    return d->mDownSampledImageLoaded;
 
370
}
 
371
 
 
372
Document::LoadingState LoadingDocumentImpl::loadingState() const
 
373
{
 
374
    if (!document()->image().isNull()) {
 
375
        return Document::Loaded;
 
376
    } else if (d->mMetaInfoLoaded) {
 
377
        return Document::MetaInfoLoaded;
 
378
    } else if (document()->kind() != MimeTypeUtils::KIND_UNKNOWN) {
 
379
        return Document::KindDetermined;
 
380
    } else {
 
381
        return Document::Loading;
 
382
    }
 
383
}
 
384
 
 
385
void LoadingDocumentImpl::slotMetaInfoLoaded()
 
386
{
 
387
    LOG("");
 
388
    Q_ASSERT(!d->mMetaInfoFuture.isRunning());
 
389
    if (!d->mMetaInfoFuture.result()) {
 
390
        setDocumentErrorString(
 
391
            i18nc("@info", "Loading meta information failed.")
 
392
        );
 
393
        emit loadingFailed();
 
394
        switchToImpl(new EmptyDocumentImpl(document()));
 
395
        return;
 
396
    }
 
397
 
 
398
    setDocumentFormat(d->mFormat);
 
399
    setDocumentImageSize(d->mImageSize);
 
400
    setDocumentExiv2Image(d->mExiv2Image);
 
401
 
 
402
    d->mMetaInfoLoaded = true;
 
403
    emit metaInfoLoaded();
 
404
 
 
405
    // Start image loading if necessary
 
406
    // We test if mImageDataFuture is not already running because code connected to
 
407
    // metaInfoLoaded() signal could have called loadImage()
 
408
    if (!d->mImageDataFuture.isRunning() && d->mImageDataInvertedZoom != 0) {
 
409
        d->startImageDataLoading();
 
410
    }
 
411
}
 
412
 
 
413
void LoadingDocumentImpl::slotImageLoaded()
 
414
{
 
415
    LOG("");
 
416
    if (d->mImage.isNull()) {
 
417
        setDocumentErrorString(
 
418
            i18nc("@info", "Loading image failed.")
 
419
        );
 
420
        emit loadingFailed();
 
421
        switchToImpl(new EmptyDocumentImpl(document()));
 
422
        return;
 
423
    }
 
424
 
 
425
    if (d->mAnimated) {
 
426
        if (d->mImage.size() == d->mImageSize) {
 
427
            // We already decoded the first frame at the right size, let's show
 
428
            // it
 
429
            setDocumentImage(d->mImage);
 
430
        }
 
431
 
 
432
        switchToImpl(new AnimatedDocumentLoadedImpl(
 
433
                         document(),
 
434
                         d->mData));
 
435
 
 
436
        return;
 
437
    }
 
438
 
 
439
    if (d->mImageDataInvertedZoom != 1 && d->mImage.size() != d->mImageSize) {
 
440
        LOG("Loaded a down sampled image");
 
441
        d->mDownSampledImageLoaded = true;
 
442
        // We loaded a down sampled image
 
443
        setDocumentDownSampledImage(d->mImage, d->mImageDataInvertedZoom);
 
444
        return;
 
445
    }
 
446
 
 
447
    LOG("Loaded a full image");
 
448
    setDocumentImage(d->mImage);
 
449
    DocumentLoadedImpl* impl;
 
450
    if (d->mJpegContent.get()) {
 
451
        impl = new JpegDocumentLoadedImpl(
 
452
            document(),
 
453
            d->mJpegContent.release());
 
454
    } else {
 
455
        impl = new DocumentLoadedImpl(
 
456
            document(),
 
457
            d->mData);
 
458
    }
 
459
    switchToImpl(impl);
 
460
}
458
461
 
459
462
} // namespace