Check-in [b7a570dae7]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:rework tkpath macosx backend to support macos 11.x
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: b7a570dae7804a016a2689bb2bc56be7e7bdb7d9
User & Date: chw 2021-10-24 12:54:54
Context
2021-10-24
15:27
add tcl-opencv upstream changes check-in: 6ead21a4b9 user: chw tags: trunk
12:54
rework tkpath macosx backend to support macos 11.x check-in: b7a570dae7 user: chw tags: trunk
2021-10-22
16:11
add tcl-opencv upstream changes check-in: 465c823edf user: chw tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to jni/tkpath/macosx/tkMacOSXPath.c.

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
/* Seems to work for both Endians. */
#define BlueFloatFromXColorPtr(xc)   ((float) ((xc)->blue >> 8) / 255.0)
#define GreenFloatFromXColorPtr(xc)  ((float) ((xc)->green >> 8) / 255.0)
#define RedFloatFromXColorPtr(xc)    ((float) ((xc)->red >> 8) / 255.0)

#define Blue255FromXColorPtr(xc)   ((xc)->blue >> 8)
#define Green255FromXColorPtr(xc)  ((xc)->green >> 8)
#define Red255FromXColorPtr(xc)    ((xc)->red >> 8)


#ifndef FloatToFixed
#define FloatToFixed(a) ((Fixed)((float) (a) * fixed1))
#endif

extern int gAntiAlias;
extern int gSurfaceCopyPremultiplyAlpha;
extern int gDepixelize;

const CGFloat kValidDomain[2] = {0, 1};
const CGFloat kValidRange[8] = {0, 1, 0, 1, 0, 1, 0, 1};

/*
 * This is used as a place holder for platform dependent
 * stuff between each call.
 */
typedef struct TkPathContext_ {
    CGContextRef    c;
    int             saveCount;
    CGrafPtr        port;	/* QD graphics port, NULL for bitmaps. */
    char            *data;	/* bitmap data, NULL for windows. */
    int             widthCode;  /* Used to depixelize the strokes:
                                 * 0: not integer width
                                 * 1: odd integer width
                                 * 2: even integer width */

    /* fields from TK TkMacOSXDrawingContext: */
    NSView *view;
    HIShapeRef clipRgn;
    CGRect portBounds;
    int xOff, yOff;
} TkPathContext_;

#define MAX_NL 32
typedef struct PathATSUIRecord {
    ATSUStyle       atsuStyle;
    ATSUTextLayout  atsuLayout;
    UniChar         *buffer;	/* @@@ Not sure this needs to be cached! */
    int             nlc;
    int             nl[MAX_NL + 1];
    ATSUTextMeasurement   dx[MAX_NL];
    ATSUTextMeasurement   dy[MAX_NL];
} PathATSUIRecord;

typedef struct FillInfo {
    double fillOpacity;
    GradientStopArray *stopArrPtr;
} FillInfo;

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXDrawableView --
 *
 *      This function returns the NSView for a given X drawable.
 *
 * Results:
 *      A NSView* or nil.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

