summaryrefslogtreecommitdiffstats
path: root/src/gvcore/thumbnailloadjob.cpp
blob: 6d1f60961557ddc31f4dbb38c15256d17a2a72de (plain)
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
// vim: set tabstop=4 shiftwidth=4 noexpandtab:
/*	Gwenview - A simple image viewer for TDE
	Copyright 2000-2004 Aur�lien G�teau
	This class is based on the ImagePreviewJob class from Konqueror.
	Original copyright follows.
*/
/*	This file is part of the KDE project
	Copyright (C) 2000 David Faure <faure@kde.org>
				  2000 Carsten Pfeiffer <pfeiffer@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.

	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, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
#include "thumbnailloadjob.moc"

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <assert.h>

// TQt
#include <tqdir.h>
#include <tqfile.h>
#include <tqimage.h>
#include <tqpixmap.h>
#include <tqtimer.h>

// KDE 
#include <tdeapplication.h>
#include <kdebug.h>
#include <tdefileitem.h>
#include <kiconloader.h>
#include <tdeio/previewjob.h>
#include <klargefile.h>
#include <kmdcodec.h>
#include <kstandarddirs.h>
#include <tdetempfile.h>

// libjpeg 
#include <setjmp.h>
#define XMD_H
extern "C" {
#include <jpeglib.h>
}

// Local
#include "cache.h"
#include "mimetypeutils.h"
#include "miscconfig.h"
#include "imageutils/jpegcontent.h"
#include "imageutils/imageutils.h"
#include "thumbnailsize.h"
#include "fileviewconfig.h"
namespace Gwenview {

#undef ENABLE_LOG
#undef LOG
//#define ENABLE_LOG
#ifdef ENABLE_LOG
#define LOG(x) kdDebug() << k_funcinfo << x << endl
#else
#define LOG(x) ;
#endif


static TQString generateOriginalURI(KURL url) {
	// Don't include the password if any
	url.setPass(TQString());
	return url.url();
}


static TQString generateThumbnailPath(const TQString& uri, int size) {
	KMD5 md5( TQFile::encodeName(uri).data() );
	TQString baseDir=ThumbnailLoadJob::thumbnailBaseDir(size);
	return baseDir + TQString(TQFile::encodeName( md5.hexDigest())) + ".png";
}

//------------------------------------------------------------------------
//
// ThumbnailThread
//
//------------------------------------------------------------------------
void ThumbnailThread::load(
	const TQString& originalURI, time_t originalTime, int originalSize, const TQString& originalMimeType,
	const TQString& pixPath,
	const TQString& thumbnailPath,
	int size, bool storeThumbnail)
{
	TQMutexLocker lock( &mMutex );
	assert( mPixPath.isNull());

	mOriginalURI = TSDeepCopy(originalURI);
	mOriginalTime = originalTime;
	mOriginalSize = originalSize;
	mOriginalMimeType = TSDeepCopy(originalMimeType);
	mPixPath = TSDeepCopy(pixPath);
	mThumbnailPath = TSDeepCopy(thumbnailPath);
	mThumbnailSize = size;
	mStoreThumbnailsInCache = storeThumbnail;
	if(!running()) start();
	mCond.wakeOne();
}

void ThumbnailThread::run() {
	TQMutexLocker lock( &mMutex );
	while( !testCancel()) {
		// empty mPixPath means nothing to do
		while( mPixPath.isNull()) {
			mCond.cancellableWait( &mMutex );
			if( testCancel()) return;
		}
		loadThumbnail();
		mPixPath = TQString(); // done, ready for next
		TQSize size(mOriginalWidth, mOriginalHeight);
		emitCancellableSignal( this, TQT_SIGNAL( done( const TQImage&, const TQSize&)), mImage, size);
	}
}

void ThumbnailThread::loadThumbnail() {
	mImage = TQImage();
	bool loaded=false;
	bool needCaching=true;
	
	// If it's a JPEG, try to load a small image directly from the file
	if (isJPEG()) {
		ImageUtils::JPEGContent content;
		content.load(mPixPath);
		mOriginalWidth = content.size().width();
		mOriginalHeight = content.size().height();
		mImage = content.thumbnail();
	
		if( !mImage.isNull()
			&& ( mImage.width() >= mThumbnailSize // don't use small thumbnails
			|| mImage.height() >= mThumbnailSize )) {
			loaded = true;
			needCaching = false;
		}
		if(!loaded) {
			loaded=loadJPEG();
		}
		if (loaded && MiscConfig::autoRotateImages()) {
			// Rotate if necessary
			ImageUtils::Orientation orientation = content.orientation();
			mImage=ImageUtils::transform(mImage,orientation);
		}
	}
	// File is not a JPEG, or JPEG optimized load failed, load file using TQt
	if (!loaded) {
		TQImage originalImage;
		if (originalImage.load(mPixPath)) {
			mOriginalWidth=originalImage.width();
			mOriginalHeight=originalImage.height();
			int thumbSize=mThumbnailSize<=ThumbnailSize::NORMAL ? ThumbnailSize::NORMAL : ThumbnailSize::LARGE;

			if( testCancel()) return;

			if (TQMAX(mOriginalWidth, mOriginalHeight)<=thumbSize ) {
				mImage=originalImage;
				needCaching = false;
			} else {
				mImage=ImageUtils::scale(originalImage,thumbSize,thumbSize,ImageUtils::SMOOTH_FAST,TQ_ScaleMin);
			}
			loaded = true;
		}
	}

	if( testCancel()) return;

	if( mStoreThumbnailsInCache && needCaching ) {
		mImage.setText("Thumb::URI", 0, mOriginalURI);
		mImage.setText("Thumb::MTime", 0, TQString::number(mOriginalTime));
		mImage.setText("Thumb::Size", 0, TQString::number(mOriginalSize));
		mImage.setText("Thumb::Mimetype", 0, mOriginalMimeType);
		mImage.setText("Thumb::Image::Width", 0, TQString::number(mOriginalWidth));
		mImage.setText("Thumb::Image::Height", 0, TQString::number(mOriginalHeight));
		mImage.setText("Software", 0, "Gwenview");

		TQString thumbnailDir = ThumbnailLoadJob::thumbnailBaseDir(mThumbnailSize);
		TDEStandardDirs::makeDir(thumbnailDir, 0700);

		KTempFile tmp(thumbnailDir + "/gwenview", ".png");
		tmp.setAutoDelete(true);
		if (tmp.status()!=0) {
			TQString reason( strerror(tmp.status()) );
			kdWarning() << "Could not create a temporary file.\nReason: " << reason << endl;
			return;
		}

		if (!mImage.save(tmp.name(), "PNG")) {
			kdWarning() << "Could not save thumbnail for file " << mOriginalURI << endl;
			return;
		}
		
		rename(TQFile::encodeName(tmp.name()), TQFile::encodeName(mThumbnailPath));
	}
}


bool ThumbnailThread::isJPEG() {
	TQString format=TQImageIO::imageFormat(mPixPath);
	return format=="JPEG";
}



struct JPEGFatalError : public jpeg_error_mgr {
	jmp_buf mJmpBuffer;

	static void handler(j_common_ptr cinfo) {
		JPEGFatalError* error=static_cast<JPEGFatalError*>(cinfo->err);
		(error->output_message)(cinfo);
		longjmp(error->mJmpBuffer,1);
	}
};

bool ThumbnailThread::loadJPEG() {
	struct jpeg_decompress_struct cinfo;

	// Open file
	FILE* inputFile=fopen(TQFile::encodeName( mPixPath ).data(), "rb");
	if(!inputFile) return false;
	
	// Error handling
	struct JPEGFatalError jerr;
	cinfo.err = jpeg_std_error(&jerr);
	cinfo.err->error_exit = JPEGFatalError::handler;
	if (setjmp(jerr.mJmpBuffer)) {
		jpeg_destroy_decompress(&cinfo);
		fclose(inputFile);
		return false;
	}

	// Init decompression
	jpeg_create_decompress(&cinfo);
	jpeg_stdio_src(&cinfo, inputFile);
	jpeg_read_header(&cinfo, TRUE);

	// Get image size and check if we need a thumbnail
	int size= mThumbnailSize <= ThumbnailSize::NORMAL ? ThumbnailSize::NORMAL : ThumbnailSize::LARGE;
	int imgSize = TQMAX(cinfo.image_width, cinfo.image_height);

	if (imgSize<=size) {
		fclose(inputFile);
		return mImage.load(mPixPath);
	}	

	// Compute scale value
	int scale=1;
	while(size*scale*2<=imgSize) {
		scale*=2;
	}
	if(scale>8) scale=8;

	cinfo.scale_num=1;
	cinfo.scale_denom=scale;

	// Create TQImage
	jpeg_start_decompress(&cinfo);

	switch(cinfo.output_components) {
	case 3:
	case 4:
		mImage.create( cinfo.output_width, cinfo.output_height, 32 );
		break;
	case 1: // B&W image
		mImage.create( cinfo.output_width, cinfo.output_height, 8, 256 );
		for (int i=0; i<256; i++)
			mImage.setColor(i, tqRgb(i,i,i));
		break;
	default:
		jpeg_destroy_decompress(&cinfo);
		fclose(inputFile);
		return false;
	}

	uchar** lines = mImage.jumpTable();
	while (cinfo.output_scanline < cinfo.output_height) {
		jpeg_read_scanlines(&cinfo, lines + cinfo.output_scanline, cinfo.output_height);
	}
	jpeg_finish_decompress(&cinfo);

// Expand 24->32 bpp
	if ( cinfo.output_components == 3 ) {
		for (uint j=0; j<cinfo.output_height; j++) {
			uchar *in = mImage.scanLine(j) + cinfo.output_width*3;
			TQRgb *out = (TQRgb*)( mImage.scanLine(j) );

			for (uint i=cinfo.output_width; i--; ) {
				in-=3;
				out[i] = tqRgb(in[0], in[1], in[2]);
			}
		}
	}

	int newMax = TQMAX(cinfo.output_width, cinfo.output_height);
	int newx = size*cinfo.output_width / newMax;
	int newy = size*cinfo.output_height / newMax;

	mImage=ImageUtils::scale(mImage,newx, newy,ImageUtils::SMOOTH_FAST);

	jpeg_destroy_decompress(&cinfo);
	fclose(inputFile);

	return true;
}


//------------------------------------------------------------------------
//
// ThumbnailLoadJob static methods
//
//------------------------------------------------------------------------
TQString ThumbnailLoadJob::thumbnailBaseDir() {
	static TQString dir;
	if (!dir.isEmpty()) return dir;
	dir=TQDir::homeDirPath() + "/.thumbnails/";
	return dir;
}


TQString ThumbnailLoadJob::thumbnailBaseDir(int size) {
	TQString dir = thumbnailBaseDir();
	if (size<=ThumbnailSize::NORMAL) {
		dir+="normal/";
	} else {
		dir+="large/";
	}
	return dir;
}


void ThumbnailLoadJob::deleteImageThumbnail(const KURL& url) {
	TQString uri=generateOriginalURI(url);
	TQFile::remove(generateThumbnailPath(uri, ThumbnailSize::NORMAL));
	TQFile::remove(generateThumbnailPath(uri, ThumbnailSize::LARGE));
}


//------------------------------------------------------------------------
//
// ThumbnailLoadJob implementation
//
//------------------------------------------------------------------------


/*

 This class tries to first generate the most important thumbnails, i.e.
 first the currently selected one, then the ones that are visible, and then
 the rest, the closer the the currently selected one the sooner

 mAllItems contains all thumbnails
 mItems contains pending thumbnails, in the priority order
 mCurrentItem is currently processed thumbnail, already removed from mItems
 mProcessedState needs to match mAllItems, and contains information about every
   thumbnail whether it has been already processed

 thumbnailIndex() returns index of a thumbnail in mAllItems, or -1
 updateItemsOrder() builds mItems from mAllItems
*/

