Tk Source Code

Changes On Branch bug-d6e9b4db_svg-match-big-file
Login

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

Changes In Branch bug-d6e9b4db_svg-match-big-file Excluding Merge-Ins

This is equivalent to a diff from 033989e8 to 4ca1ecb0

2020-09-28
13:58
close fork check-in: 41245ce2 user: dgp tags: trunk
09:26
Merge trunk Closed-Leaf check-in: 4ca1ecb0 user: oehhar tags: bug-d6e9b4db_svg-match-big-file
09:04
Nanosvg Upstream commit https://github.com/memononen/nanosvg/commit/ddd39e96691584fc15475c78346dff758b347767 Upstream comment: Fix for #185 - prevent infinite loop when gradient ID is left to empty string - prevent infinite loop when gradient references to self - lookup up to 32 references back check-in: 033989e8 user: oehhar tags: trunk
08:59
nanosvg.h: Upstream commit https://github.com/memononen/nanosvg/commit/e7f5981b1efef8cb5db6f62915ca4e25482b1e5b Upstream Comment: Fix for #184 - make sure nsvg__addPath() hands only valid number of pointts (1+N*3) - require moveTo path command before handling other commands - require (sign+)digit for a valid path command coordinate - allow to add bezier segment only after there’s at leat one point (now also consistent with nsvg__lineTo) check-in: 32168c27 user: oehhar tags: trunk
2020-09-22
07:11
Merge trunk. All tests pass except bind-34.3 check-in: 4f705dd5 user: oehhar tags: bug-d6e9b4db_svg-match-big-file

Changes to generic/tkImgSVGnano.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28


29
30
31
32
33

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70


71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117































































































































118
119
120
121
122
123
124
125
126
127
128
129



130
131

132
133
134


135

136
137
138
139
140
141


142
143
144
145
146
147
148
149
150
151


152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190

191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241



242
243


244
245
246

247
248
249
250
251

252
253
254
255
256


257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320




























































































































321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/*
 * tkImgSVGnano.c
 *
 *	A photo file handler for SVG files.
 *
 * Copyright (c) 2013-14 Mikko Mononen [email protected]
 * Copyright (c) 2018 Christian Gollwitzer [email protected]
 * Copyright (c) 2018 Christian Werner https://www.androwish.org/
 * Copyright (c) 2018 Rene Zaumseil [email protected]
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * This handler is build using the original nanosvg library files from
 * https://github.com/memononen/nanosvg
 *
 */

#include "tkInt.h"
#define NANOSVG_malloc	ckalloc
#define NANOSVG_realloc	ckrealloc
#define NANOSVG_free	ckfree
#define NANOSVG_SCOPE MODULE_SCOPE
#define NANOSVG_ALL_COLOR_KEYWORDS
#define NANOSVG_IMPLEMENTATION
#include "nanosvg.h"
#define NANOSVGRAST_IMPLEMENTATION
#include "nanosvgrast.h"



/* Additional parameters to nsvgRasterize() */

typedef struct {
    double scale;

    int scaleToHeight;
    int scaleToWidth;
} RastOpts;

/*
 * 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_Channel chan, const char *fileName,
			    Tcl_Obj *format, int *widthPtr, int *heightPtr,
			    Tcl_Interp *interp);
static int		FileReadSVG(Tcl_Interp *interp, Tcl_Channel chan,
			    const char *fileName, Tcl_Obj *format,
			    Tk_PhotoHandle imageHandle, int destX, int destY,
			    int width, int height, int srcX, int srcY);
static int		StringMatchSVG(Tcl_Obj *dataObj, Tcl_Obj *format,
			    int *widthPtr, int *heightPtr, Tcl_Interp *interp);
static int		StringReadSVG(Tcl_Interp *interp, Tcl_Obj *dataObj,
			    Tcl_Obj *format, Tk_PhotoHandle imageHandle,
			    int destX, int destY, int width, int height,
			    int srcX, int srcY);
static NSVGimage *	ParseSVGWithOptions(Tcl_Interp *interp,
			    const char *input, TkSizeT length, Tcl_Obj *format,
			    RastOpts *ropts);


static int		RasterizeSVG(Tcl_Interp *interp,
			    Tk_PhotoHandle imageHandle, NSVGimage *nsvgImage,
			    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);
static int		CacheSVG(Tcl_Interp *interp, ClientData dataOrChan,
			    Tcl_Obj *formatObj, 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);

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

Tk_PhotoImageFormat tkImgFmtSVGnano = {
    "svg",			/* name */
    FileMatchSVG,		/* fileMatchProc */
    StringMatchSVG,		/* stringMatchProc */
    FileReadSVG,		/* fileReadProc */
    StringReadSVG,		/* stringReadProc */
    NULL,			/* fileWriteProc */
    NULL,			/* stringWriteProc */
    NULL
};

