File: GSGState.m

package info (click to toggle)
gnustep-back 0.14.0-2
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 3,416 kB
  • ctags: 1,025
  • sloc: objc: 35,429; ansic: 6,048; makefile: 212; sh: 116
file content (1222 lines) | stat: -rw-r--r-- 28,368 bytes parent folder | download
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
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
/* GSGState - Generic graphic state

   Copyright (C) 1998 Free Software Foundation, Inc.

   Written by:  Adam Fedor <fedor@gnu.org>
   Date: Mar 2002
   
   This file is part of the GNU Objective C User Interface 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 <Foundation/NSObjCRuntime.h>
#include <AppKit/NSAffineTransform.h>
#include <AppKit/NSBezierPath.h>
#include <AppKit/NSColor.h>
#include <AppKit/NSColorSpace.h>
#include <AppKit/NSImage.h>
#include <GNUstepGUI/GSFontInfo.h>
#include <AppKit/NSGraphics.h>
#include "gsc/GSContext.h"
#include "gsc/GSGState.h"
#include "gsc/GSFunction.h"
#include "math.h"
#include <GNUstepBase/Unicode.h>

#define CHECK_PATH \
  if (!path) \
    { \
      path = [NSBezierPath new]; \
    }

@implementation GSGState

/* Designated initializer. */
- initWithDrawContext: (GSContext *)drawContext
{
  self = [super init];
  if (!self)
    return nil;

  drawcontext = drawContext;
  offset = NSMakePoint(0, 0);
  path   = nil;
  font   = nil;
  fillColorS   = nil;
  strokeColorS = nil;
  [self DPSinitgraphics];
  return self;
}

- (void) dealloc
{
  TEST_RELEASE(font);
  TEST_RELEASE(path);
  RELEASE(ctm);
  RELEASE(textCtm);
  RELEASE(fillColorS);
  RELEASE(strokeColorS);
  TEST_RELEASE(pattern);
  [super dealloc];
}

- (id) deepen
{
  NSZone *zone = GSObjCZone(self);

  if (path)
    self->path = [path copyWithZone: zone];

  self->ctm     = [ctm copyWithZone: zone];
  self->textCtm = [textCtm copyWithZone: zone];

  // Just retain the other objects
  if (font != nil)
    RETAIN(font);
  if (fillColorS != nil)
    RETAIN(fillColorS);
  if (strokeColorS != nil)
    RETAIN(strokeColorS);
  if (pattern != nil)
    RETAIN(pattern);

  return self;
}

- copyWithZone: (NSZone *)zone
{
  GSGState *new = (GSGState *)NSCopyObject(self, 0, zone);  
  /* Do a deep copy since gstates are isolated from each other */
  return [new deepen];
}

- (void) setOffset: (NSPoint)theOffset
{
  offset = theOffset;
}

- (NSPoint) offset
{
  return offset;
}

/** Subclasses should override this method to be notified of changes
    in the current color */
- (void) setColor: (device_color_t *)color state: (color_state_t)cState
{
  float alpha;
  alpha = fillColor.field[AINDEX];
  if (cState & COLOR_FILL)
    fillColor = *color;
  fillColor.field[AINDEX] = alpha;
  alpha = strokeColor.field[AINDEX];
  if (cState & COLOR_STROKE)
    strokeColor = *color;
  strokeColor.field[AINDEX] = alpha;
  cstate = cState;
  DESTROY(pattern);
}

- (void) GSSetPatterColor: (NSImage*)image 
{
  ASSIGN(pattern, image);
}

- (void) compositeGState: (GSGState *)source
                fromRect: (NSRect)aRect
                 toPoint: (NSPoint)aPoint
                      op: (NSCompositingOperation)op
{
  [self subclassResponsibility: _cmd];
}

- (void) dissolveGState: (GSGState *)source
               fromRect: (NSRect)aRect
                toPoint: (NSPoint)aPoint
                  delta: (float)delta
{
  [self subclassResponsibility: _cmd];
}

- (void) compositeGState: (GSGState *)source
                fromRect: (NSRect)aRect
                 toPoint: (NSPoint)aPoint
                      op: (NSCompositingOperation)op
                fraction: (float)delta
{
  if (op == NSCompositeSourceOver)
    {
      [self dissolveGState: source
	          fromRect: aRect
                   toPoint: aPoint
	             delta: delta];
    }
  else
    {
      [self compositeGState: source
	          fromRect: aRect
                   toPoint: aPoint
	                op: op];
    }

}

