File: NSImageRep.m

package info (click to toggle)
gnustep-gui 0.25.0-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 13,088 kB
  • ctags: 3,417
  • sloc: objc: 153,800; ansic: 18,239; cpp: 579; yacc: 462; makefile: 143; sh: 5
file content (947 lines) | stat: -rw-r--r-- 24,937 bytes parent folder | download | duplicates (3)
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
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
/** <title>NSImageRep</title>

   <abstract>Abstract representation of an image.</abstract>

   Copyright (C) 1996 Free Software Foundation, Inc.

   Author: Adam Fedor <fedor@colorado.edu>
   Date: Feb 1996

   This file is part of the GNUstep Application Kit Library.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser 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
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; see the file COPYING.LIB.
   If not, see <http://www.gnu.org/licenses/> or write to the 
   Free Software Foundation, 51 Franklin Street, Fifth Floor, 
   Boston, MA 02110-1301, USA.
*/

#include "config.h"
#include <string.h>
#import <Foundation/NSAffineTransform.h>
#import <Foundation/NSArray.h>
#import <Foundation/NSData.h>
#import <Foundation/NSValue.h>
#import <Foundation/NSURL.h>
#import <Foundation/NSException.h>
#import <Foundation/NSNotification.h>
#import <Foundation/NSUserDefaults.h>
#import <Foundation/NSDebug.h>
#import "AppKit/NSAffineTransform.h"
#import "AppKit/NSImageRep.h"
#import "AppKit/NSBitmapImageRep.h"
#import "AppKit/NSCachedImageRep.h"
#import "AppKit/NSEPSImageRep.h"
#import "AppKit/NSPasteboard.h"
#import "AppKit/NSGraphicsContext.h"
#import "AppKit/NSView.h"
#import "AppKit/NSColor.h"
#import "AppKit/NSWindow.h"
#import "AppKit/NSScreen.h"
#import "AppKit/DPSOperators.h"
#import "AppKit/PSOperators.h"
#import "GNUstepGUI/GSImageMagickImageRep.h"

static NSMutableArray *imageReps = nil;
static Class NSImageRep_class = NULL;

@implementation NSImageRep

+ (void) initialize
{
  /* While there are four imageRep subclasses, in practice, only two of
     them can load in data from an external source. */
  if (self == [NSImageRep class])
    {
      NSImageRep_class = self;
      imageReps = [[NSMutableArray alloc] initWithCapacity: 4];
      [imageReps addObject: [NSBitmapImageRep class]];
#if HAVE_IMAGEMAGICK
      [imageReps addObject: [GSImageMagickImageRep class]];
#endif
    }
}

// Managing NSImageRep Subclasses
+ (Class) imageRepClassForData: (NSData *)data
{
  int i, count;

  count = [imageReps count];
  for (i = 0; i < count; i++)
    {
      Class rep = [imageReps objectAtIndex: i];
      if ([rep canInitWithData: data])
	return rep;
    }
  return Nil;
}

+ (Class) imageRepClassForFileType: (NSString *)type
{
  int i, count;

  count = [imageReps count];
  for (i = 0; i < count; i++)
    {
      Class rep = [imageReps objectAtIndex: i];
      if ([[rep imageFileTypes] indexOfObject: type] != NSNotFound)
	{
	  return rep;
	}
    }
  return Nil;
}

+ (Class) imageRepClassForPasteboardType: (NSString *)type
{
  int i, count;

  count = [imageReps count];
  for (i = 0; i < count; i++)
    {
      Class rep = [imageReps objectAtIndex: i];

      if ([[rep imagePasteboardTypes] indexOfObject: type] != NSNotFound)
	{
	  return rep;
	}
    }
  return Nil;
}

+ (void) registerImageRepClass: (Class)imageRepClass
{
  if ([imageReps containsObject: imageRepClass] == NO)
    {
      Class c = imageRepClass;

      while (c != nil && c != [NSObject class] && c != [NSImageRep class])
	{
	  c = [c superclass];
	}
      if (c != [NSImageRep class])
	{
	  [NSException raise: NSInvalidArgumentException
		      format: @"Attempt to register non-imagerep class"];
	}
      [imageReps addObject: imageRepClass];
    }
  [[NSNotificationCenter defaultCenter]
    postNotificationName: NSImageRepRegistryChangedNotification
		  object: self];
}

