Tk Source Code

Check-in [5b7e8328]
Login

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

Overview
Comment:TIP529 image metadata: implement svg intermediate metadata memory
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | tip-529-image-metadata
Files: files | file ages | folders
SHA3-256: 5b7e8328145b33e19d9658a0fea2e8ae744e1685a955b8dd5b98ecb89f0a8a8b
User & Date: oehhar 2020-06-21 12:06:34
Context
2020-06-22
13:21
TIP 529 image metadata: svg metadata optimization for -dpi parameter check-in: d78fe967 user: oehhar tags: tip-529-image-metadata
2020-06-21
12:06
TIP529 image metadata: implement svg intermediate metadata memory check-in: 5b7e8328 user: oehhar tags: tip-529-image-metadata
2020-06-12
12:12
TIP529 image metadata: correct stubs entry check-in: 30dd114b user: oehhar tags: tip-529-image-metadata
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to generic/tkImgGIF.c.

1056
1057
1058
1059
1060
1061
1062
1063

1064
1065
1066
1067
1068
1069
1070
1056
1057
1058
1059
1060
1061
1062

1063
1064
1065
1066
1067
1068
1069
1070







-
+







*
* Side effects:
*	The transparent color is set if present in current extensions
*       The data of the following extensions are saved to the metadata dict:
*       - Application extension
*         - XMP data is stored in key "XMP"
*         - any other under the key Application_<name><code>
*         - Comment extension in key "Comment"
*         - Comment extension in key "comment"
*       Plain text extensions are currently ignored.
*
*----------------------------------------------------------------------
*/

static int
DoExtension(
1092
1093
1094
1095
1096
1097
1098
1099

1100
1101
1102
1103
1104
1105
1106
1092
1093
1094
1095
1096
1097
1098

1099
1100
1101
1102
1103
1104
1105
1106







-
+







	    return -1;
	}
	if ((buf[0] & 0x1) != 0) {
	    *transparent = buf[3];
	}
	break;
    case 0xfe:			/* Comment Extension */
	strcpy(extensionStreamName,"Comment");
	strcpy(extensionStreamName,"comment");
        /* copy the extension data below */
	break;
    case 0xff:			/* Application Extension */
	/* Length: 11
	 * Application Identifier: 8 bytes
	 * Application Authentication code: 3 Bytes
	 */
2095
2096
2097
2098
2099
2100
2101
2102

2103
2104
2105
2106
2107
2108
2109
2095
2096
2097
2098
2099
2100
2101

2102
2103
2104
2105
2106
2107
2108
2109







-
+







	Tcl_Obj *itemData;
	
	/*
	 * Check and code comment block
	 */
	
	if (TCL_ERROR == Tcl_DictObjGet(interp, metadataInObj,
		Tcl_NewStringObj("Comment",-1),
		Tcl_NewStringObj("comment",-1),
		&itemData)) {
	    return TCL_ERROR;
	}
	if (itemData != NULL) {
	    int length;
	    unsigned char *comment;
	    comment = Tcl_GetByteArrayFromObj(itemData, &length);

Changes to generic/tkImgSVGnano.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
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







+
+
+
+
+
-
+
+

+
+
+
+

+



+
+
+
+
+
+
+
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+















-







#define NANOSVG_SCOPE MODULE_SCOPE
#define NANOSVG_ALL_COLOR_KEYWORDS
#define NANOSVG_IMPLEMENTATION
#include "nanosvg.h"
#define NANOSVGRAST_IMPLEMENTATION
#include "nanosvgrast.h"

/*
 * Serialized data version
 * This consists of "svg" plus binary '1' at byte locations in an int.
 * It serves as indication, version and endinaess check
 */
/* Additional parameters to nsvgRasterize() */

#define STRUCTURE_VERSION ('s'+256*'v'+65535*'g'+16777216*1)

/*
 * Serialized image data header
 */

typedef struct {
    unsigned int structureVersion;
    double scale;
    int scaleToHeight;
    int scaleToWidth;
    float width;				// Width of the image.
    float height;				// Height of the image.
    int shapeCount;
    int pathCount;
    int ptsCount;
    int gradientCount;
    int gradientStopCount;
} serializedHeader;
} RastOpts;

/*
 * Serialized structures from NSCG
 * All pointers are replaced by array indexes
 */

typedef struct NSVGgradientSerialized {
    float xform[6];
    char spread;
    float fx, fy;
    int nstops;
    int stops;
} NSVGgradientSerialized;

typedef struct NSVGpaintSerialized {
    char type;
    union {
	unsigned int color;
	int gradient;
    };
} NSVGpaintSerialized;


typedef struct NSVGpathSerialized
{
    int pts;					// Cubic bezier points: x0,y0, [cpx1,cpx1,cpx2,cpy2,x1,y1], ...
    int npts;					// Total number of bezier points.
						// Caution: pair of floats
    char closed;				// Flag indicating if shapes should be treated as closed.
    float bounds[4];			// Tight bounding box of the shape [minx,miny,maxx,maxy].
    int next;		// Pointer to next path, or NULL if last element.
} NSVGpathSerialized;

typedef struct NSVGshapeSerialized
{
    char id[64];				// Optional 'id' attr of the shape or its group
    NSVGpaintSerialized fill;		// Fill paint
    NSVGpaintSerialized stroke;		// Stroke paint
    float opacity;				// Opacity of the shape.
    float strokeWidth;			// Stroke width (scaled).
    float strokeDashOffset;		// Stroke dash offset (scaled).
    float strokeDashArray[8];			// Stroke dash array (scaled).
    char strokeDashCount;				// Number of dash values in dash array.
    char strokeLineJoin;		// Stroke join type.
    char strokeLineCap;			// Stroke cap type.
    float miterLimit;			// Miter limit
    char fillRule;				// Fill rule, see NSVGfillRule.
    unsigned char flags;		// Logical or of NSVG_FLAGS_* flags
    float bounds[4];			// Tight bounding box of the shape [minx,miny,maxx,maxy].
    int paths;			// Linked list of paths in the image.
    int next;		// Pointer to next shape, or NULL if last element.
} NSVGshapeSerialized;


/*
 * Per interp cache of last NSVGimage which was matched to
 * be immediately rasterized after the match. This helps to
 * eliminate double parsing of the SVG file/string.
 */

typedef struct {
    /* A poiner to remember if it is the same svn image (data)
     * It is a Tcl_Channel if image created by -file option
     * or a Tcl_Obj, if image is created with the -data option
     */
    ClientData dataOrChan;
    Tcl_DString formatString;
    NSVGimage *nsvgImage;
    RastOpts ropts;
} NSVGcache;

static int		FileMatchSVG(Tcl_Interp *interp, Tcl_Channel chan,
			    const char *fileName, Tcl_Obj *formatObj,
			    Tcl_Obj *metadataInObj, int *widthPtr,
			    int *heightPtr, Tcl_Obj *metadataOutObj,
			    int *closeChannelPtr,
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
142
143
144
145
146
147
148

149
150

151
152
153
154




155
156
157
158
159


160





161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182







-
+

-
+
+
+

-
-
-
-
+
+
+
+
+
-
-
+
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







			    Tcl_Obj *format, Tcl_Obj *metadataIn,
			    Tk_PhotoHandle imageHandle,
			    int destX, int destY, int width, int height,
			    int srcX, int srcY,
			    Tcl_Obj *metadataOut, Tcl_DString *driverInternal);
static NSVGimage *	ParseSVGWithOptions(Tcl_Interp *interp,
			    const char *input, TkSizeT length, Tcl_Obj *format,
			    RastOpts *ropts);
			    serializedHeader *serializedHeaderPtr);
static int		RasterizeSVG(Tcl_Interp *interp,
			    Tk_PhotoHandle imageHandle, NSVGimage *nsvgImage,
			    Tk_PhotoHandle imageHandle,
			    char *svgBlob,
			    TkSizeT serializeDataLength,
			    int destX, int destY, int width, int height,
			    int srcX, int srcY, RastOpts *ropts);
static double		GetScaleFromParameters(NSVGimage *nsvgImage,
			    RastOpts *ropts, int *widthPtr, int *heightPtr);