- (void) compositerect: (NSRect)aRect
                    op: (NSCompositingOperation)op
{
  [self subclassResponsibility: _cmd];
}

- (NSPoint) pointInMatrixSpace: (NSPoint)aPoint
{
  return [ctm transformPoint: aPoint];
}

- (NSPoint) deltaPointInMatrixSpace: (NSPoint)aPoint
{
  return [ctm deltaPointInMatrixSpace: aPoint];
}

- (NSRect) rectInMatrixSpace: (NSRect)rect
{
  return [ctm rectInMatrixSpace: rect];
}

@end

@implementation GSGState (Ops)

/* ----------------------------------------------------------------------- */
/* Color operations */
/* ----------------------------------------------------------------------- */
- (void) DPScurrentalpha: (float*)a
{
  *a = fillColor.field[AINDEX];
}

- (void) DPScurrentcmykcolor: (float*)c : (float*)m : (float*)y : (float*)k
{
  device_color_t new = fillColor;
  gsColorToCMYK(&new);
  *c = new.field[0];
  *m = new.field[1];
  *y = new.field[2];
  *k = new.field[3];
}

- (void) DPScurrentgray: (float*)gray
{
  device_color_t gcolor = fillColor;
  gsColorToGray(&gcolor);
  *gray = gcolor.field[0];
}

- (void) DPScurrenthsbcolor: (float*)h : (float*)s : (float*)b
{
  device_color_t gcolor = fillColor;
  gsColorToHSB(&gcolor);
  *h = gcolor.field[0]; *s = gcolor.field[1]; *b = gcolor.field[2];
}

- (void) DPScurrentrgbcolor: (float*)r : (float*)g : (float*)b
{
  device_color_t gcolor = fillColor;
  gsColorToRGB(&gcolor);
  *r = gcolor.field[0]; *g = gcolor.field[1]; *b = gcolor.field[2];
}

#define CLAMP(x) \
  if (x < 0.0) x = 0.0; \
  if (x > 1.0) x = 1.0;

- (void) DPSsetalpha: (float)a
{
  CLAMP(a)
  fillColor.field[AINDEX] = strokeColor.field[AINDEX] = a;
  [self setColor: &fillColor state: COLOR_FILL];
  [self setColor: &strokeColor state: COLOR_STROKE];
}

- (void) DPSsetcmykcolor: (float)c : (float)m : (float)y : (float)k
{
  device_color_t col;
  CLAMP(c)
  CLAMP(m)
  CLAMP(y)
  CLAMP(k)
  gsMakeColor(&col, cmyk_colorspace, c, m, y, k);
  [self setColor: &col state: COLOR_BOTH];
}

- (void) DPSsetgray: (float)gray
{
  device_color_t col;
  CLAMP(gray)
  gsMakeColor(&col, gray_colorspace, gray, 0, 0, 0);
  [self setColor: &col  state: COLOR_BOTH];
}

- (void) DPSsethsbcolor: (float)h : (float)s : (float)b
{
  device_color_t col;
  CLAMP(h)
  CLAMP(s)
  CLAMP(b)
  gsMakeColor(&col, hsb_colorspace, h, s, b, 0);
  [self setColor: &col state: COLOR_BOTH];
}

- (void) DPSsetrgbcolor: (float)r : (float)g : (float)b
{
  device_color_t col;
  CLAMP(r)
  CLAMP(g)
  CLAMP(b)
  gsMakeColor(&col, rgb_colorspace, r, g, b, 0);
  [self setColor: &col state: COLOR_BOTH];
}


- (void) GSSetFillColorspace: (void *)spaceref
{
  device_color_t col;

  ASSIGN(fillColorS, spaceref);
  gsMakeColor(&col, rgb_colorspace, 0, 0, 0, 0);
  [self setColor: &col state: COLOR_FILL];
}

- (void) GSSetStrokeColorspace: (void *)spaceref
{
  device_color_t col;

  ASSIGN(strokeColorS, spaceref);
  gsMakeColor(&col, rgb_colorspace, 0, 0, 0, 0);
  [self setColor: &col state: COLOR_STROKE];
}