/*
 *----------------------------------------------------------------------
 *
 * FileMatchSVG --
 *
 *	This function is invoked by the photo image type to see if a file
 *	contains image data in SVG format.
 *
 * Results:
 *	The return value is >0 if the file can be successfully parsed,
 *	and 0 otherwise.
 *
 * Side effects:
 *	The file is saved in the internal cache for further use.
 *
 *----------------------------------------------------------------------
 */
































































































































static int
FileMatchSVG(
    Tcl_Channel chan,
    const char *fileName,
    Tcl_Obj *formatObj,
    int *widthPtr, int *heightPtr,
    Tcl_Interp *interp)
{
    TkSizeT length;
    Tcl_Obj *dataObj = Tcl_NewObj();
    const char *data;



    RastOpts ropts;
    NSVGimage *nsvgImage;

    (void)fileName;

    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;
    }
    data = TkGetStringFromObj(dataObj, &length);
    nsvgImage = ParseSVGWithOptions(interp, data, length, formatObj, &ropts);


    Tcl_DecrRefCount(dataObj);
    if (nsvgImage != NULL) {
        GetScaleFromParameters(nsvgImage, &ropts, widthPtr, heightPtr);
        if ((*widthPtr <= 0.0) || (*heightPtr <= 0.0)) {
	    nsvgDelete(nsvgImage);
	    return 0;
        }
        if (!CacheSVG(interp, chan, formatObj, nsvgImage, &ropts)) {
	    nsvgDelete(nsvgImage);
        }


        return 1;
    }
    return 0;
}

/*
 *----------------------------------------------------------------------
 *
 * 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.
 *
 * Results:
 *	A standard TCL completion code. If TCL_ERROR is returned then an error
 *	message is left in the interp's result.
 *
 * Side effects:
 *	The access position in file f is changed, and new data is added to the
 *	image given by imageHandle.
 *
 *----------------------------------------------------------------------
 */

static int
FileReadSVG(
    Tcl_Interp *interp,
    Tcl_Channel chan,
    const char *fileName,
    Tcl_Obj *formatObj,
    Tk_PhotoHandle imageHandle,
    int destX, int destY,
    int width, int height,
    int srcX, int srcY)
{
    TkSizeT length;
    const char *data;
    RastOpts ropts;
    NSVGimage *nsvgImage = GetCachedSVG(interp, chan, formatObj, &ropts);

    (void)fileName;

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

	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_SetErrorCode(interp, "TK", "IMAGE", "SVG", "READ_ERROR", NULL);
	    return TCL_ERROR;
	}
	data = TkGetStringFromObj(dataObj, &length);
	nsvgImage = ParseSVGWithOptions(interp, data, length, formatObj,
			    &ropts);
	Tcl_DecrRefCount(dataObj);
	if (nsvgImage == NULL) {
	    return TCL_ERROR;
	}
    }
    return RasterizeSVG(interp, imageHandle, nsvgImage, destX, destY,
		width, height, srcX, srcY, &ropts);
}

/*
 *----------------------------------------------------------------------
 *
 * StringMatchSVG --
 *
 *	This function is invoked by the photo image type to see if a string
 *	contains image data in SVG format.
 *
 * Results:
 *	The return value is >0 if the file can be successfully parsed,
 *	and 0 otherwise.
 *
 * Side effects:
 *	The file is saved in the internal cache for further use.
 *
 *----------------------------------------------------------------------
 */

static int
StringMatchSVG(
    Tcl_Obj *dataObj,
    Tcl_Obj *formatObj,
    int *widthPtr, int *heightPtr,
    Tcl_Interp *interp)
{
    TkSizeT length;
    const char *data;



    RastOpts ropts;
    NSVGimage *nsvgImage;



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

    nsvgImage = ParseSVGWithOptions(interp, data, length, formatObj, &ropts);
    if (nsvgImage != NULL) {
        GetScaleFromParameters(nsvgImage, &ropts, widthPtr, heightPtr);
        if ((*widthPtr <= 0.0) || (*heightPtr <= 0.0)) {
	    nsvgDelete(nsvgImage);

	    return 0;
        }
        if (!CacheSVG(interp, dataObj, formatObj, nsvgImage, &ropts)) {
	    nsvgDelete(nsvgImage);
        }


        return 1;
    }
    return 0;
}