static NSVGcache *	GetCachePtr(Tcl_Interp *interp);
			    int srcX, int srcY);
static double		GetScaleFromParameters(
			    serializedHeader *serializedHeaderPtr,
			    int *widthPtr, int *heightPtr);
static void		SerializeNSVG(Tcl_DString *driverInternalPtr,
static int		CacheSVG(Tcl_Interp *interp, ClientData dataOrChan,
			    Tcl_Obj *formatObj, NSVGimage *nsvgImage,
			    NSVGimage *nsvgImage);
			    RastOpts *ropts);
static NSVGimage *	GetCachedSVG(Tcl_Interp *interp, ClientData dataOrChan,
			    Tcl_Obj *formatObj, RastOpts *ropts);
static void		CleanCache(Tcl_Interp *interp);
static void		FreeCache(ClientData clientData, Tcl_Interp *interp);
static void SerializePath(struct NSVGpath *pathPtr,
			    serializedHeader *serializedHeaderPtr,
			    Tcl_DString *pathDStringPtr,
			    Tcl_DString *ptrDStringPtr);
static struct NSVGpaintSerialized SerializePaint(struct NSVGpaint *paintPtr,
			    serializedHeader *serializedHeaderPtr,
			    Tcl_DString *gradientDStringPtr,
			    Tcl_DString *gradientStopDStringPtr);
static char * StringCheckMetadata(Tcl_Obj *dataObj,
			    Tcl_Obj *metadataInObj, int *LengthPtr);
static int SaveSVGBLOBToMetadata(Tcl_Interp *interp, Tcl_Obj *metadataOutObj,
			    Tcl_DString *driverInternalPtr);
static void nsvgRasterizeSerialized(NSVGrasterizer* r, char *svgBlobPtr, float tx,
			    float ty, float scale, unsigned char* dst, int w,
			    int h, int stride);

/*
 * The format record for the SVG nano file format:
 */

Tk_PhotoImageFormatVersion3 tkImgFmtSVGnano = {
    "svg",			/* name */
139
140
141
142
143
144
145
146
147
148

149
150
151
152
153
154
155


156
157


158
159


160

161
162
163
164
165
166







167
168
169
170
171
172






















































































































































































































































































173
174
175
176
177
178
179
221
222
223
224
225
226
227

228
229
230
231

232
233
234
235
236
237
238
239

240
241
242
243
244
245

246
247
248
249
250


251
252
253
254
255
256
257

258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547







-


+

-





+
+

-
+
+


+
+
-
+




-
-
+
+
+
+
+
+
+
-





+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







    int *closeChannelPtr,	/* Return if the channel may be closed */
    Tcl_DString *driverInternalPtr)
				/* memory passed to FileReadGIF */
{
    TkSizeT length;
    Tcl_Obj *dataObj = Tcl_NewObj();
    const char *data;
    RastOpts ropts;
    NSVGimage *nsvgImage;
    (void)fileName;
    serializedHeader *serializedHeaderPtr;

    CleanCache(interp);
    if (Tcl_ReadChars(chan, dataObj, -1, 0) == TCL_IO_FAILURE) {
	/* in case of an error reading the file */
	Tcl_DecrRefCount(dataObj);
	return 0;
    }
    Tcl_DStringSetLength(driverInternalPtr, sizeof(serializedHeader));
    serializedHeaderPtr = (serializedHeader *)Tcl_DStringValue(driverInternalPtr);
    data = TkGetStringFromObj(dataObj, &length);
    nsvgImage = ParseSVGWithOptions(interp, data, length, formatObj, &ropts);
    nsvgImage = ParseSVGWithOptions(interp, data, length, formatObj,
	    serializedHeaderPtr);
    Tcl_DecrRefCount(dataObj);
    if (nsvgImage != NULL) {
	serializedHeaderPtr->width = nsvgImage->width;
	serializedHeaderPtr->height = nsvgImage->height;
        GetScaleFromParameters(nsvgImage, &ropts, widthPtr, heightPtr);
        GetScaleFromParameters(serializedHeaderPtr, widthPtr, heightPtr);
        if ((*widthPtr <= 0.0) || (*heightPtr <= 0.0)) {
	    nsvgDelete(nsvgImage);
	    return 0;
        }
        if (!CacheSVG(interp, chan, formatObj, nsvgImage, &ropts)) {
	    nsvgDelete(nsvgImage);
	
	/*
	 * Serialize the NSVGImage structure
	 * As the DString is resized, serializedHeaderPtr may get invalid
	 */
	SerializeNSVG(driverInternalPtr, nsvgImage);
	nsvgDelete(nsvgImage);
        }
        return 1;
    }
    return 0;
}

/*
 *----------------------------------------------------------------------
 *
 * SerializeNSVG --
 *
 *	This function saves the NSVGimage structure into the DString.
 *
 * Results:
 *	none.
 *
 * Side effects:
 *	The DString size is changed and thus, the value pointer may
 *	change.
 *
 *----------------------------------------------------------------------
 */

static void SerializeNSVG(Tcl_DString *driverInternalPtr, NSVGimage *nsvgImage) {
    serializedHeader *serializedHeaderPtr;
    Tcl_DString  shapeDString, pathDString, ptsDString, gradientDString,
	gradientStopDString;
    NSVGshape *shapePtr;

    serializedHeaderPtr = (serializedHeader *)Tcl_DStringValue(driverInternalPtr);
    Tcl_DStringInit(&shapeDString);
    Tcl_DStringInit(&pathDString);
    Tcl_DStringInit(&ptsDString);
    Tcl_DStringInit(&gradientDString);
    Tcl_DStringInit(&gradientStopDString);

    serializedHeaderPtr->structureVersion = STRUCTURE_VERSION;
    serializedHeaderPtr->shapeCount = 0;
    serializedHeaderPtr->pathCount = 0;
    serializedHeaderPtr->ptsCount = 0;
    serializedHeaderPtr->gradientCount = 0;
    serializedHeaderPtr->gradientStopCount = 0;
    
    for ( shapePtr = nsvgImage->shapes; shapePtr != NULL;
	    shapePtr = shapePtr->next) {
	NSVGshapeSerialized shapeSerialized;

	/*
	 * Copy serialized shape fix data
	 */

	memcpy(shapeSerialized.id, shapePtr->id, 64 * sizeof(char));

	shapeSerialized.fill = SerializePaint(&(shapePtr->fill),
		serializedHeaderPtr, &gradientDString, &gradientStopDString);

	shapeSerialized.stroke = SerializePaint(&(shapePtr->stroke),
		serializedHeaderPtr, &gradientDString, &gradientStopDString);

	shapeSerialized.opacity = shapePtr->opacity;
	shapeSerialized.strokeWidth = shapePtr->strokeWidth;
	shapeSerialized.strokeDashOffset = shapePtr->strokeDashOffset;
	memcpy(shapeSerialized.strokeDashArray, shapePtr->strokeDashArray,
		8*sizeof(float));
	shapeSerialized.strokeDashCount = shapePtr->strokeDashCount;
	shapeSerialized.strokeLineJoin = shapePtr->strokeLineJoin;
	shapeSerialized.strokeLineCap = shapePtr->strokeLineCap;
	shapeSerialized.miterLimit = shapePtr->miterLimit;
	shapeSerialized.fillRule = shapePtr->fillRule;
	shapeSerialized.flags = shapePtr->flags;
	memcpy(shapeSerialized.bounds, shapePtr->bounds, 4*sizeof(float));
	
	/*
	 * Serialize the paths linked list
	 */

	if ( shapePtr->paths == NULL ) {
	    shapeSerialized.paths = -1;
	} else {
	    shapeSerialized.paths = serializedHeaderPtr->pathCount;
	    SerializePath(shapePtr->paths, serializedHeaderPtr, &pathDString,
		    &ptsDString);
	}

	/*
	 * generate next array position and save to DString
	 */
	
	serializedHeaderPtr->shapeCount++;
	shapeSerialized.next =
		shapePtr->next == NULL ? -1:
		serializedHeaderPtr->shapeCount;
	
	Tcl_DStringAppend(&shapeDString,
		(const char *)&shapeSerialized, sizeof(NSVGshapeSerialized));
    }
    
    /*
     * Write the DStrings into the driver memory one after the other
     * Note: serializedHeaderPtr may get invalid due to DString resize
     */
    
    if (Tcl_DStringLength(&shapeDString) > 0) {
    	Tcl_DStringAppend(driverInternalPtr,
		    Tcl_DStringValue(&shapeDString),
		    Tcl_DStringLength(&shapeDString));
    }
    Tcl_DStringFree(&shapeDString);

    if (Tcl_DStringLength(&pathDString) > 0) {
    	Tcl_DStringAppend(driverInternalPtr,
		    Tcl_DStringValue(&pathDString),
		    Tcl_DStringLength(&pathDString));
    }
    Tcl_DStringFree(&pathDString);
    
    if (Tcl_DStringLength(&ptsDString) > 0) {
    	Tcl_DStringAppend(driverInternalPtr,
		    Tcl_DStringValue(&ptsDString),
		    Tcl_DStringLength(&ptsDString));
    }
    Tcl_DStringFree(&ptsDString);

    if (Tcl_DStringLength(&gradientDString) > 0) {
    	Tcl_DStringAppend(driverInternalPtr,
		    Tcl_DStringValue(&gradientDString),
		    Tcl_DStringLength(&gradientDString));
    }
    Tcl_DStringFree(&gradientDString);

    if (Tcl_DStringLength(&gradientStopDString) > 0) {
    	Tcl_DStringAppend(driverInternalPtr,
		    Tcl_DStringValue(&gradientStopDString),
		    Tcl_DStringLength(&gradientStopDString));
    }
    Tcl_DStringFree(&gradientStopDString);
}