NSView *
TkMacOSXDrawableView(MacDrawable *macWin)
{
    NSView *result = nil;

    if (!macWin) {
        result = nil;
    } else if (!macWin->toplevel) {
        result = macWin->view;
    } else if (!(macWin->toplevel->flags & TK_EMBEDDED)) {
        result = macWin->toplevel->view;
    } else {
        TkWindow *contWinPtr = TkpGetOtherWindow(macWin->toplevel->winPtr);

        if (contWinPtr) {
            result = TkMacOSXDrawableView(contWinPtr->privatePtr);
        }
    }
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * TkpClipDrawableToRect --
 *
 *      Clip all drawing into the drawable d to the given rectangle.
 *      If width or height are negative, reset to no clipping.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Subsequent drawing into d is offset and clipped as specified.
 *
 *----------------------------------------------------------------------
 */

void
TkpClipDrawableToRect(
    Display *display,
    Drawable d,
    int x, int y,
    int width, int height)
{
    MacDrawable *macDraw = (MacDrawable *) d;
    NSView *view = TkMacOSXDrawableView(macDraw);

    if (macDraw->drawRgn) {
        CFRelease(macDraw->drawRgn);
        macDraw->drawRgn = NULL;
    }
    if (width >= 0 && height >= 0) {
        CGRect drawRect = CGRectMake(x + macDraw->xOff, y + macDraw->yOff,
                width, height);
        HIShapeRef drawRgn = HIShapeCreateWithRect(&drawRect);

        if (macDraw->winPtr && (macDraw->flags & TK_CLIP_INVALID)) {
            TkMacOSXUpdateClipRgn(macDraw->winPtr);
        }
        if (macDraw->visRgn) {
            macDraw->drawRgn = HIShapeCreateIntersection(macDraw->visRgn,
                    drawRgn);
            CFRelease(drawRgn);
        } else {
            macDraw->drawRgn = drawRgn;
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXGetClipRgn --







|



















|
|
|
|
|
|
|









|
|
|
|
|
|
|
|
|











|


|


|










|

|

|

|

|
|
|









|
|


|


|












<


|
|


|
|
|

|
|
|
|
|
|
|
|
|
|







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
/* Seems to work for both Endians. */
#define BlueFloatFromXColorPtr(xc)   ((float) ((xc)->blue >> 8) / 255.0)
#define GreenFloatFromXColorPtr(xc)  ((float) ((xc)->green >> 8) / 255.0)
#define RedFloatFromXColorPtr(xc)    ((float) ((xc)->red >> 8) / 255.0)

#define Blue255FromXColorPtr(xc)   ((xc)->blue >> 8)
#define Green255FromXColorPtr(xc)  ((xc)->green >> 8)
#define Red255FromXColorPtr(xc)	   ((xc)->red >> 8)


#ifndef FloatToFixed
#define FloatToFixed(a) ((Fixed)((float) (a) * fixed1))
#endif

extern int gAntiAlias;
extern int gSurfaceCopyPremultiplyAlpha;
extern int gDepixelize;

const CGFloat kValidDomain[2] = {0, 1};
const CGFloat kValidRange[8] = {0, 1, 0, 1, 0, 1, 0, 1};

/*
 * This is used as a place holder for platform dependent
 * stuff between each call.
 */
typedef struct TkPathContext_ {
    CGContextRef    c;
    int		    saveCount;
    CGrafPtr	    port;	/* QD graphics port, NULL for bitmaps. */
    char	    *data;	/* bitmap data, NULL for windows. */
    int		    widthCode;	/* Used to depixelize the strokes:
				 * 0: not integer width
				 * 1: odd integer width
				 * 2: even integer width */

    /* fields from TK TkMacOSXDrawingContext: */
    NSView *view;
    HIShapeRef clipRgn;
    CGRect portBounds;
    int xOff, yOff;
} TkPathContext_;

#define MAX_NL 32
typedef struct PathTextRecord {
    CTFontRef		   fontRef;
    CFMutableDictionaryRef fontAttr;
    UniChar		   *buffer;
    int			   nlc;
    int			   nl[MAX_NL + 1];
    float		   dx[MAX_NL];
    float		   dy[MAX_NL];
} PathTextRecord;

typedef struct FillInfo {
    double fillOpacity;
    GradientStopArray *stopArrPtr;
} FillInfo;

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXDrawableView --
 *
 *	This function returns the NSView for a given X drawable.
 *
 * Results:
 *	A NSView* or nil.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

NSView *
TkMacOSXDrawableView(MacDrawable *macWin)
{
    NSView *result = nil;

    if (!macWin) {
	result = nil;
    } else if (!macWin->toplevel) {
	result = macWin->view;
    } else if (!(macWin->toplevel->flags & TK_EMBEDDED)) {
	result = macWin->toplevel->view;
    } else {
	TkWindow *contWinPtr = TkpGetOtherWindow(macWin->toplevel->winPtr);

	if (contWinPtr) {
	    result = TkMacOSXDrawableView(contWinPtr->privatePtr);
	}
    }
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * TkpClipDrawableToRect --
 *
 *	Clip all drawing into the drawable d to the given rectangle.
 *	If width or height are negative, reset to no clipping.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Subsequent drawing into d is offset and clipped as specified.
 *
 *----------------------------------------------------------------------
 */

void
TkpClipDrawableToRect(
    Display *display,
    Drawable d,
    int x, int y,
    int width, int height)
{
    MacDrawable *macDraw = (MacDrawable *) d;


    if (macDraw->drawRgn) {
	CFRelease(macDraw->drawRgn);
	macDraw->drawRgn = NULL;
    }
    if (width >= 0 && height >= 0) {
	CGRect drawRect =
	    CGRectMake(x + macDraw->xOff, y + macDraw->yOff, width, height);
	HIShapeRef drawRgn = HIShapeCreateWithRect(&drawRect);

	if (macDraw->winPtr && (macDraw->flags & TK_CLIP_INVALID)) {
	    TkMacOSXUpdateClipRgn(macDraw->winPtr);
	}
	if (macDraw->visRgn) {
	    macDraw->drawRgn =
		HIShapeCreateIntersection(macDraw->visRgn, drawRgn);
	    CFRelease(drawRgn);
	} else {
	    macDraw->drawRgn = drawRgn;
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXGetClipRgn --
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
#ifdef TK_MAC_DEBUG_DRAWING
	TkMacOSXDbgMsg("%s visRgn  ", macDraw->winPtr->pathName);
	TkMacOSXDebugFlashRegion(drawable, macDraw->visRgn);
#endif
    }

    if (macDraw->drawRgn) {
        clipRgn = HIShapeCreateCopy(macDraw->drawRgn);
    } else if (macDraw->visRgn) {
        clipRgn = HIShapeCreateCopy(macDraw->visRgn);
    }

    return clipRgn;
}

void
PathSetUpCGContext(Drawable d, TkPathContext_ *dcPtr)
{
    CGrafPtr port;
    MacDrawable *macDraw = (MacDrawable *) d;
    int dontDraw;

    dcPtr->c = NULL;
    dcPtr->view = NULL;
    dcPtr->clipRgn = NULL;

    port = TkMacOSXGetDrawablePort(d);

    dcPtr->clipRgn = TkMacOSXGetClipRgn(d);
    dontDraw = dcPtr->clipRgn ? HIShapeIsEmpty(dcPtr->clipRgn) : 0;
    if (dontDraw) {
        goto end;
    }

    NSView *view = TkMacOSXDrawableView(macDraw);
    if (view) {
        NSView *fView = [NSView focusView];

        if (view != fView) {
	    [view setNeedsDisplay:YES];
	    dontDraw = 1;
	}
        if (dontDraw) {
            goto end;
        }
        [[view window] disableFlushWindow];
        dcPtr->view = view;
        NSGraphicsContext *currentGraphicsContext = [NSGraphicsContext currentContext];
        dcPtr->c = (CGContextRef)[currentGraphicsContext graphicsPort];
        dcPtr->portBounds = NSRectToCGRect([view bounds]);
        if (dcPtr->clipRgn) {
	    /* ??? */
        }
    } else if (macDraw && (macDraw->flags & TK_IS_PIXMAP)) {
	CGRect bounds = CGRectMake(0, 0, macDraw->size.width, macDraw->size.height);
        dcPtr->portBounds = bounds;
	dcPtr->c = macDraw->context;
	if (!dcPtr->c) {
	    Tcl_Panic("PathSetUpCGContext(): no context to draw into!");
	}
    } else {
        Tcl_Panic("PathSetUpCGContext(): no NSView to draw into!");
    }

    /*
     * Core Graphics defines the origin to be the bottom left
     * corner of the CGContext and the positive y-axis points up.
     * Move the origin and flip the y-axis for all subsequent
     * Core Graphics drawing operations.
     */

    CGContextSaveGState(dcPtr->c);
    dcPtr->saveCount = 1;
    if (dcPtr->view) {
	CGRect cgbounds = CGContextGetClipBoundingBox(dcPtr->c);
	dcPtr->portBounds = NSRectToCGRect([view bounds]);
    }
    dcPtr->portBounds.origin.x += macDraw->xOff;
    dcPtr->portBounds.origin.y += macDraw->yOff;

    dcPtr->xOff = macDraw->xOff;
    dcPtr->yOff = macDraw->yOff;

end:
    if (dontDraw && dcPtr->clipRgn) {
        CFRelease(dcPtr->clipRgn);
        dcPtr->clipRgn = NULL;
    }
}

void
PathReleaseCGContext(TkPathContext_ *dcPtr)
{
    if (dcPtr->c) {
        CGContextSynchronize(dcPtr->c);
	if (dcPtr->view) {
            [[dcPtr->view window] setViewsNeedDisplay:YES];
            [[dcPtr->view window] enableFlushWindow];
	}
	while (dcPtr->saveCount > 0) {
            CGContextRestoreGState(dcPtr->c);
	    dcPtr->saveCount--;
        }
    }
    if (dcPtr->clipRgn) {
        CFRelease(dcPtr->clipRgn);
        dcPtr->clipRgn = NULL;
    }
}

CGColorSpaceRef GetTheColorSpaceRef(void)
{
    static CGColorSpaceRef deviceRGB = NULL;

    if (deviceRGB == NULL) {
        deviceRGB = CGColorSpaceCreateDeviceRGB();
    }
    return deviceRGB;
}

static LookupTable LineCapStyleLookupTable[] = {
    {CapNotLast, 		kCGLineCapButt},
    {CapButt, 	 		kCGLineCapButt},
    {CapRound, 	 		kCGLineCapRound},
    {CapProjecting, 	kCGLineCapSquare}
};

static LookupTable LineJoinStyleLookupTable[] = {
    {JoinMiter, 	kCGLineJoinMiter},
    {JoinRound,		kCGLineJoinRound},
    {JoinBevel, 	kCGLineJoinBevel}
};

void
PathSetCGContextStyle(CGContextRef c, Tk_PathStyle *style)
{
    Tk_PathDash *dashPtr;
    int fill = 0, stroke = 0;

    /** Drawing attribute functions. **/

    /* Set the line width in the current graphics state to `width'. */
    CGContextSetLineWidth(c, style->strokeWidth);

    /* Set the line cap in the current graphics state to `cap'. */
    CGContextSetLineCap(c,
            TableLookup(LineCapStyleLookupTable, 4, style->capStyle));

    /* Set the line join in the current graphics state to `join'. */
    CGContextSetLineJoin(c,
            TableLookup(LineJoinStyleLookupTable, 3, style->joinStyle));

    /* Set the miter limit in the current graphics state to `limit'. */
    CGContextSetMiterLimit(c, style->miterLimit);

    /* Set the line dash patttern in the current graphics state. */
    dashPtr = style->dashPtr;
    if ((dashPtr != NULL) && (dashPtr->number != 0)) {
        CGFloat *dashes = (CGFloat *)ckalloc(dashPtr->number * sizeof(CGFloat));
        int i;

        for (i = 0; i < dashPtr->number; i++) {
            dashes[i] = dashPtr->array[i] * style->strokeWidth;
	}
        CGContextSetLineDash(c, style->offset, dashes, dashPtr->number);
        ckfree((char *)dashes);
    }

    /* Set the current fill colorspace in the context `c' to `DeviceRGB' and
     * set the components of the current fill color to `(red, green, blue,
     * alpha)'. */
    if (GetColorFromPathColor(style->fill) != NULL) {
        fill = 1;
        CGContextSetRGBFillColor(c,
                RedFloatFromXColorPtr(style->fill->color),
                GreenFloatFromXColorPtr(style->fill->color),
                BlueFloatFromXColorPtr(style->fill->color),
                style->fillOpacity);
    }

    /* Set the current stroke colorspace in the context `c' to `DeviceRGB' and
    * set the components of the current stroke color to `(red, green, blue,
    * alpha)'. */
    if (style->strokeColor != NULL) {
        stroke = 1;
        CGContextSetRGBStrokeColor(c,
                RedFloatFromXColorPtr(style->strokeColor),
                GreenFloatFromXColorPtr(style->strokeColor),
                BlueFloatFromXColorPtr(style->strokeColor),
                style->strokeOpacity);
    }
    if (stroke && fill) {
        CGContextSetTextDrawingMode(c, kCGTextFillStroke);
    } else if (stroke) {
        CGContextSetTextDrawingMode(c, kCGTextStroke);
    } else if (fill) {
        CGContextSetTextDrawingMode(c, kCGTextFill);
    }
}

/* Various ATSUI support functions. */

static OSStatus
CreateATSUIStyle(const char *fontFamily, float fontSize,
		 Boolean isBold, Boolean isItalic, ATSUStyle *atsuStylePtr)
{
    OSStatus	err = noErr;
    ATSUStyle 	style;
    ATSUFontID	atsuFont;
    Fixed	atsuSize;
    Boolean	isUnderline = false;
    static const ATSUAttributeTag tags[] = {
	kATSUFontTag, kATSUSizeTag,
	kATSUQDBoldfaceTag, kATSUQDItalicTag,
	kATSUQDUnderlineTag
    };
    static const ByteCount sizes[] =  {
	sizeof(ATSUFontID), sizeof(Fixed), sizeof(Boolean),
	sizeof(Boolean), sizeof(Boolean)
    };
    const ATSUAttributeValuePtr values[] = {
	&atsuFont, &atsuSize, &isBold, &isItalic, &isUnderline
    };

    *atsuStylePtr = NULL;
    style = NULL;

    atsuFont = 0;
    atsuSize = FloatToFixed(fontSize);
    err = ATSUFindFontFromName((Ptr) fontFamily, strlen(fontFamily),
			       kFontFamilyName, kFontNoPlatformCode,
			       kFontNoScriptCode, kFontNoLanguageCode,

			       &atsuFont);
    if (err != noErr) {
        return err;
    }
    err = ATSUCreateStyle(&style);
    if (err != noErr) {
        if (style) {
	    ATSUDisposeStyle(style);

	}
        return err;
    }
    err = ATSUSetAttributes(style, sizeof(tags)/sizeof(tags[0]),
			    tags, sizes, values);
    if (err != noErr) {
        if (style) {
	    ATSUDisposeStyle(style);

	}
        return err;
    }
    *atsuStylePtr = style;
    return noErr;
}

static OSStatus
CreateLayoutForString(UniChar *buffer, CFIndex length,
		      ATSUStyle atsuStyle, ATSUTextLayout *layoutPtr)
{

    ATSUTextLayout layout = NULL;

    OSStatus err = noErr;

    *layoutPtr = NULL;
    err = ATSUCreateTextLayoutWithTextPtr(buffer, 0,
					  length, length, 1,
					  (unsigned long *) &length,
					  &atsuStyle, &layout);
    if (err == noErr) {
        *layoutPtr = layout;
    }
    ATSUSetTransientFontMatching(layout, true);

    return err;
}

TkPathContext
TkPathInit(Tk_Window tkwin, Drawable d)
{
    TkPathContext_ *context =
	(TkPathContext_ *) ckalloc(sizeof(TkPathContext_));

    bzero(context, sizeof(TkPathContext_));

    PathSetUpCGContext(d, context);
    context->port = TkMacOSXGetDrawablePort(d);
    context->data = NULL;
    context->widthCode = 0;
    return (TkPathContext) context;
}

TkPathContext
TkPathInitSurface(Display *display, int width, int height)
{
    CGContextRef cgContext;
    TkPathContext_ *context =
	(TkPathContext_ *) ckalloc((unsigned) (sizeof(TkPathContext_)));
    size_t bytesPerRow;
    char *data;

    /* Move up into own function */
    bzero(context, sizeof(TkPathContext_));
    bytesPerRow = 4*width;
    /* Round up to nearest multiple of 16 */
    bytesPerRow = (bytesPerRow + (16-1)) & ~(16-1);
    data = ckalloc(height*bytesPerRow);

    /* Make it RGBA with 32 bit depth. */
    cgContext = CGBitmapContextCreate(data, width, height, 8, bytesPerRow,
            GetTheColorSpaceRef(), kCGImageAlphaPremultipliedLast);
    if (cgContext == NULL) {
        ckfree((char *) context);
        return (TkPathContext) NULL;
    }
    CGContextClearRect(cgContext, CGRectMake(0, 0, width, height));
    CGContextTranslateCTM(cgContext, 0, height);
    CGContextScaleCTM(cgContext, 1, -1);
    context->c = cgContext;
    context->port = NULL;
    context->data = data;
    context->clipRgn = NULL;
    context->saveCount = 0;
    context->xOff = context->yOff = 0;
    return (TkPathContext) context;
}

void
TkPathPushTMatrix(TkPathContext ctx, TMatrix *mPtr)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGAffineTransform transform;




    if (mPtr == NULL) {
        return;
    }
    /* Return the transform [ a b c d tx ty ]. */
    transform = CGAffineTransformMake(
            (float) mPtr->a, (float) mPtr->b,
            (float) mPtr->c, (float) mPtr->d,
            (float) mPtr->tx, (float) mPtr->ty);
    CGContextConcatCTM(context->c, transform);
}

void
TkPathResetTMatrix(TkPathContext ctx)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;




    context->widthCode = 0;
    while (context->saveCount > 0) {
	CGContextRestoreGState(context->c);
	context->saveCount--;
    }
    CGContextSaveGState(context->c);
    context->saveCount++;







|

|






|





|
|
|



|
|

|




|

|



|
|
|
|
|
|
|
|
|

|


|
|
|



|









|
|
|
<
|

|
|

|
|


|
|
|




|

|
|
|
|
|

|
|
|
|

|
|
|








|





|
|
|
|



|

|















|



|







|
|

|
|

|
|






|
|
|
|
|
|



|
|

|
|
|
|
|
|


|

|

|



|

|
|
|

<
<
|
<
<
<
|
<
<
<
<
<
<
<
<
<
<

<
|
>
|
|
|
|
<
>
|
<
<
|
<
<
|
<
>

<
<
<
<
<
|
<
>

<
<
<
<
<
|
<
<
<
<
>
|
>
|
|
<
<
<
<
<
<
<

<
>
|






|

|
<












|




|







|

|
|










|








>
>
>

|



|
|
|







>
>
>
>







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
#ifdef TK_MAC_DEBUG_DRAWING
	TkMacOSXDbgMsg("%s visRgn  ", macDraw->winPtr->pathName);
	TkMacOSXDebugFlashRegion(drawable, macDraw->visRgn);
#endif
    }

    if (macDraw->drawRgn) {
	clipRgn = HIShapeCreateCopy(macDraw->drawRgn);
    } else if (macDraw->visRgn) {
	clipRgn = HIShapeCreateCopy(macDraw->visRgn);
    }

    return clipRgn;
}

void
PathSetUpCGContext(Drawable d, TkPathContext_ *context)
{
    CGrafPtr port;
    MacDrawable *macDraw = (MacDrawable *) d;
    int dontDraw;

    context->c = NULL;
    context->view = NULL;
    context->clipRgn = NULL;

    port = TkMacOSXGetDrawablePort(d);

    context->clipRgn = TkMacOSXGetClipRgn(d);
    dontDraw = context->clipRgn ? HIShapeIsEmpty(context->clipRgn) : 0;
    if (dontDraw) {
	goto end;
    }

    NSView *view = TkMacOSXDrawableView(macDraw);
    if (view) {
	NSView *fView = [NSView focusView];

	if (view != fView) {
	    [view setNeedsDisplay:YES];
	    dontDraw = 1;
	}
	if (dontDraw) {
	    goto end;
	}
	[[view window] disableFlushWindow];
	context->view = view;
	NSGraphicsContext *currentGraphicsContext = [NSGraphicsContext currentContext];
	context->c = (CGContextRef)[currentGraphicsContext graphicsPort];
	context->portBounds = NSRectToCGRect([view bounds]);
	if (context->clipRgn) {
	    /* ??? */
	}
    } else if (macDraw && (macDraw->flags & TK_IS_PIXMAP)) {
	CGRect bounds = CGRectMake(0, 0, macDraw->size.width, macDraw->size.height);
	context->portBounds = bounds;
	context->c = macDraw->context;
	if (!context->c) {
	    Tcl_Panic("PathSetUpCGContext(): no context to draw into!");
	}
    } else {
	Tcl_Panic("PathSetUpCGContext(): no NSView to draw into!");
    }

    /*
     * Core Graphics defines the origin to be the bottom left
     * corner of the CGContext and the positive y-axis points up.
     * Move the origin and flip the y-axis for all subsequent
     * Core Graphics drawing operations.
     */

    CGContextSaveGState(context->c);
    context->saveCount = 1;
    if (context->view) {

	context->portBounds = NSRectToCGRect([view bounds]);
    }
    context->portBounds.origin.x += macDraw->xOff;
    context->portBounds.origin.y += macDraw->yOff;

    context->xOff = macDraw->xOff;
    context->yOff = macDraw->yOff;

end:
    if (dontDraw && context->clipRgn) {
	CFRelease(context->clipRgn);
	context->clipRgn = NULL;
    }
}

void
PathReleaseCGContext(TkPathContext_ *context)
{
    if (context->c) {
	CGContextSynchronize(context->c);
	if (context->view) {
	    [[context->view window] setViewsNeedDisplay:YES];
	    [[context->view window] enableFlushWindow];
	}
	while (context->saveCount > 0) {
	    CGContextRestoreGState(context->c);
	    context->saveCount--;
	}
    }
    if (context->clipRgn) {
	CFRelease(context->clipRgn);
	context->clipRgn = NULL;
    }
}

CGColorSpaceRef GetTheColorSpaceRef(void)
{
    static CGColorSpaceRef deviceRGB = NULL;

    if (deviceRGB == NULL) {
	deviceRGB = CGColorSpaceCreateDeviceRGB();
    }
    return deviceRGB;
}

static LookupTable LineCapStyleLookupTable[] = {
    {CapNotLast,		kCGLineCapButt},
    {CapButt,			kCGLineCapButt},
    {CapRound,			kCGLineCapRound},
    {CapProjecting,		kCGLineCapSquare}
};

static LookupTable LineJoinStyleLookupTable[] = {
    {JoinMiter,		kCGLineJoinMiter},
    {JoinRound,		kCGLineJoinRound},
    {JoinBevel,		kCGLineJoinBevel}
};

void
PathSetCGContextStyle(CGContextRef c, Tk_PathStyle *style)
{
    Tk_PathDash *dashPtr;
    int fill = 0, stroke = 0;

    /** Drawing attribute functions. **/

    /* Set the line width in the current graphics state to `width'. */
    CGContextSetLineWidth(c, style->strokeWidth);

    /* Set the line cap in the current graphics state to `cap'. */
    CGContextSetLineCap(c,
	    TableLookup(LineCapStyleLookupTable, 4, style->capStyle));

    /* Set the line join in the current graphics state to `join'. */
    CGContextSetLineJoin(c,
	    TableLookup(LineJoinStyleLookupTable, 3, style->joinStyle));

    /* Set the miter limit in the current graphics state to `limit'. */
    CGContextSetMiterLimit(c, style->miterLimit);

    /* Set the line dash patttern in the current graphics state. */
    dashPtr = style->dashPtr;
    if ((dashPtr != NULL) && (dashPtr->number != 0)) {
	CGFloat *dashes = (CGFloat *)ckalloc(dashPtr->number * sizeof(CGFloat));
	int i;

	for (i = 0; i < dashPtr->number; i++) {
	    dashes[i] = dashPtr->array[i] * style->strokeWidth;
	}
	CGContextSetLineDash(c, style->offset, dashes, dashPtr->number);
	ckfree((char *)dashes);
    }

    /* Set the current fill colorspace in the context `c' to `DeviceRGB' and
     * set the components of the current fill color to `(red, green, blue,
     * alpha)'. */
    if (GetColorFromPathColor(style->fill) != NULL) {
	fill = 1;
	CGContextSetRGBFillColor(c,
		RedFloatFromXColorPtr(style->fill->color),
		GreenFloatFromXColorPtr(style->fill->color),
		BlueFloatFromXColorPtr(style->fill->color),
		style->fillOpacity);
    }

    /* Set the current stroke colorspace in the context `c' to `DeviceRGB' and
     * set the components of the current stroke color to `(red, green, blue,
     * alpha)'. */
    if (style->strokeColor != NULL) {
	stroke = 1;
	CGContextSetRGBStrokeColor(c,
		RedFloatFromXColorPtr(style->strokeColor),
		GreenFloatFromXColorPtr(style->strokeColor),
		BlueFloatFromXColorPtr(style->strokeColor),
		style->strokeOpacity);
    }
    if (stroke && fill) {
	CGContextSetTextDrawingMode(c, kCGTextFillStroke);
    } else if (stroke) {
	CGContextSetTextDrawingMode(c, kCGTextStroke);
    } else if (fill) {
	CGContextSetTextDrawingMode(c, kCGTextFill);
    }
}

/* Various text support functions. */

static int
CreateTextStyle(const char *fontFamily, float fontSize,
		Boolean isBold, Boolean isItalic, CTFontRef *fontRefPtr)
{


    CFStringRef fontName;



    CTFontRef	fontRef;












    fontName = CFStringCreateWithCString(NULL, fontFamily,
					 kCFStringEncodingUTF8);
    fontRef = CTFontCreateWithName(fontName, fontSize, NULL);
    CFRelease(fontName);
    if (fontRef != NULL) {
	CTFontSymbolicTraits traits = 0;

	CTFontSymbolicTraits traitMask = kCTFontBoldTrait | kCTFontItalicTrait;
	CTFontRef newRef;





	if (isBold) {

	    traits |= kCTFontBoldTrait;
	}





	if (isItalic) {

	    traits |= kCTFontItalicTrait;
	}





	newRef = CTFontCreateCopyWithSymbolicTraits(fontRef, 0.0, NULL,




						    traits, traitMask);
	if (newRef != NULL) {
	    CFRelease(fontRef);
	    fontRef = newRef;
	}







    }

    *fontRefPtr = fontRef;
    return (fontRef == NULL) ? -1 : 0;
}

TkPathContext
TkPathInit(Tk_Window tkwin, Drawable d)
{
    TkPathContext_ *context =
	(TkPathContext_ *)ckalloc(sizeof(TkPathContext_));

    memset(context, 0, sizeof(TkPathContext_));

    PathSetUpCGContext(d, context);
    context->port = TkMacOSXGetDrawablePort(d);
    context->data = NULL;
    context->widthCode = 0;
    return (TkPathContext) context;
}

TkPathContext
TkPathInitSurface(Display *display, int width, int height)
{
    CGContextRef cgContext;
    TkPathContext_ *context =
	(TkPathContext_ *)ckalloc(sizeof(TkPathContext_));
    size_t bytesPerRow;
    char *data;

    /* Move up into own function */
    memset(context, 0, sizeof(TkPathContext_));
    bytesPerRow = 4*width;
    /* Round up to nearest multiple of 16 */
    bytesPerRow = (bytesPerRow + (16-1)) & ~(16-1);
    data = ckalloc(height*bytesPerRow);

    /* Make it RGBA with 32 bit depth. */
    cgContext = CGBitmapContextCreate(data, width, height, 8, bytesPerRow,
	    GetTheColorSpaceRef(), kCGImageAlphaPremultipliedLast);
    if (cgContext == NULL) {
	ckfree((char *)context);
	return (TkPathContext) NULL;
    }
    CGContextClearRect(cgContext, CGRectMake(0, 0, width, height));
    CGContextTranslateCTM(cgContext, 0, height);
    CGContextScaleCTM(cgContext, 1, -1);
    context->c = cgContext;
    context->port = NULL;
    context->data = data;
    context->clipRgn = NULL;
    context->saveCount = 0;
    context->xOff = context->yOff = 0;
    return (TkPathContext)context;
}

void
TkPathPushTMatrix(TkPathContext ctx, TMatrix *mPtr)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGAffineTransform transform;

    if (context->c == NULL) {
	return;
    }
    if (mPtr == NULL) {
	return;
    }
    /* Return the transform [ a b c d tx ty ]. */
    transform = CGAffineTransformMake(
	    (float) mPtr->a, (float) mPtr->b,
	    (float) mPtr->c, (float) mPtr->d,
	    (float) mPtr->tx, (float) mPtr->ty);
    CGContextConcatCTM(context->c, transform);
}

void
TkPathResetTMatrix(TkPathContext ctx)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;

    if (context->c == NULL) {
	return;
    }
    context->widthCode = 0;
    while (context->saveCount > 0) {
	CGContextRestoreGState(context->c);
	context->saveCount--;
    }
    CGContextSaveGState(context->c);
    context->saveCount++;
569
570
571
572
573
574
575



576
577
578
579
580
581
582
}

void
TkPathSaveState(TkPathContext ctx)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;




    CGContextSaveGState(context->c);
    context->saveCount++;
}