+ (NSArray *) registeredImageRepClasses
{
  return (NSArray *)imageReps;
}

+ (void) unregisterImageRepClass: (Class)imageRepClass
{
  [imageReps removeObject: imageRepClass];
  [[NSNotificationCenter defaultCenter]
    postNotificationName: NSImageRepRegistryChangedNotification
		  object: self];
}

// Creating an NSImageRep
+ (id) imageRepWithContentsOfFile: (NSString *)filename
{
  NSArray* array;

  array = [self imageRepsWithContentsOfFile: filename];
  if ([array count])
    return [array objectAtIndex: 0];
  return nil;
}

/* Helper for +imageRepsWithContentsOfFile: and imageRepsWithContentsOfURL:.
It would make sense (and make initialization of images from data more natural
for the user) to make this a real method and call it +imageRepsWithData:, but
that's already the name of one of the method concrete image reps need to
implement, so we can't do that. */
+ (NSArray *) _imageRepsWithData: (NSData *)data
{
  Class rep;

  if (self == NSImageRep_class)
    {
      rep = [self imageRepClassForData: data];
    }
  else if ([self canInitWithData: data])
    {
      rep = self;
    }
  else
    return nil;

  if ([rep respondsToSelector: @selector(imageRepsWithData:)])
    return [rep imageRepsWithData: data];
  else if ([rep respondsToSelector: @selector(imageRepWithData:)])
    {
      NSImageRep *imageRep = [rep imageRepWithData: data];

      if (imageRep != nil)
	return [NSArray arrayWithObject: imageRep];
    }

  return nil;
}

+ (NSArray *) imageRepsWithContentsOfFile: (NSString *)filename
{
  NSString *ext;
  Class rep;
  NSData* data;

  // Is the file extension already the file type?
  ext = [filename pathExtension];
  if (!ext)
    {
      /* With no extension, we can't tell the type from the file name.
      Use the data instead. */
      data = [NSData dataWithContentsOfFile: filename];
      return [self _imageRepsWithData: data];
    }
  ext = [ext lowercaseString];

  if (self == NSImageRep_class)
    {
      rep = [self imageRepClassForFileType: ext];
    }
  else if ([[self imageFileTypes] containsObject: ext])
    {
      rep = self;
    }
  else
    return nil;

  // filter non-native types to native format
  if (![[rep imageUnfilteredFileTypes] containsObject: ext])
    {
      NSPasteboard *p = [NSPasteboard pasteboardByFilteringFile: filename];
      NSArray *nativeTypes = [rep imageUnfilteredFileTypes];
      NSMutableArray *ptypes = [NSMutableArray arrayWithCapacity: [nativeTypes count]];
      NSEnumerator *enumerator = [nativeTypes objectEnumerator];
      NSString *type;

      // Convert the native types to pasteboard types
      while ((type = [enumerator nextObject]) != nil)
        {
          NSString *type2 = NSCreateFileContentsPboardType(type);
          [ptypes addObject: type2];
        }

      type = [p availableTypeFromArray: ptypes];
      data = [p dataForType: type];
      NSDebugLLog(@"NSImage", @"Filtering data for %@ from %@ of type %@ to %@", filename, p, type, data);
    }
  else
    {
      data = [NSData dataWithContentsOfFile: filename];
    }

  if (nil == data)
    return nil;

  if ([rep respondsToSelector: @selector(imageRepsWithData:)])
    {
      return [rep imageRepsWithData: data];
    }
  else if ([rep respondsToSelector: @selector(imageRepWithData:)])
    {
      NSImageRep *imageRep = [rep imageRepWithData: data];
      
      if (imageRep != nil)
        return [NSArray arrayWithObject: imageRep];
    }

  return nil;
}

+ (id)imageRepWithContentsOfURL:(NSURL *)anURL
{
  NSArray* array;

  array = [self imageRepsWithContentsOfURL: anURL];
  if ([array count])
    return [array objectAtIndex: 0];
  return nil;
}