/*
 *----------------------------------------------------------------------
 *
 * SerializePaint --
 *
 *	This function transforms the NSVGpaint structure to a serialize
 *	version.
 *	The child structures gradient and gradientStop are serialized into
 *	their DString memory.
 *
 * Results:
 *	NSVGPaintSerialized structure.
 *
 * Side effects:
 *	The DString size is changed and thus, the value pointer may
 *	change.
 *
 *----------------------------------------------------------------------
 */

static struct NSVGpaintSerialized SerializePaint(struct NSVGpaint *paintPtr,
	serializedHeader *serializedHeaderPtr,
	Tcl_DString *gradientDStringPtr,
	Tcl_DString *gradientStopDStringPtr)
{
    struct NSVGpaintSerialized paintSerialized;
    
    paintSerialized.type = paintPtr->type;

    if (paintPtr->type == NSVG_PAINT_LINEAR_GRADIENT
	    || paintPtr->type == NSVG_PAINT_RADIAL_GRADIENT) {
	
	/*
	 * Gradient union pointer present
	 */

	NSVGgradient* gradientPtr;
	NSVGgradientSerialized gradientSerialized;
	
	gradientPtr = paintPtr->gradient;
	memcpy(&(gradientSerialized.xform),  gradientPtr->xform,
		6 * sizeof(float) );
	gradientSerialized.spread = gradientPtr->spread;
	gradientSerialized.fx = gradientPtr->fx;
	gradientSerialized.fy = gradientPtr->fy;
	
	/*
	 * Copy gradient stop array to DString
	 */

	gradientSerialized.nstops = gradientPtr->nstops;
	if ( gradientPtr->nstops == 0 ) {
	    gradientSerialized.stops = -1;
	} else {
	    gradientSerialized.stops = serializedHeaderPtr->gradientStopCount;
	    Tcl_DStringAppend(gradientStopDStringPtr,
		    (const char *)gradientPtr->stops,
		    gradientPtr->nstops * sizeof(NSVGgradientStop));

	    (serializedHeaderPtr->gradientStopCount) += gradientPtr->nstops;
	}
    } else {
	
	/*
	 * Color union or nothing present
	 */

	paintSerialized.color = paintPtr->color;
    }
    return paintSerialized;
}
/*
 *----------------------------------------------------------------------
 *
 * SerializePath --
 *
 *	This function serializes a linked list of NSVGpath structure into
 *	the corresponding DString array.
 *
 * Results:
 *	none
 *
 * Side effects:
 *	The DString size is changed and thus, the value pointer may
 *	change.
 *
 *----------------------------------------------------------------------
 */

static void SerializePath(struct NSVGpath *pathPtr,
	serializedHeader *serializedHeaderPtr,
	Tcl_DString *pathDStringPtr,
	Tcl_DString *ptsDStringPtr)
{
 
    /*
     * loop over path linked list
     */
    
    for (;pathPtr != NULL; pathPtr = pathPtr->next) {
	NSVGpathSerialized pathSerialized;
	int index;

	/*
	 * Save points in the ptr dstring.
	 * The first index and the count is saved.
	 */

	pathSerialized.npts = pathPtr->npts;
	if (pathPtr->npts == 0) {
	    pathSerialized.pts = -1;
	} else {

	    /*
	     * Attention: npts is a pair of floats
	     */

	    pathSerialized.pts = serializedHeaderPtr->ptsCount;
	    for (index = 0; index < (pathPtr->npts) * 2; index++) {
	        float ptCurrent;
	        ptCurrent = pathPtr->pts[index];
	        Tcl_DStringAppend(ptsDStringPtr,
	    	    (const char *)&ptCurrent, sizeof(float));
	        (serializedHeaderPtr->ptsCount)++;
	    }
	}
    
	/*
	 * Copy the other items of the path structure
	 */
    
	pathSerialized.closed = pathPtr->closed;
	memcpy(pathSerialized.bounds, pathPtr->bounds, 4*sizeof(float));
    
	/*
	 * Build the next item and add to DString
	 */

	serializedHeaderPtr->pathCount++;
	pathSerialized.next = (pathPtr->next == NULL) ? -1 :
		serializedHeaderPtr->pathCount;

	Tcl_DStringAppend(pathDStringPtr,
	        (const char *)&pathSerialized, sizeof(NSVGpathSerialized));
    }
}
/*
 *----------------------------------------------------------------------
 *
 * FileReadSVG --
 *
 *	This function is called by the photo image type to read SVG format
 *	data from a file and write it into a given photo image.
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
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







-
-
-
+
-


-
-
-
+
-
-
-
-
+
+
-
-
+
+
-
-
-
+
-
-
-
-
-
-
-
+
+
+
+
-







				 * written to. */
    int srcX, int srcY,		/* Coordinates of top-left pixel to be used in
				 * image being read. */
    Tcl_Obj *metadataOutObj,	/* metadata return dict, may be NULL */
    Tcl_DString *driverInternalPtr)
				/* memory passed from FileMatchGIF */
{
    TkSizeT length;
    const char *data;
    RastOpts ropts;
    int result;
    NSVGimage *nsvgImage = GetCachedSVG(interp, chan, formatObj, &ropts);
    (void)fileName;

    if (nsvgImage == NULL) {
        Tcl_Obj *dataObj = Tcl_NewObj();

    result = RasterizeSVG(interp, imageHandle,
	if (Tcl_ReadChars(chan, dataObj, -1, 0) == TCL_IO_FAILURE) {
	    /* in case of an error reading the file */
	    Tcl_DecrRefCount(dataObj);
	    Tcl_SetObjResult(interp, Tcl_NewStringObj("read error", -1));
	    Tcl_DStringValue(driverInternalPtr),
	    Tcl_DStringLength(driverInternalPtr), destX, destY, width, height,
	    Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "READ_ERROR", NULL);
	    return TCL_ERROR;
	    srcX, srcY);
    if (result == TCL_OK) {
	}
	data = TkGetStringFromObj(dataObj, &length);
	nsvgImage = ParseSVGWithOptions(interp, data, length, formatObj,
	result =  SaveSVGBLOBToMetadata(interp, metadataOutObj,
			    &ropts);
	Tcl_DecrRefCount(dataObj);
	if (nsvgImage == NULL) {
	    return TCL_ERROR;
	}
    }
    return RasterizeSVG(interp, imageHandle, nsvgImage, destX, destY,
		driverInternalPtr);
    }

    return result;
		width, height, srcX, srcY, &ropts);
}