ThumbnailLoadJob::ThumbnailLoadJob(const TQValueVector<const KFileItem*>* items, int size)
: TDEIO::Job(false), mState( STATE_NEXTTHUMB ),
  mCurrentVisibleIndex( -1 ), mFirstVisibleIndex( -1 ), mLastVisibleIndex( -1 ),
  mThumbnailSize(size), mSuspended( false )
{
	LOG("");
	
	mBrokenPixmap=TDEGlobal::iconLoader()->loadIcon("file_broken", 
		TDEIcon::NoGroup, ThumbnailSize::MIN);

	// Look for images and store the items in our todo list
	Q_ASSERT(!items->empty());
	mAllItems=*items;
	mProcessedState.resize( mAllItems.count());
	tqFill( mProcessedState.begin(), mProcessedState.end(), false );
	mCurrentItem = NULL;

	connect(&mThumbnailThread, TQT_SIGNAL(done(const TQImage&, const TQSize&)),
		TQT_SLOT(thumbnailReady(const TQImage&, const TQSize&)) );
	Cache::instance()->updateAge(); // see addThumbnail in Cache
}


ThumbnailLoadJob::~ThumbnailLoadJob() {
	LOG("");
	mThumbnailThread.cancel();
	mThumbnailThread.wait();
}


void ThumbnailLoadJob::start() {
	// build mItems from mAllItems if not done yet
	if (mLastVisibleIndex == -1 ) {
		setPriorityItems( NULL, NULL, NULL );
	}
	if (mItems.isEmpty()) {
		LOG("Nothing to do");
		emit result(this);
		delete this;
		return;
	}

	determineNextIcon();
}