- (void) GSSetFillColor: (const float *)values
{
  device_color_t dcolor;
  NSColor *color;

  if ((fillColorS == nil) 
      || ((color = [NSColor colorWithColorSpace: fillColorS
                            components: values
                            count: [fillColorS numberOfColorComponents] + 1]) == nil)
      || ((color = [color colorUsingColorSpaceName: NSDeviceRGBColorSpace]) == nil))
    {
      DPS_ERROR(DPSundefined, @"No fill colorspace defined, assume DeviceRGB");
      gsMakeColor(&dcolor, rgb_colorspace, values[0], values[1], 
                  values[2], values[3]);
    }
  else 
    {
      [color getRed: &dcolor.field[0]
             green: &dcolor.field[1]
             blue: &dcolor.field[2]
             alpha: &dcolor.field[AINDEX]];
    }

  [self setColor: &dcolor state: COLOR_FILL];
}

- (void) GSSetStrokeColor: (const float *)values
{
  device_color_t dcolor;
  NSColor *color;

  if ((strokeColorS == nil) 
      || ((color = [NSColor colorWithColorSpace: strokeColorS
                            components: values
                            count: [strokeColorS numberOfColorComponents] + 1]) == nil)
      || ((color = [color colorUsingColorSpaceName: NSDeviceRGBColorSpace]) == nil))
    {
      DPS_ERROR(DPSundefined, @"No stroke colorspace defined, assume DeviceRGB");
      gsMakeColor(&dcolor, rgb_colorspace, values[0], values[1], 
                  values[2], values[3]);
    }
  else 
    {
      [color getRed: &dcolor.field[0]
             green: &dcolor.field[1]
             blue: &dcolor.field[2]
             alpha: &dcolor.field[AINDEX]];
    }

  [self setColor: &dcolor state: COLOR_STROKE];
}

/* ----------------------------------------------------------------------- */
/* Text operations */
/* ----------------------------------------------------------------------- */

typedef enum {
  show_delta, show_array_x, show_array_y, show_array_xy
} show_array_t;

/* Omnibus show string routine that combines that characteristics of
   ashow, awidthshow, widthshow, xshow, xyshow, and yshow */
- (void) _showString: (const char *)s
	    xCharAdj: (float)cx
	    yCharAdj: (float)cy
		char: (char)c
	    adjArray: (const float *)arr
	     arrType: (show_array_t)type
	  isRelative: (BOOL)relative;
{
  NSPoint point = [path currentPoint];
  unichar *uch;
  unsigned int ulen;
  int i;

  /* 
     FIXME: We should use proper glyph generation here.
  */
  uch = NULL;
  ulen = 0;
  GSToUnicode(&uch, &ulen, (const unsigned char*)s, strlen(s),
    [font mostCompatibleStringEncoding], NSDefaultMallocZone(), 0);

  for (i = 0; i < ulen; i++)
    {
      NSPoint delta;
      NSGlyph glyph;

      glyph = (NSGlyph)uch[i];
      [self GSShowGlyphs: &glyph : 1];
      /* Note we update the current point according to the current 
	 transformation scaling, although the text isn't currently
	 scaled (FIXME). */
      if (type == show_array_xy)
	{
	  delta.x = arr[2*i]; delta.y = arr[2*i+1];
	}
      else if (type == show_array_x)
	{
	  delta.x = arr[i]; delta.y = 0;
	}
      else if (type == show_array_y)
	{
	  delta.x = 0; delta.y = arr[i];
	}
      else
	{
	  delta.x = arr[0]; delta.y = arr[1];
	}
      delta = [ctm deltaPointInMatrixSpace: delta];
      if (relative == YES)
	{
	  NSSize advancement;

	  advancement = [font advancementForGlyph: glyph];
	  /* Use only delta transformations (no offset). Is this conversion needed?*/
	  advancement = [ctm transformSize: NSMakeSize(advancement.width, 
						       [font ascender])];
	  delta.x += advancement.width;
	  delta.y += advancement.height;
	}
      if (c && *(s+i) == c)
	{
	  NSPoint cdelta;

	  cdelta.x = cx; cdelta.y = cy;
	  cdelta = [ctm deltaPointInMatrixSpace: cdelta];
	  delta.x += cdelta.x; delta.y += cdelta.y;
	}
      point.x += delta.x;
      if (type != show_delta)
        {
	  point.y += delta.y;
	}
      [path moveToPoint: point];
    }
  free(uch);
}