/*
 *----------------------------------------------------------------------
 *
 * StringReadSVG --
 *
 *	This function is called by the photo image type to read SVG format
 *	data from a string and write it into a given photo image.
 *
 * Results:
 *	A standard TCL completion code. If TCL_ERROR is returned then an error
 *	message is left in the interp's result.
 *
 * Side effects:
 *	New data is added to the image given by imageHandle.
 *
 *----------------------------------------------------------------------
 */

static int
StringReadSVG(
    Tcl_Interp *interp,
    Tcl_Obj *dataObj,
    Tcl_Obj *formatObj,
    Tk_PhotoHandle imageHandle,
    int destX, int destY,
    int width, int height,
    int srcX, int srcY)
{
    TkSizeT length;
    const char *data;
    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);
}

/*
 *----------------------------------------------------------------------
 *
 * ParseSVGWithOptions --
 *
 *	This function is called to parse the given input string as SVG.
 *
 * Results:
 *	Return a newly create NSVGimage on success, and NULL otherwise.
 *
 * Side effects:
 *
 *----------------------------------------------------------------------
 */





























































































































static NSVGimage *
ParseSVGWithOptions(
    Tcl_Interp *interp,
    const char *input,
    TkSizeT length,
    Tcl_Obj *formatObj,
    RastOpts *ropts)
{
    Tcl_Obj **objv = NULL;
    int objc = 0;
    double dpi = 96.0;
    char *inputCopy = NULL;
    NSVGimage *nsvgImage;
    int parameterScaleSeen = 0;
    static const char *const fmtOptions[] = {
        "-dpi", "-scale", "-scaletoheight", "-scaletowidth", NULL
    };
    enum fmtOptions {
	OPT_DPI, OPT_SCALE, OPT_SCALE_TO_HEIGHT, OPT_SCALE_TO_WIDTH
    };

    /*
     * The parser destroys the original input string,
     * therefore first duplicate.
     */

    inputCopy = (char *)attemptckalloc(length+1);
    if (inputCopy == NULL) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj("cannot alloc data buffer", -1));
	Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "OUT_OF_MEMORY", NULL);
	goto error;
    }
    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;
    if ((formatObj != NULL) &&
	    Tcl_ListObjGetElements(interp, formatObj, &objc, &objv) != TCL_OK) {
        goto error;
    }
    for (; objc > 0 ; objc--, objv++) {
	int optIndex;

	/*
	 * Ignore the "svg" part of the format specification.
	 */

	if (!strcasecmp(Tcl_GetString(objv[0]), "svg")) {
	    continue;
	}

	if (Tcl_GetIndexFromObjStruct(interp, objv[0], fmtOptions,
		sizeof(char *), "option", 0, &optIndex) == TCL_ERROR) {
	    goto error;
	}

	if (objc < 2) {
	    ckfree(inputCopy);
	    inputCopy = NULL;
	    Tcl_WrongNumArgs(interp, 1, objv, "value");
	    goto error;
	}

	objc--;
	objv++;

	/*
	 * check that only one scale option is given
	 */
	switch ((enum fmtOptions) optIndex) {
	case OPT_SCALE:
	case OPT_SCALE_TO_HEIGHT:
	case OPT_SCALE_TO_WIDTH:
	    if ( parameterScaleSeen ) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj(
			"only one of -scale, -scaletoheight, -scaletowidth may be given", -1));
		Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "BAD_SCALE",
			NULL);
		goto error;
	    }
	    parameterScaleSeen = 1;
	    break;
	default:
	    break;
	}

	/*
	 * Decode parameters
	 */
	switch ((enum fmtOptions) optIndex) {
	case OPT_DPI:
	    if (Tcl_GetDoubleFromObj(interp, objv[0], &dpi) == TCL_ERROR) {
	        goto error;
	    }
	    if (dpi < 0.0) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj(
			"-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) ==
		TCL_ERROR) {
	        goto error;
	    }
	    if (ropts->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) {
	        goto error;
	    }
	    if (ropts->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) {
	        goto error;
	    }
	    if (ropts->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;
	}
    }

    nsvgImage = nsvgParse(inputCopy, "px", (float) dpi);
    if (nsvgImage == NULL) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj("cannot parse SVG image", -1));
	Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "PARSE_ERROR", NULL);
	goto error;
    }
    ckfree(inputCopy);
    return nsvgImage;

error:
    if (inputCopy != NULL) {
        ckfree(inputCopy);
    }
    return NULL;
}

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



|















|
|
|






>
>





>




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






|
|
|
|
|
|
|








|
|


|
|
<
<
<



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












>
>
>

<
>


|
>
>
|
>
|
|
|


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

|







|
|


|
|


|
|


















|
>


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