void
TkPathRestoreState(TkPathContext ctx)
{







>
>
>







535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
}

void
TkPathSaveState(TkPathContext ctx)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;

    if (context->c == NULL) {
	return;
    }
    CGContextSaveGState(context->c);
    context->saveCount++;
}

void
TkPathRestoreState(TkPathContext ctx)
{
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
void
TkPathBeginPath(TkPathContext ctx, Tk_PathStyle *stylePtr)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    int nint;
    double width;




    CGContextBeginPath(context->c);
    PathSetCGContextStyle(context->c, stylePtr);
    if (stylePtr->strokeColor == NULL) {
        context->widthCode = 0;
    } else {
        width = stylePtr->strokeWidth;
        nint = (int) (width + 0.5);
        context->widthCode = fabs(width - nint) > 0.01 ? 0 : 2 - nint % 2;
    }
}

void
TkPathMoveTo(TkPathContext ctx, double x, double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;




    if (gDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    CGContextMoveToPoint(context->c, x, y);
}

void
TkPathLineTo(TkPathContext ctx, double x, double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;




    if (gDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    CGContextAddLineToPoint(context->c, x, y);
}

void
TkPathLinesTo(TkPathContext ctx, double *pts, int n)
{
    /* TkPathContext_ *context = (TkPathContext_ *) ctx; */
    /* Add a set of lines to the context's path. */
    /* CGContextAddLines(context->c, const CGPoint points[], size_t count); */
}

void
TkPathQuadBezier(TkPathContext ctx, double ctrlX, double ctrlY,
		 double x, double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;




    if (gDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    CGContextAddQuadCurveToPoint(context->c, ctrlX, ctrlY, x, y);
}

void
TkPathCurveTo(TkPathContext ctx, double ctrlX1, double ctrlY1,
	      double ctrlX2, double ctrlY2, double x, double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;




    if (gDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    CGContextAddCurveToPoint(context->c, ctrlX1, ctrlY1, ctrlX2, ctrlY2, x, y);
}

void
TkPathArcTo(TkPathContext ctx,
	    double rx, double ry,
	    double phiDegrees,	 	/* The rotation angle in degrees! */
	    char largeArcFlag, char sweepFlag, double x, double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;




    /* @@@ Should we try to use the native arc functions here? */
    if (gDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    TkPathArcToUsingBezier(ctx, rx, ry, phiDegrees, largeArcFlag, sweepFlag, x, y);
}

void
TkPathRect(TkPathContext ctx, double x, double y, double width, double height)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGRect r;




    if (gDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    r = CGRectMake(x, y, width, height);
    CGContextAddRect(context->c, r);
}

void
TkPathOval(TkPathContext ctx, double cx, double cy, double rx, double ry)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGRect r;




    r = CGRectMake(cx-rx, cy-ry, 2*rx, 2*ry);
    CGContextAddEllipseInRect(context->c, r);
}


CGInterpolationQuality convertInterpolationToCGInterpolation(int interpolation)
{
    switch (interpolation) {
        case kPathImageInterpolationNone:
            return kCGInterpolationNone;
        case kPathImageInterpolationFast:
            return kCGInterpolationLow;
        case kPathImageInterpolationBest:
            return kCGInterpolationHigh;
        default:
            return kCGInterpolationMedium;
    }






}

void
TkPathImage(TkPathContext ctx, Tk_Image image, Tk_PhotoHandle photo,
	    double x, double y, double width0, double height0,
	    double fillOpacity, XColor *tintColor, double tintAmount,
	    int interpolation, PathRect *srcRegion)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGImageRef cgImage;
    CGDataProviderRef provider;
    CGColorSpaceRef colorspace;
    CGImageAlphaInfo alphaInfo;
    size_t size;
    Tk_PhotoImageBlock block;
    unsigned char *data = NULL;
    unsigned char *ptr = NULL;
    unsigned char *srcPtr, *dstPtr;
    int srcR, srcG, srcB, srcA;     /* The source pixel offsets. */
    int dstR, dstG, dstB, dstA;     /* The destination pixel offsets. */
    int pitch;
    int iwidth, iheight;
    int i, j;




    /* Return value? */
    Tk_PhotoGetImage(photo, &block);
    size = block.pitch * block.height;
    iheight = block.height;
    iwidth = block.width;
    pitch = block.pitch;
    double width = (width0 == 0.0) ? (double)iwidth : width0;







>
>
>



|

|
|
|








>
>
>

|
|









>
>
>

|
|


















>
>
>

|
|










>
>
>

|
|







|




>
>
>


|
|










>
>
>

|
|











>
>
>



<




|
|
|
|
|
|
|
|

>
>
>
>
>
>


















|
|




>
>
>







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
void
TkPathBeginPath(TkPathContext ctx, Tk_PathStyle *stylePtr)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    int nint;
    double width;

    if (context->c == NULL) {
	return;
    }
    CGContextBeginPath(context->c);
    PathSetCGContextStyle(context->c, stylePtr);
    if (stylePtr->strokeColor == NULL) {
	context->widthCode = 0;
    } else {
	width = stylePtr->strokeWidth;
	nint = (int) (width + 0.5);
	context->widthCode = (fabs(width - nint) > 0.01) ? 0 : 2 - nint % 2;
    }
}

void
TkPathMoveTo(TkPathContext ctx, double x, double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;

    if (context->c == NULL) {
	return;
    }
    if (gDepixelize) {
	x = PATH_DEPIXELIZE(context->widthCode, x);
	y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    CGContextMoveToPoint(context->c, x, y);
}

void
TkPathLineTo(TkPathContext ctx, double x, double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;

    if (context->c == NULL) {
	return;
    }
    if (gDepixelize) {
	x = PATH_DEPIXELIZE(context->widthCode, x);
	y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    CGContextAddLineToPoint(context->c, x, y);
}

void
TkPathLinesTo(TkPathContext ctx, double *pts, int n)
{
    /* TkPathContext_ *context = (TkPathContext_ *) ctx; */
    /* Add a set of lines to the context's path. */
    /* CGContextAddLines(context->c, const CGPoint points[], size_t count); */
}

void
TkPathQuadBezier(TkPathContext ctx, double ctrlX, double ctrlY,
		 double x, double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;

    if (context->c == NULL) {
	return;
    }
    if (gDepixelize) {
	x = PATH_DEPIXELIZE(context->widthCode, x);
	y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    CGContextAddQuadCurveToPoint(context->c, ctrlX, ctrlY, x, y);
}

void
TkPathCurveTo(TkPathContext ctx, double ctrlX1, double ctrlY1,
	      double ctrlX2, double ctrlY2, double x, double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;

    if (context->c == NULL) {
	return;
    }
    if (gDepixelize) {
	x = PATH_DEPIXELIZE(context->widthCode, x);
	y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    CGContextAddCurveToPoint(context->c, ctrlX1, ctrlY1, ctrlX2, ctrlY2, x, y);
}

void
TkPathArcTo(TkPathContext ctx,
	    double rx, double ry,
	    double phiDegrees,		/* The rotation angle in degrees! */
	    char largeArcFlag, char sweepFlag, double x, double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;

    if (context->c == NULL) {
	return;
    }
    /* @@@ Should we try to use the native arc functions here? */
    if (gDepixelize) {
	x = PATH_DEPIXELIZE(context->widthCode, x);
	y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    TkPathArcToUsingBezier(ctx, rx, ry, phiDegrees, largeArcFlag, sweepFlag, x, y);
}

void
TkPathRect(TkPathContext ctx, double x, double y, double width, double height)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGRect r;

    if (context->c == NULL) {
	return;
    }
    if (gDepixelize) {
	x = PATH_DEPIXELIZE(context->widthCode, x);
	y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    r = CGRectMake(x, y, width, height);
    CGContextAddRect(context->c, r);
}

void
TkPathOval(TkPathContext ctx, double cx, double cy, double rx, double ry)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGRect r;

    if (context->c == NULL) {
	return;
    }
    r = CGRectMake(cx-rx, cy-ry, 2*rx, 2*ry);
    CGContextAddEllipseInRect(context->c, r);
}


CGInterpolationQuality convertInterpolationToCGInterpolation(int interpolation)
{
    switch (interpolation) {
	case kPathImageInterpolationNone:
	    return kCGInterpolationNone;
	case kPathImageInterpolationFast:
	    return kCGInterpolationLow;
	case kPathImageInterpolationBest:
	    return kCGInterpolationHigh;
	default:
	    return kCGInterpolationMedium;
    }
}

static void
FreePixelBuffer(void *data, const void *ptr, unsigned long size)
{
    ckfree((char *)data);
}

void
TkPathImage(TkPathContext ctx, Tk_Image image, Tk_PhotoHandle photo,
	    double x, double y, double width0, double height0,
	    double fillOpacity, XColor *tintColor, double tintAmount,
	    int interpolation, PathRect *srcRegion)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGImageRef cgImage;
    CGDataProviderRef provider;
    CGColorSpaceRef colorspace;
    CGImageAlphaInfo alphaInfo;
    size_t size;
    Tk_PhotoImageBlock block;
    unsigned char *data = NULL;
    unsigned char *ptr = NULL;
    unsigned char *srcPtr, *dstPtr;
    int srcR, srcG, srcB, srcA;	    /* The source pixel offsets. */
    int dstR, dstG, dstB, dstA;	    /* The destination pixel offsets. */
    int pitch;
    int iwidth, iheight;
    int i, j;

    if (context->c == NULL) {
	return;
    }
    /* Return value? */
    Tk_PhotoGetImage(photo, &block);
    size = block.pitch * block.height;
    iheight = block.height;
    iwidth = block.width;
    pitch = block.pitch;
    double width = (width0 == 0.0) ? (double)iwidth : width0;
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
     */
    srcR = dstR = block.offset[0];
    srcG = dstG = block.offset[1];
    srcB = dstB = block.offset[2];
    srcA = dstA = block.offset[3];

    if (srcA == 3) {
        alphaInfo = kCGImageAlphaLast;
    } else if (srcA == 0) {
        alphaInfo = kCGImageAlphaFirst;
    } else {
        /* @@@ What to do here? */
        return;
    }

    if (block.pixelSize == 4) {
        if ((srcR == dstR) && (srcG == dstG) && (srcB == dstB) &&
	    (srcA == dstA) && (fillOpacity >= 1.0) &&
	    ((tintAmount <= 0.0) || (tintColor == NULL))) {
            ptr = (unsigned char *) block.pixelPtr;
        } else {
            data = (unsigned char *) ckalloc(pitch*iheight);
            ptr = data;

            if (tintColor && tintAmount > 0.0) {
#ifdef TINT_INT_CALCULATION
                uint32_t tintR, tintG, tintB, uAmount, uRemain, uOpacity;

                if (tintAmount > 1.0)
                    tintAmount = 1.0;

                uAmount = (uint32_t)(tintAmount * 256.0);
                uRemain = 256 - uAmount;
                uOpacity = (uint32_t)(fillOpacity * 256.0);
                tintR = Red255FromXColorPtr(tintColor);
                tintG = Green255FromXColorPtr(tintColor);
                tintB = Blue255FromXColorPtr(tintColor);
                for (i = 0; i < iheight; i++) {
                    srcPtr = block.pixelPtr + i*pitch;
                    dstPtr = ptr + i*pitch;
                    for (j = 0; j < iwidth; j++) {
                        /* extract */
                        uint32_t r = *(srcPtr+srcR);
                        uint32_t g = *(srcPtr+srcG);
                        uint32_t b = *(srcPtr+srcB);
                        uint32_t a = *(srcPtr+srcA);

                        /* transform */
                        uint32_t lumAmount = /* 0-256 */
			    ((r * 6966 + g * 23436 + b * 2366) * uAmount) >> 23;
                        r = (uRemain * r + lumAmount * tintR);
                        g = (uRemain * g + lumAmount * tintG);
                        b = (uRemain * b + lumAmount * tintB);

                        /* fix range */
                        r = r>0xFFFF ? 0xFFFF : r;
                        g = g>0xFFFF ? 0xFFFF : g;
                        b = b>0xFFFF ? 0xFFFF : b;

                        /* and put back */
                        *(dstPtr+dstR) = r >> 8;
                        *(dstPtr+dstG) = g >> 8;
                        *(dstPtr+dstB) = b >> 8;
                        *(dstPtr+dstA) = (a * uOpacity) >> 8;
                        srcPtr += 4;
                        dstPtr += 4;
                    }
                }
#else
                float tintR, tintG, tintB;

                if (tintAmount > 1.0)
                    tintAmount = 1.0;

                tintR = RedFloatFromXColorPtr(tintColor);
                tintG = GreenFloatFromXColorPtr(tintColor);
                tintB = BlueFloatFromXColorPtr(tintColor);
                for (i = 0; i < iheight; i++) {
                    srcPtr = block.pixelPtr + i*pitch;
                    dstPtr = ptr + i*pitch;
                    for (j = 0; j < iwidth; j++) {
                        /* extract */
                        int r = *(srcPtr+srcR);
                        int g = *(srcPtr+srcG);
                        int b = *(srcPtr+srcB);

                        /* transform */
                        int lum = (int)(0.2126*r + 0.7152*g + 0.0722*b);
                        r = (int)((1.0-tintAmount)*r + tintAmount*lum*tintR);
                        g = (int)((1.0-tintAmount)*g + tintAmount*lum*tintG);
                        b = (int)((1.0-tintAmount)*b + tintAmount*lum*tintB);

                        /* fix range */
                        r = r<0 ? 0 : r>255 ? 255 : r;
                        g = g<0 ? 0 : g>255 ? 255 : g;
                        b = b<0 ? 0 : b>255 ? 255 : b;

                        /* and put back */
                        *(dstPtr+dstR) = r;
                        *(dstPtr+dstG) = g;
                        *(dstPtr+dstB) = b;
                        *(dstPtr+dstA) = *(srcPtr+srcA) * fillOpacity;
                        srcPtr += 4;
                        dstPtr += 4;
                    }
                }
#endif
            } else {
                for (i = 0; i < iheight; i++) {
                    srcPtr = block.pixelPtr + i*pitch;
                    dstPtr = ptr + i*pitch;
                    for (j = 0; j < iwidth; j++) {
                        *(dstPtr+dstR) = *(srcPtr+srcR);
                        *(dstPtr+dstG) = *(srcPtr+srcG);
                        *(dstPtr+dstB) = *(srcPtr+srcB);
                        *(dstPtr+dstA) = *(srcPtr+srcA) * fillOpacity;
                        srcPtr += 4;
                        dstPtr += 4;
                    }
                }
            }
        }
    } else {
        ptr = (unsigned char *) block.pixelPtr;
        return;
    }
    provider = CGDataProviderCreateWithData(NULL, ptr, size, NULL);
    colorspace = CGColorSpaceCreateDeviceRGB();
    cgImage = CGImageCreate(block.width, block.height,
            8, 				/* bitsPerComponent */
            block.pixelSize*8,	 	/* bitsPerPixel */
            block.pitch, 		/* bytesPerRow */
            colorspace,			/* colorspace */
            alphaInfo,			/* alphaInfo */
            provider, NULL,
            interpolation > 0 ? 1 : 0,  /* shouldInterpolate */
            kCGRenderingIntentDefault);
    CGDataProviderRelease(provider);
    CGColorSpaceRelease(colorspace);
    if (width == 0.0) {
        width = (double) block.width;
    }
    if (height == 0.0) {
        height = (double) block.height;
    }

    CGContextSaveGState(context->c);
    context->saveCount++;

    if (srcRegion != NULL) {
        width = (width0 == 0.0) ? srcRegion->x2 - srcRegion->x1 : width0;
        height = (height0 == 0.0) ? srcRegion->y2 - srcRegion->y1 : height0;
        double xscale = width / (srcRegion->x2 - srcRegion->x1);
        double yscale = height / (srcRegion->y2 - srcRegion->y1);
        CGContextSetInterpolationQuality(context->c,
		convertInterpolationToCGInterpolation(interpolation));
        CGContextTranslateCTM(context->c, x, y+height);
        CGContextScaleCTM(context->c, xscale, -yscale);
        CGContextClipToRect(context->c, CGRectMake(0.0, 0.0,
				width/xscale, height/yscale));
        CGContextDrawTiledImage(context->c,
                CGRectMake(srcRegion->x1, fmod(srcRegion->y2, iheight),
			   iwidth, iheight),
				cgImage);
    } else {
        /*
	 * Flip back to an upright coordinate system since
	 * CGContextDrawImage expect this.
	 */
        CGContextSetInterpolationQuality(context->c,
		convertInterpolationToCGInterpolation(interpolation));
        CGContextTranslateCTM(context->c, x, y+height);
        CGContextScaleCTM(context->c, 1, -1);
        CGContextDrawImage(context->c, CGRectMake(0.0, 0.0, width, height),
			   cgImage);
    }
    CGImageRelease(cgImage);
    CGContextRestoreGState(context->c);
    context->saveCount--;
    if (data) {
        ckfree((char *)data);
    }
}

void
TkPathClosePath(TkPathContext ctx)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;




    CGContextClosePath(context->c);
}

/*
 * @@@ Problems: don't want Tcl_Interp, finding matching font not
 * while processing options. Separate font style from layout???
 */


Boolean isItalic(enum FontSlant slant)
{
    switch(slant) {
        case PATH_TEXT_SLANT_NORMAL: return false;
        case PATH_TEXT_SLANT_ITALIC: return true;
        case PATH_TEXT_SLANT_OBLIQUE: return true;
        default: return false;
    }
}

Boolean
isBold(enum FontWeight weight)
{
    switch(weight) {
        case PATH_TEXT_WEIGHT_NORMAL: return false;
        case PATH_TEXT_WEIGHT_BOLD: return true;
        default: return false;
    }
}

int
TkPathTextConfig(Tcl_Interp *interp, Tk_PathTextStyle *textStylePtr,
		 char *utf8, void **customPtr)
{
    PathATSUIRecord	*recordPtr;
    ATSUStyle 		atsuStyle = NULL;
    ATSUTextLayout 	atsuLayout = NULL;
    CFStringRef 	cf;
    UniChar 		*buffer;
    CFRange 		range;
    CFIndex 		length;
    OSStatus 		err;
    Tcl_Encoding	enc;
    Tcl_DString		ds;




    if (utf8 == NULL) {
        return TCL_OK;
    }

    TkPathTextFree(textStylePtr, *customPtr);



    enc = Tcl_GetEncoding(NULL, "utf-8");
    Tcl_DStringInit(&ds);
    Tcl_UtfToExternalDString(enc, utf8, -1, &ds);
    Tcl_FreeEncoding(enc);
    cf = CFStringCreateWithCString(NULL, Tcl_DStringValue(&ds),
				   kCFStringEncodingUTF8);
    Tcl_DStringFree(&ds);
    length = CFStringGetLength(cf);
    if (length == 0) {

        return TCL_OK;
    }
    range = CFRangeMake(0, length);
    err = CreateATSUIStyle(textStylePtr->fontFamily, textStylePtr->fontSize,
			   isBold(textStylePtr->fontWeight),
			   isItalic(textStylePtr->fontSlant), &atsuStyle);
    if (err != noErr) {
        Tcl_SetObjResult(interp,
		Tcl_NewStringObj("font style couldn't be created", -1));
        return TCL_ERROR;
    }
    buffer = (UniChar *) ckalloc(length * sizeof(UniChar));
    CFStringGetCharacters(cf, range, buffer);
    err = CreateLayoutForString(buffer, length, atsuStyle, &atsuLayout);
    CFRelease(cf);
    if (err != noErr) {
        Tcl_SetObjResult(interp,
		Tcl_NewStringObj("text layout couldn't be created", -1));
        ckfree((char *)buffer);
        return TCL_ERROR;
    }
    recordPtr = (PathATSUIRecord *) ckalloc(sizeof(PathATSUIRecord));
    recordPtr->atsuStyle = atsuStyle;
    recordPtr->atsuLayout = atsuLayout;








    recordPtr->buffer = buffer;
    int i, j;
    recordPtr->nl[0] = 0;
    for (i = 0, j = 1; i < length; i++) {
        if ((j < MAX_NL) && (buffer[i] == '\n')) {
            recordPtr->nl[j++] = i + 1;
            buffer[i] = 0x2028;
        }
    }
    recordPtr->nl[j] = i + 1;
    recordPtr->nlc = j;
    *customPtr = (PathATSUIRecord *) recordPtr;
    return TCL_OK;
}

static void drawMultilineText(PathATSUIRecord *recordPtr)

{
    int i;


    for (i = 0; i < recordPtr->nlc; i++) {
        ATSUDrawText(recordPtr->atsuLayout, recordPtr->nl[i],
		     recordPtr->nl[i+1] - recordPtr->nl[i] - 1,
















		     recordPtr->dx[i], recordPtr->dy[i]);


    }

}

void
TkPathTextDraw(TkPathContext ctx, Tk_PathStyle *style,
	       Tk_PathTextStyle *textStylePtr,
	       double x, double y, int fillOverStroke,
	       char *utf8, void *custom)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    PathATSUIRecord *recordPtr = (PathATSUIRecord *) custom;

    ByteCount iSize = sizeof(CGContextRef);

    ATSUAttributeTag iTag = kATSUCGContextTag;
    ATSUAttributeValuePtr iValuePtr = &(context->c);


    ATSUSetLayoutControls(recordPtr->atsuLayout, 1, &iTag, &iSize, &iValuePtr);
    CGContextSaveGState(context->c);
    context->saveCount++;
    CGContextTranslateCTM(context->c, x, y);
    CGContextScaleCTM(context->c, 1, -1);












    if ((style->strokeColor != NULL) &&
	(GetColorFromPathColor(style->fill) != NULL)) {
        CGContextSetTextDrawingMode(context->c, fillOverStroke ?
				    kCGTextStroke : kCGTextFill);
        drawMultilineText(recordPtr);
        CGContextSetTextDrawingMode(context->c, fillOverStroke ?
				    kCGTextFill : kCGTextStroke);
        drawMultilineText(recordPtr);
    } else {
        drawMultilineText(recordPtr);
    }
    CGContextRestoreGState(context->c);
    context->saveCount--;
}

void
TkPathTextFree(Tk_PathTextStyle *textStylePtr, void *custom)
{
    PathATSUIRecord *recordPtr = (PathATSUIRecord *) custom;

    if (recordPtr) {
        if (recordPtr->atsuStyle) {
            ATSUDisposeStyle(recordPtr->atsuStyle);

        }
        if (recordPtr->atsuLayout) {
            ATSUDisposeTextLayout(recordPtr->atsuLayout);

        }
        if (recordPtr->buffer) {

            ckfree((char *) recordPtr->buffer);
        }

    }
}

PathRect
TkPathTextMeasureBbox(Display *display, Tk_PathTextStyle *textStylePtr,
		      char *utf8, double *lineSpacing, void *custom)
{
    PathATSUIRecord *recordPtr = (PathATSUIRecord *) custom;
    PathRect r,ri;
    int i;
    ATSTrapezoid b;
    ItemCount numBounds;
    double x = 0.0;
    double y = 0.0;
    double baseX = 0.0;
    double lineSp = 0;


    for (i = 0; i < recordPtr->nlc; i++) {





        b.upperRight.x = b.upperLeft.x = 0;







        ATSUGetGlyphBounds(recordPtr->atsuLayout, 0, 0,

                recordPtr->nl[i], recordPtr->nl[i+1] - recordPtr->nl[i] - 1,



                kATSUseFractionalOrigins, 1, &b, &numBounds);

        ri.x1 = MIN(Fix2X(b.upperLeft.x), Fix2X(b.lowerLeft.x));
        ri.y1 = MIN(Fix2X(b.upperLeft.y), Fix2X(b.upperRight.y));
        ri.x2 = MAX(Fix2X(b.upperRight.x), Fix2X(b.lowerRight.x));
        ri.y2 = MAX(Fix2X(b.lowerLeft.y), Fix2X(b.lowerRight.y));
        if (i == 0) {
            baseX = ri.x1;
            r.x1 = ri.x1;
            r.y1 = ri.y1;
            r.x2 = ri.x2;
            r.y2 = ri.y2;
        } else {
            x = ri.x1 - baseX;
            ri.x1 -= x;
            ri.y1 += y;
            ri.x2 -= x;
            ri.y2 += y;
            if (r.x1 > ri.x1) r.x1 = ri.x1;
            if (r.y1 > ri.y1) r.y1 = ri.y1;
            if (r.x2 < ri.x2) r.x2 = ri.x2;
            if (r.y2 < ri.y2) r.y2 = ri.y2;
        }
        recordPtr->dx[i] = X2Fix(-x);
        recordPtr->dy[i] = X2Fix(-y);
        y = r.y2 - r.y1;
	lineSp += y;
    }

    if (lineSpacing != NULL && i > 0) {
	*lineSpacing = lineSp / i;
    }








|

|

|
|



|


|
|
|
|

|

|

|
|
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|

|
|
|

|
|
|
|

|
|
|
|
|
|
|
|
|

|

|
|
>
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|

|
|
|
|

|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|

|
|

|
|
|
|
|
|
|
|

<

|


|






|
|
|
|
|

|
|
|

|
|



|



|

|
|
|





<
<
<







>
>
>








>
|


|
|
|
|



|



|
|
|







|
|
<
|
|
|
|
<


>
>
>


|

>
|
>
>










>
|


|
|
|
|
|
|
|

|

<

<
<
<
<
<
<
|
|
|
>
>
>
>
>
>
>
>

<


|
|
|
|



|



|
>



>

|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>

>








|
|
>
|
>
|
|
>
|
<




>
>
>
>
>
>
>
>
>
>
>
>


|

|
|

|

|








|


|
|
>
|
|
|
>
|
|
>
|
|
>







|
|

<
<




>


>
>
>
>
>
|
>
>
>
>
>
>
|
<
>
|
>
>
>
|
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|







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
     */
    srcR = dstR = block.offset[0];
    srcG = dstG = block.offset[1];
    srcB = dstB = block.offset[2];
    srcA = dstA = block.offset[3];

    if (srcA == 3) {
	alphaInfo = kCGImageAlphaLast;
    } else if (srcA == 0) {
	alphaInfo = kCGImageAlphaFirst;
    } else {
	/* @@@ What to do here? */
	return;
    }

    if (block.pixelSize == 4) {
	if ((srcR == dstR) && (srcG == dstG) && (srcB == dstB) &&
	    (srcA == dstA) && (fillOpacity >= 1.0) &&
	    ((tintAmount <= 0.0) || (tintColor == NULL))) {
	    ptr = (unsigned char *) block.pixelPtr;
	} else {
	    data = (unsigned char *)ckalloc(pitch*iheight);
	    ptr = data;

	    if (tintColor && tintAmount > 0.0) {
#ifdef TINT_INT_CALCULATION
		uint32_t tintR, tintG, tintB, uAmount, uRemain, uOpacity;

		if (tintAmount > 1.0) {
		    tintAmount = 1.0;
		}
		uAmount = (uint32_t)(tintAmount * 256.0);
		uRemain = 256 - uAmount;
		uOpacity = (uint32_t)(fillOpacity * 256.0);
		tintR = Red255FromXColorPtr(tintColor);
		tintG = Green255FromXColorPtr(tintColor);
		tintB = Blue255FromXColorPtr(tintColor);
		for (i = 0; i < iheight; i++) {
		    srcPtr = block.pixelPtr + i*pitch;
		    dstPtr = ptr + i*pitch;
		    for (j = 0; j < iwidth; j++) {
			/* extract */
			uint32_t r = *(srcPtr+srcR);
			uint32_t g = *(srcPtr+srcG);
			uint32_t b = *(srcPtr+srcB);
			uint32_t a = *(srcPtr+srcA);

			/* transform */
			uint32_t lumAmount = /* 0-256 */
			    ((r * 6966 + g * 23436 + b * 2366) * uAmount) >> 23;
			r = (uRemain * r + lumAmount * tintR);
			g = (uRemain * g + lumAmount * tintG);
			b = (uRemain * b + lumAmount * tintB);

			/* fix range */
			r = (r>0xFFFF) ? 0xFFFF : r;
			g = (g>0xFFFF) ? 0xFFFF : g;
			b = (b>0xFFFF) ? 0xFFFF : b;

			/* and put back */
			*(dstPtr+dstR) = r >> 8;
			*(dstPtr+dstG) = g >> 8;
			*(dstPtr+dstB) = b >> 8;
			*(dstPtr+dstA) = (a * uOpacity) >> 8;
			srcPtr += 4;
			dstPtr += 4;
		    }
		}
#else
		float tintR, tintG, tintB;

		if (tintAmount > 1.0) {
		    tintAmount = 1.0;
		}
		tintR = RedFloatFromXColorPtr(tintColor);
		tintG = GreenFloatFromXColorPtr(tintColor);
		tintB = BlueFloatFromXColorPtr(tintColor);
		for (i = 0; i < iheight; i++) {
		    srcPtr = block.pixelPtr + i*pitch;
		    dstPtr = ptr + i*pitch;
		    for (j = 0; j < iwidth; j++) {
			/* extract */
			int r = *(srcPtr+srcR);
			int g = *(srcPtr+srcG);
			int b = *(srcPtr+srcB);

			/* transform */
			int lum = (int)(0.2126*r + 0.7152*g + 0.0722*b);
			r = (int)((1.0-tintAmount)*r + tintAmount*lum*tintR);
			g = (int)((1.0-tintAmount)*g + tintAmount*lum*tintG);
			b = (int)((1.0-tintAmount)*b + tintAmount*lum*tintB);

			/* fix range */
			r = (r<0) ? 0 : (r>255) ? 255 : r;
			g = (g<0) ? 0 : (g>255) ? 255 : g;
			b = (b<0) ? 0 : (b>255) ? 255 : b;

			/* and put back */
			*(dstPtr+dstR) = r;
			*(dstPtr+dstG) = g;
			*(dstPtr+dstB) = b;
			*(dstPtr+dstA) = *(srcPtr+srcA) * fillOpacity;
			srcPtr += 4;
			dstPtr += 4;
		    }
		}
#endif
	    } else {
		for (i = 0; i < iheight; i++) {
		    srcPtr = block.pixelPtr + i*pitch;
		    dstPtr = ptr + i*pitch;
		    for (j = 0; j < iwidth; j++) {
			*(dstPtr+dstR) = *(srcPtr+srcR);
			*(dstPtr+dstG) = *(srcPtr+srcG);
			*(dstPtr+dstB) = *(srcPtr+srcB);
			*(dstPtr+dstA) = *(srcPtr+srcA) * fillOpacity;
			srcPtr += 4;
			dstPtr += 4;
		    }
		}
	    }
	}
    } else {
	ptr = (unsigned char *) block.pixelPtr;
	return;
    }
    provider = CGDataProviderCreateWithData(data, ptr, size, FreePixelBuffer);
    colorspace = GetTheColorSpaceRef();
    cgImage = CGImageCreate(block.width, block.height,
	    8,				/* bitsPerComponent */
	    block.pixelSize*8,		/* bitsPerPixel */
	    block.pitch,		/* bytesPerRow */
	    colorspace,			/* colorspace */
	    (CGBitmapInfo) alphaInfo,	/* alphaInfo */
	    provider, NULL,
	    (interpolation > 0) ? 1 : 0,/* shouldInterpolate */
	    kCGRenderingIntentDefault);
    CGDataProviderRelease(provider);

    if (width == 0.0) {
	width = (double) block.width;
    }
    if (height == 0.0) {
	height = (double) block.height;
    }

    CGContextSaveGState(context->c);
    context->saveCount++;

    if (srcRegion != NULL) {
	width = (width0 == 0.0) ? srcRegion->x2 - srcRegion->x1 : width0;
	height = (height0 == 0.0) ? srcRegion->y2 - srcRegion->y1 : height0;
	double xscale = width / (srcRegion->x2 - srcRegion->x1);
	double yscale = height / (srcRegion->y2 - srcRegion->y1);
	CGContextSetInterpolationQuality(context->c,
		convertInterpolationToCGInterpolation(interpolation));
	CGContextTranslateCTM(context->c, x, y+height);
	CGContextScaleCTM(context->c, xscale, -yscale);
	CGContextClipToRect(context->c, CGRectMake(0.0, 0.0,
				width/xscale, height/yscale));
	CGContextDrawTiledImage(context->c,
		CGRectMake(srcRegion->x1, fmod(srcRegion->y2, iheight),
			   iwidth, iheight),
				cgImage);
    } else {
	/*
	 * Flip back to an upright coordinate system since
	 * CGContextDrawImage expect this.
	 */
	CGContextSetInterpolationQuality(context->c,
		convertInterpolationToCGInterpolation(interpolation));
	CGContextTranslateCTM(context->c, x, y+height);
	CGContextScaleCTM(context->c, 1, -1);
	CGContextDrawImage(context->c, CGRectMake(0.0, 0.0, width, height),
			   cgImage);
    }
    CGImageRelease(cgImage);
    CGContextRestoreGState(context->c);
    context->saveCount--;



}

void
TkPathClosePath(TkPathContext ctx)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;

    if (context->c == NULL) {
	return;
    }
    CGContextClosePath(context->c);
}

/*
 * @@@ Problems: don't want Tcl_Interp, finding matching font not
 * while processing options. Separate font style from layout???
 */

static Boolean
isItalic(enum FontSlant slant)
{
    switch(slant) {
	case PATH_TEXT_SLANT_NORMAL: return false;
	case PATH_TEXT_SLANT_ITALIC: return true;
	case PATH_TEXT_SLANT_OBLIQUE: return true;
	default: return false;
    }
}

static Boolean
isBold(enum FontWeight weight)
{
    switch(weight) {
	case PATH_TEXT_WEIGHT_NORMAL: return false;
	case PATH_TEXT_WEIGHT_BOLD: return true;
	default: return false;
    }
}

int
TkPathTextConfig(Tcl_Interp *interp, Tk_PathTextStyle *textStylePtr,
		 char *utf8, void **customPtr)
{
    PathTextRecord	*recordPtr;
    CTFontRef		fontRef = NULL;

    CFStringRef		cf;
    UniChar		*buffer;
    CFRange		range;
    CFIndex		length;

    Tcl_Encoding	enc;
    Tcl_DString		ds;
    int			err, i, j;
    float		zero = 0.0;
    CFNumberRef		zeroRef;

    if (utf8 == NULL) {
	return TCL_OK;
    }
    if (*customPtr) {
	TkPathTextFree(textStylePtr, *customPtr);
	*customPtr = NULL;
    }

    enc = Tcl_GetEncoding(NULL, "utf-8");
    Tcl_DStringInit(&ds);
    Tcl_UtfToExternalDString(enc, utf8, -1, &ds);
    Tcl_FreeEncoding(enc);
    cf = CFStringCreateWithCString(NULL, Tcl_DStringValue(&ds),
				   kCFStringEncodingUTF8);
    Tcl_DStringFree(&ds);
    length = CFStringGetLength(cf);
    if (length == 0) {
	CFRelease(cf);
	return TCL_OK;
    }
    range = CFRangeMake(0, length);
    err = CreateTextStyle(textStylePtr->fontFamily, textStylePtr->fontSize,
			  isBold(textStylePtr->fontWeight),
			  isItalic(textStylePtr->fontSlant), &fontRef);
    if (err != 0) {
	CFRelease(cf);
	Tcl_SetResult(interp, "font style couldn't be created", TCL_STATIC);
	return TCL_ERROR;
    }
    buffer = (UniChar *)ckalloc(length * sizeof(UniChar));
    CFStringGetCharacters(cf, range, buffer);

    CFRelease(cf);






    recordPtr = (PathTextRecord *)ckalloc(sizeof(PathTextRecord));
    recordPtr->fontRef = fontRef;
    recordPtr->fontAttr =
	CFDictionaryCreateMutable(kCFAllocatorDefault,
				  2,
				  &kCFTypeDictionaryKeyCallBacks,
				  &kCFTypeDictionaryValueCallBacks);
    zeroRef = CFNumberCreate(NULL, kCFNumberFloat32Type, &zero);
    CFDictionarySetValue(recordPtr->fontAttr, kCTKernAttributeName, zeroRef);
    CFRelease(zeroRef);
    CFDictionarySetValue(recordPtr->fontAttr, kCTFontAttributeName, fontRef);
    recordPtr->buffer = buffer;

    recordPtr->nl[0] = 0;
    for (i = 0, j = 1; i < length; i++) {
	if ((j < MAX_NL) && (buffer[i] == '\n')) {
	    recordPtr->nl[j++] = i + 1;
	    buffer[i] = 0x2028;
	}
    }
    recordPtr->nl[j] = i + 1;
    recordPtr->nlc = j;
    *customPtr = (PathTextRecord *) recordPtr;
    return TCL_OK;
}

static void
drawMultilineText(CGContextRef c, PathTextRecord *recordPtr)
{
    int i;

    CGContextSetShouldAntialias(c, true);
    for (i = 0; i < recordPtr->nlc; i++) {
	UniChar *start = recordPtr->buffer + recordPtr->nl[i];
	int len = recordPtr->nl[i+1] - recordPtr->nl[i] - 1;
	CFMutableStringRef str;
	CFAttributedStringRef mastr;
	CTLineRef ctline;

	str =
	    CFStringCreateMutableWithExternalCharactersNoCopy(NULL, start,
							      len, len,
							      kCFAllocatorNull);
	if (str == NULL) {
	    continue;
	}
	mastr = CFAttributedStringCreate(kCFAllocatorDefault, str,
					 recordPtr->fontAttr);
	CFRelease(str);
	ctline = CTLineCreateWithAttributedString(mastr);
	CFRelease(mastr);
	CGContextSetTextPosition(c, recordPtr->dx[i], recordPtr->dy[i]);
	CTLineDraw(ctline, c);
	CFRelease(ctline);
    }
    CGContextSetShouldAntialias(c, gAntiAlias);
}

void
TkPathTextDraw(TkPathContext ctx, Tk_PathStyle *style,
	       Tk_PathTextStyle *textStylePtr,
	       double x, double y, int fillOverStroke,
	       char *utf8, void *custom)
{
    TkPathContext_	*context = (TkPathContext_ *) ctx;
    PathTextRecord	*recordPtr = (PathTextRecord *) custom;
    CGColorSpaceRef	colorSpaceRef;
    CGColorRef		fgColor;
    CGFloat		rgba[4] = {0, 0, 0, 1};

    if (context->c == NULL) {
	return;
    }

    CGContextSaveGState(context->c);
    context->saveCount++;
    CGContextTranslateCTM(context->c, x, y);
    CGContextScaleCTM(context->c, 1, -1);
    colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    if ((style->fill != NULL) && (style->fill->color != NULL)) {
	rgba[0] = RedFloatFromXColorPtr(style->fill->color);
	rgba[1] = GreenFloatFromXColorPtr(style->fill->color);
	rgba[2] = BlueFloatFromXColorPtr(style->fill->color);
	rgba[3] = style->fillOpacity;
    }
    fgColor = CGColorCreate(colorSpaceRef, rgba);
    CFDictionarySetValue(recordPtr->fontAttr, kCTForegroundColorAttributeName,
			 fgColor);
    CGColorSpaceRelease(colorSpaceRef);
    CFRelease(fgColor);
    if ((style->strokeColor != NULL) &&
	(GetColorFromPathColor(style->fill) != NULL)) {
	CGContextSetTextDrawingMode(context->c, fillOverStroke ?
				    kCGTextStroke : kCGTextFill);
	drawMultilineText(context->c, recordPtr);
	CGContextSetTextDrawingMode(context->c, fillOverStroke ?
				    kCGTextFill : kCGTextStroke);
	drawMultilineText(context->c, recordPtr);
    } else {
	drawMultilineText(context->c, recordPtr);
    }
    CGContextRestoreGState(context->c);
    context->saveCount--;
}

void
TkPathTextFree(Tk_PathTextStyle *textStylePtr, void *custom)
{
    PathTextRecord *recordPtr = (PathTextRecord *) custom;

    if (recordPtr) {
	if (recordPtr->fontRef) {
	    CFRelease(recordPtr->fontRef);
	    recordPtr->fontRef = NULL;
	}
	if (recordPtr->fontAttr) {
	    CFRelease(recordPtr->fontAttr);
	    recordPtr->fontAttr = NULL;
	}
	if (recordPtr->buffer) {
	    ckfree((char *)recordPtr->buffer);
	    recordPtr->buffer = NULL;
	}
	ckfree((char *)recordPtr);
    }
}

PathRect
TkPathTextMeasureBbox(Display *display, Tk_PathTextStyle *textStylePtr,
		      char *utf8, double *lineSpacing, void *custom)
{
    PathTextRecord *recordPtr = (PathTextRecord *) custom;
    PathRect r, ri;
    int i;


    double x = 0.0;
    double y = 0.0;
    double baseX = 0.0;
    double lineSp = 0;
    CGFloat width, leading, ascent, descent;

    for (i = 0; i < recordPtr->nlc; i++) {
	UniChar *start = recordPtr->buffer + recordPtr->nl[i];
	int len = recordPtr->nl[i+1] - recordPtr->nl[i] - 1;
	CFMutableStringRef str;
	CFAttributedStringRef mastr;
	CTLineRef ctline;

	str =
	    CFStringCreateMutableWithExternalCharactersNoCopy(NULL, start,
							      len, len,
							      kCFAllocatorNull);
	if (str == NULL) {
	    continue;
	}

	mastr = CFAttributedStringCreate(kCFAllocatorDefault, str,
					 recordPtr->fontAttr);
	CFRelease(str);
	ctline = CTLineCreateWithAttributedString(mastr);
	CFRelease(mastr);
	width = CTLineGetTypographicBounds(ctline, &ascent, &descent, &leading);
	CFRelease(ctline);
	ri.x1 = leading;
	ri.y1 = ascent;
	ri.x2 = width;
	ri.y2 = descent;
	if (i == 0) {
	    baseX = ri.x1;
	    r.x1 = ri.x1;
	    r.y1 = ri.y1;
	    r.x2 = ri.x2;
	    r.y2 = ri.y2;
	} else {
	    x = ri.x1 - baseX;
	    ri.x1 -= x;
	    ri.y1 += y;
	    ri.x2 -= x;
	    ri.y2 += y;
	    if (r.x1 > ri.x1) r.x1 = ri.x1;
	    if (r.y1 > ri.y1) r.y1 = ri.y1;
	    if (r.x2 < ri.x2) r.x2 = ri.x2;
	    if (r.y2 < ri.y2) r.y2 = ri.y2;
	}
	recordPtr->dx[i] = -x;
	recordPtr->dy[i] = -y;
	y = r.y2 - r.y1;
	lineSp += y;
    }

    if (lineSpacing != NULL && i > 0) {
	*lineSpacing = lineSp / i;
    }

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
1223
1224
1225
1226
1227
1228
1229
1230




1231
1232
1233
1234
1235
1236
1237
1238
1239
1240



1241
1242
1243
1244
1245
1246
1247
1248



1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260



1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298

1299
1300
1301
1302
1303
1304
1305
1306
1307
1308

    width = CGBitmapContextGetWidth(c);
    height = CGBitmapContextGetHeight(c);
    data = CGBitmapContextGetData(c);
    bytesPerRow = CGBitmapContextGetBytesPerRow(c);

    Tk_PhotoGetImage(photo, &block);
    pixel = (unsigned char *) attemptckalloc(height*bytesPerRow);
    if (pixel == NULL) {
        return;
    }
    if (gSurfaceCopyPremultiplyAlpha) {
        PathCopyBitsPremultipliedAlphaRGBA(data, pixel, width, height,
					   bytesPerRow);
    } else {
        memcpy(pixel, data, height*bytesPerRow);
    }
    block.pixelPtr = pixel;
    block.width = width;
    block.height = height;
    block.pitch = bytesPerRow;
    block.pixelSize = 4;
    block.offset[0] = 0;
    block.offset[1] = 1;
    block.offset[2] = 2;
    block.offset[3] = 3;
    /* Should change this to check for errors... */
    Tk_PhotoPutBlock(interp, photo, &block, 0, 0, width, height,
		     TK_PHOTO_COMPOSITE_OVERLAY);
    ckfree((char *) pixel);
}

void
TkPathClipToPath(TkPathContext ctx, int fillRule)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;





    /*
     * If you need to grow the clipping path after it’s shrunk,
     * you must save the graphics state before you clip, then
     * restore the graphics state to restore the current clipping path.
     */
    CGContextSaveGState(context->c);
    context->saveCount++;
    if (fillRule == WindingRule) {
        CGContextClip(context->c);
    } else if (fillRule == EvenOddRule) {
        CGContextEOClip(context->c);
    }
}

void
TkPathReleaseClipToPath(TkPathContext ctx)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;





    CGContextRestoreGState(context->c);
    context->saveCount--;
}

void
TkPathStroke(TkPathContext ctx, Tk_PathStyle *style)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;




    CGContextStrokePath(context->c);
}