- (void) DPSashow: (float)x : (float)y : (const char*)s
{
  float arr[2];

  arr[0] = x; arr[1] = y;
  [self _showString: s
    xCharAdj: 0 yCharAdj: 0 char: 0 adjArray: arr arrType: show_delta
    isRelative: YES];
}

- (void) DPSawidthshow: (float)cx : (float)cy : (int)c : (float)ax : (float)ay 
		      : (const char*)s
{
  float arr[2];

  arr[0] = ax; arr[1] = ay;
  [self _showString: s
    xCharAdj: cx yCharAdj: cy char: c adjArray: arr arrType: show_delta
    isRelative: YES];
}

- (void) DPScharpath: (const char*)s : (int)count
{
  NSGlyph glBuf[count];
  int i;

  if (!font)
    return;

  // FIXME
  for (i = 0; i < count; i++)
    {
      glBuf[i] = [font glyphForCharacter: s[i]];  
    }
  
  CHECK_PATH;
  [font appendBezierPathWithGlyphs: glBuf
        count: count
        toBezierPath: path];
}

- (void) appendBezierPathWithPackedGlyphs: (const char *)packedGlyphs
                                     path: (NSBezierPath*)aPath
{
  unsigned int count = packedGlyphs[0];
  NSMultibyteGlyphPacking packing;
  NSGlyph glBuf[count];
  int i;
  int j;
  unsigned char a, b, c, d;

  if (!font)
    return;

  packing = [font glyphPacking];
  j = 1;
  for (i = 0; i < count; i++)
    {
      switch (packing)
        {
          case NSOneByteGlyphPacking: 
            glBuf[i] = (NSGlyph)packedGlyphs[j++]; 
            break;
          case NSTwoByteGlyphPacking: 
            a= packedGlyphs[j++];
            glBuf[i] = (NSGlyph)((a << 8) | packedGlyphs[j++]);
            break;
          case NSFourByteGlyphPacking:
            a = packedGlyphs[j++];
            b = packedGlyphs[j++];
            c = packedGlyphs[j++];
            d = packedGlyphs[j++];
            glBuf[i] = (NSGlyph)((a << 24) | (b << 16) 
                                 | (c << 8) | d);
            break;          
          case NSJapaneseEUCGlyphPacking:
          case NSAsciiWithDoubleByteEUCGlyphPacking:
          default:
            // FIXME
            break;
        }
    }

  [font appendBezierPathWithGlyphs: glBuf
        count: count
        toBezierPath: aPath];
}

- (void) DPSshow: (const char*)s
{
  [self subclassResponsibility: _cmd];
}

- (void) DPSwidthshow: (float)x : (float)y : (int)c : (const char*)s
{
  float arr[2];

  arr[0] = 0; arr[1] = 0;
  [self _showString: s
    xCharAdj: x yCharAdj: y char: c adjArray: arr arrType: show_delta
    isRelative: YES];
}

- (void) DPSxshow: (const char*)s : (const float*)numarray : (int)size
{
  [self _showString: s
    xCharAdj: 0 yCharAdj: 0 char: 0 adjArray: numarray arrType: show_array_x
    isRelative: NO];
}

- (void) DPSxyshow: (const char*)s : (const float*)numarray : (int)size
{
  [self _showString: s
    xCharAdj: 0 yCharAdj: 0 char: 0 adjArray: numarray arrType: show_array_xy
    isRelative: NO];
}

- (void) DPSyshow: (const char*)s : (const float*)numarray : (int)size
{
  [self _showString: s
    xCharAdj: 0 yCharAdj: 0 char: 0 adjArray: numarray arrType: show_array_y
    isRelative: NO];
}

- (void) GSSetCharacterSpacing: (float)extra
{
  charSpacing = extra;
}

- (void) GSSetFont: (GSFontInfo *)fontref
{
  if (font == fontref)
    return;
  ASSIGN(font, fontref);
}

- (void) GSSetFontSize: (float)size
{
}

- (NSAffineTransform *) GSGetTextCTM
{
  return textCtm;
}

- (NSPoint) GSGetTextPosition
{
  return [textCtm transformPoint: NSMakePoint(0,0)];
}

- (void) GSSetTextCTM: (NSAffineTransform *)newCtm
{
  ASSIGN(textCtm, newCtm);
}

- (void) GSSetTextDrawingMode: (GSTextDrawingMode)mode
{
  textMode = mode;
}