|







|
|


|
|
<
<
<













>
>
>

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

|







|
|


|
|


|

















|

<
|
|
<
<

|


|







|


|





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









<
<
<

|
<
<
<
<
<
<
<








|
|
|




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

|
|
|
















|
|


|
|



|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

















41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64








65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237

238
239
240
241
242
243
244
245
246
247
248
249
250

251
252
253




254
255
256


257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300



301
302
303
304
305
306
307
308
309

310
311
312
313

314
315
316
317
318
319
320
321
322
323
324
325
326
327
328



329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353




354
355
356


357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397

398
399


400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553



554
555







556
557
558
559
560
561
562
563
564
565
566
567
568
569
570








571

572








































































































573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
/*
 * tkImgSVGnano.c
 *
 *  A photo file handler for SVG files.
 *
 * Copyright (c) 2013-14 Mikko Mononen [email protected]
 * Copyright (c) 2018 Christian Gollwitzer [email protected]
 * Copyright (c) 2018 Christian Werner https://www.androwish.org/
 * Copyright (c) 2018 Rene Zaumseil [email protected]
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * This handler is build using the original nanosvg library files from
 * https://github.com/memononen/nanosvg
 *
 */

#include "tkInt.h"
#define NANOSVG_malloc  ckalloc
#define NANOSVG_realloc ckrealloc
#define NANOSVG_free    ckfree
#define NANOSVG_SCOPE MODULE_SCOPE
#define NANOSVG_ALL_COLOR_KEYWORDS
#define NANOSVG_IMPLEMENTATION
#include "nanosvg.h"
#define NANOSVGRAST_IMPLEMENTATION
#include "nanosvgrast.h"

#define MAX_MATCH_BYTES 4096

/* Additional parameters to nsvgRasterize() */

typedef struct {
    double scale;
    double dpi;
    int scaleToHeight;
    int scaleToWidth;
} RastOpts;


















static int      FileMatchSVG(Tcl_Channel chan, const char *fileName,
                Tcl_Obj *format, int *widthPtr, int *heightPtr,
                Tcl_Interp *interp);
static int      FileReadSVG(Tcl_Interp *interp, Tcl_Channel chan,
                const char *fileName, Tcl_Obj *format,
                Tk_PhotoHandle imageHandle, int destX, int destY,
                int width, int height, int srcX, int srcY);
static int      StringMatchSVG(Tcl_Obj *dataObj, Tcl_Obj *format,
                int *widthPtr, int *heightPtr, Tcl_Interp *interp);
static int      StringReadSVG(Tcl_Interp *interp, Tcl_Obj *dataObj,
                Tcl_Obj *format, Tk_PhotoHandle imageHandle,
                int destX, int destY, int width, int height,
                int srcX, int srcY);
static NSVGimage * ParseSVGWithOptions(Tcl_Interp *interp,
                const char *input, TkSizeT length, Tcl_Obj *format,
                RastOpts *ropts);
static int      ParseFormatOptions( Tcl_Interp *interp,
                Tcl_Obj *formatObj, RastOpts *ropts);
static int      RasterizeSVG(Tcl_Interp *interp,
                Tk_PhotoHandle imageHandle, NSVGimage *nsvgImage,
                int destX, int destY, int width, int height,
                int srcX, int srcY, RastOpts *ropts);
static double   GetScaleFromParameters(float svgWidth, float svgHeight,
                RastOpts *ropts, int *widthPtr, int *heightPtr);









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

Tk_PhotoImageFormat tkImgFmtSVGnano = {
    "svg",              /* name */
    FileMatchSVG,       /* fileMatchProc */
    StringMatchSVG,     /* stringMatchProc */
    FileReadSVG,        /* fileReadProc */
    StringReadSVG,      /* stringReadProc */
    NULL,               /* fileWriteProc */
    NULL,               /* stringWriteProc */
    NULL
};