void
TkPathFill(TkPathContext ctx, Tk_PathStyle *style)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;




    if (style->fillRule == WindingRule) {
        CGContextFillPath(context->c);
    } else if (style->fillRule == EvenOddRule) {
        CGContextEOFillPath(context->c);
    }
}

void
TkPathFillAndStroke(TkPathContext ctx, Tk_PathStyle *style)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;




    if (style->fillRule == WindingRule) {
        CGContextDrawPath(context->c, kCGPathFillStroke);
    } else if (style->fillRule == EvenOddRule) {
        CGContextDrawPath(context->c, kCGPathEOFillStroke);
    }
}

void
TkPathEndPath(TkPathContext ctx)
{
    /* TkPathContext_ *context = (TkPathContext_ *) ctx; */
    /* Empty ??? */
}

void
TkPathFree(TkPathContext ctx)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;

    PathReleaseCGContext(context);
    if (context->data) {
        ckfree(context->data);
    }
    ckfree((char *) ctx);
}

int
TkPathDrawingDestroysPath(void)
{
    return 1;
}

int
TkPathPixelAlign(void)
{
    return 0;
}


/* TkPathGetCurrentPosition --
 *
 * 	Returns the current pen position in untransformed coordinates!
 */

int
TkPathGetCurrentPosition(TkPathContext ctx, PathPoint *ptPtr)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGPoint cgpt;