void ThumbnailLoadJob::suspend() {
	mSuspended = true;
}

void ThumbnailLoadJob::resume() {
	if( !mSuspended ) return;
	mSuspended = false;
	if( mState == STATE_NEXTTHUMB ) // don't load next while already loading
		determineNextIcon();
}

//-Internal--------------------------------------------------------------
void ThumbnailLoadJob::appendItem(const KFileItem* item) {
	int index = thumbnailIndex( item );
	if( index >= 0 ) {
		mProcessedState[ index ] = false;
		return;
	}
	mAllItems.append(item);
	mProcessedState.append( false );
	updateItemsOrder();
}


void ThumbnailLoadJob::itemRemoved(const KFileItem* item) {
	Q_ASSERT(item);

	// If we are removing the next item, update to be the item after or the
	// first if we removed the last item
	mItems.remove( item );
	int index = thumbnailIndex( item );
	if( index >= 0 ) {
		mAllItems.erase( mAllItems.begin() + index );
		mProcessedState.erase( mProcessedState.begin() + index );
	}

	if (item == mCurrentItem) {
		// Abort
		mCurrentItem = NULL;
		if (subjobs.first()) {
			subjobs.first()->kill();
			subjobs.removeFirst();
		}
		determineNextIcon();
	}
}


void ThumbnailLoadJob::setPriorityItems(const KFileItem* current, const KFileItem* first, const KFileItem* last) {
	if( mAllItems.isEmpty()) {
		mCurrentVisibleIndex = mFirstVisibleIndex = mLastVisibleIndex = 0;
		return;
	}
	mFirstVisibleIndex = -1;
	mLastVisibleIndex = - 1;
	mCurrentVisibleIndex = -1;
	if( first != NULL ) mFirstVisibleIndex = thumbnailIndex( first );
	if( last != NULL ) mLastVisibleIndex = thumbnailIndex( last );
	if( current != NULL ) mCurrentVisibleIndex = thumbnailIndex( current );
	if( mFirstVisibleIndex == -1 ) mFirstVisibleIndex = 0;
	if( mLastVisibleIndex == -1 ) mLastVisibleIndex = mAllItems.count() - 1;
	if( mCurrentVisibleIndex == -1 ) mCurrentVisibleIndex = mFirstVisibleIndex;
	updateItemsOrder();
}