/*
 *----------------------------------------------------------------------
 *
 * StringMatchSVG --
 *
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
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







-

+
+

-

+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
+
+

+
+
-
+




-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

+
+
+
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







    int *heightPtr,		/* where to put the string height */
    Tcl_Obj *metadataOut,	/* metadata return dict, may be NULL */
    Tcl_DString *driverInternalPtr)
				/* memory to pass to StringReadGIF */
{
    TkSizeT length;
    const char *data;
    RastOpts ropts;
    NSVGimage *nsvgImage;
    serializedHeader *serializedHeaderPtr;
    char * svgBlobPtr;

    CleanCache(interp);
    data = TkGetStringFromObj(dataObj, &length);

    
    /*
     * Check for the special data to indicate that the metadata should be used.
     * On special data, get the serialized header structure and check it.
     */
    
    svgBlobPtr = StringCheckMetadata( dataObj, metadataInObj, &length);

    if (NULL != svgBlobPtr) {
	GetScaleFromParameters((serializedHeader *) svgBlobPtr, widthPtr,
		heightPtr);
	return 1;
    }

    /*
     * Check the passed data object and serialize it on success.
     */

    Tcl_DStringSetLength(driverInternalPtr, sizeof(serializedHeader));
    serializedHeaderPtr = (serializedHeader *)Tcl_DStringValue(driverInternalPtr);
    nsvgImage = ParseSVGWithOptions(interp, data, length, formatObj, &ropts);
    nsvgImage = ParseSVGWithOptions(interp, data, length, formatObj,
	    serializedHeaderPtr);

    if (nsvgImage != NULL) {
	serializedHeaderPtr->width = nsvgImage->width;
	serializedHeaderPtr->height = nsvgImage->height;
        GetScaleFromParameters(nsvgImage, &ropts, widthPtr, heightPtr);
        GetScaleFromParameters(serializedHeaderPtr, widthPtr, heightPtr);
        if ((*widthPtr <= 0.0) || (*heightPtr <= 0.0)) {
	    nsvgDelete(nsvgImage);
	    return 0;
        }
        if (!CacheSVG(interp, dataObj, formatObj, nsvgImage, &ropts)) {
	    nsvgDelete(nsvgImage);
        }
        return 1;

	/*
	 * Serialize the NSVGImage structure
	 * As the DString is resized, serializedHeaderPtr may get invalid
	 */

	SerializeNSVG(driverInternalPtr, nsvgImage);
	
	nsvgDelete(nsvgImage);
        return 1;
    }
    return 0;
}

/*
 *----------------------------------------------------------------------
 *
 * StringCheckMetadata --
 *
 *	Check the passed tring for a metadata serialized structure.
 *
 * Results:
 *	The svg blob pointer on success, NULL otherwise.
 *
 * Side effects:
 *	The file is saved in the internal cache for further use.
 *
 *----------------------------------------------------------------------
 */

static char * StringCheckMetadata(
    Tcl_Obj *dataObj,		/* the object containing the image data */
    Tcl_Obj *metadataInObj,	/* metadata input, may be NULL */
    TkSizeT *lengthOutPtr)	/* output data length on success */
{
    TkSizeT length;
    const char *data;
    serializedHeader *serializedHeaderPtr;
    char * svgBlobPtr;
    Tcl_Obj *itemData;

    /*
     * Check for the special data to indicate that the metadata should be used.
     * On special data, get the serialized header structure and check it.
     */

    if (NULL == metadataInObj) {
	return NULL;
    }

    data = TkGetStringFromObj(dataObj, &length);
    if (0 != strcmp(data, "<svg data=\"metadata\" />") ) {
    return 0;
}
	return NULL;
    }
    if (TCL_ERROR == Tcl_DictObjGet(NULL, metadataInObj,
	    Tcl_NewStringObj("SVGBLOB",-1), &itemData)) {
	return NULL;
    }
    if (itemData == NULL) {
	return NULL;
    }
    svgBlobPtr = Tcl_GetByteArrayFromObj(itemData, &length);
    if (length < sizeof(serializedHeader) ) {
	return NULL;
    }
    serializedHeaderPtr = (serializedHeader *)svgBlobPtr;
    if (serializedHeaderPtr->structureVersion != STRUCTURE_VERSION ) {
	return NULL;
    }
    *lengthOutPtr = length;
    return svgBlobPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * StringReadSVG --
 *
 *	This function is called by the photo image type to read SVG format
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
751
752
753
754
755
756
757

758
759
760
761
762

763
764

765
766
767
768
769
770

771


772










773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841







-
+




-
+

-
+

+
+
+

-
+
-
-

-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







 */