- (void) GSSetTextPosition: (NSPoint)loc
{
  [textCtm translateToPoint: loc];
}

- (void) GSShowText: (const char *)string : (size_t) length
{
  [self subclassResponsibility: _cmd];
}

- (void) GSShowGlyphs: (const NSGlyph *)glyphs : (size_t) length
{
  [self subclassResponsibility: _cmd];
}


/* ----------------------------------------------------------------------- */
/* Gstate operations */
/* ----------------------------------------------------------------------- */
- (void) DPSinitgraphics
{
  DESTROY(path);
  DESTROY(font);
  DESTROY(fillColorS);
  DESTROY(strokeColorS);
  if (ctm)
    [ctm makeIdentityMatrix];
  else
    ctm = [[NSAffineTransform allocWithZone: GSObjCZone(self)] init];

   /* Initialize colors. By default the same color is used for filling and 
     stroking unless fill and/or stroke color is set explicitly */
  gsMakeColor(&fillColor, gray_colorspace, 0, 0, 0, 0);
  fillColor.field[AINDEX] = 1.0;
  strokeColor.field[AINDEX] = 1.0;
  [self setColor: &fillColor state: COLOR_BOTH];

  charSpacing = 0;
  textMode    = GSTextFill;
  if (textCtm)
    [textCtm makeIdentityMatrix];
  else
    textCtm = [[NSAffineTransform allocWithZone: GSObjCZone(self)] init];
}

- (void)DPScurrentflat: (float *)flatness 
{
  if (path)
    *flatness = [path flatness];
  else 
    *flatness = 1.0;
}

- (void) DPScurrentlinecap: (int*)linecap
{
  [self subclassResponsibility: _cmd];
}

- (void) DPScurrentlinejoin: (int*)linejoin
{
  [self subclassResponsibility: _cmd];
}

- (void) DPScurrentlinewidth: (float*)width
{
  [self subclassResponsibility: _cmd];
}

- (void) DPScurrentmiterlimit: (float*)limit
{
  [self subclassResponsibility: _cmd];
}

- (NSPoint) currentPoint
{
  NSAffineTransform *ictm;
  NSPoint user;

  if (path == nil)
    {
      return NSMakePoint(0, 0);
    }

  // This is rather slow, but it is not used very often
  ictm = [ctm copyWithZone: GSObjCZone(self)];
  [ictm invert];
  user = [ictm transformPoint: [path currentPoint]];
  RELEASE(ictm);
  return user;
}

- (void)DPScurrentpoint: (float *)x : (float *)y 
{
  NSPoint user;

  user = [self currentPoint];
  *x = user.x;
  *y = user.y;
}

- (void) DPScurrentstrokeadjust: (int*)b
{
  [self subclassResponsibility: _cmd];
}

- (void) DPSsetdash: (const float*)pat : (int)size : (float)offset
{
  [self subclassResponsibility: _cmd];
}

- (void)DPSsetflat: (float)flatness 
{
  if (path)
    [path setFlatness: flatness];
}

- (void) DPSsetlinecap: (int)linecap
{
  [self subclassResponsibility: _cmd];
}

- (void) DPSsetlinejoin: (int)linejoin
{
  [self subclassResponsibility: _cmd];
}

- (void) DPSsetlinewidth: (float)width
{
  [self subclassResponsibility: _cmd];
}

- (void) DPSsetmiterlimit: (float)limit
{
  [self subclassResponsibility: _cmd];
}

- (void) DPSsetstrokeadjust: (int)b
{
  [self subclassResponsibility: _cmd];
}

/* ----------------------------------------------------------------------- */
/* Matrix operations */
/* ----------------------------------------------------------------------- */
- (void)DPSconcat: (const float *)m
{
  NSAffineTransformStruct matrix;
  NSAffineTransform *new_ctm = [NSAffineTransform new];

  matrix.m11 = m[0];
  matrix.m12 = m[1];
  matrix.m21 = m[2];
  matrix.m22 = m[3];
  matrix.tX  = m[4];
  matrix.tY  = m[5];
  [new_ctm setTransformStruct: matrix];

  [ctm prependTransform: new_ctm];
  RELEASE(new_ctm);
}

- (void)DPSinitmatrix 
{
  [ctm makeIdentityMatrix];
}

- (void)DPSrotate: (float)angle 
{
  [ctm rotateByDegrees: angle];
}