void ThumbnailLoadJob::updateItemsOrder() {
	mItems.clear();
	int forward = mCurrentVisibleIndex + 1;
	int backward = mCurrentVisibleIndex;
	int first = mFirstVisibleIndex;
	int last = mLastVisibleIndex;
	updateItemsOrderHelper( forward, backward, first, last );
	if( first != 0 || last != int( mAllItems.count()) - 1 ) {
		// add non-visible items
		updateItemsOrderHelper( last + 1, first - 1, 0, mAllItems.count() - 1);
	}
}

void ThumbnailLoadJob::updateItemsOrderHelper( int forward, int backward, int first, int last ) {
	// start from the current item, add one following it, and one preceding it, for all visible items
	while( forward <= last || backward >= first ) {
		// start with backward - that's the curent item for the first time
		while( backward >= first ) {
			if( !mProcessedState[ backward ] ) {
				mItems.append( mAllItems[ backward ] );
				--backward;
				break;
			}
			--backward;
		}
		while( forward <= last ) {
			if( !mProcessedState[ forward ] ) {
				mItems.append( mAllItems[ forward ] );
				++forward;
				break;
			}
			++forward;
		}
	}
}

void ThumbnailLoadJob::determineNextIcon() {
	mState = STATE_NEXTTHUMB;
	if( mSuspended ) {
		return;
	}

	// No more items ?
	if (mItems.isEmpty()) {
		// Done
		LOG("emitting result");
		emit result(this);
		delete this;
		return;
	}

	mCurrentItem=mItems.first();
	mItems.pop_front();
	Q_ASSERT( !mProcessedState[ thumbnailIndex( mCurrentItem )] );
	mProcessedState[ thumbnailIndex( mCurrentItem )] = true;

	// First, stat the orig file
	mState = STATE_STATORIG;
	mOriginalTime = 0;
	mCurrentURL = mCurrentItem->url();
	mCurrentURL.cleanPath();

	// Do direct stat instead of using KIO if the file is local (faster)
	if( mCurrentURL.isLocalFile()
		&& !TDEIO::probably_slow_mounted( mCurrentURL.path())) {
		KDE_struct_stat buff;
		if ( KDE_stat( TQFile::encodeName(mCurrentURL.path()), &buff ) == 0 )  {
			mOriginalTime = buff.st_mtime;
			TQTimer::singleShot( 0, this, TQT_SLOT( checkThumbnail()));
		}
	}
	if( mOriginalTime == 0 ) { // KIO must be used
		TDEIO::Job* job = TDEIO::stat(mCurrentURL,false);
		job->setWindow(TDEApplication::kApplication()->mainWidget());
		LOG( "TDEIO::stat orig " << mCurrentURL.url() );
		addSubjob(job);
	}
}