|

|


|


|













|







>
>
>
>

|






|

|







>
>
>
>










>
>
>








>
>
>

|

|








>
>
>

|

|

















|

|














>
|

|







1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387

    width = CGBitmapContextGetWidth(c);
    height = CGBitmapContextGetHeight(c);
    data = CGBitmapContextGetData(c);
    bytesPerRow = CGBitmapContextGetBytesPerRow(c);

    Tk_PhotoGetImage(photo, &block);
    pixel = (unsigned char *)attemptckalloc(height*bytesPerRow);
    if (pixel == NULL) {
	return;
    }
    if (gSurfaceCopyPremultiplyAlpha) {
	PathCopyBitsPremultipliedAlphaRGBA(data, pixel, width, height,
					   bytesPerRow);
    } else {
	memcpy(pixel, data, height*bytesPerRow);
    }
    block.pixelPtr = pixel;
    block.width = width;
    block.height = height;
    block.pitch = bytesPerRow;
    block.pixelSize = 4;
    block.offset[0] = 0;
    block.offset[1] = 1;
    block.offset[2] = 2;
    block.offset[3] = 3;
    /* Should change this to check for errors... */
    Tk_PhotoPutBlock(interp, photo, &block, 0, 0, width, height,
		     TK_PHOTO_COMPOSITE_OVERLAY);
    ckfree((char *)pixel);
}