+ (NSArray *)imageRepsWithContentsOfURL:(NSURL *)anURL
{
  NSData *data;

  // FIXME: Should we use the file type for URLs or only check the data?
  data = [anURL resourceDataUsingCache: YES];

  return [self _imageRepsWithData: data];
}

+ (id) imageRepWithPasteboard: (NSPasteboard *)pasteboard
{
  NSArray* array;

  array = [self imageRepsWithPasteboard: pasteboard];
  if ([array count])
    return [array objectAtIndex: 0];
  return nil;
}

+ (NSArray *) imageRepsWithPasteboard: (NSPasteboard *)pasteboard
{
  int i, count;
  NSMutableArray* array;
  NSArray *reps;

  if (self == NSImageRep_class)
    {
      reps = imageReps;
    }
  else
    {
      reps = [NSArray arrayWithObject: self];
    }

  array = [NSMutableArray arrayWithCapacity: 1];

  count = [reps count];
  for (i = 0; i < count; i++)
    {
      NSString* ptype;
      Class rep = [reps objectAtIndex: i];

      ptype = [pasteboard availableTypeFromArray: [rep imagePasteboardTypes]];
      if (ptype != nil)
	{
	  NSData* data = [pasteboard dataForType: ptype];

	  if ([rep respondsToSelector: @selector(imageRepsWithData:)])
	    [array addObjectsFromArray: [rep imageRepsWithData: data]];
	  else if ([rep respondsToSelector: @selector(imageRepWithData:)])
	    {
	      NSImageRep *imageRep = [rep imageRepWithData: data];

	      if (rep != nil)
		[array addObject: imageRep];
	    }
	}
    }

  if ([array count] == 0)
    return nil;

  return (NSArray *)array;
}


// Checking Data Types
+ (BOOL) canInitWithData: (NSData *)data
{
  /* Subclass responsibility */
  return NO;
}

+ (BOOL) canInitWithPasteboard: (NSPasteboard *)pasteboard
{
  NSArray *pbTypes = [pasteboard types];
  NSArray *myTypes = [self imageUnfilteredPasteboardTypes];

  return ([pbTypes firstObjectCommonWithArray: myTypes] != nil);
}

+ (NSArray *) imageFileTypes
{
  NSArray *nativeTypes = [self imageUnfilteredFileTypes];
  NSEnumerator *enumerator = [nativeTypes objectEnumerator];
  NSMutableArray *filteredTypes = [[NSMutableArray alloc] initWithCapacity: 
                                                            [nativeTypes count]];
  NSString *type;
  
  while ((type = [enumerator nextObject]) != nil)
    {
      NSEnumerator *enum2 = [[NSPasteboard typesFilterableTo: 
                                             NSCreateFileContentsPboardType(type)]
                              objectEnumerator];
      NSString *type2;

      while ((type2 = [enum2 nextObject]) != nil)
        {
          NSString *fileType = NSGetFileType(type2);
          
          if (nil != fileType)
            {
              type2 = fileType;
            }
          if ([filteredTypes indexOfObject: type2] == NSNotFound)
            {
              [filteredTypes addObject: type2];
            }
        }
    }

  return AUTORELEASE(filteredTypes);
}

+ (NSArray *) imagePasteboardTypes
{
  // FIXME: We should check what conversions are defined by services.
  return [self imageUnfilteredPasteboardTypes];
}

+ (NSArray *) imageUnfilteredFileTypes
{
  /* Subclass responsibility */
  return nil;
}

+ (NSArray *) imageUnfilteredPasteboardTypes
{
  /* Subclass responsibility */
  return nil;
}


// Instance methods
- (void) dealloc
{
  RELEASE(_colorSpace);
  [super dealloc];
}

// Setting the Size of the Image
- (void) setSize: (NSSize)aSize
{
  _size = aSize;
}

- (NSSize) size
{
  return _size;
}

// Specifying Information about the Representation
- (NSInteger) bitsPerSample
{
  return _bitsPerSample;
}

- (NSString *) colorSpaceName
{
  return _colorSpace;
}

- (BOOL) hasAlpha
{
  return _hasAlpha;
}

- (BOOL) isOpaque
{
  return _isOpaque;
}