/*
 *----------------------------------------------------------------------
 *
 * FileMatchSVG --
 *
 *  This function is invoked by the photo image type to see if a file
 *  contains image data in SVG format.
 *
 * Results:
 *  The return value is >0 if the file can be successfully parsed,
 *  and 0 otherwise.



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

static int svg_parseUnits(const char* units)
{
    if (units[0] == 'p' && units[1] == 'x')
        return NSVG_UNITS_PX;
    else if (units[0] == 'p' && units[1] == 't')
        return NSVG_UNITS_PT;
    else if (units[0] == 'p' && units[1] == 'c')
        return NSVG_UNITS_PC;
    else if (units[0] == 'm' && units[1] == 'm')
        return NSVG_UNITS_MM;
    else if (units[0] == 'c' && units[1] == 'm')
        return NSVG_UNITS_CM;
    else if (units[0] == 'i' && units[1] == 'n')
        return NSVG_UNITS_IN;
    else if (units[0] == '%')
        return NSVG_UNITS_PERCENT;
    else if (units[0] == 'e' && units[1] == 'm')
        return NSVG_UNITS_EM;
    else if (units[0] == 'e' && units[1] == 'x')
        return NSVG_UNITS_EX;
    return NSVG_UNITS_USER;
}

static NSVGcoordinate svg_parseCoordinateRaw(const char* str)
{
    NSVGcoordinate coord = {0, NSVG_UNITS_USER};
    char units[32]="";
    sscanf(str, "%f%2s", &coord.value, units);
    coord.units = svg_parseUnits(units);
    return coord;
}

static float svg_convertToPixels(NSVGcoordinate c, float dpi)
{
    switch (c.units) {
        case NSVG_UNITS_USER:    return c.value;
        case NSVG_UNITS_PX:      return c.value;
        case NSVG_UNITS_PT:      return c.value / 72.0f * dpi;
        case NSVG_UNITS_PC:      return c.value / 6.0f * dpi;
        case NSVG_UNITS_MM:      return c.value / 25.4f * dpi;
        case NSVG_UNITS_CM:      return c.value / 2.54f * dpi;
        case NSVG_UNITS_IN:      return c.value * dpi;
        case NSVG_UNITS_PERCENT: return 0.0f;
        default:                 return c.value;
    }
    return c.value;
}

static float svg_parseCoordinate(const char* str, float dpi)
{
    NSVGcoordinate coord = svg_parseCoordinateRaw(str);
    return svg_convertToPixels(coord, dpi);
}

static int
IsSvgFile(
    const char *data,
    int maxInd,
    float dpi,
    float *svgWidth,
    float *svgHeight)
{
    int curInd = 0;
    const char *svgStart   = NULL;
    const char *svgEnd     = NULL;
    const char *widthStr   = NULL;
    const char *heightStr  = NULL;
    const char *viewBoxStr = NULL;

    svgEnd = data + maxInd;
    while (data[curInd] && curInd < maxInd) {
        if (data[curInd] == '<') {
            curInd++;
            if (curInd + 3 < maxInd && strncmp(&data[curInd], "svg", 3) == 0) {
                curInd += 3;
                svgStart = &data[curInd];
            }
        } else if (data[curInd] == '>' && svgStart) {
            svgEnd = &data[curInd];
            break;
        }
        curInd++;
    }
    if (!svgStart) {
        return 0;
    }
    widthStr   = strstr(svgStart, " width=");
    heightStr  = strstr(svgStart, " height=");
    viewBoxStr = strstr(svgStart, " viewBox=");
    if (viewBoxStr && viewBoxStr < svgEnd) {
        float viewMinx, viewMiny, viewWidth, viewHeight;
        sscanf(viewBoxStr + 10, "%f%*[%%, \t]%f%*[%%, \t]%f%*[%%, \t]%f", 
               &viewMinx, &viewMiny, &viewWidth, &viewHeight);
        *svgWidth  = viewWidth;
        *svgHeight = viewHeight;
    }
    if (widthStr && widthStr < svgEnd) {
        float val = svg_parseCoordinate( widthStr + 8, dpi);
        if (val > 0.0f) {
            *svgWidth = val;
        } else {
            return 0;
        }
    }
    if (heightStr && heightStr < svgEnd) {
        float val = svg_parseCoordinate( heightStr + 9, dpi);
        if (val > 0.0f) {
            *svgHeight = val;
        } else {
            return 0;
        }
    }
    if (*svgHeight == 0.0f && *svgWidth > 0.0f) {
        *svgHeight = *svgWidth;
    }
    if (*svgWidth == 0.0f && *svgHeight > 0.0f) {
        *svgWidth = *svgHeight;
    }
    if (*svgWidth == 0.0f) {
        *svgWidth = 300.0f;
    }
    if (*svgHeight == 0.0f) {
        *svgHeight = 300.0f;
    }
    return 1;
}

static int
FileMatchSVG(
    Tcl_Channel chan,
    const char *fileName,
    Tcl_Obj *formatObj,
    int *widthPtr, int *heightPtr,
    Tcl_Interp *interp)
{
    TkSizeT length;
    Tcl_Obj *dataObj = Tcl_NewObj();
    const char *data;
    unsigned int maxInd;
    float svgWidth  = 0.0f;
    float svgHeight = 0.0f;
    RastOpts ropts;

    int numBytesRead;
    (void)fileName;

    if (!ParseFormatOptions(interp, formatObj, &ropts)) {
        return 0;
    }
    numBytesRead = Tcl_ReadChars(chan, dataObj, MAX_MATCH_BYTES, 0);
    if (numBytesRead == TCL_IO_FAILURE) {
        /* in case of an error reading the file */
        Tcl_DecrRefCount(dataObj);
        return 0;
    }
    data = TkGetStringFromObj(dataObj, &length);

    maxInd = length < MAX_MATCH_BYTES? length: MAX_MATCH_BYTES;
    if (!IsSvgFile (data, maxInd, ropts.dpi, &svgWidth, &svgHeight)) {
        Tcl_DecrRefCount(dataObj);




        return 0;
    }
    GetScaleFromParameters(svgWidth, svgHeight, &ropts, widthPtr, heightPtr);


    Tcl_DecrRefCount(dataObj);
    if ((*widthPtr <= 0.0) || (*heightPtr <= 0.0)) {
        return 0;
    }
    return 1;
}