- (void)DPSscale: (float)x : (float)y 
{
  [ctm scaleXBy: x  yBy: y];
}

- (void)DPStranslate: (float)x : (float)y 
{
  [ctm translateToPoint: NSMakePoint(x, y)];
}

- (NSAffineTransform *) GSCurrentCTM
{
  return AUTORELEASE([ctm copy]);
}

- (void) GSSetCTM: (NSAffineTransform *)newctm
{
  ASSIGN(ctm, newctm);
}

- (void) GSConcatCTM: (NSAffineTransform *)newctm
{
  [ctm prependTransform: newctm];
}

/* ----------------------------------------------------------------------- */
/* Paint operations */
/* ----------------------------------------------------------------------- */
- (void) DPSarc: (float)x : (float)y : (float)r : (float)angle1 : (float)angle2 
{
  NSBezierPath *newPath;

  newPath = [[NSBezierPath alloc] init];
  if ((path != nil) && ([path elementCount] != 0))
    {
      [newPath lineToPoint: [self currentPoint]];
    }
  [newPath appendBezierPathWithArcWithCenter: NSMakePoint(x, y)  
	   radius: r
	   startAngle: angle1
	   endAngle: angle2
	   clockwise: NO];
  [newPath transformUsingAffineTransform: ctm];
  CHECK_PATH;
  [path appendBezierPath: newPath];
  RELEASE(newPath);
}

- (void) DPSarcn: (float)x : (float)y : (float)r : (float)angle1 : (float)angle2 
{
  NSBezierPath *newPath;

  newPath = [[NSBezierPath alloc] init];
  if ((path != nil) && ([path elementCount] != 0))
    {
      [newPath lineToPoint: [self currentPoint]];
    }
  [newPath appendBezierPathWithArcWithCenter: NSMakePoint(x, y)  
	   radius: r
	   startAngle: angle1
	   endAngle: angle2
	   clockwise: YES];
  [newPath transformUsingAffineTransform: ctm];
  CHECK_PATH;
  [path appendBezierPath: newPath];
  RELEASE(newPath);
}

- (void)DPSarct: (float)x1 : (float)y1 : (float)x2 : (float)y2 : (float)r 
{
  NSBezierPath *newPath;

  newPath = [[NSBezierPath alloc] init];
  if ((path != nil) && ([path elementCount] != 0))
    {
	[newPath lineToPoint: [self currentPoint]];
    }
  [newPath appendBezierPathWithArcFromPoint: NSMakePoint(x1, y1)
	   toPoint: NSMakePoint(x2, y2)
	   radius: r];
  [newPath transformUsingAffineTransform: ctm];
  CHECK_PATH;
  [path appendBezierPath: newPath];
  RELEASE(newPath);
}

- (void) DPSclip
{
  [self subclassResponsibility: _cmd];
}

- (void)DPSclosepath 
{
  CHECK_PATH;
  [path closePath];
}

- (void)DPScurveto: (float)x1 : (float)y1 : (float)x2 : (float)y2 : (float)x3 
		  : (float)y3 
{
  NSPoint p1 = [ctm transformPoint: NSMakePoint(x1, y1)];
  NSPoint p2 = [ctm transformPoint: NSMakePoint(x2, y2)];
  NSPoint p3 = [ctm transformPoint: NSMakePoint(x3, y3)];

  CHECK_PATH;
  [path curveToPoint: p3 controlPoint1: p1 controlPoint2: p2];
}

- (void) DPSeoclip
{
  [self subclassResponsibility: _cmd];
}

- (void) DPSeofill
{
  [self subclassResponsibility: _cmd];
}

- (void) DPSfill
{
  [self subclassResponsibility: _cmd];
}

- (void)DPSflattenpath 
{
  if (path)
    ASSIGN(path, [path bezierPathByFlatteningPath]);
}

- (void) DPSinitclip;
{
  [self subclassResponsibility: _cmd];
}

- (void)DPSlineto: (float)x : (float)y 
{
  NSPoint p = [ctm transformPoint: NSMakePoint(x, y)];

  CHECK_PATH;
  [path lineToPoint: p];
}

- (void)DPSmoveto: (float)x : (float)y 
{
  NSPoint p = [ctm transformPoint: NSMakePoint(x, y)];

  CHECK_PATH;
  [path moveToPoint: p];
}

- (void)DPSnewpath 
{
  if (path)
    [path removeAllPoints];
}