- (NSInteger) pixelsWide
{
  return _pixelsWide;
}

- (NSInteger) pixelsHigh
{
  return _pixelsHigh;
}

- (void) setAlpha: (BOOL)flag
{
  _hasAlpha = flag;
}

- (void) setBitsPerSample: (NSInteger)anInt
{
  _bitsPerSample = anInt;
}

- (void) setColorSpaceName: (NSString *)aString
{
  ASSIGN(_colorSpace, aString);
}

- (void) setOpaque: (BOOL)flag
{
  _isOpaque = flag;
}

- (void) setPixelsWide: (NSInteger)anInt
{
  _pixelsWide = anInt;
}

- (void) setPixelsHigh: (NSInteger)anInt
{
  _pixelsHigh = anInt;
}

// Drawing the Image
- (BOOL) draw
{
  /* Subclass should implement this. */
  return YES;
}

- (BOOL) drawAtPoint: (NSPoint)aPoint
{
  BOOL ok, reset;
  NSGraphicsContext *ctxt;
  NSAffineTransform *ctm = nil;

  if (_size.width == 0 && _size.height == 0)
    return NO;

  NSDebugLLog(@"NSImage", @"Drawing at point %f %f\n", aPoint.x, aPoint.y);
  reset = 0;
  ctxt = GSCurrentContext();
  if (aPoint.x != 0 || aPoint.y != 0)
    {
      ctm = GSCurrentCTM(ctxt);
      DPStranslate(ctxt, aPoint.x, aPoint.y);
      reset = 1;
    }
  ok = [self draw];
  if (reset)
    GSSetCTM(ctxt, ctm);
  return ok;
}

- (BOOL) drawInRect: (NSRect)aRect
{
  NSSize scale;
  BOOL ok;
  NSGraphicsContext *ctxt;
  NSAffineTransform *ctm;

  NSDebugLLog(@"NSImage", @"Drawing in rect (%f %f %f %f)\n", 
	      NSMinX(aRect), NSMinY(aRect), NSWidth(aRect), NSHeight(aRect));
  if (_size.width == 0 && _size.height == 0)
    return NO;

  ctxt = GSCurrentContext();
  scale = NSMakeSize(NSWidth(aRect) / _size.width, 
		     NSHeight(aRect) / _size.height);
  ctm = GSCurrentCTM(ctxt);
  DPStranslate(ctxt, NSMinX(aRect), NSMinY(aRect));
  DPSscale(ctxt, scale.width, scale.height);
  ok = [self draw];
  GSSetCTM(ctxt, ctm);
  return ok;
}