void ThumbnailLoadJob::slotResult(TDEIO::Job * job) {
	LOG(mState);
	subjobs.remove(job);
	Q_ASSERT(subjobs.isEmpty());	// We should have only one job at a time ...

	switch (mState) {
	case STATE_NEXTTHUMB:
		Q_ASSERT(false);
		determineNextIcon();
		return;

	case STATE_STATORIG: {
		// Could not stat original, drop this one and move on to the next one
		if (job->error()) {
			emitThumbnailLoadingFailed();
			determineNextIcon();
			return;
		}

		// Get modification time of the original file
		TDEIO::UDSEntry entry = static_cast<TDEIO::StatJob*>(job)->statResult();
		TDEIO::UDSEntry::ConstIterator it= entry.begin();
		mOriginalTime = 0;
		for (; it!=entry.end(); ++it) {
			if ((*it).m_uds == TDEIO::UDS_MODIFICATION_TIME) {
				mOriginalTime = (time_t)((*it).m_long);
				break;
			}
		}
		checkThumbnail();
		return;
	}

	case STATE_DOWNLOADORIG: 
		if (job->error()) {
			emitThumbnailLoadingFailed();
			LOG("Delete temp file " << mTempPath);
			TQFile::remove(mTempPath);
			mTempPath = TQString();
			determineNextIcon();
		} else {
			startCreatingThumbnail(mTempPath);
		}
		return;
	
	case STATE_PREVIEWJOB:
		determineNextIcon();
		return;
	}
}


void ThumbnailLoadJob::thumbnailReady( const TQImage& im, const TQSize& _size) {
	TQImage img = TSDeepCopy( im );
	TQSize size = _size;
	if ( !img.isNull()) {
		emitThumbnailLoaded(img, size);
	} else {
		emitThumbnailLoadingFailed();
	}
	if( !mTempPath.isEmpty()) {
		LOG("Delete temp file " << mTempPath);
		TQFile::remove(mTempPath);
		mTempPath = TQString();
	}
	determineNextIcon();
}