/*
 *----------------------------------------------------------------------
 *
 * 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.
 *
 * Results:
 *  A standard TCL completion code. If TCL_ERROR is returned then an error
 *  message is left in the interp's result.
 *
 * Side effects:
 *  The access position in file f is changed, and new data is added to the
 *  image given by imageHandle.
 *
 *----------------------------------------------------------------------
 */

static int
FileReadSVG(
    Tcl_Interp *interp,
    Tcl_Channel chan,
    const char *fileName,
    Tcl_Obj *formatObj,
    Tk_PhotoHandle imageHandle,
    int destX, int destY,
    int width, int height,
    int srcX, int srcY)
{
    TkSizeT length;
    const char *data;
    RastOpts ropts;
    NSVGimage *nsvgImage = NULL;
    Tcl_Obj *dataObj = Tcl_NewObj();
    (void)fileName;




    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_SetErrorCode(interp, "TK", "IMAGE", "SVG", "READ_ERROR", NULL);
        return TCL_ERROR;
    }
    data = TkGetStringFromObj(dataObj, &length);
    nsvgImage = ParseSVGWithOptions(interp, data, length, formatObj, &ropts);

    Tcl_DecrRefCount(dataObj);
    if (nsvgImage == NULL) {
        return TCL_ERROR;
    }

    return RasterizeSVG(interp, imageHandle, nsvgImage, destX, destY,
                        width, height, srcX, srcY, &ropts);
}

/*
 *----------------------------------------------------------------------
 *
 * StringMatchSVG --
 *
 *  This function is invoked by the photo image type to see if a string
 *  contains image data in SVG format.
 *
 * Results:
 *  The return value is >0 if the file can be successfully parsed,
 *  and 0 otherwise.



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

static int
StringMatchSVG(
    Tcl_Obj *dataObj,
    Tcl_Obj *formatObj,
    int *widthPtr, int *heightPtr,
    Tcl_Interp *interp)
{
    TkSizeT length;
    const char *data;
    unsigned int maxInd;
    float svgWidth  = 0.0f;
    float svgHeight = 0.0f;
    RastOpts ropts;

    if (!ParseFormatOptions (interp, formatObj, &ropts)) {
        return 0;
    }

    data = TkGetStringFromObj (dataObj, &length);
    maxInd = length < MAX_MATCH_BYTES? length: MAX_MATCH_BYTES;





    if (!IsSvgFile (data, maxInd, ropts.dpi, &svgWidth, &svgHeight)) {
        return 0;
    }



    GetScaleFromParameters (svgWidth, svgHeight, &ropts, widthPtr, heightPtr);
    if ((*widthPtr <= 0.0) || (*heightPtr <= 0.0)) {
        return 0;
    }
    return 1;
}

/*
 *----------------------------------------------------------------------
 *
 * StringReadSVG --
 *
 *  This function is called by the photo image type to read SVG format
 *  data from a string and write it into a given photo image.
 *
 * Results:
 *  A standard TCL completion code. If TCL_ERROR is returned then an error
 *  message is left in the interp's result.
 *
 * Side effects:
 *  New data is added to the image given by imageHandle.
 *
 *----------------------------------------------------------------------
 */

static int
StringReadSVG(
    Tcl_Interp *interp,
    Tcl_Obj *dataObj,
    Tcl_Obj *formatObj,
    Tk_PhotoHandle imageHandle,
    int destX, int destY,
    int width, int height,
    int srcX, int srcY)
{
    TkSizeT length;
    const char *data;
    RastOpts ropts;
    NSVGimage *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);
}