/* New code path that delegates as much as possible to the backend and whose 
behavior precisely matches Cocoa. */
- (void) nativeDrawInRect: (NSRect)dstRect
                 fromRect: (NSRect)srcRect
                operation: (NSCompositingOperation)op
                 fraction: (CGFloat)delta
{
  NSGraphicsContext *ctxt = GSCurrentContext();
  /* An intermediate image used to scale the image to be drawn as needed */
  NSCachedImageRep *cache;
  /* The scaled image graphics state we used as the source from which we 
     draw into the destination (the current graphics context)*/
  int gState;
  /* The context of the cache window */
  NSGraphicsContext *cacheCtxt;
  const NSSize repSize = [self size];
  /* The size of the cache window */
  NSSize cacheSize;
  
  CGFloat repToCacheWidthScaleFactor;
  CGFloat repToCacheHeightScaleFactor;
  
  NSRect srcRectInCache;
  NSAffineTransform *transform, *backup;
  
  // FIXME: Revisit this calculation of cache size

  if (([self pixelsWide] == NSImageRepMatchesDevice &&
       [self pixelsHigh] == NSImageRepMatchesDevice) &&
      (dstRect.size.width > repSize.width ||
       dstRect.size.height > repSize.height))
    {
      cacheSize = [[ctxt GSCurrentCTM] transformSize: dstRect.size];
    }
  else
    {
      cacheSize = [[ctxt GSCurrentCTM] transformSize: repSize];
    }
  
  if (cacheSize.width < 0)
    cacheSize.width *= -1;
  if (cacheSize.height < 0)
    cacheSize.height *= -1;
  
  repToCacheWidthScaleFactor = cacheSize.width / repSize.width;
  repToCacheHeightScaleFactor = cacheSize.height / repSize.height;
  
  srcRectInCache = NSMakeRect(srcRect.origin.x * repToCacheWidthScaleFactor, 
			      srcRect.origin.y * repToCacheHeightScaleFactor, 
			      srcRect.size.width * repToCacheWidthScaleFactor, 
			      srcRect.size.height * repToCacheHeightScaleFactor);
  
  cache = [[NSCachedImageRep alloc]
                initWithSize: NSMakeSize(ceil(cacheSize.width), ceil(cacheSize.height))
                       depth: [[NSScreen mainScreen] depth]
                    separate: YES
                       alpha: YES];
  
  [[[cache window] contentView] lockFocus];
  cacheCtxt = GSCurrentContext();
  
  /* Clear the cache window surface */
  DPScompositerect(cacheCtxt, 0, 0, ceil(cacheSize.width), ceil(cacheSize.height), NSCompositeClear);
  gState = [cacheCtxt GSDefineGState];
  
  //NSLog(@"Draw in cache size %@", NSStringFromSize(cacheSize));
  
  [self drawInRect: NSMakeRect(0, 0, cacheSize.width, cacheSize.height)];

  [[[cache window] contentView] unlockFocus];
  
  //NSLog(@"Draw in %@ from %@ from cache rect %@", NSStringFromRect(dstRect), 
  //  NSStringFromRect(srcRect), NSStringFromRect(srcRectInCache));
  
  backup = [ctxt GSCurrentCTM];
  
  transform = [NSAffineTransform transform];
  [transform translateXBy: dstRect.origin.x yBy: dstRect.origin.y];
  [transform scaleXBy: dstRect.size.width / srcRectInCache.size.width
		  yBy: dstRect.size.height / srcRectInCache.size.height];
  [transform concat];
  
  [ctxt GSdraw: gState
       toPoint: NSMakePoint(0,0)
      fromRect: srcRectInCache
     operation: op
      fraction: delta];
  
  [ctxt GSSetCTM: backup];
  
  [ctxt GSUndefineGState: gState];
  DESTROY(cache);
}