- (NSBezierPath *) bezierPath
{
  // This is rather slow, but it is not used very often
  NSBezierPath *newPath = [path copy];
  NSAffineTransform *ictm = [ctm copyWithZone: GSObjCZone(self)];

  [ictm invert];
  [newPath transformUsingAffineTransform: ictm];
  RELEASE(ictm);
  return AUTORELEASE(newPath);
}

- (void)DPSpathbbox: (float *)llx : (float *)lly : (float *)urx : (float *)ury 
{
  NSBezierPath *bpath = [self bezierPath];
  NSRect rect = [bpath controlPointBounds];

  if (llx)
    *llx = NSMinX(rect);
  if (lly)
    *lly = NSMinY(rect);
  if (urx)
    *urx = NSMaxX(rect);
  if (ury)
    *ury = NSMaxY(rect);
}

- (void)DPSrcurveto: (float)x1 : (float)y1 : (float)x2 : (float)y2 : (float)x3 
		   : (float)y3 
{
  NSPoint p1 = [ctm deltaPointInMatrixSpace: NSMakePoint(x1, y1)];
  NSPoint p2 = [ctm deltaPointInMatrixSpace: NSMakePoint(x2, y2)];
  NSPoint p3 = [ctm deltaPointInMatrixSpace: NSMakePoint(x3, y3)];
 
  CHECK_PATH;
  [path relativeCurveToPoint: p3
	controlPoint1: p1
	controlPoint2: p2];
}

- (void) DPSrectclip: (float)x : (float)y : (float)w : (float)h
{
  NSBezierPath *oldPath = path;

  path = [[NSBezierPath alloc] init];
  [path appendBezierPathWithRect: NSMakeRect(x, y, w, h)];
  [path transformUsingAffineTransform: ctm];
  [self DPSclip];
  RELEASE(path);
  path = oldPath;
  if (path)
    [path removeAllPoints];
}

- (void) DPSrectfill: (float)x : (float)y : (float)w : (float)h
{
  NSBezierPath *oldPath = path;

  path = [[NSBezierPath alloc] init];
  [path appendBezierPathWithRect: NSMakeRect(x, y, w, h)];
  [path transformUsingAffineTransform: ctm];
  [self DPSfill];
  RELEASE(path);
  path = oldPath;
}

- (void) DPSrectstroke: (float)x : (float)y : (float)w : (float)h
{
  NSBezierPath *oldPath = path;

  path = [[NSBezierPath alloc] init];
  [path appendBezierPathWithRect: NSMakeRect(x, y, w, h)];
  [path transformUsingAffineTransform: ctm];
  [self DPSstroke];
  RELEASE(path);
  path = oldPath;
}

- (void)DPSreversepath 
{
  if (path)
    ASSIGN(path, [path bezierPathByReversingPath]);
}

- (void)DPSrlineto: (float)x : (float)y 
{
  NSPoint p = [ctm deltaPointInMatrixSpace: NSMakePoint(x, y)];
 
  CHECK_PATH;
  [path relativeLineToPoint: p];
}

- (void)DPSrmoveto: (float)x : (float)y 
{
  NSPoint p = [ctm deltaPointInMatrixSpace: NSMakePoint(x, y)];
 
  CHECK_PATH;
  [path relativeMoveToPoint: p];
}

- (void) DPSstroke;
{
  [self subclassResponsibility: _cmd];
}

- (void) GSSendBezierPath: (NSBezierPath *)newpath
{
  int count = 10;
  float dash_pattern[10];
  float phase;

  // Appending to the current path is a lot faster than copying!
  //ASSIGNCOPY(path, newpath);
  CHECK_PATH;
  [path removeAllPoints];
  [path appendBezierPath: newpath];
  [path transformUsingAffineTransform: ctm];

  // The following should be moved down into the specific subclasses
  [self DPSsetlinewidth: [newpath lineWidth]];
  [self DPSsetlinejoin: [newpath lineJoinStyle]];
  [self DPSsetlinecap: [newpath lineCapStyle]];
  [self DPSsetmiterlimit: [newpath miterLimit]];
  [self DPSsetflat: [newpath flatness]];

  [newpath getLineDash: dash_pattern count: &count phase: &phase];
  [self DPSsetdash: dash_pattern : count : phase];
}

