forked from eglaysher/vitaminsee
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImageLoader.m
931 lines (810 loc) · 28.4 KB
/
ImageLoader.m
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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
/////////////////////////////////////////////////////////////////////////
// File: $URL$
// Module: Loads images in a seperate thread.
// Part of: VitaminSEE
//
// ID: $Id: ApplicationController.m 123 2005-04-18 00:21:02Z elliot $
// Revision: $Revision$
// Last edited: $Date$
// Author: $Author$
// Copyright: (c) 2005 Elliot Glaysher
// Created: 9/13/05
//
/////////////////////////////////////////////////////////////////////////
//
// 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.
//
////////////////////////////////////////////////////////////////////////
#import "ImageLoader.h"
#import "EGPath.h"
#import "pthread.h"
#import "Util.h"
#import "ViewerDocument.h"
#import "NSString+FileTasks.h"
#define CACHE_SIZE 3
// Externed constants
NSString* SCALE_IMAGE_PROPORTIONALLY = @"Scale Image Proportionally";
NSString* SCALE_IMAGE_TO_FIT = @"Scale Image to Fit";
NSString* SCALE_IMAGE_TO_FIT_WIDTH = @"Scale Image to Fit Width";
NSString* SCALE_IMAGE_TO_FIT_HEIGHT = @"Scale Image to Fit Height";
NSString* NO_SMOOTHING = @"No Smoothing";
NSString* LOW_SMOOTHING = @"Low Smoothing";
NSString* HIGH_SMOOTHING = @"High Smoothing";
NSString* IL_REQUESTER = @"Requester";
NSString* IL_REQUESTER_ID = @"Requester ID";
NSString* IL_PATH = @"Path";
NSString* IL_PARTIAL = @"Partial";
NSString* IL_SCALE_MODE = @"Scale Mode";
NSString* IL_VIEWING_AREA_HEIGHT = @"Viewing Area Height";
NSString* IL_VIEWING_AREA_WIDTH = @"Viewing Area Width";
NSString* IL_SMOOTHING = @"Smoothing";
NSString* IL_IMAGE = @"Image";
NSString* IL_PIXEL_WIDTH = @"Pixel Width";
NSString* IL_PIXEL_HEIGHT = @"Pixel Height";
NSString* IL_SCALE_RATIO = @"Scale Ratio";
NSString* IL_DATE = @"Date";
NSString* IL_IMAGE_REP = @"Image Rep";
NSString* IL_DATA_SIZE = @"Data Size";
// No data structures can be written to when the taskQueueLock is locked.
static pthread_mutex_t taskQueueLock;
static pthread_cond_t conditionLock;
// Map of requester to handle. Each request has the following form:
// 'requester id' => {
// @"Requester" => id,
// @"Path" => EGPath*,
// @"Scale Mode" => NSString,
// @"Viewing Area Height" => NSNumber,
// @"Viewing Area Width" => NSNumber
// @"Smoothing" => NSNumber // based on smoothing tag
// }
static NSMutableDictionary* taskQueue;
// Array of the next images to preload... [EGPath, EGPath...]
static NSMutableArray* preloadQueue = 0;
// Image cache (and its mutex) consisting of:
// EGPath* => {
// @"Date" => NSDate (of load),
// @"Path" => EGPath*,
// @"Image Rep" => NSImageRep*,
// @"Data Size" => NSNumber*
// }
//
static pthread_mutex_t imageCacheLock;
static NSMutableDictionary* imageCache = 0;
/** Describes a set of functions used to check if a certain task should be
* canceled our not.
*
* We use a function pointer instead of a selector both because of speed
* issues...and because there's no performSelector: on Class objects.
*
* @see newTaskForSameRequester, newTaskThatPreemptsPreload
*/
typedef BOOL (*CANCELCHECK)(NSDictionary*);
/** Callback function used by methods that ask for a function pointer of
* CANCELCHECK. This function checks to see if the requester who has requested
* the image currently being worked with has requested another (different?)
* picture.
*
* @param currentTask Task Dictionary containing current task.
* @return Whether the loading of the currentTask should be canceled.
* @see CANCELCHECK
*/
static BOOL newTaskForSameRequester(NSDictionary* currentTask)
{
id obj;
id req = [currentTask objectForKey:IL_REQUESTER];
//(id)CFDictionaryGetValue((CFDictionaryRef)currentTask, IL_REQUESTER);
NSNumber* num = [req documentID];
pthread_mutex_lock(&taskQueueLock);
{
obj = [taskQueue objectForKey:num];
//(id)CFDictionaryGetValue((CFDictionaryRef)taskQueue, num);
}
pthread_mutex_unlock(&taskQueueLock);
return obj != nil;
}
//-----------------------------------------------------------------------------
/** Callback funcction used by methods that ask for a function pointer of
* CANCELCHECK. This function checks to see if for the preloading task
* represented by currentTask should be canceled. Preloading tasks are canceled
* when an image load request has been issued for a file that ISN'T the file
* currently being preloaded.
*
* @param currentTask Task Dictionary containing current preload task.
* @return Whether the loading of the currentTask should be canceled.
* @see CANCELCHECK
*/
static BOOL newTaskThatPreemptsPreload(NSDictionary* currentTask)
{
BOOL cancel = NO;
pthread_mutex_lock(&taskQueueLock);
{
int count = [taskQueue count];
if([taskQueue count]) {
cancel = YES;
EGPath* path = [currentTask objectForKey:IL_PATH];
NSArray* keys = [taskQueue allKeys];
// Walk through the paths being requested one by one. If one of them
// is the same as the path currently being loaded in currentTask,
// then
int i;
for(i = 0; i < count; ++i) {
// Working on making this the correct expression
NSDictionary* dic = [taskQueue objectForKey:[keys objectAtIndex:i]];
EGPath* thisPath = [dic objectForKey:IL_PATH];
if([path isEqual:thisPath]) {
// NSLog(@"Continuing with preload because a display command needs it.");
cancel = NO;
break;
}
}
}
}
pthread_mutex_unlock(&taskQueueLock);
return cancel;
}
@interface ImageLoader (Private)
+(void)doDisplayImage:(NSMutableDictionary*)task
debugMode:(BOOL)debugMode;
+(NSImageRep*)loadImageForTask:(NSMutableDictionary*)task
cancelFunction:(CANCELCHECK)cancelFunction;
+(NSSize)calculateTargetImageSize:(NSMutableDictionary*)task
imageRep:(NSImageRep*)imageRep;
+(void)evictImages;
+(void)doPreloadImage:(EGPath*)path;
@end
@implementation ImageLoader
/** Class initializer. Creates mutexes and class variables. Spawns thread
* handeling thread.
*/
+(void)initialize
{
// Create the main data structures
pthread_mutex_init(&taskQueueLock, NULL);
pthread_cond_init(&conditionLock, NULL);
pthread_mutex_init(&imageCacheLock, NULL);
taskQueue = [[NSMutableDictionary alloc] init];
preloadQueue = [[NSMutableArray alloc] init];
imageCache = [[NSMutableDictionary alloc] init];
// Spawn child thread here.
[NSThread detachNewThreadSelector:@selector(taskHandlerThread:)
toTarget:[ImageLoader class]
withObject:nil];
}
//-----------------------------------------------------------------------------
/** Function called by user which loads an image. This function sets the passed
* in task as the current image to load for the object that called this
* function.
*
* @param task Task Dictionary that
*/
+(void)loadTask:(NSMutableDictionary*)task
{
id requester = [task objectForKey:IL_REQUESTER];
NSNumber* num = [requester documentID];
// Record the document id in the task dictionary
[task setObject:num forKey:IL_REQUESTER_ID];
pthread_mutex_lock(&taskQueueLock);
{
// set this as the current request for the requesting object.
[taskQueue setObject:task forKey:num];
// Inform the thread that there's something new to do.
pthread_cond_signal(&conditionLock);
}
pthread_mutex_unlock(&taskQueueLock);
}
//-----------------------------------------------------------------------------
/** Function called by user which preloads an image into memory. This function
* will simply add the path of the file into a FIFO queue (which pops from the
* front when there's more then CACHED_IMAGE images.)
*
* @param file EGPath to the file to load
*/
+(void)preloadImage:(EGPath*)file
{
pthread_mutex_lock(&taskQueueLock);
{
[preloadQueue addObject:file];
// Inform the thread that there's something new to do.
pthread_cond_signal(&conditionLock);
}
pthread_mutex_unlock(&taskQueueLock);
}
//-----------------------------------------------------------------------------
/** Remove a possible pending load operation.
*/
+(void)unregisterRequester:(id)requester
{
NSNumber* num = [requester documentID];
pthread_mutex_lock(&taskQueueLock);
{
// Remove any pending loads for this object
[taskQueue removeObjectForKey:num];
// Remove any pending calls to this object
[NSObject cancelPreviousPerformRequestsWithTarget:requester];
}
pthread_mutex_unlock(&taskQueueLock);
}
//-----------------------------------------------------------------------------
/** Clears all the caches. Used when all windows are closed to reclaim memory.
*/
+(void)clearAllCaches
{
pthread_mutex_lock(&taskQueueLock);
{
[preloadQueue removeAllObjects];
}
pthread_mutex_unlock(&taskQueueLock);
pthread_mutex_lock(&imageCacheLock);
{
[imageCache removeAllObjects];
}
pthread_mutex_unlock(&imageCacheLock);
}
//-----------------------------------------------------------------------------
/** Get a list of files in the image cache.
*
* @return An NSArray containing the file names in the image cache
* @note This method is used primarily in unit testing; it is not relied on in
* normal code.
*/
+(NSArray*)imagesInCache
{
NSArray* toReturn;
pthread_mutex_lock(&imageCacheLock);
{
toReturn = [[[imageCache allKeys] copy] autorelease];
}
pthread_mutex_unlock(&imageCacheLock);
return toReturn;
}
@end
// ----------------------------------------------------------------------------
@implementation ImageLoader (Private)
/** Main function for the task handler thread. Handles loading and preloading
* reuqests and passes the data back to the main thread.
*
* @param nilObject Object placeholder since
* +detachNewThreadSelector:toTarget:withObject: requires passing
* an object.
*/
+(void)taskHandlerThread:(id)nilObject
{
NSAutoreleasePool *npool = [[NSAutoreleasePool alloc] init];
// We are the most important thread in the program
[NSThread setThreadPriority:0.5];
// Handle queue
while(1)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Let's wait for stuff
pthread_mutex_lock(&taskQueueLock);
int taskQueueCount = CFDictionaryGetCount((CFDictionaryRef)taskQueue);
int preloadQueueCount = CFArrayGetCount((CFArrayRef)preloadQueue);
while(taskQueueCount == 0 && preloadQueueCount == 0)
{
if(pthread_cond_wait(&conditionLock, &taskQueueLock))
NSLog(@"Invalid wait!?");
taskQueueCount = CFDictionaryGetCount((CFDictionaryRef)taskQueue);
preloadQueueCount = CFArrayGetCount((CFArrayRef)preloadQueue);
}
// Okay, taskQueueLock is locked. Let's try individual tasks.
if(taskQueueCount)
{
// Check the requester at the front of
id firstRequester = (id)CFArrayGetValueAtIndex(
(CFArrayRef)[taskQueue allKeys], 0);
NSMutableDictionary* currentTask = (id)CFDictionaryGetValue(
(CFDictionaryRef)taskQueue, firstRequester);
[currentTask retain];
[taskQueue removeObjectForKey:firstRequester];
pthread_mutex_unlock(&taskQueueLock);
if(currentTask)
[self doDisplayImage:currentTask debugMode:NO];
}
else if(preloadQueueCount)
{
while([preloadQueue count] > CACHE_SIZE)
[preloadQueue removeObjectAtIndex:0];
EGPath* path = [[preloadQueue objectAtIndex:0] retain];
[preloadQueue removeObjectAtIndex:0];
pthread_mutex_unlock(&taskQueueLock);
if(path)
[self doPreloadImage:path];
[path release];
}
else
{
// Unlock the mutex
pthread_mutex_unlock(&taskQueueLock);
}
[pool release];
}
[npool release];
}
//-----------------------------------------------------------------------------
/** Internal function called by +taskHandlerThread: which will load an image
* (or get it from the cache if already in memory), scale the image to whatever
* the requester asks for, and then pass the image back to the main thread.
*
* @param task Task Dictionary representing the current task
* @param debugMode Used during unit testing. Passed to the waitUntilDone
* parameter on -performSelectorOnMainThread:, so that when
* debugMode is NO in production code, things work asynchronously,
* while they'll work synchronously in unit testing, since OCUnit
* has to run everything from one thread.
*
* @note This function is way too long; it is a textbook example of a function
* that is too long, takes on too many responsibilities and is confusing.
*/
+(void)doDisplayImage:(NSMutableDictionary*)task
debugMode:(BOOL)debugMode
{
id requester = [task objectForKey:IL_REQUESTER];
NSNumber* size;
// It takes time to load data. Should we cancel?
if(newTaskForSameRequester(task)) {
[task release];
return;
}
// Now start spinning.
[requester performSelectorOnMainThread:@selector(beginCountdownToDisplayProgressIndicator)
withObject:nil
waitUntilDone:debugMode];
// Get an imageRep for the current image requested in task
NSImageRep* imageRep = [self loadImageForTask:task
cancelFunction:newTaskForSameRequester];
size = [[task objectForKey:IL_DATA_SIZE] retain];
// If we can't load the file, error out.
if(imageRep == nil) {
[task release];
[size release];
// TODO: Scream and die, since something is wrong here.
return;
}
// Now we get the target size of the image.
NSSize displaySize = [self calculateTargetImageSize:task imageRep:imageRep];
// It took time to load data. Should we cancel?
if(newTaskForSameRequester(task)) {
[imageRep release];
[task release];
[size release];
return;
}
NSImage* imageToRet;
NSString* smoothing = [task objectForKey:IL_SMOOTHING];
BOOL noSmoothing = [smoothing isEqualToString:NO_SMOOTHING];
BOOL naturalSize = ([imageRep pixelsWide] <= displaySize.width &&
[imageRep pixelsHigh] <= displaySize.height);
BOOL animated = imageRepIsAnimated(imageRep);
if(noSmoothing || naturalSize || animated)
{
// Draw the image by just making an NSImage from the imageRep. This is
// done when the image will have no smoothing, or when we are
// rendering an animated GIF.
imageToRet = [[NSImage alloc] init];
[imageToRet addRepresentation:imageRep];
// Scale it anyway, because some pictures LIE about their size.
[imageToRet setScalesWhenResized:YES];
[imageToRet setSize:NSMakeSize(displaySize.width, displaySize.height)];
// Okay, if this image is animated, but it doesn't have have an frame
// duration, we're dealing with a broken GIF. Hack it so that it has
// a frame duration, even if it's wrong so at least there's some animation...
if([imageRep isKindOfClass:[NSBitmapImageRep class]] &&
[[(NSBitmapImageRep*)imageRep valueForProperty:NSImageFrameCount] intValue] > 1 &&
![(NSBitmapImageRep*)imageRep valueForProperty:NSImageCurrentFrameDuration] )
{
[(NSBitmapImageRep*)imageRep setProperty:NSImageCurrentFrameDuration
withValue:[NSNumber numberWithFloat:0.1f]];
}
// Now give us a chance to BAIL if we've already been given another display
// command
if(newTaskForSameRequester(task)) {
[imageToRet release];
[imageRep release];
[task release];
[size release];
return;
}
[task setObject:imageToRet forKey:IL_IMAGE];
// Bundle imageToRet up for transport across thread boundaries.
[requester performSelectorOnMainThread:@selector(receiveImage:)
withObject:task
waitUntilDone:debugMode];
}
else
{
// First, we draw the image with no interpolation, and send that
// representation to the screen for SPEED so it LOOKS like we are doing
// something.
imageToRet = [[NSImage alloc] initWithSize:displaySize];
// This block could throw on a bad file. We catch and error
@try
{
[imageToRet lockFocus];
{
[[NSGraphicsContext currentContext]
setImageInterpolation:NSImageInterpolationNone];
[imageRep drawInRect:NSMakeRect(0,0,displaySize.width,
displaySize.height)];
}
[imageToRet unlockFocus];
}
@catch(NSException* e)
{
// The image will still be locked, even if -lock fails.
[imageToRet unlockFocus];
[imageToRet release];
NSLog(@"Exception: %@:%@", [e name] , [e reason]);
//
// // Alert the user to a problem
// NSString* format = NSLocalizedString(@"Can not display %@",
// @"Error message: 'Can not display FILENAME'");
// NSString* informativeText = NSLocalizedString(@"Please chcek that it's a valid file",
// @"Localized informative text on can't load image error");
// [vitaminSEEController stopProgressIndicator];
// [vitaminSEEController displayAlert:[NSString stringWithFormat:
// format, [path lastPathComponent]]
// informativeText:informativeText
// helpAnchor:@"VITAMINSEE_IMAGE_WONT_LOAD_ANCHOR"];
return;
}
// Now give us a chance to BAIL if we've already been given another display
// command
if(newTaskForSameRequester(task)) {
[imageRep release];
[imageToRet release];
[task release];
[size release];
// NSLog(@"Bailing after first pass...");
return;
}
// Bundle imageToRet up for transport across thread boundaries.
NSMutableDictionary* taskCopy = [task mutableCopy];
[task setObject:imageToRet forKey:IL_IMAGE];
[task setObject:[NSNumber numberWithBool:NO] forKey:IL_PARTIAL];
[imageToRet release];
[requester performSelectorOnMainThread:@selector(receiveImage:)
withObject:task
waitUntilDone:debugMode];
// Draw the image onto a new NSImage using smooth scaling. This is done
// whenever the image isn't animated so that the picture will have
// some antialiasin lovin' applied to it.
@try
{
imageToRet = [[NSImage alloc] initWithSize:displaySize];
[imageToRet lockFocus];
{
if([[taskCopy objectForKey:IL_SMOOTHING] isEqualToString:LOW_SMOOTHING])
{
[[NSGraphicsContext currentContext]
setImageInterpolation:NSImageInterpolationLow];
}
else
{
[[NSGraphicsContext currentContext]
setImageInterpolation:NSImageInterpolationHigh];
}
[imageRep drawInRect:NSMakeRect(0,0,displaySize.width,displaySize. height)];
}
[imageToRet unlockFocus];
}
@catch(NSException* e)
{
// The image will still be locked, even if -lock fails.
[imageToRet unlockFocus];
[imageToRet release];
NSLog(@"Exception: %@:%@", [e name] , [e reason]);
// In this case, don't update the display; it just won't be as
// pretty on screen.
return;
}
// Now give us a chance to BAIL if we've already been given another
// display command
if(newTaskForSameRequester(taskCopy)) {
[imageRep release];
[imageToRet release];
[taskCopy release];
[size release];
// NSLog(@"Bailing after second pass!");
return;
}
// Now display the final image:
// Bundle imageToRet up for transport across thread boundaries.
[taskCopy setObject:imageToRet forKey:IL_IMAGE];
[requester performSelectorOnMainThread:@selector(receiveImage:)
withObject:taskCopy
waitUntilDone:debugMode];
}
[imageToRet release];
[imageRep release];
[size release];
// An image has been displayed so stop the spinner
// [vitaminSEEController stopProgressIndicator];
}
//-----------------------------------------------------------------------------
/** Loads a file into memory, checking to see if we should cancel every 300
* kilobytes that we load from disk
*
* @param path EGPath to the file to load
* @param cancelFunction Function pointer to function to check if we should cancel
* @param task Task Dictionary passed to the cancelFunction
* @note Caller is responsible for releasing returned object.
*/
+(NSData*)loadFile:(EGPath*)path cancelFunction:(CANCELCHECK)cancelFunction
taskToCancel:(NSDictionary*)task
{
// Open up the file, and allocate the memory that will eventually be used to
// store our data.
NSString* filesystemPath = [path fileSystemPath];
FILE* inFile = fopen([filesystemPath fileSystemRepresentation], "r");
if(inFile == 0)
{
NSLog(@"Error! Could not open file %@!", filesystemPath);
return NULL;
}
int fileSize = [filesystemPath fileSize];
void* rawdata = malloc(fileSize);
// Check to see if we should cancel every 300 kilobytes.
const int iterations = 300 / 4;
int fileSizeRemaining = fileSize;
void* curPtr = rawdata;
int count = 0;
const int BLOCKSIZE = 1024 * 4;
while(fileSizeRemaining > 0)
{
if(fileSizeRemaining > (BLOCKSIZE))
{
// Load data
if(fread(curPtr, 1, BLOCKSIZE, inFile) != BLOCKSIZE) {
// Read error. Bail.
free(rawdata);
fclose(inFile);
return nil;
}
curPtr += BLOCKSIZE;
fileSizeRemaining -= BLOCKSIZE;
// It takes time to load data. Should we cancel?
if(count > iterations) {
if(cancelFunction && cancelFunction(task)) {
// We're aborting the load; free the resources we're using.
free(rawdata);
fclose(inFile);
return nil;
}
count = -1;
}
count++;
}
else
{
// Load the remaining chunk into memory.
if(fread(curPtr, 1, fileSizeRemaining, inFile) != fileSizeRemaining) {
// Read error. Bail.
free(rawdata);
fclose(inFile);
return nil;
}
fileSizeRemaining -= fileSizeRemaining;
}
}
fclose(inFile);
return [[NSData alloc] initWithBytesNoCopy:rawdata length:fileSize];
}
//-----------------------------------------------------------------------------
/** Will load an image (or get it out of a cache), checking to see whether we
* should cancel after every major step.
*
* @param task Task Dictionary
* @param cancelFunction Callback function which is used to control whether we
* should cancel loading.
* @return Unmodified NSImageRep of the image
* @note Caller is responsible for releasing returned object.
*/
+(NSImageRep*)loadImageForTask:(NSMutableDictionary*)task
cancelFunction:(CANCELCHECK)cancelFunction
{
// First, we load the data from
NSData* imageData;
EGPath* path = [task objectForKey:IL_PATH];
if(!task) return nil;
if(!path) return nil;
// First we check to see if the data is already loaded and resident in the
// cache.
pthread_mutex_lock(&imageCacheLock);
{
NSEnumerator* e = [imageCache objectEnumerator];
id obj;
while(obj = [e nextObject])
{
if([[obj objectForKey:IL_PATH] isEqual:path]) {
id dataSize = [obj objectForKey:IL_DATA_SIZE];
if(dataSize)
[task setObject:dataSize forKey:IL_DATA_SIZE];
else
[task setObject:[NSNumber numberWithInt:0]
forKey:IL_DATA_SIZE];
// Unlock the mutex since we're leaving the function
pthread_mutex_unlock(&imageCacheLock);
return [[obj objectForKey:IL_IMAGE_REP] retain];
}
}
}
pthread_mutex_unlock(&imageCacheLock);
// If the file wasn't in the cache, then we need to load it.
imageData = [self loadFile:path cancelFunction:cancelFunction taskToCancel:task];
// Check to see if the current task was canceled.
if(!imageData) {
return nil;
}
// Now let's build the image
Class imageRepClass = [NSImageRep imageRepClassForData:imageData];
if(imageRepClass == nil) {
// This should never happen, but let's make sure memory doesn't leak
// all over the place in case it does.
[imageData release];
return nil;
}
// Load the image from the data loaded from disk.
NSImageRep* imageRep = [[imageRepClass alloc] initWithData:imageData];
NSNumber* filesize = [NSNumber numberWithInt:[imageData length]];
[task setValue:filesize forKey:IL_DATA_SIZE];
[imageData release];
// It takes time to load data. Should we cancel?
if(cancelFunction && cancelFunction(task)) {
[imageRep release];
return nil;
}
// OK, we took the trouble of loading this image, store it in the cache.
[self evictImages];
NSMutableDictionary* dict = [NSMutableDictionary
dictionaryWithObjectsAndKeys:[NSDate date], IL_DATE,
path, IL_PATH,
imageRep, IL_IMAGE_REP,
filesize, IL_DATA_SIZE,
nil];
pthread_mutex_lock(&imageCacheLock);
{
[imageCache setObject:dict forKey:path];
}
pthread_mutex_unlock(&imageCacheLock);
return imageRep;
}
//-----------------------------------------------------------------------------
/** Calculates the target size of the image, based on the options in the Task
* Dictionary.
*
* @param task Task Dictionary
* @param imageRep Orriginal representation of the image
* @return The target size.
*/
+(NSSize)calculateTargetImageSize:(NSMutableDictionary*)task
imageRep:(NSImageRep*)imageRep
{
NSSize size;
NSString* scaleMode = [task objectForKey:IL_SCALE_MODE];
int imageWidth = [imageRep pixelsWide];
int imageHeight = [imageRep pixelsHigh];
// Add the height and width to our task list.
[task setObject:[NSNumber numberWithInt:imageWidth] forKey:IL_PIXEL_WIDTH];
[task setObject:[NSNumber numberWithInt:imageHeight] forKey:IL_PIXEL_HEIGHT];
if([scaleMode isEqualToString:SCALE_IMAGE_PROPORTIONALLY])
{
// Simply scale the image by the scale ratio if we're scaling the image
// proportionally
double scaleRatio = [[task objectForKey:IL_SCALE_RATIO] doubleValue];
size.width = imageWidth * scaleRatio;
size.height = imageHeight * scaleRatio;
}
else if([scaleMode isEqualToString:SCALE_IMAGE_TO_FIT])
{
float viewingAreaHeight = [[task objectForKey:IL_VIEWING_AREA_HEIGHT]
floatValue];
float viewingAreaWidth = [[task objectForKey:IL_VIEWING_AREA_WIDTH]
floatValue];
// First check to see if the image will fit within the boundaries of the
// window
float outputRatio = 0.0f;
if(imageWidth <= viewingAreaWidth && imageHeight <= viewingAreaHeight)
{
size.width = imageWidth;
size.height = imageHeight;
outputRatio = 1.0;
}
else
{
// Find the best ratio
float heightRatio = MIN(viewingAreaHeight/imageHeight,
imageHeight/viewingAreaHeight);
float widthRatio = MIN(viewingAreaWidth/imageWidth,
imageWidth/viewingAreaWidth);
float maxRatio = MAX(heightRatio, widthRatio);
float minRatio = MIN(heightRatio, widthRatio);
float maxHeight = imageHeight * maxRatio;
float maxWidth = imageWidth * maxRatio;
if(maxHeight <= viewingAreaHeight && maxWidth <= viewingAreaWidth)
{
outputRatio = maxRatio;
size.width = maxWidth;
size.height = maxHeight;
}
else
{
outputRatio = minRatio;
size.width = imageWidth * minRatio;
size.height = imageHeight * minRatio;
}
}
[task setObject:[NSNumber numberWithFloat:outputRatio]
forKey:IL_SCALE_RATIO];
}
// Round down, so we don't have a scroll bar apear for 0.1 pixels.
size.width = floor(size.width);
size.height = floor(size.height);
return size;
}
//-----------------------------------------------------------------------------
/** Internal function called by +taskHandlerThread: which will preload the image
* file in path.
*
* @param path Path to image to preload
*/
+(void)doPreloadImage:(EGPath*)path
{
BOOL objectNotLoaded;
pthread_mutex_lock(&imageCacheLock);
{
objectNotLoaded = ![imageCache objectForKey:path];
}
pthread_mutex_unlock(&imageCacheLock);
if(objectNotLoaded)
{
NSMutableDictionary* dictionary = [NSMutableDictionary
dictionaryWithObject:path forKey:IL_PATH];
[[self loadImageForTask:dictionary
cancelFunction:newTaskThatPreemptsPreload] release];
}
}
//-----------------------------------------------------------------------------
/** Evicts the oldest image in the cache.
*/
+(void)evictImages
{
pthread_mutex_lock(&imageCacheLock);
{
if([imageCache count] > CACHE_SIZE)
{
NSString* oldestPath = nil;
NSDate* oldestDate = [NSDate date];
NSArray* currentImages = [imageCache allKeys];
int i = 0, count = [currentImages count];
for(; i < count; ++i)
{
NSString* cur = (NSString*)CFArrayGetValueAtIndex((CFArrayRef)
currentImages, i);
NSDictionary* cacheEntry = [imageCache objectForKey:cur];
if([oldestDate compare:[cacheEntry objectForKey:IL_DATE]] ==
NSOrderedDescending)
{
// this is older!
oldestDate = [cacheEntry objectForKey:IL_DATE];
oldestPath = cur;
}
}
[imageCache removeObjectForKey:oldestPath];
}
}
pthread_mutex_unlock(&imageCacheLock);
}
@end