static int
StringReadSVG(
    Tcl_Interp *interp,		/* interpreter for reporting errors in */
    Tcl_Obj *dataObj,		/* object containing the image */
    Tcl_Obj *formatObj,		/* format object, or NULL */
    Tcl_Obj *metadataIn,	/* metadata input, may be NULL */
    Tcl_Obj *metadataInObj,	/* metadata input, may be NULL */
    Tk_PhotoHandle imageHandle,	/* the image to write this data into */
    int destX, int destY,	/* The rectangular region of the */
    int width, int height,	/* image to copy */
    int srcX, int srcY,
    Tcl_Obj *metadataOut,	/* metadata return dict, may be NULL */
    Tcl_Obj *metadataOutObj,	/* metadata return dict, may be NULL */
    Tcl_DString *driverInternalPtr)
				/* memory passed from StringReadGIF */
				/* memory passed from StringReadSVG */
{
    int result;
    TkSizeT serializedDataLength;
    char * data;
    TkSizeT length;
    const char *data;
    char * svgBlobPtr;
    RastOpts ropts;
    NSVGimage *nsvgImage = GetCachedSVG(interp, dataObj, formatObj, &ropts);

    if (nsvgImage == NULL) {
        data = TkGetStringFromObj(dataObj, &length);
	nsvgImage = ParseSVGWithOptions(interp, data, length, formatObj,
			    &ropts);
    }
    if (nsvgImage == NULL) {
	return TCL_ERROR;
    }
    return RasterizeSVG(interp, imageHandle, nsvgImage, destX, destY,
		width, height, srcX, srcY, &ropts);
    data = TkGetStringFromObj(dataObj, &length);

    
    /*
     * Check for the special data to indicate that the metadata should be used.
     * On special data, get the serialized header structure and use it.
     */
    
    svgBlobPtr = StringCheckMetadata( dataObj, metadataInObj,
	    &serializedDataLength);

    if (NULL != svgBlobPtr) {
	return RasterizeSVG(interp, imageHandle, svgBlobPtr,
		serializedDataLength, destX, destY, width, height, srcX, srcY);
    }

    /*
     * Otherwise, the SVGBlob data is contained in the driver internal
     * DString. Use that memory.
     */
    
    result = RasterizeSVG(interp, imageHandle,
	    Tcl_DStringValue(driverInternalPtr),
	    Tcl_DStringLength(driverInternalPtr), destX, destY, width, height,
	    srcX, srcY);
    if (result != TCL_OK) {
	return result;
    }

    return SaveSVGBLOBToMetadata(interp, metadataOutObj,
	    driverInternalPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * SaveSVGBLOBToMetadata --
 *
 *	Copy the driver internal DString into the metadata key SVGBLOB.
 *
 * Results:
 *	A TCL result value.
 *
 * Side effects:
 *	Change the output metadata.
 *
 *----------------------------------------------------------------------
 */

static int SaveSVGBLOBToMetadata(
    Tcl_Interp *interp,		/* interpreter for reporting errors in */
    Tcl_Obj *metadataOutObj,	/* metadata return dict, may be NULL */
    Tcl_DString *driverInternalPtr)
				/* memory passed from xxxReadSVG */
{
    if (metadataOutObj == NULL) {
	return TCL_OK;
    }
    return Tcl_DictObjPut(interp, metadataOutObj,
	Tcl_NewStringObj("SVGBLOB",-1),
	Tcl_NewByteArrayObj(Tcl_DStringValue(driverInternalPtr),
		Tcl_DStringLength(driverInternalPtr)));
}

/*
 *----------------------------------------------------------------------
 *
 * ParseSVGWithOptions --
 *
353
354
355
356
357
358
359
360

361
362
363
364
365
366
367
851
852
853
854
855
856
857

858
859
860
861
862
863
864
865







-
+








static NSVGimage *
ParseSVGWithOptions(
    Tcl_Interp *interp,
    const char *input,
    TkSizeT length,
    Tcl_Obj *formatObj,
    RastOpts *ropts)
    serializedHeader *serializedHeaderPtr)
{
    Tcl_Obj **objv = NULL;
    int objc = 0;
    double dpi = 96.0;
    char *inputCopy = NULL;
    NSVGimage *nsvgImage;
    int parameterScaleSeen = 0;
386
387
388
389
390
391
392
393
394
395



396
397
398
399
400
401
402
884
885
886
887
888
889
890



891
892
893
894
895
896
897
898
899
900







-
-
-
+
+
+







    memcpy(inputCopy, input, length);
    inputCopy[length] = '\0';

    /*
     * Process elements of format specification as a list.
     */

    ropts->scale = 1.0;
    ropts->scaleToHeight = 0;
    ropts->scaleToWidth = 0;
    serializedHeaderPtr->scale = 1.0;
    serializedHeaderPtr->scaleToHeight = 0;
    serializedHeaderPtr->scaleToWidth = 0;
    if ((formatObj != NULL) &&
	    Tcl_ListObjGetElements(interp, formatObj, &objc, &objv) != TCL_OK) {
        goto error;
    }
    for (; objc > 0 ; objc--, objv++) {
	int optIndex;

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
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







-
+
+



-
+








-
-
+
+


-
+








-
-
+
+


-
+







			"-dpi value must be positive", -1));
		Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "BAD_DPI",
			NULL);
		goto error;
	    }
	    break;
	case OPT_SCALE:
	    if (Tcl_GetDoubleFromObj(interp, objv[0], &ropts->scale) ==
	    if (Tcl_GetDoubleFromObj(interp, objv[0],
		    &(serializedHeaderPtr->scale)) ==
		TCL_ERROR) {
	        goto error;
	    }
	    if (ropts->scale <= 0.0) {
	    if (serializedHeaderPtr->scale <= 0.0) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj(
			"-scale value must be positive", -1));
		Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "BAD_SCALE",
			NULL);
		goto error;
	    }
	    break;
	case OPT_SCALE_TO_HEIGHT:
	    if (Tcl_GetIntFromObj(interp, objv[0], &ropts->scaleToHeight) ==
		TCL_ERROR) {
	    if (Tcl_GetIntFromObj(interp, objv[0],
		&(serializedHeaderPtr->scaleToHeight)) == TCL_ERROR) {
	        goto error;
	    }
	    if (ropts->scaleToHeight <= 0) {
	    if (serializedHeaderPtr->scaleToHeight <= 0) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj(
			"-scaletoheight value must be positive", -1));
		Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "BAD_SCALE",
			NULL);
		goto error;
	    }
	    break;
	case OPT_SCALE_TO_WIDTH:
	    if (Tcl_GetIntFromObj(interp, objv[0], &ropts->scaleToWidth) ==
		TCL_ERROR) {
	    if (Tcl_GetIntFromObj(interp, objv[0],
		    &(serializedHeaderPtr->scaleToWidth)) == TCL_ERROR) {
	        goto error;
	    }
	    if (ropts->scaleToWidth <= 0) {
	    if (serializedHeaderPtr->scaleToWidth <= 0) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj(
			"-scaletowidth value must be positive", -1));
		Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "BAD_SCALE",
			NULL);
		goto error;
	    }
	    break;
516
517
518
519
520
521
522



























































523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543


544
545
546

547
548
549
550
551
552
553
554
555
556
557



558
559
560
561
562
563
564

565
566
567
568
569
570
571
572


573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625

626
627
628
629
630
631
632
633
634
635

636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661

662
663
664
665
666

667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713




714
715
716
717
718
719
720
721
722
723
724
725
726




































































































































































727
728
729
730
731

732
733
734
735
736
737
738






























739
740
741
742





743
744
745
746

747
748
749



750
751
752
753
754
755
756
757
758












759
760
761












762
763
764
765
766
767





768
769

770
771
772
773
774



775
776
777
778
779
780






781
782
783





784
785
786
787
788
789
790
















791
792






793
794
795
796



797
798
799
800





801
802
803
804



805
806

807
808
809
810
811
812
813
















814
815
816
817
818
819











820
821
822
823





824
825
826









827
828


829
830
831
832




833
834
835
836
837





838
839
840





841
842
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100

1101
1102
1103
1104

1105

1106
1107
1108
1109
1110
1111
1112
1113


1114
1115
1116
1117
1118
1119
1120
1121
1122

1123
1124
1125
1126
1127
1128
1129
1130

1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152

1153
1154
1155
1156
1157
1158
1159
1160


1161
1162
1163
1164
1165
1166
















1167










1168


























1169





1170


1171





1172

1173






























1174
1175
1176
1177
1178
1179
1180
1181
1182
1183













1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
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
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









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
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







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+




















-
+
+


-
+
-








-
-
+
+
+






-
+







-
+
+




















-








-
-






-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
+
-
-

-
-
-
-
-

-

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-






+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
+
+
+
+
+
-
-
-
-
+
-
-
-
+
+
+
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
+
+
+
+
+
-
-
+
-
-
-
-
-
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
-
-
-
+
+
+
+
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+
+
+
+
+
+
-
-
-
-
+
+
+
-
-
-
-
+
+
+
+
+
-
-
-
-
+
+
+
-
-
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
+
+
+
+
+
-
-
-
+
+
+
+
+
+
+
+
+
-
-
+
+

-
-
-
+
+
+
+
-
-
-
-
-
+
+
+
+
+
-
-
-
+
+
+
+
+


    }
    return NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * GetScaleFromParameters --
 *
 *	Get the scale value from the already parsed parameters -scale,
 *	-scaletoheight and -scaletowidth.
 *
 *	The image width and height is also returned.
 *
 * Results:
 *	The evaluated or configured scale value, or 0.0 on failure
 *
 * Side effects:
 *	heightPtr and widthPtr are set to height and width of the image.
 *
 *----------------------------------------------------------------------
 */

static double
GetScaleFromParameters(
    serializedHeader *serializedHeaderPtr,
    int *widthPtr,
    int *heightPtr)
{
    double scale;
    int width, height;

    if ((serializedHeaderPtr->width == 0.0) || (serializedHeaderPtr->height == 0.0)) {
        width = height = 0;
        scale = 1.0;
    } else if (serializedHeaderPtr->scaleToHeight > 0) {
	/*
	 * Fixed height
	 */
	height = serializedHeaderPtr->scaleToHeight;
	scale = height / serializedHeaderPtr->height;
	width = (int) ceil(serializedHeaderPtr->width * scale);
    } else if (serializedHeaderPtr->scaleToWidth > 0) {
	/*
	 * Fixed width
	 */
	width = serializedHeaderPtr->scaleToWidth;
	scale = width / serializedHeaderPtr->width;
	height = (int) ceil(serializedHeaderPtr->height * scale);
    } else {
	/*
	 * Scale factor
	 */
	scale = serializedHeaderPtr->scale;
	width = (int) ceil(serializedHeaderPtr->width * scale);
	height = (int) ceil(serializedHeaderPtr->height * scale);
    }

    *heightPtr = height;
    *widthPtr = width;
    return scale;
}

/*
 *----------------------------------------------------------------------
 *
 * RasterizeSVG --
 *
 *	This function is called to rasterize the given nsvgImage and
 *	fill the imageHandle with data.
 *
 * Results:
 *	A standard TCL completion code. If TCL_ERROR is returned then an error
 *	message is left in the interp's result.
 *
 *
 * Side effects:
 *	On error the given nsvgImage will be deleted.
 *
 *----------------------------------------------------------------------
 */