- (void) GSRectClipList: (const NSRect *)rects : (int) count
{
  int i;
  NSRect union_rect;

  if (count == 0)
    return;

  /* 
     The specification is not clear if the union of the rects 
     should produce the new clip rect or if the outline of all rects 
     should be used as clip path.
  */
  union_rect = rects[0];
  for (i = 1; i < count; i++)
    union_rect = NSUnionRect(union_rect, rects[i]);

  [self DPSrectclip: NSMinX(union_rect) : NSMinY(union_rect)
	  : NSWidth(union_rect) : NSHeight(union_rect)];
}


- (void) GSRectFillList: (const NSRect *)rects : (int) count
{
  int i;
  for (i=0; i < count; i++)
    [self DPSrectfill: NSMinX(rects[i]) : NSMinY(rects[i])
	  : NSWidth(rects[i]) : NSHeight(rects[i])];
}

- (NSDictionary *) GSReadRect: (NSRect)r
{
  return nil;
}

- (void)DPSimage: (NSAffineTransform*) matrix 
		: (int) pixelsWide : (int) pixelsHigh
		: (int) bitsPerSample : (int) samplesPerPixel 
		: (int) bitsPerPixel : (int) bytesPerRow : (BOOL) isPlanar
		: (BOOL) hasAlpha : (NSString *) colorSpaceName
		: (const unsigned char *const [5]) data
{
  [self subclassResponsibility: _cmd];
}

- (void) DPSshfill: (NSDictionary *)shader
{
  NSNumber *v;
  NSDictionary *function_dict;
  GSFunction2in3out *function;
  NSAffineTransform *matrix, *inverse;
  NSAffineTransformStruct	ts;
  NSRect rect;
  int iwidth, iheight;
  double x, y;
  int i;
  unsigned char *data;

  v = [shader objectForKey: @"ShadingType"];

  /* only type 1 shaders */
  if ([v intValue] != 1)
    {
      NSLog(@"ShadingType != 1 not supported.");
      return;
    }

  /* in device rgb space */
  if ([shader objectForKey: @"ColorSpace"])
    if (![[shader objectForKey: @"ColorSpace"] isEqual: NSDeviceRGBColorSpace])
      {
        NSLog(@"Only device RGB ColorSpace supported for shading.");
        return;
      }

  function_dict = [shader objectForKey: @"Function"];
  if (!function_dict)
    {
      NSLog(@"Shading function not set.");
      return;
    }

  function = [[GSFunction2in3out alloc] initWith: function_dict];
  if (!function)
    return;

  matrix = [ctm copy];
  if ([shader objectForKey: @"Matrix"])
    {
      [matrix prependTransform: [shader objectForKey: @"Matrix"]];
    }

  inverse = [matrix copy];
  [inverse invert];

  rect = [function affectedRect];
  iwidth = rect.size.width;
  iheight = rect.size.height;
  data = objc_malloc(sizeof(char) * iwidth * iheight * 4);
  i = 0;

  for (y = NSMinY(rect); y < NSMaxY(rect); y++)
    {
      double in[2], out[3];
      NSPoint p;

      p = [inverse transformPoint: NSMakePoint(NSMinX(rect), y)];
      in[0] = p.x;
      in[1] = p.y;
          
      out[0] = out[1] = out[2] = 0.0;
      for (x = NSMinX(rect); x < NSMaxX(rect); x++)
        {
          char r, g, b, a;
            
          [function eval: in : out];
     
          // Set data at x - NSMinX(rect), y - NSMinY(rect) to out
          r = out[0] * 255;
          g = out[1] * 255;
          b = out[2] * 255;
          a = 255;
          data[i++] = r;
          data[i++] = g;
          data[i++] = b;
          data[i++] = a;

          // This gives the same result as: 
          // p = [inverse transformPoint: NSMakePoint(x, y)];
          in[0] += ts.m11;
          in[1] += ts.m12;
        }
    }

  // Copy data to device
  DESTROY(matrix);
  matrix = [NSAffineTransform new];
  [matrix translateXBy: NSMinX(rect) yBy: NSMinY(rect)];
  [self DPSimage: matrix 
        : iwidth : iheight
        : 8 : 4 
        : 32 : 4 * iwidth  : NO
        : YES : NSDeviceRGBColorSpace
        : (const unsigned char **)&data];
  objc_free(data);

  DESTROY(matrix);
  DESTROY(inverse);
  DESTROY(function);
}

@end