/*
 *----------------------------------------------------------------------
 *
 * ParseSVGWithOptions --
 *
 *  This function is called to parse the given input string as SVG.
 *
 * Results:
 *  Return a newly create NSVGimage on success, and NULL otherwise.
 *
 * Side effects:
 *
 *----------------------------------------------------------------------
 */

static int
ParseFormatOptions(
    Tcl_Interp *interp,
    Tcl_Obj *formatObj,
    RastOpts *ropts)
{
    Tcl_Obj **objv = NULL;
    int objc = 0;
    int parameterScaleSeen = 0;
    static const char *const fmtOptions[] = {
        "-dpi", "-scale", "-scaletoheight", "-scaletowidth", NULL
    };
    enum fmtOptions {
        OPT_DPI, OPT_SCALE, OPT_SCALE_TO_HEIGHT, OPT_SCALE_TO_WIDTH
    };

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

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

        /*
         * Ignore the "svg" part of the format specification.
         */

        if (!strcasecmp(Tcl_GetString(objv[0]), "svg")) {
            continue;
        }

        if (Tcl_GetIndexFromObjStruct(interp, objv[0], fmtOptions,
            sizeof(char *), "option", 0, &optIndex) == TCL_ERROR) {
            return 0;
        }

        if (objc < 2) {
            Tcl_WrongNumArgs(interp, 1, objv, "value");
            return 0;
        }

        objc--;
        objv++;

        /*
         * check that only one scale option is given
         */
        switch ((enum fmtOptions) optIndex) {
            case OPT_SCALE:
            case OPT_SCALE_TO_HEIGHT:
            case OPT_SCALE_TO_WIDTH:
                if ( parameterScaleSeen ) {
                    Tcl_SetObjResult(interp, Tcl_NewStringObj(
                        "only one of -scale, -scaletoheight, -scaletowidth may be given", -1));
                    Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "BAD_SCALE", NULL);
                    return 0;
                }
                parameterScaleSeen = 1;
                break;
            default:
                break;
        }

        /*
         * Decode parameters
         */
        switch ((enum fmtOptions) optIndex) {
            case OPT_DPI:
                if (Tcl_GetDoubleFromObj(interp, objv[0], &ropts->dpi) == TCL_ERROR) {
                    return 0;
                }
                if (ropts->dpi < 0.0) {
                    Tcl_SetObjResult(interp, Tcl_NewStringObj(
                        "-dpi value must be positive", -1));
                    Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "BAD_DPI", NULL);
                    return 0;
                }
                break;
            case OPT_SCALE:
                if (Tcl_GetDoubleFromObj(interp, objv[0], &ropts->scale) == TCL_ERROR) {
                    return 0;
                }
                if (ropts->scale <= 0.0) {
                    Tcl_SetObjResult(interp, Tcl_NewStringObj(
                        "-scale value must be positive", -1));
                    Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "BAD_SCALE", NULL);
                    return 0;
                }
                break;
            case OPT_SCALE_TO_HEIGHT:
                if (Tcl_GetIntFromObj(interp, objv[0], &ropts->scaleToHeight) == TCL_ERROR) {
                    return 0;
                }
                if (ropts->scaleToHeight <= 0) {
                    Tcl_SetObjResult(interp, Tcl_NewStringObj(
                        "-scaletoheight value must be positive", -1));
                    Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "BAD_SCALE", NULL);
                    return 0;
                }
                break;
            case OPT_SCALE_TO_WIDTH:
                if (Tcl_GetIntFromObj(interp, objv[0], &ropts->scaleToWidth) == TCL_ERROR) {
                    return 0;
                }
                if (ropts->scaleToWidth <= 0) {
                    Tcl_SetObjResult(interp, Tcl_NewStringObj(
                        "-scaletowidth value must be positive", -1));
                    Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "BAD_SCALE", NULL);
                    return 0;
                }
                break;
        }
    }
    return 1;
}

static NSVGimage *
ParseSVGWithOptions(
    Tcl_Interp *interp,
    const char *input,
    TkSizeT length,
    Tcl_Obj *formatObj,
    RastOpts *ropts)
{



    char *inputCopy = NULL;
    NSVGimage *nsvgImage = NULL;








    /*
     * The parser destroys the original input string,
     * therefore first duplicate.
     */

    inputCopy = (char *)attemptckalloc(length+1);
    if (inputCopy == NULL) {
        Tcl_SetObjResult(interp, Tcl_NewStringObj("cannot alloc data buffer", -1));
        Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "OUT_OF_MEMORY", NULL);
        goto error;
    }
    memcpy(inputCopy, input, length);
    inputCopy[length] = '\0';









    ParseFormatOptions (interp, formatObj, ropts);










































































































    nsvgImage = nsvgParse(inputCopy, "px", ropts->dpi);
    if (nsvgImage == NULL) {
        Tcl_SetObjResult(interp, Tcl_NewStringObj("cannot parse SVG image", -1));
        Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "PARSE_ERROR", NULL);
        goto error;
    }
    ckfree(inputCopy);
    return nsvgImage;