void
TkPathClipToPath(TkPathContext ctx, int fillRule)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;

    if (context->c == NULL) {
	return;
    }

    /*
     * If you need to grow the clipping path after it is shrunk,
     * you must save the graphics state before you clip, then
     * restore the graphics state to restore the current clipping path.
     */
    CGContextSaveGState(context->c);
    context->saveCount++;
    if (fillRule == WindingRule) {
	CGContextClip(context->c);
    } else if (fillRule == EvenOddRule) {
	CGContextEOClip(context->c);
    }
}

void
TkPathReleaseClipToPath(TkPathContext ctx)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;

    if (context->c == NULL) {
	return;
    }

    CGContextRestoreGState(context->c);
    context->saveCount--;
}

void
TkPathStroke(TkPathContext ctx, Tk_PathStyle *style)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;

    if (context->c == NULL) {
	return;
    }
    CGContextStrokePath(context->c);
}

void
TkPathFill(TkPathContext ctx, Tk_PathStyle *style)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;

    if (context->c == NULL) {
	return;
    }
    if (style->fillRule == WindingRule) {
	CGContextFillPath(context->c);
    } else if (style->fillRule == EvenOddRule) {
	CGContextEOFillPath(context->c);
    }
}

void
TkPathFillAndStroke(TkPathContext ctx, Tk_PathStyle *style)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;

    if (context->c == NULL) {
	return;
    }
    if (style->fillRule == WindingRule) {
	CGContextDrawPath(context->c, kCGPathFillStroke);
    } else if (style->fillRule == EvenOddRule) {
	CGContextDrawPath(context->c, kCGPathEOFillStroke);
    }
}