void ThumbnailLoadJob::checkThumbnail() {
	// If we are in the thumbnail dir, just load the file
	if (mCurrentURL.isLocalFile()
		&& mCurrentURL.directory(false).startsWith(thumbnailBaseDir()) )
	{
		TQImage image(mCurrentURL.path());
		emitThumbnailLoaded(image, image.size());
		determineNextIcon();
		return;
	}
	TQSize imagesize;
	if( mOriginalTime == time_t( Cache::instance()->timestamp( mCurrentURL ).toTime_t())) {
		TQPixmap cached = Cache::instance()->thumbnail( mCurrentURL, imagesize );
		if( !cached.isNull()) {
			emit thumbnailLoaded(mCurrentItem, cached, imagesize);
			determineNextIcon();
			return;
		}
	}
	
	mOriginalURI=generateOriginalURI(mCurrentURL);
	mThumbnailPath=generateThumbnailPath(mOriginalURI, mThumbnailSize);

	LOG("Stat thumb " << mThumbnailPath);
	
	TQImage thumb;
	if ( thumb.load(mThumbnailPath) ) { 
		if (thumb.text("Thumb::URI", 0) == mOriginalURI &&
			thumb.text("Thumb::MTime", 0).toInt() == mOriginalTime )
		{
			int width=0, height=0;
			TQSize size;
			bool ok;

			width=thumb.text("Thumb::Image::Width", 0).toInt(&ok);
			if (ok) height=thumb.text("Thumb::Image::Height", 0).toInt(&ok);
			if (ok) {
				size=TQSize(width, height);
			} else {
				LOG("Thumbnail for " << mOriginalURI << " does not contain correct image size information");
				KFileMetaInfo fmi(mCurrentURL);
				if (fmi.isValid()) {
					KFileMetaInfoItem item=fmi.item("Dimensions");
					if (item.isValid()) {
						size=item.value().toSize();
					} else {
						LOG("KFileMetaInfoItem for " << mOriginalURI << " did not get image size information");
					}
				} else {
					LOG("Could not get a valid KFileMetaInfo instance for " << mOriginalURI);
				}
			}
			emitThumbnailLoaded(thumb, size);
			determineNextIcon();
			return;
		}
	}

	// Thumbnail not found or not valid
	if ( MimeTypeUtils::rasterImageMimeTypes().contains(mCurrentItem->mimetype()) ) {
		// This is a raster image
		if (mCurrentURL.isLocalFile()) {
			// Original is a local file, create the thumbnail
			startCreatingThumbnail(mCurrentURL.path());
		} else {
			// Original is remote, download it
			mState=STATE_DOWNLOADORIG;
			KTempFile tmpFile;
			mTempPath=tmpFile.name();
			KURL url;
			url.setPath(mTempPath);
			TDEIO::Job* job=TDEIO::file_copy(mCurrentURL, url,-1,true,false,false);
			job->setWindow(TDEApplication::kApplication()->mainWidget());
			LOG("Download remote file " << mCurrentURL.prettyURL());
			addSubjob(job);
		}
	} else {
		// Not a raster image, use a KPreviewJob
		mState=STATE_PREVIEWJOB;
		KFileItemList list;
		list.append(mCurrentItem);
		TDEIO::Job* job=TDEIO::filePreview(list, mThumbnailSize);
		job->setWindow(TDEApplication::kApplication()->mainWidget());
		connect(job, TQT_SIGNAL(gotPreview(const KFileItem*, const TQPixmap&)),
			this, TQT_SLOT(slotGotPreview(const KFileItem*, const TQPixmap&)) );
		connect(job, TQT_SIGNAL(failed(const KFileItem*)),
			this, TQT_SLOT(emitThumbnailLoadingFailed()) );
		addSubjob(job);
		return;
	}
}

void ThumbnailLoadJob::startCreatingThumbnail(const TQString& pixPath) {
	LOG("Creating thumbnail from " << pixPath);
	mThumbnailThread.load( mOriginalURI, mOriginalTime, mCurrentItem->size(),
		mCurrentItem->mimetype(), pixPath, mThumbnailPath, mThumbnailSize,
		FileViewConfig::storeThumbnailsInCache());
}


void ThumbnailLoadJob::slotGotPreview(const KFileItem* item, const TQPixmap& pixmap) {
	LOG("");
	TQSize size;
	emit thumbnailLoaded(item, pixmap, size);
}


void ThumbnailLoadJob::emitThumbnailLoaded(const TQImage& img, TQSize size) {
	int biggestDimension=TQMAX(img.width(), img.height());

	TQImage thumbImg;
	if (biggestDimension>mThumbnailSize) {
		// Scale down thumbnail if necessary
		thumbImg=ImageUtils::scale(img,mThumbnailSize, mThumbnailSize, ImageUtils::SMOOTH_FAST,TQ_ScaleMin);
	} else {
		thumbImg=img;
	}
	TQDateTime tm;
	tm.setTime_t( mOriginalTime );
	TQPixmap thumb( thumbImg ); // store as TQPixmap in cache (faster to retrieve, no conversion needed)
	Cache::instance()->addThumbnail( mCurrentURL, thumb, size, tm );
	emit thumbnailLoaded(mCurrentItem, thumb, size);
}


void ThumbnailLoadJob::emitThumbnailLoadingFailed() {
	TQSize size;
	emit thumbnailLoaded(mCurrentItem, mBrokenPixmap, size);
}


} // namespace