/* Old code path that can probably partially be merged with the new native implementation.
Fallback for backends other than Cairo. */
- (void) guiDrawInRect: (NSRect)dstRect
              fromRect: (NSRect)srcRect
             operation: (NSCompositingOperation)op
              fraction: (CGFloat)delta
{
  NSGraphicsContext *ctxt = GSCurrentContext();
  NSAffineTransform *transform;
  NSSize repSize;

  repSize = [self size];

  if (![ctxt isDrawingToScreen])
    {
      /* We can't composite or dissolve if we aren't drawing to a screen,
         so we'll just draw the right part of the image in the right
         place. This code will only get used by the GSStreamContext. */
      NSPoint p;
      double fx, fy;

      fx = dstRect.size.width / srcRect.size.width;
      fy = dstRect.size.height / srcRect.size.height;

      p.x = dstRect.origin.x / fx - srcRect.origin.x;
      p.y = dstRect.origin.y / fy - srcRect.origin.y;

      DPSgsave(ctxt);
      DPSrectclip(ctxt, dstRect.origin.x, dstRect.origin.y,
                  dstRect.size.width, dstRect.size.height);
      DPSscale(ctxt, fx, fy);
      [self drawInRect: NSMakeRect(p.x, p.y, repSize.width, repSize.height)];
      DPSgrestore(ctxt);

      return;
    }

  /* Figure out what the effective transform from rep space to
     'window space' is.  */
  transform = [ctxt GSCurrentCTM];

  [transform scaleXBy: dstRect.size.width / srcRect.size.width
                  yBy: dstRect.size.height / srcRect.size.height];

  /* We can't composite or dissolve directly from the image reps, so we
     create a temporary off-screen window large enough to hold the
     transformed image, draw the image rep there, and composite from there
     to the destination.

     Optimization: Since we do the entire image at once, we might need a
     huge buffer.  If this starts hurting too much, there are a couple of
     things we could do to:


     1. Take srcRect into account and only process the parts of the image
     we really need.
     2. Take the clipping path into account.  Desirable, especially if we're
     being drawn as lots of small strips in a scrollview.  We don't have
     the clipping path here, though.
     3. Allocate a permanent but small buffer and process the image
     piecewise.

     */
  {
    NSCachedImageRep *cache;
    NSAffineTransformStruct ts;
    NSPoint p;
    CGFloat x0, y0, x1, y1, w, h;
    NSInteger gState;
    NSGraphicsContext *ctxt1;

    /* Figure out how big we need to make the window that'll hold the
       transformed image.  */
    p = [transform transformPoint: NSMakePoint(0, repSize.height)];
    x0 = x1 = p.x;
    y0 = y1 = p.y;

    p = [transform transformPoint: NSMakePoint(repSize.width, 0)];
    x0 = MIN(x0, p.x);
    y0 = MIN(y0, p.y);
    x1 = MAX(x1, p.x);
    y1 = MAX(y1, p.y);

    p = [transform transformPoint: NSMakePoint(repSize.width, repSize.height)];
    x0 = MIN(x0, p.x);
    y0 = MIN(y0, p.y);
    x1 = MAX(x1, p.x);
    y1 = MAX(y1, p.y);

    p = [transform transformPoint: NSMakePoint(0, 0)];
    x0 = MIN(x0, p.x);
    y0 = MIN(y0, p.y);
    x1 = MAX(x1, p.x);
    y1 = MAX(y1, p.y);

    x0 = floor(x0);
    y0 = floor(y0);
    x1 = ceil(x1);
    y1 = ceil(y1);

    w = x1 - x0;
    h = y1 - y0;

    /* This is where we want the origin of image space to be in our
       window.  */
    p.x -= x0;
    p.y -= y0;

    cache = [[NSCachedImageRep alloc]
                initWithSize: NSMakeSize(w, h)
                       depth: [[NSScreen mainScreen] depth]
                    separate: YES
                       alpha: YES];

    [[[cache window] contentView] lockFocus];
    // The context of the cache window
    ctxt1 = GSCurrentContext();
    DPScompositerect(ctxt1, 0, 0, w, h, NSCompositeClear);

    /* Set up the effective transform.  We also save a gState with this
       transform to make it easier to do the final composite.  */
    ts = [transform transformStruct];
    ts.tX = p.x;
    ts.tY = p.y;
    [transform setTransformStruct: ts];
    [ctxt1 GSSetCTM: transform];
    gState = [ctxt1 GSDefineGState];

    {
      // Hack for xlib. Without it, transparent parts of images are black
      [[NSColor clearColor] set];
      NSRectFill(NSMakeRect(0, 0, repSize.width, repSize.height));
    }

    [self drawInRect: NSMakeRect(0, 0, repSize.width, repSize.height)];

    /* If we're doing a dissolve, use a DestinationIn composite to lower
       the alpha of the pixels.  */
    if (delta != 1.0)
      {
        DPSsetalpha(ctxt1, delta);
        DPScompositerect(ctxt1, 0, 0, repSize.width, repSize.height,
                         NSCompositeDestinationIn);
      }

    [[[cache window] contentView] unlockFocus];

    DPScomposite(ctxt, srcRect.origin.x, srcRect.origin.y,
                 srcRect.size.width, srcRect.size.height, gState,
                 dstRect.origin.x, dstRect.origin.y, op);

    [ctxt GSUndefineGState: gState];

    DESTROY(cache);
  }
}

/**
 * Fallback implementation for subclasses which don't implement their
 * own direct drawing
 * TODO: explain how -draw, -drawInRect:, -drawAtPoint: clear their background
 */