void
TkPathEndPath(TkPathContext ctx)
{
    /* TkPathContext_ *context = (TkPathContext_ *) ctx; */
    /* Empty ??? */
}

void
TkPathFree(TkPathContext ctx)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;

    PathReleaseCGContext(context);
    if (context->data) {
	ckfree(context->data);
    }
    ckfree((char *)ctx);
}

int
TkPathDrawingDestroysPath(void)
{
    return 1;
}

int
TkPathPixelAlign(void)
{
    return 0;
}

/*
 * TkPathGetCurrentPosition --
 *
 *	Returns the current pen position in untransformed coordinates!
 */

int
TkPathGetCurrentPosition(TkPathContext ctx, PathPoint *ptPtr)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGPoint cgpt;
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407





1408
1409
1410

1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440


1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456





1457
1458
1459

1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
/*
 * Using CGShading for fill gradients.
 */

static void
ShadeEvaluate(void *info, const CGFloat *in, CGFloat *out)
{
    FillInfo            *fillInfo = (FillInfo *)info;
    GradientStopArray 	*stopArrPtr = fillInfo->stopArrPtr;
    double              fillOpacity = fillInfo->fillOpacity;
    GradientStop        **stopPtrPtr = stopArrPtr->stops;
    GradientStop	*stop1 = NULL, *stop2 = NULL;
    int			nstops = stopArrPtr->nstops;
    int			i = 0;
    float 		par = *in;
    float		f1, f2;

    /* Find the two stops for this point. Tricky! */
    while ((i < nstops) && ((*stopPtrPtr)->offset < par)) {
        stopPtrPtr++, i++;
    }
    if (i == 0) {
        /* First stop > 0. */
        stop1 = *stopPtrPtr;
        stop2 = stop1;
    } else if (i == nstops) {
        /* We have stepped beyond the last stop; step back! */
        stop1 = *(stopPtrPtr - 1);
        stop2 = stop1;
    } else {
        stop1 = *(stopPtrPtr - 1);
        stop2 = *stopPtrPtr;
    }
    /*
     * Interpolate between the two stops.
     * "If two gradient stops have the same offset value,
     * then the latter gradient stop controls the color value at the
     * overlap point."
     */
    if (fabs(stop2->offset - stop1->offset) < 1e-6) {
        *out++ = RedFloatFromXColorPtr(stop2->color);
        *out++ = GreenFloatFromXColorPtr(stop2->color);
        *out++ = BlueFloatFromXColorPtr(stop2->color);
        *out++ = stop2->opacity * fillOpacity;
    } else {
        f1 = (stop2->offset - par)/(stop2->offset - stop1->offset);
        f2 = (par - stop1->offset)/(stop2->offset - stop1->offset);
        *out++ = f1 * RedFloatFromXColorPtr(stop1->color) +
                f2 * RedFloatFromXColorPtr(stop2->color);
        *out++ = f1 * GreenFloatFromXColorPtr(stop1->color) +
                f2 * GreenFloatFromXColorPtr(stop2->color);
        *out++ = f1 * BlueFloatFromXColorPtr(stop1->color) +
                f2 * BlueFloatFromXColorPtr(stop2->color);
        *out++ = (f1 * stop1->opacity + f2 * stop2->opacity) * fillOpacity;
    }
}

static void
ShadeRelease(void *info)
{
    /* Not sure if anything to do here. */
}

void
TkPathPaintLinearGradient(TkPathContext ctx, PathRect *bbox,
			  LinearGradientFill *fillPtr, int fillRule,
			  double fillOpacity, TMatrix *mPtr)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGShadingRef 		shading;
    CGPoint 			start, end;
    CGColorSpaceRef	 	colorSpaceRef;
    CGFunctionRef 		function;
    CGFunctionCallbacks		callbacks;
    PathRect 			*trans = fillPtr->transitionPtr;
    FillInfo			fillInfo;






    fillInfo.fillOpacity = fillOpacity;
    fillInfo.stopArrPtr = fillPtr->stopArrPtr;


    callbacks.version = 0;
    callbacks.evaluate = ShadeEvaluate;
    callbacks.releaseInfo = ShadeRelease;
    colorSpaceRef = CGColorSpaceCreateDeviceRGB();

    /*
     * We need to do like this since this is how SVG defines gradient drawing
     * in case the transition vector is in relative coordinates.
     */
    CGContextSaveGState(context->c);
    context->saveCount++;
    if (fillPtr->units == kPathGradientUnitsBoundingBox) {
        CGContextTranslateCTM(context->c, bbox->x1, bbox->y1);
        CGContextScaleCTM(context->c, bbox->x2 - bbox->x1, bbox->y2 - bbox->y1);
    }
    function = CGFunctionCreate((void *) &fillInfo, 1, kValidDomain, 4,
				kValidRange, &callbacks);
    start = CGPointMake(trans->x1, trans->y1);
    end   = CGPointMake(trans->x2, trans->y2);
    shading = CGShadingCreateAxial(colorSpaceRef, start, end, function, 1, 1);
    if (mPtr) {
        /* @@@ I'm not completely sure of the order of transforms here! */
        TkPathPushTMatrix(ctx, mPtr);
    }
    CGContextDrawShading(context->c, shading);
    CGContextRestoreGState(context->c);
    context->saveCount--;
    CGShadingRelease(shading);
    CGFunctionRelease(function);
    CGColorSpaceRelease(colorSpaceRef);


}