static int
RasterizeSVG(
    Tcl_Interp *interp,
    Tk_PhotoHandle imageHandle,
    NSVGimage *nsvgImage,
    char *svgBlobPtr,
    TkSizeT serializedDataLength,
    int destX, int destY,
    int width, int height,
    int srcX, int srcY,
    int srcX, int srcY)
    RastOpts *ropts)
{
    int w, h, c;
    NSVGrasterizer *rast;
    unsigned char *imgData;
    Tk_PhotoImageBlock svgblock;
    double scale;
    (void)srcX;
    (void)srcY;

    scale = GetScaleFromParameters(nsvgImage, ropts, &w, &h);
    
    scale = GetScaleFromParameters((serializedHeader *) svgBlobPtr,
	    &w, &h);

    rast = nsvgCreateRasterizer();
    if (rast == NULL) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj("cannot initialize rasterizer", -1));
	Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "RASTERIZER_ERROR",
		NULL);
	goto cleanAST;
	return TCL_ERROR;
    }
    imgData = (unsigned char *)attemptckalloc(w * h *4);
    if (imgData == NULL) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj("cannot alloc image buffer", -1));
	Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "OUT_OF_MEMORY", NULL);
	goto cleanRAST;
    }
    nsvgRasterize(rast, nsvgImage, 0, 0,

    nsvgRasterizeSerialized(rast, svgBlobPtr, 0, 0,
	    (float) scale, imgData, w, h, w * 4);
    /* transfer the data to a photo block */
    svgblock.pixelPtr = imgData;
    svgblock.width = w;
    svgblock.height = h;
    svgblock.pitch = w * 4;
    svgblock.pixelSize = 4;
    for (c = 0; c <= 3; c++) {
	svgblock.offset[c] = c;
    }
    if (Tk_PhotoExpand(interp, imageHandle,
		destX + width, destY + height) != TCL_OK) {
	goto cleanRAST;
    }
    if (Tk_PhotoPutBlock(interp, imageHandle, &svgblock, destX, destY,
		width, height, TK_PHOTO_COMPOSITE_SET) != TCL_OK) {
	goto cleanimg;
    }
    ckfree(imgData);
    nsvgDeleteRasterizer(rast);
    nsvgDelete(nsvgImage);
    return TCL_OK;

cleanimg:
    ckfree(imgData);

cleanRAST:
    nsvgDeleteRasterizer(rast);

cleanAST:
    nsvgDelete(nsvgImage);
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * GetScaleFromParameters --
 *
 *	Get the scale value from the already parsed parameters -scale,
 *	-scaletoheight and -scaletowidth.
 *
 *	The image width and height is also returned.
 *
 * Results:
 *	The evaluated or configured scale value, or 0.0 on failure
 *
 * Side effects:
 *	heightPtr and widthPtr are set to height and width of the image.
 *
 *----------------------------------------------------------------------
 */

 * Rasterize Serialized --
static double
GetScaleFromParameters(
    NSVGimage *nsvgImage,
    RastOpts *ropts,
    int *widthPtr,
    int *heightPtr)
{
    double scale;
    int width, height;

 *
    if ((nsvgImage->width == 0.0) || (nsvgImage->height == 0.0)) {
        width = height = 0;
        scale = 1.0;
    } else if (ropts->scaleToHeight > 0) {
	/*
	 * Fixed height
	 */
	height = ropts->scaleToHeight;
	scale = height / nsvgImage->height;
	width = (int) ceil(nsvgImage->width * scale);
    } else if (ropts->scaleToWidth > 0) {
	/*
	 * Fixed width
	 */
	width = ropts->scaleToWidth;
	scale = width / nsvgImage->width;
	height = (int) ceil(nsvgImage->height * scale);
    } else {
	/*
	 * Scale factor
	 */
	scale = ropts->scale;
	width = (int) ceil(nsvgImage->width * scale);
	height = (int) ceil(nsvgImage->height * scale);
    }

 *	Fiunctions of svgnrast.h which requires modification due to the
    *heightPtr = height;
    *widthPtr = width;
    return scale;
}

 *	serialized data structure.
/*
 *----------------------------------------------------------------------
 *
 * GetCachePtr --
 *
 *	This function is called to get the per interpreter used
 *	svg image cache.
 *
 * Results:
 * 	Return a pointer to the used cache.
 *
 * Side effects:
 *	Initialize the cache on the first call.
 *
 *----------------------------------------------------------------------
 */

static NSVGcache *
GetCachePtr(
    Tcl_Interp *interp
) {
    NSVGcache *cachePtr = (NSVGcache *)Tcl_GetAssocData(interp, "tksvgnano", NULL);
    if (cachePtr == NULL) {
	cachePtr = (NSVGcache *)ckalloc(sizeof(NSVGcache));
	cachePtr->dataOrChan = NULL;
	Tcl_DStringInit(&cachePtr->formatString);
	cachePtr->nsvgImage = NULL;
	Tcl_SetAssocData(interp, "tksvgnano", FreeCache, cachePtr);
    }
    return cachePtr;
}

/*
 *----------------------------------------------------------------------
 *
 * CacheSVG --
 *
 *	Add the given svg image informations to the cache for further usage.
 *
 * Results:
 *	Return 1 on success, and 0 otherwise.
 *
 * Side effects:
 *
 *----------------------------------------------------------------------
 */

static void nsvg__flattenShapeSerialized(NSVGrasterizer* r, int pathIndex,
	NSVGpathSerialized *pathSerializedPtr, float *ptsSerializedPtr,
	float scale)
{
static int
CacheSVG(
    Tcl_Interp *interp,
    ClientData dataOrChan,
    Tcl_Obj *formatObj,
    NSVGimage *nsvgImage,
    RastOpts *ropts)
{
    TkSizeT length;
    const char *data;
    NSVGcache *cachePtr = GetCachePtr(interp);

    if (cachePtr != NULL) {
    int i, j;
    NSVGpathSerialized* path;

    for (; pathIndex != -1; pathIndex = pathSerializedPtr[pathIndex].next) {
	path = &(pathSerializedPtr[pathIndex]);
	r->npoints = 0;
	// Flatten path
	nsvg__addPathPoint(r,
		ptsSerializedPtr[path->pts]*scale,
		ptsSerializedPtr[path->pts+1]*scale, 0);
	for (i = 0; i < path->npts-1; i += 3) {
	    float* p = &ptsSerializedPtr[path->pts+i*2];
	    nsvg__flattenCubicBez(r, p[0]*scale,p[1]*scale, p[2]*scale,p[3]*scale, p[4]*scale,p[5]*scale, p[6]*scale,p[7]*scale, 0, 0);
	}
	// Close path
	nsvg__addPathPoint(r, ptsSerializedPtr[path->pts]*scale,
		ptsSerializedPtr[path->pts+1]*scale, 0);
	// Build edges
	for (i = 0, j = r->npoints-1; i < r->npoints; j = i++)
	    nsvg__addEdge(r, r->points[j].x, r->points[j].y, r->points[i].x, r->points[i].y);
    }
}

static void nsvg__initPaintSerialized(NSVGcachedPaint* cache,
	NSVGpaintSerialized* paint, float opacity,
	NSVGgradientSerialized *gradientSerializedPtr,
	NSVGgradientStop *gradientStopPtr)
{
    int i, j;
    NSVGgradientSerialized* grad;

    cache->type = paint->type;

    if (paint->type == NSVG_PAINT_COLOR) {
	cache->colors[0] = nsvg__applyOpacity(paint->color, opacity);
	return;
    }

    grad = &(gradientSerializedPtr[paint->gradient]);

    cache->spread = grad->spread;
    memcpy(cache->xform, grad->xform, sizeof(float)*6);

    if (grad->nstops == 0) {
	for (i = 0; i < 256; i++)
	    cache->colors[i] = 0;
    } if (grad->nstops == 1) {
	for (i = 0; i < 256; i++)
	    cache->colors[i] = nsvg__applyOpacity(
		    gradientStopPtr[grad->stops+i].color, opacity);
    } else {
	unsigned int ca, cb = 0;
	float ua, ub, du, u;
	int ia, ib, count;

	ca = nsvg__applyOpacity(gradientStopPtr[grad->stops].color, opacity);
	ua = nsvg__clampf(gradientStopPtr[grad->stops].offset, 0, 1);
	ub = nsvg__clampf(gradientStopPtr[grad->stops+grad->nstops-1].offset,
		ua, 1);
	ia = (int)(ua * 255.0f);
	ib = (int)(ub * 255.0f);
	for (i = 0; i < ia; i++) {
	    cache->colors[i] = ca;
	}

	for (i = 0; i < grad->nstops-1; i++) {
	    ca = nsvg__applyOpacity(gradientStopPtr[grad->stops+i].color,
		    opacity);
	    cb = nsvg__applyOpacity(gradientStopPtr[grad->stops+i+1].color,
		    opacity);
	    ua = nsvg__clampf(gradientStopPtr[grad->stops+i].offset, 0, 1);
	    ub = nsvg__clampf(gradientStopPtr[grad->stops+i+1].offset, 0, 1);
	    ia = (int)(ua * 255.0f);
	    ib = (int)(ub * 255.0f);
	    count = ib - ia;
	    if (count <= 0) continue;
	    u = 0;
	    du = 1.0f / (float)count;
	    for (j = 0; j < count; j++) {
		cache->colors[ia+j] = nsvg__lerpRGBA(ca,cb,u);
		u += du;
	    }
	}

	for (i = ib; i < 256; i++)
	    cache->colors[i] = cb;
    }

}

static void nsvg__flattenShapeStrokeSerialized(NSVGrasterizer* r,
	NSVGshapeSerialized* shape, NSVGpathSerialized *pathSerializedPtr,
	float *ptsSerializedPtr, float scale)
{
    int i, j, closed, pathIndex;
    NSVGpathSerialized* path;
    NSVGpoint* p0, *p1;
    float miterLimit = shape->miterLimit;
    int lineJoin = shape->strokeLineJoin;
    int lineCap = shape->strokeLineCap;
    float lineWidth = shape->strokeWidth * scale;

    for (pathIndex = shape->paths; pathIndex != -1;
	    pathIndex = pathSerializedPtr[pathIndex].next) {
	path = &(pathSerializedPtr[pathIndex]);
	// Flatten path
	r->npoints = 0;
	nsvg__addPathPoint(r, ptsSerializedPtr[path->pts]*scale,
		ptsSerializedPtr[path->pts+1]*scale, NSVG_PT_CORNER);
	for (i = 0; i < path->npts-1; i += 3) {
	    float* p = &ptsSerializedPtr[path->pts+i*2];
	    nsvg__flattenCubicBez(r, p[0]*scale,p[1]*scale, p[2]*scale,
		    p[3]*scale, p[4]*scale,p[5]*scale, p[6]*scale,p[7]*scale, 0,
		    NSVG_PT_CORNER);
	}
	if (r->npoints < 2)
	    continue;

	closed = path->closed;

	// If the first and last points are the same, remove the last, mark as closed path.
	p0 = &r->points[r->npoints-1];
	p1 = &r->points[0];
	if (nsvg__ptEquals(p0->x,p0->y, p1->x,p1->y, r->distTol)) {
	    r->npoints--;
	    p0 = &r->points[r->npoints-1];
	    closed = 1;
	}

	if (shape->strokeDashCount > 0) {
	    int idash = 0, dashState = 1;
	    float totalDist = 0, dashLen, allDashLen, dashOffset;
	    NSVGpoint cur;

	    if (closed)
		nsvg__appendPathPoint(r, r->points[0]);

	    // Duplicate points -> points2.
	    nsvg__duplicatePoints(r);
	    r->npoints = 0;
	    cur = r->points2[0];
	    nsvg__appendPathPoint(r, cur);

	    // Figure out dash offset.
	    allDashLen = 0;
	    for (j = 0; j < shape->strokeDashCount; j++)
		allDashLen += shape->strokeDashArray[j];
	    if (shape->strokeDashCount & 1)
		allDashLen *= 2.0f;
	    // Find location inside pattern
	    dashOffset = fmodf(shape->strokeDashOffset, allDashLen);
	    if (dashOffset < 0.0f)
		dashOffset += allDashLen;

	    while (dashOffset > shape->strokeDashArray[idash]) {
		dashOffset -= shape->strokeDashArray[idash];
		idash = (idash + 1) % shape->strokeDashCount;
	    }
	    dashLen = (shape->strokeDashArray[idash] - dashOffset) * scale;

	    for (j = 1; j < r->npoints2; ) {
		float dx = r->points2[j].x - cur.x;
		float dy = r->points2[j].y - cur.y;
		float dist = sqrtf(dx*dx + dy*dy);
        cachePtr->dataOrChan = dataOrChan;
	if (formatObj != NULL) {
	    data = TkGetStringFromObj(formatObj, &length);
	    Tcl_DStringAppend(&cachePtr->formatString, data, length);
	}

	cachePtr->nsvgImage = nsvgImage;
	cachePtr->ropts = *ropts;
	return 1;
    }
    return 0;
}

		if ((totalDist + dist) > dashLen) {
		    // Calculate intermediate point
		    float d = (dashLen - totalDist) / dist;
		    float x = cur.x + dx * d;
		    float y = cur.y + dy * d;
		    nsvg__addPathPoint(r, x, y, NSVG_PT_CORNER);

		    // Stroke
		    if (r->npoints > 1 && dashState) {
			    nsvg__prepareStroke(r, miterLimit, lineJoin);
			    nsvg__expandStroke(r, r->points, r->npoints, 0,
				    lineJoin, lineCap, lineWidth);
		    }
		    // Advance dash pattern
		    dashState = !dashState;
		    idash = (idash+1) % shape->strokeDashCount;
		    dashLen = shape->strokeDashArray[idash] * scale;
		    // Restart
		    cur.x = x;
		    cur.y = y;
		    cur.flags = NSVG_PT_CORNER;
		    totalDist = 0.0f;
		    r->npoints = 0;
		    nsvg__appendPathPoint(r, cur);
		} else {
		    totalDist += dist;
		    cur = r->points2[j];
		    nsvg__appendPathPoint(r, cur);
		    j++;
		}
/*
 *----------------------------------------------------------------------
 *
 * GetCachedSVG --
	    }
	    // Stroke any leftover path
	    if (r->npoints > 1 && dashState)
		nsvg__expandStroke(r, r->points, r->npoints, 0, lineJoin,
			lineCap, lineWidth);
 *
 *	Try to get the NSVGimage from the internal cache.
 *
 * Results:
	} else {
 *	Return the found NSVGimage on success, and NULL otherwise.
 *
 * Side effects:
	    nsvg__prepareStroke(r, miterLimit, lineJoin);
	    nsvg__expandStroke(r, r->points, r->npoints, closed, lineJoin,
		    lineCap, lineWidth);
 *	Calls the CleanCache() function.
 *
 *----------------------------------------------------------------------
 */

static NSVGimage *
GetCachedSVG(
    Tcl_Interp *interp,
    ClientData dataOrChan,
	}
    }
}


/*
 *----------------------------------------------------------------------
 *
 * RasterizeSVGSerialized --
 *
 *	This function is called to rasterize the given nsvgImage and
 *	fill the imageHandle with data.
    Tcl_Obj *formatObj,
    RastOpts *ropts)
{
 *
 * Results:
 *	A standard TCL completion code. If TCL_ERROR is returned then an error
 *	message is left in the interp's result.
 *
 *
 * Side effects:
 *	On error the given nsvgImage will be deleted.
 *
 *----------------------------------------------------------------------
 */

    TkSizeT length;
    const char *data;
    NSVGcache *cachePtr = GetCachePtr(interp);
    NSVGimage *nsvgImage = NULL;

    if ((cachePtr != NULL) && (cachePtr->nsvgImage != NULL) &&
static void nsvgRasterizeSerialized(NSVGrasterizer* r,
	char *svgBlobPtr, float tx, float ty, float scale,
	unsigned char* dst, int w, int h, int stride)
{
    NSVGshapeSerialized *shape = NULL;
	(cachePtr->dataOrChan == dataOrChan)) {
        if (formatObj != NULL) {
    NSVGedge *e = NULL;
	    data = TkGetStringFromObj(formatObj, &length);
	    if (strcmp(data, Tcl_DStringValue(&cachePtr->formatString)) == 0) {
	        nsvgImage = cachePtr->nsvgImage;
		*ropts = cachePtr->ropts;
		cachePtr->nsvgImage = NULL;
    NSVGcachedPaint cache;
    int i, shapeIndex;
    serializedHeader * serializedHeaderPtr;
	    }
	} else if (Tcl_DStringLength(&cachePtr->formatString) == 0) {
	    nsvgImage = cachePtr->nsvgImage;
	    *ropts = cachePtr->ropts;
	    cachePtr->nsvgImage = NULL;
	}
    NSVGshapeSerialized *shapeSerializedPtr;
    NSVGpathSerialized *pathSerializedPtr;
    float *ptsSerializedPtr;
    NSVGgradientSerialized *gradientSerializedPtr;
    NSVGgradientStop *gradientStopPtr;

    }
    CleanCache(interp);
    return nsvgImage;
    /*
     * Prepare the array pointers of the data array placed after serializedHeader
     */
    serializedHeaderPtr = (serializedHeader *) svgBlobPtr;
    svgBlobPtr += sizeof (serializedHeader);
}

/*
 *----------------------------------------------------------------------
 *
 * CleanCache --
 *
    shapeSerializedPtr = (NSVGshapeSerialized *) svgBlobPtr;
    svgBlobPtr += serializedHeaderPtr->shapeCount * sizeof(NSVGshapeSerialized);
    pathSerializedPtr = (NSVGpathSerialized *) svgBlobPtr;
    svgBlobPtr += serializedHeaderPtr->pathCount * sizeof(NSVGpathSerialized);
    ptsSerializedPtr = (float *) svgBlobPtr;
    svgBlobPtr += serializedHeaderPtr->ptsCount * sizeof(float);
    gradientSerializedPtr = (NSVGgradientSerialized *) svgBlobPtr;
    svgBlobPtr += serializedHeaderPtr->gradientCount *
	    sizeof(NSVGgradientSerialized);
    gradientStopPtr = (NSVGgradientStop *) svgBlobPtr;

    r->bitmap = dst;
    r->width = w;
    r->height = h;
    r->stride = stride;

 *	Reset the cache and delete the saved image in it.
 *
    if (w > r->cscanline) {
	r->cscanline = w;
	r->scanline = (unsigned char*)NANOSVG_realloc(r->scanline, w);
	if (r->scanline == NULL) return;
    }

 * Results:
 *
 * Side effects:
 *
    for (i = 0; i < h; i++)
	memset(&dst[i*stride], 0, w*4);

 *----------------------------------------------------------------------
 */

static void
    for (shapeIndex = 0 ; shapeIndex < serializedHeaderPtr->shapeCount;
	    shapeIndex++) {
	shape = &(shapeSerializedPtr[shapeIndex]);
	if (!(shape->flags & NSVG_FLAGS_VISIBLE))
	    continue;
CleanCache(Tcl_Interp *interp)
{
    NSVGcache *cachePtr = GetCachePtr(interp);


	if (shape->fill.type != NSVG_PAINT_NONE) {
	    nsvg__resetPool(r);
    if (cachePtr != NULL) {
        cachePtr->dataOrChan = NULL;
	    r->freelist = NULL;
        Tcl_DStringSetLength(&cachePtr->formatString, 0);
	if (cachePtr->nsvgImage != NULL) {
	    nsvgDelete(cachePtr->nsvgImage);
	    cachePtr->nsvgImage = NULL;
	}
    }
}
	    r->nedges = 0;

	    nsvg__flattenShapeSerialized(r, shape->paths, pathSerializedPtr, ptsSerializedPtr,
		    scale);

	    // Scale and translate edges
	    for (i = 0; i < r->nedges; i++) {
		e = &r->edges[i];
		e->x0 = tx + e->x0;
		e->y0 = (ty + e->y0) * NSVG__SUBSAMPLES;
		e->x1 = tx + e->x1;
		e->y1 = (ty + e->y1) * NSVG__SUBSAMPLES;
	    }

	    // Rasterize edges
	    qsort(r->edges, r->nedges, sizeof(NSVGedge), nsvg__cmpEdge);

/*
 *----------------------------------------------------------------------
 *
 * FreeCache --
 *
	    // now, traverse the scanlines and find the intersections on each scanline, use non-zero rule
	    nsvg__initPaintSerialized(&cache, &shape->fill, shape->opacity,
		    gradientSerializedPtr, gradientStopPtr);

	    nsvg__rasterizeSortedEdges(r, tx,ty,scale, &cache, shape->fillRule);
	}
	if (shape->stroke.type != NSVG_PAINT_NONE && (shape->strokeWidth * scale) > 0.01f) {
	    nsvg__resetPool(r);
	    r->freelist = NULL;
	    r->nedges = 0;

 *	This function is called to clean up the internal cache data.
 *
 * Results:
 *
	    nsvg__flattenShapeStrokeSerialized(r, shape, pathSerializedPtr,
		    ptsSerializedPtr, scale);

	    //			dumpEdges(r, "edge.svg");

 * Side effects:
 *	Existing image data in the cache and the cache will be deleted.
 *
	    // Scale and translate edges
	    for (i = 0; i < r->nedges; i++) {
		e = &r->edges[i];
		e->x0 = tx + e->x0;
		e->y0 = (ty + e->y0) * NSVG__SUBSAMPLES;
		e->x1 = tx + e->x1;
		e->y1 = (ty + e->y1) * NSVG__SUBSAMPLES;
	    }

 *----------------------------------------------------------------------
 */
	    // Rasterize edges
	    qsort(r->edges, r->nedges, sizeof(NSVGedge), nsvg__cmpEdge);

static void
FreeCache(ClientData clientData, Tcl_Interp *interp)
{
	    // now, traverse the scanlines and find the intersections on each scanline, use non-zero rule
	    nsvg__initPaintSerialized(&cache, &shape->stroke, shape->opacity,
		    gradientSerializedPtr, gradientStopPtr);

    NSVGcache *cachePtr = (NSVGcache *)clientData;
    (void)interp;

    Tcl_DStringFree(&cachePtr->formatString);
    if (cachePtr->nsvgImage != NULL) {
	    nsvg__rasterizeSortedEdges(r, tx,ty,scale, &cache, NSVG_FILLRULE_NONZERO);
	}
    }

    nsvg__unpremultiplyAlpha(dst, w, h, stride);
        nsvgDelete(cachePtr->nsvgImage);
    }
    ckfree(cachePtr);

    r->bitmap = NULL;
    r->width = 0;
    r->height = 0;
    r->stride = 0;
}

Changes to tests/imgSVGnano.test.

202
203
204
205
206
207
208
























209
210
211
212
213
214
215
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







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







    tcltest::removeFile tmpplus.svg
} -body {
    foo configure -format "svg -scale 2"
} -cleanup {
    rename foo ""
    tcltest::removeFile tmpplus.svg
} -returnCodes error -match glob -result {couldn't open "*/tmpplus.svg": no such file or directory}

test imgSVGnano-5.0 {svgblob metadata creation} -setup {
    catch {rename foo ""}
    tcltest::makeFile $data(plus) tmpplus.svg
} -body {
    image create photo foo -file [file join [tcltest::configure -tmpdir] tmpplus.svg]
	dict keys [foo cget -metadata]
} -cleanup {
    rename foo ""
    tcltest::removeFile tmpplus.svg
} -result {SVGBLOB}

test imgSVGnano-5.1 {scale with svgblob metadata} -setup {
    catch {rename foo ""}
    tcltest::makeFile $data(plus) tmpplus.svg
} -body {
    image create photo foo -file [file join [tcltest::configure -tmpdir] tmpplus.svg]
	foo configure -file "" -data "<svg data=\"metadata\" />"
    foo configure -format "svg -scale 2"
    lappend res [image width foo] [image height foo]
} -cleanup {
    rename foo ""
    tcltest::removeFile tmpplus.svg
} -result {200 200}

};# end of namespace svgnano

namespace delete svgnano
imageFinish
cleanupTests
return