- (BOOL) drawInRect: (NSRect)dstRect
	   fromRect: (NSRect)srcRect
	  operation: (NSCompositingOperation)op
	   fraction: (CGFloat)delta
     respectFlipped: (BOOL)respectFlipped
	      hints: (NSDictionary*)hints
{
  NSAffineTransform *backup = nil;
  NSGraphicsContext *ctx = GSCurrentContext();
  const BOOL compensateForFlip = (respectFlipped && [ctx isFlipped]);
  const NSSize repSize = [self size];

  // Handle abbreviated parameters

  if (NSEqualRects(srcRect, NSZeroRect))
    {
      srcRect.size = repSize;
    }
  if (NSEqualSizes(dstRect.size, NSZeroSize))
    {
      dstRect.size = repSize;
    }

  if (dstRect.size.width <= 0 || dstRect.size.height <= 0
    || srcRect.size.width <= 0 || srcRect.size.height <= 0)
    return NO;

  // Clip to image bounds

  if (srcRect.origin.x < 0)
    srcRect.origin.x = 0;
  if (srcRect.origin.y < 0)
    srcRect.origin.y = 0;
  if (NSMaxX(srcRect) > repSize.width)
    srcRect.size.width = repSize.width - srcRect.origin.x;
  if (NSMaxY(srcRect) > repSize.height)
    srcRect.size.height = repSize.height - srcRect.origin.y;

  // FIXME: Hints are currently ignored

  // Compensate for flip

  if (compensateForFlip)
    {
      NSAffineTransform *newXform;

      backup = [[ctx GSCurrentCTM] retain];

      newXform = [backup copy];
      [newXform translateXBy: dstRect.origin.x yBy: dstRect.origin.y + dstRect.size.height];
      [newXform scaleXBy: 1 yBy: -1];
      [ctx GSSetCTM: newXform];
      [newXform release];

      dstRect.origin = NSMakePoint(0, 0);
    }

  // Draw

  if ([ctx supportsDrawGState])
  {
    [self nativeDrawInRect: dstRect fromRect: srcRect operation: op fraction: delta];
  }
  else
  {
    [self guiDrawInRect: dstRect fromRect: srcRect operation: op fraction: delta];
  }

  // Undo flip compensation

  if (compensateForFlip)
    {
      [ctx GSSetCTM: backup];
      [backup release];
    }

  return YES;
}

// NSCopying protocol
- (id) copyWithZone: (NSZone *)zone
{
  NSImageRep	*copy;

  copy = (NSImageRep*)NSCopyObject(self, 0, zone);
  copy->_colorSpace = [_colorSpace copyWithZone: zone];

  return copy;
}

// NSCoding protocol
- (void) encodeWithCoder: (NSCoder*)aCoder
{
  if ([aCoder allowsKeyedCoding])
    {
      // FIXME
    }
  else
    {
      [aCoder encodeObject: _colorSpace];
      [aCoder encodeSize: _size];
      [aCoder encodeValueOfObjCType: @encode(BOOL) at: &_hasAlpha];
      [aCoder encodeValueOfObjCType: @encode(BOOL) at: &_isOpaque];
      [aCoder encodeValueOfObjCType: @encode(NSInteger) at: &_bitsPerSample];
      [aCoder encodeValueOfObjCType: @encode(NSInteger) at: &_pixelsWide];
      [aCoder encodeValueOfObjCType: @encode(NSInteger) at: &_pixelsHigh];
    }
}

- (id) initWithCoder: (NSCoder*)aDecoder
{
  if ([aDecoder allowsKeyedCoding])
    {
      // FIXME
    }
  else
    {
      [aDecoder decodeValueOfObjCType: @encode(id) at: &_colorSpace];
      _size = [aDecoder decodeSize];
      [aDecoder decodeValueOfObjCType: @encode(BOOL) at: &_hasAlpha];
      [aDecoder decodeValueOfObjCType: @encode(BOOL) at: &_isOpaque];
      [aDecoder decodeValueOfObjCType: @encode(NSInteger) at: &_bitsPerSample];
      [aDecoder decodeValueOfObjCType: @encode(NSInteger) at: &_pixelsWide];
      [aDecoder decodeValueOfObjCType: @encode(NSInteger) at: &_pixelsHigh];
    }
  return self;
}

- (NSString*)description
{
  return [NSString stringWithFormat: @"<%@: %p size: %@ pixelsWide: %d pixelsHigh: %d colorSpaceName: %@ bps: %d>",
		   [self class],
		   self,
		   NSStringFromSize([self size]),
		   (int)[self pixelsWide],
		   (int)[self pixelsHigh],
		   [self colorSpaceName],
		   (int)[self bitsPerSample]];
}

@end