void
TkPathPaintRadialGradient(TkPathContext ctx, PathRect *bbox,
			  RadialGradientFill *fillPtr, int fillRule,
			  double fillOpacity, TMatrix *mPtr)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGShadingRef 		shading;
    CGPoint 			start, end;
    CGColorSpaceRef 		colorSpaceRef;
    CGFunctionRef 		function;
    CGFunctionCallbacks		callbacks;
    RadialTransition		*tPtr = fillPtr->radialPtr;
    FillInfo			fillInfo;






    fillInfo.fillOpacity = fillOpacity;
    fillInfo.stopArrPtr = fillPtr->stopArrPtr;


    callbacks.version = 0;
    callbacks.evaluate = ShadeEvaluate;
    callbacks.releaseInfo = ShadeRelease;
    colorSpaceRef = CGColorSpaceCreateDeviceRGB();

    /*
     * We need to do like this since this is how SVG defines gradient drawing
     * in case the transition vector is in relative coordinates.
     */
    if (fillPtr->units == kPathGradientUnitsBoundingBox) {
        CGContextSaveGState(context->c);
	context->saveCount++;
        CGContextTranslateCTM(context->c, bbox->x1, bbox->y1);
        CGContextScaleCTM(context->c, bbox->x2 - bbox->x1, bbox->y2 - bbox->y1);
    }
    function = CGFunctionCreate((void *) &fillInfo, 1, kValidDomain, 4,
				kValidRange, &callbacks);
    start = CGPointMake(tPtr->focalX, tPtr->focalY);
    end   = CGPointMake(tPtr->centerX, tPtr->centerY);
    shading = CGShadingCreateRadial(colorSpaceRef, start, 0.0, end,
				    tPtr->radius, function, 1, 1);
    if (mPtr) {
        /* @@@ I'm not completely sure of the order of transforms here! */
        TkPathPushTMatrix(ctx, mPtr);
    }
    CGContextDrawShading(context->c, shading);
    CGShadingRelease(shading);
    CGFunctionRelease(function);
    CGColorSpaceRelease(colorSpaceRef);
    if (fillPtr->units == kPathGradientUnitsBoundingBox) {
        CGContextRestoreGState(context->c);
	context->saveCount--;
    }
}

int
TkPathSetup(Tcl_Interp *interp)
{







|
|
|
|



|
<



|


|
|
|

|
|
|

|
|








|
|
|
|

|
|
|
|
|
|
|
|
|






|







|
|
|
|
|
|
|
|

>
>
>
>
>
|
|

>












|
|

|


|


|
|


<
<



>
>








|
|
|
|


|

>
>
>
>
>
|
|

>










|

|
|

|


|



|
|






|







1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424

1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519


1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
/*
 * Using CGShading for fill gradients.
 */

static void
ShadeEvaluate(void *info, const CGFloat *in, CGFloat *out)
{
    FillInfo		*fillInfo = (FillInfo *)info;
    GradientStopArray	*stopArrPtr = fillInfo->stopArrPtr;
    double		fillOpacity = fillInfo->fillOpacity;
    GradientStop	**stopPtrPtr = stopArrPtr->stops;
    GradientStop	*stop1 = NULL, *stop2 = NULL;
    int			nstops = stopArrPtr->nstops;
    int			i = 0;
    CGFloat		par = *in, f1, f2;


    /* Find the two stops for this point. Tricky! */
    while ((i < nstops) && ((*stopPtrPtr)->offset < par)) {
	stopPtrPtr++, i++;
    }
    if (i == 0) {
	/* First stop > 0. */
	stop1 = *stopPtrPtr;
	stop2 = stop1;
    } else if (i == nstops) {
	/* We have stepped beyond the last stop; step back! */
	stop1 = *(stopPtrPtr - 1);
	stop2 = stop1;
    } else {
	stop1 = *(stopPtrPtr - 1);
	stop2 = *stopPtrPtr;
    }
    /*
     * Interpolate between the two stops.
     * "If two gradient stops have the same offset value,
     * then the latter gradient stop controls the color value at the
     * overlap point."
     */
    if (fabs(stop2->offset - stop1->offset) < 1e-6) {
	out[0] = RedFloatFromXColorPtr(stop2->color);
	out[1] = GreenFloatFromXColorPtr(stop2->color);
	out[2] = BlueFloatFromXColorPtr(stop2->color);
	out[3] = stop2->opacity * fillOpacity;
    } else {
	f1 = (stop2->offset - par)/(stop2->offset - stop1->offset);
	f2 = (par - stop1->offset)/(stop2->offset - stop1->offset);
	out[0] = f1 * RedFloatFromXColorPtr(stop1->color) +
		f2 * RedFloatFromXColorPtr(stop2->color);
	out[1] = f1 * GreenFloatFromXColorPtr(stop1->color) +
		f2 * GreenFloatFromXColorPtr(stop2->color);
	out[2] = f1 * BlueFloatFromXColorPtr(stop1->color) +
		f2 * BlueFloatFromXColorPtr(stop2->color);
	out[3] = (f1 * stop1->opacity + f2 * stop2->opacity) * fillOpacity;
    }
}

static void
ShadeRelease(void *info)
{
    ckfree((char *)info);
}

void
TkPathPaintLinearGradient(TkPathContext ctx, PathRect *bbox,
			  LinearGradientFill *fillPtr, int fillRule,
			  double fillOpacity, TMatrix *mPtr)
{
    TkPathContext_	*context = (TkPathContext_ *) ctx;
    CGShadingRef	shading;
    CGPoint		start, end;
    CGColorSpaceRef	colorSpaceRef;
    CGFunctionRef	function;
    CGFunctionCallbacks callbacks;
    PathRect		*trans = fillPtr->transitionPtr;
    FillInfo		*fillInfo;

    if (context->c == NULL) {
	return;
    }

    fillInfo = (FillInfo *)ckalloc(sizeof(FillInfo));
    fillInfo->fillOpacity = fillOpacity;
    fillInfo->stopArrPtr = fillPtr->stopArrPtr;

    memset(&callbacks, 0, sizeof(callbacks));
    callbacks.version = 0;
    callbacks.evaluate = ShadeEvaluate;
    callbacks.releaseInfo = ShadeRelease;
    colorSpaceRef = CGColorSpaceCreateDeviceRGB();

    /*
     * We need to do like this since this is how SVG defines gradient drawing
     * in case the transition vector is in relative coordinates.
     */
    CGContextSaveGState(context->c);
    context->saveCount++;
    if (fillPtr->units == kPathGradientUnitsBoundingBox) {
	CGContextTranslateCTM(context->c, bbox->x1, bbox->y1);
	CGContextScaleCTM(context->c, bbox->x2 - bbox->x1, bbox->y2 - bbox->y1);
    }
    function = CGFunctionCreate((void *)fillInfo, 1, kValidDomain, 4,
				kValidRange, &callbacks);
    start = CGPointMake(trans->x1, trans->y1);
    end	  = CGPointMake(trans->x2, trans->y2);
    shading = CGShadingCreateAxial(colorSpaceRef, start, end, function, 1, 1);
    if (mPtr) {
	/* @@@ I'm not completely sure of the order of transforms here! */
	TkPathPushTMatrix(ctx, mPtr);
    }
    CGContextDrawShading(context->c, shading);


    CGShadingRelease(shading);
    CGFunctionRelease(function);
    CGColorSpaceRelease(colorSpaceRef);
    CGContextRestoreGState(context->c);
    context->saveCount--;
}

void
TkPathPaintRadialGradient(TkPathContext ctx, PathRect *bbox,
			  RadialGradientFill *fillPtr, int fillRule,
			  double fillOpacity, TMatrix *mPtr)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGShadingRef		shading;
    CGPoint			start, end;
    CGColorSpaceRef		colorSpaceRef;
    CGFunctionRef		function;
    CGFunctionCallbacks		callbacks;
    RadialTransition		*tPtr = fillPtr->radialPtr;
    FillInfo		*fillInfo;

    if (context->c == NULL) {
	return;
    }

    fillInfo = (FillInfo *)ckalloc(sizeof(FillInfo));
    fillInfo->fillOpacity = fillOpacity;
    fillInfo->stopArrPtr = fillPtr->stopArrPtr;

    memset(&callbacks, 0, sizeof(callbacks));
    callbacks.version = 0;
    callbacks.evaluate = ShadeEvaluate;
    callbacks.releaseInfo = ShadeRelease;
    colorSpaceRef = CGColorSpaceCreateDeviceRGB();

    /*
     * We need to do like this since this is how SVG defines gradient drawing
     * in case the transition vector is in relative coordinates.
     */
    if (fillPtr->units == kPathGradientUnitsBoundingBox) {
	CGContextSaveGState(context->c);
	context->saveCount++;
	CGContextTranslateCTM(context->c, bbox->x1, bbox->y1);
	CGContextScaleCTM(context->c, bbox->x2 - bbox->x1, bbox->y2 - bbox->y1);
    }
    function = CGFunctionCreate((void *)fillInfo, 1, kValidDomain, 4,
				kValidRange, &callbacks);
    start = CGPointMake(tPtr->focalX, tPtr->focalY);
    end	  = CGPointMake(tPtr->centerX, tPtr->centerY);
    shading = CGShadingCreateRadial(colorSpaceRef, start, 0.0, end,
				    tPtr->radius, function, 1, 1);
    if (mPtr) {
	/* @@@ I'm not completely sure of the order of transforms here! */
	TkPathPushTMatrix(ctx, mPtr);
    }
    CGContextDrawShading(context->c, shading);
    CGShadingRelease(shading);
    CGFunctionRelease(function);
    CGColorSpaceRelease(colorSpaceRef);
    if (fillPtr->units == kPathGradientUnitsBoundingBox) {
	CGContextRestoreGState(context->c);
	context->saveCount--;
    }
}

int
TkPathSetup(Tcl_Interp *interp)
{

Changes to undroid/build-undroidwish-macosx.sh.

27
28
29
30
31
32
33

34
35
36
37
38
39
40
#              of simply appending it. In theory, this allows
#              for later signing.
#
#############################################################################

set -e


SCRIPTDIR=$(dirname $0)
SCRIPTDIR=$(cd ${SCRIPTDIR} ; pwd)
AWDIR=$(dirname $SCRIPTDIR)
if ! test -d "${AWDIR}/jni" -o ! -d "${AWDIR}/assets" ; then
  echo >&2 "ERROR: installation problem"
  exit 1
fi







>







27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#              of simply appending it. In theory, this allows
#              for later signing.
#
#############################################################################

set -e

LANG=C
SCRIPTDIR=$(dirname $0)
SCRIPTDIR=$(cd ${SCRIPTDIR} ; pwd)
AWDIR=$(dirname $SCRIPTDIR)
if ! test -d "${AWDIR}/jni" -o ! -d "${AWDIR}/assets" ; then
  echo >&2 "ERROR: installation problem"
  exit 1
fi

Changes to undroid/build-vanilla-macosx.sh.

28
29
30
31
32
33
34

35
36
37
38
39
40
41
#              of simply appending it. In theory, this allows
#              for later signing.
#
#############################################################################

set -e


SCRIPTDIR=$(dirname $0)
SCRIPTDIR=$(cd ${SCRIPTDIR} ; pwd)
AWDIR=$(dirname $SCRIPTDIR)
if ! test -d "${AWDIR}/jni" -o ! -d "${AWDIR}/assets" ; then
  echo >&2 "ERROR: installation problem"
  exit 1
fi







>







28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#              of simply appending it. In theory, this allows
#              for later signing.
#
#############################################################################

set -e

LANG=C
SCRIPTDIR=$(dirname $0)
SCRIPTDIR=$(cd ${SCRIPTDIR} ; pwd)
AWDIR=$(dirname $SCRIPTDIR)
if ! test -d "${AWDIR}/jni" -o ! -d "${AWDIR}/assets" ; then
  echo >&2 "ERROR: installation problem"
  exit 1
fi