error:
    if (inputCopy != NULL) {
        ckfree(inputCopy);
    }
    return NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * 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,
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
    NSVGrasterizer *rast;
    unsigned char *imgData;
    Tk_PhotoImageBlock svgblock;
    double scale;
    (void)srcX;
    (void)srcY;

    scale = GetScaleFromParameters(nsvgImage, ropts, &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;
    }
    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,
	    (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:







|



|
|
<
|



|
|
|

|
<







|

|
<
|


|
|







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
    NSVGrasterizer *rast;
    unsigned char *imgData;
    Tk_PhotoImageBlock svgblock;
    double scale;
    (void)srcX;
    (void)srcY;

    scale = GetScaleFromParameters(nsvgImage->width, nsvgImage->height, ropts, &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;
    }
    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, (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:
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
}

/*
 *----------------------------------------------------------------------
 *
 * 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(
    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);
    }

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

/*
 *----------------------------------------------------------------------
 *
 * 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 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) {
        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;
}

/*
 *----------------------------------------------------------------------
 *
 * GetCachedSVG --
 *
 *	Try to get the NSVGimage from the internal cache.
 *
 * Results:
 *	Return the found NSVGimage on success, and NULL otherwise.
 *
 * Side effects:
 *	Calls the CleanCache() function.
 *
 *----------------------------------------------------------------------
 */

static NSVGimage *
GetCachedSVG(
    Tcl_Interp *interp,
    ClientData dataOrChan,
    Tcl_Obj *formatObj,
    RastOpts *ropts)
{
    TkSizeT length;
    const char *data;
    NSVGcache *cachePtr = GetCachePtr(interp);
    NSVGimage *nsvgImage = NULL;

    if ((cachePtr != NULL) && (cachePtr->nsvgImage != NULL) &&
	(cachePtr->dataOrChan == dataOrChan)) {
        if (formatObj != NULL) {
	    data = TkGetStringFromObj(formatObj, &length);
	    if (strcmp(data, Tcl_DStringValue(&cachePtr->formatString)) == 0) {
	        nsvgImage = cachePtr->nsvgImage;
		*ropts = cachePtr->ropts;
		cachePtr->nsvgImage = NULL;
	    }
	} else if (Tcl_DStringLength(&cachePtr->formatString) == 0) {
	    nsvgImage = cachePtr->nsvgImage;
	    *ropts = cachePtr->ropts;
	    cachePtr->nsvgImage = NULL;
	}
    }
    CleanCache(interp);
    return nsvgImage;
}

/*
 *----------------------------------------------------------------------
 *
 * CleanCache --
 *
 *	Reset the cache and delete the saved image in it.
 *
 * Results:
 *
 * Side effects:
 *
 *----------------------------------------------------------------------
 */

static void
CleanCache(Tcl_Interp *interp)
{
    NSVGcache *cachePtr = GetCachePtr(interp);

    if (cachePtr != NULL) {
        cachePtr->dataOrChan = NULL;
        Tcl_DStringSetLength(&cachePtr->formatString, 0);
	if (cachePtr->nsvgImage != NULL) {
	    nsvgDelete(cachePtr->nsvgImage);
	    cachePtr->nsvgImage = NULL;
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * FreeCache --
 *
 *	This function is called to clean up the internal cache data.
 *
 * Results:
 *
 * Side effects:
 *	Existing image data in the cache and the cache will be deleted.
 *
 *----------------------------------------------------------------------
 */

static void
FreeCache(ClientData clientData, Tcl_Interp *interp)
{
    NSVGcache *cachePtr = (NSVGcache *)clientData;
    (void)interp;

    Tcl_DStringFree(&cachePtr->formatString);
    if (cachePtr->nsvgImage != NULL) {
        nsvgDelete(cachePtr->nsvgImage);
    }
    ckfree(cachePtr);
}








|
|

|


|


|






|
>







|



|
|
|
|
|
|

|
|
|
|
|
|

|
|
|
|
|
|






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

















































































































































































}

/*
 *----------------------------------------------------------------------
 *
 * 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(
    float svgWidth,
    float svgHeight,
    RastOpts *ropts,
    int *widthPtr,
    int *heightPtr)
{
    double scale;
    int width, height;

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

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