Tk Source Code

Changes On Branch tip-529-image-metadata
Login

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

Changes In Branch tip-529-image-metadata Excluding Merge-Ins

This is equivalent to a diff from 17091574 to 8be1eb72

2020-09-07
19:21
Merge 8.6 check-in: d76581ac user: marc_culler tags: trunk
2020-09-06
15:50
Merge 8.7 check-in: c9d4c2a0 user: jan.nijtmans tags: keysym-unicode
15:43
Merge 8.7 check-in: 324b2234 user: jan.nijtmans tags: strict-index, enhanced-index
2020-09-04
20:04
Merge trunk Leaf check-in: 8be1eb72 user: jan.nijtmans tags: tip-529-image-metadata
16:57
Merge 8.6 check-in: 17091574 user: jan.nijtmans tags: trunk
16:56
Merge 8.5 check-in: 29eeab61 user: jan.nijtmans tags: core-8-6-branch
16:54
Update .travis.yml, hopefully this fixes the Travis build. check-in: 58d6ce2e user: jan.nijtmans tags: tip-529-image-metadata
13:53
Merge 8.6 check-in: 2991150c user: jan.nijtmans tags: trunk

Changes to .travis.yml.

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
      os: linux
      dist: focal
      compiler: clang
      env:
        - BUILD_DIR=unix
        - CFGOPT="--enable-symbols"
# Testing on Mac, various styles
    - name: "macOS/Clang/Xcode 11.6/Shared"
      os: osx
      osx_image: xcode11.7
      env:
        - BUILD_DIR=unix
        - CFGOPT="--with-tcl=/usr/local/opt/tcl-tk/lib --enable-aqua CFLAGS=-I/usr/local/opt/tcl-tk/include"
    - name: "macOS/Clang++/Xcode 11.6/Shared"
      os: osx
      osx_image: xcode11.6
      env:
        - BUILD_DIR=unix
        - CFGOPT="--with-tcl=/usr/local/opt/tcl-tk/lib CC=clang++ --enable-aqua CFLAGS=-I/usr/local/opt/tcl-tk/include CPPFLAGS=-D__private_extern__=extern"
    - name: "macOS/Clang/Xcode 11.6/Shared"
      os: osx
      osx_image: xcode11.6
      env:
        - BUILD_DIR=unix
        - CFGOPT="--with-tcl=/usr/local/opt/tcl-tk/lib --enable-aqua CFLAGS=-I/usr/local/opt/tcl-tk/include"
      install:
        - ./configure ${CFGOPT} "--prefix=$HOME" || (cat config.log && exit 1)
      script: &mactest
        - make all tktest
    - name: "macOS/Clang/Xcode 11.6/Static"
      os: osx
      osx_image: xcode11.7
      env:
        - BUILD_DIR=unix
        - CFGOPT="--with-tcl=/usr/local/opt/tcl-tk/lib --enable-aqua --disable-shared CFLAGS=-I/usr/local/opt/tcl-tk/include"
      install:
        - ./configure ${CFGOPT} "--prefix=$HOME" || (cat config.log && exit 1)
      script: *mactest
    - name: "macOS/Clang/Xcode 11.6/Debug"
      os: osx
      osx_image: xcode11.7
      env:
        - BUILD_DIR=unix
        - CFGOPT="--with-tcl=/usr/local/opt/tcl-tk/lib --enable-aqua --enable-symbols CFLAGS=-I/usr/local/opt/tcl-tk/include"
      install:
        - ./configure ${CFGOPT} "--prefix=$HOME" || (cat config.log && exit 1)
      script: *mactest
    - name: "macOS/Clang/Xcode 11.6/Shared/XQuartz"
      os: osx
      osx_image: xcode11.7
      env:
        - BUILD_DIR=unix
        - CFGOPT="--with-tcl=/usr/local/opt/tcl-tk/lib --disable-corefoundation --x-includes=/opt/X11/include --x-libraries=/opt/X11/lib CFLAGS=-I/usr/local/opt/tcl-tk/include"
      install:
        - ./configure ${CFGOPT} "--prefix=$HOME" || (cat config.log && exit 1)







|





|

|



|

|







|








|








|







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
      os: linux
      dist: focal
      compiler: clang
      env:
        - BUILD_DIR=unix
        - CFGOPT="--enable-symbols"
# Testing on Mac, various styles
    - name: "macOS/Clang/Xcode 11.7/Shared"
      os: osx
      osx_image: xcode11.7
      env:
        - BUILD_DIR=unix
        - CFGOPT="--with-tcl=/usr/local/opt/tcl-tk/lib --enable-aqua CFLAGS=-I/usr/local/opt/tcl-tk/include"
    - name: "macOS/Clang++/Xcode 11.7/Shared"
      os: osx
      osx_image: xcode11.7
      env:
        - BUILD_DIR=unix
        - CFGOPT="--with-tcl=/usr/local/opt/tcl-tk/lib CC=clang++ --enable-aqua CFLAGS=-I/usr/local/opt/tcl-tk/include CPPFLAGS=-D__private_extern__=extern"
    - name: "macOS/Clang/Xcode 11.7/Shared"
      os: osx
      osx_image: xcode11.7
      env:
        - BUILD_DIR=unix
        - CFGOPT="--with-tcl=/usr/local/opt/tcl-tk/lib --enable-aqua CFLAGS=-I/usr/local/opt/tcl-tk/include"
      install:
        - ./configure ${CFGOPT} "--prefix=$HOME" || (cat config.log && exit 1)
      script: &mactest
        - make all tktest
    - name: "macOS/Clang/Xcode 11.7/Static"
      os: osx
      osx_image: xcode11.7
      env:
        - BUILD_DIR=unix
        - CFGOPT="--with-tcl=/usr/local/opt/tcl-tk/lib --enable-aqua --disable-shared CFLAGS=-I/usr/local/opt/tcl-tk/include"
      install:
        - ./configure ${CFGOPT} "--prefix=$HOME" || (cat config.log && exit 1)
      script: *mactest
    - name: "macOS/Clang/Xcode 11.7/Debug"
      os: osx
      osx_image: xcode11.7
      env:
        - BUILD_DIR=unix
        - CFGOPT="--with-tcl=/usr/local/opt/tcl-tk/lib --enable-aqua --enable-symbols CFLAGS=-I/usr/local/opt/tcl-tk/include"
      install:
        - ./configure ${CFGOPT} "--prefix=$HOME" || (cat config.log && exit 1)
      script: *mactest
    - name: "macOS/Clang/Xcode 11.7/Shared/XQuartz"
      os: osx
      osx_image: xcode11.7
      env:
        - BUILD_DIR=unix
        - CFGOPT="--with-tcl=/usr/local/opt/tcl-tk/lib --disable-corefoundation --x-includes=/opt/X11/include --x-libraries=/opt/X11/lib CFLAGS=-I/usr/local/opt/tcl-tk/include"
      install:
        - ./configure ${CFGOPT} "--prefix=$HOME" || (cat config.log && exit 1)

Changes to generic/tk.decls.

1086
1087
1088
1089
1090
1091
1092







1093
1094
1095
1096
1097
1098
1099
declare 278 {
    void Tk_SendVirtualEvent(Tk_Window tkwin, const char *eventName,
	    Tcl_Obj *detail)
}
declare 279 {
    Tcl_Obj *Tk_FontGetDescription(Tk_Font tkfont)
}








# Define the platform specific public Tk interface.  These functions are
# only available on the designated platform.

interface tkPlat

################################







>
>
>
>
>
>
>







1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
declare 278 {
    void Tk_SendVirtualEvent(Tk_Window tkwin, const char *eventName,
	    Tcl_Obj *detail)
}
declare 279 {
    Tcl_Obj *Tk_FontGetDescription(Tk_Font tkfont)
}

# New in Tk8.7
declare 280 {
    void Tk_CreatePhotoImageFormatVersion3(
	    const Tk_PhotoImageFormatVersion3 *formatPtr)
}


# Define the platform specific public Tk interface.  These functions are
# only available on the designated platform.

interface tkPlat

################################

Changes to generic/tk.h.

1433
1434
1435
1436
1437
1438
1439






























1440
1441
1442
1443
1444
1445
1446
	Tcl_Obj *format, Tk_PhotoHandle imageHandle, int destX, int destY,
	int width, int height, int srcX, int srcY);
typedef int (Tk_ImageFileWriteProc) (Tcl_Interp *interp, const char *fileName,
	Tcl_Obj *format, Tk_PhotoImageBlock *blockPtr);
typedef int (Tk_ImageStringWriteProc) (Tcl_Interp *interp, Tcl_Obj *format,
	Tk_PhotoImageBlock *blockPtr);
#endif /* USE_OLD_IMAGE */































/*
 * The following structure represents a particular file format for storing
 * images (e.g., PPM, GIF, JPEG, etc.). It provides information to allow image
 * files of that format to be recognized and read into a photo image.
 */








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







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
	Tcl_Obj *format, Tk_PhotoHandle imageHandle, int destX, int destY,
	int width, int height, int srcX, int srcY);
typedef int (Tk_ImageFileWriteProc) (Tcl_Interp *interp, const char *fileName,
	Tcl_Obj *format, Tk_PhotoImageBlock *blockPtr);
typedef int (Tk_ImageStringWriteProc) (Tcl_Interp *interp, Tcl_Obj *format,
	Tk_PhotoImageBlock *blockPtr);
#endif /* USE_OLD_IMAGE */

/*
 * The following alternate definitions are used with the Tk8.7 file format
 * supporting a metadata dict, internal dstring and close file flag
 */

typedef struct Tk_PhotoImageFormatVersion3 Tk_PhotoImageFormatVersion3;
typedef int (Tk_ImageFileMatchProcVersion3) (Tcl_Interp *interp,
	Tcl_Channel chan, const char *fileName, Tcl_Obj *format,
	Tcl_Obj *metadataIn, int *widthPtr, int *heightPtr,
	Tcl_Obj *metadataOut);
typedef int (Tk_ImageStringMatchProcVersion3) (Tcl_Interp *interp,
	Tcl_Obj *dataObj, Tcl_Obj *format, Tcl_Obj *metadataIn, int *widthPtr,
	int *heightPtr, Tcl_Obj *metadataOut);
typedef int (Tk_ImageFileReadProcVersion3) (Tcl_Interp *interp,
	Tcl_Channel chan,
	const char *fileName, Tcl_Obj *format, Tcl_Obj *metadataIn,
	Tk_PhotoHandle imageHandle,
	int destX, int destY, int width, int height, int srcX, int srcY,
	Tcl_Obj *metadataOut);
typedef int (Tk_ImageStringReadProcVersion3) (Tcl_Interp *interp,
	Tcl_Obj *dataObj, Tcl_Obj *format, Tcl_Obj *metadataIn,
	Tk_PhotoHandle imageHandle, int destX, int destY, int width, int height,
	int srcX, int srcY, Tcl_Obj *metadataOut);
typedef int (Tk_ImageFileWriteProcVersion3) (Tcl_Interp *interp,
	const char *fileName, Tcl_Obj *format, Tcl_Obj *metadataIn,
	Tk_PhotoImageBlock *blockPtr);
typedef int (Tk_ImageStringWriteProcVersion3) (Tcl_Interp *interp,
	Tcl_Obj *format, Tcl_Obj *metadataIn, Tk_PhotoImageBlock *blockPtr);


/*
 * The following structure represents a particular file format for storing
 * images (e.g., PPM, GIF, JPEG, etc.). It provides information to allow image
 * files of that format to be recognized and read into a photo image.
 */

1466
1467
1468
1469
1470
1471
1472
































1473
1474
1475
1476
1477
1478
1479
				 * representation of the data in a photo
				 * image.*/
    struct Tk_PhotoImageFormat *nextPtr;
				/* Next in list of all photo image formats
				 * currently known. Filled in by Tk, not by
				 * image format handler. */
};

































/*
 *----------------------------------------------------------------------
 *
 * Procedure prototypes and structures used for managing styles:
 *
 *----------------------------------------------------------------------







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







1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
				 * representation of the data in a photo
				 * image.*/
    struct Tk_PhotoImageFormat *nextPtr;
				/* Next in list of all photo image formats
				 * currently known. Filled in by Tk, not by
				 * image format handler. */
};

/*
 * The following structure is the same plus added support for the metadata
 * structure.
 */

struct Tk_PhotoImageFormatVersion3 {
    const char *name;		/* Name of image file format */
    Tk_ImageFileMatchProcVersion3 *fileMatchProc;
				/* Procedure to call to determine whether an
				 * image file matches this format. */
    Tk_ImageStringMatchProcVersion3 *stringMatchProc;
				/* Procedure to call to determine whether the
				 * data in a string matches this format. */
    Tk_ImageFileReadProcVersion3 *fileReadProc;
				/* Procedure to call to read data from an
				 * image file into a photo image. */
    Tk_ImageStringReadProcVersion3 *stringReadProc;
				/* Procedure to call to read data from a
				 * string into a photo image. */
    Tk_ImageFileWriteProcVersion3 *fileWriteProc;
				/* Procedure to call to write data from a
				 * photo image to a file. */
    Tk_ImageStringWriteProcVersion3 *stringWriteProc;
				/* Procedure to call to obtain a string
				 * representation of the data in a photo
				 * image.*/
    struct Tk_PhotoImageFormatVersion3 *nextPtr;
				/* Next in list of all photo image formats
				 * currently known. Filled in by Tk, not by
				 * image format handler. */
};

/*
 *----------------------------------------------------------------------
 *
 * Procedure prototypes and structures used for managing styles:
 *
 *----------------------------------------------------------------------

Changes to generic/tkDecls.h.

888
889
890
891
892
893
894



895
896
897
898
899
900
901
/* 277 */
EXTERN Tcl_Obj *	Tk_NewWindowObj(Tk_Window tkwin);
/* 278 */
EXTERN void		Tk_SendVirtualEvent(Tk_Window tkwin,
				const char *eventName, Tcl_Obj *detail);
/* 279 */
EXTERN Tcl_Obj *	Tk_FontGetDescription(Tk_Font tkfont);




typedef struct {
    const struct TkPlatStubs *tkPlatStubs;
    const struct TkIntStubs *tkIntStubs;
    const struct TkIntPlatStubs *tkIntPlatStubs;
    const struct TkIntXlibStubs *tkIntXlibStubs;
} TkStubHooks;







>
>
>







888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
/* 277 */
EXTERN Tcl_Obj *	Tk_NewWindowObj(Tk_Window tkwin);
/* 278 */
EXTERN void		Tk_SendVirtualEvent(Tk_Window tkwin,
				const char *eventName, Tcl_Obj *detail);
/* 279 */
EXTERN Tcl_Obj *	Tk_FontGetDescription(Tk_Font tkfont);
/* 280 */
EXTERN void		Tk_CreatePhotoImageFormatVersion3(
				const Tk_PhotoImageFormatVersion3 *formatPtr);

typedef struct {
    const struct TkPlatStubs *tkPlatStubs;
    const struct TkIntStubs *tkIntStubs;
    const struct TkIntPlatStubs *tkIntPlatStubs;
    const struct TkIntXlibStubs *tkIntXlibStubs;
} TkStubHooks;
1180
1181
1182
1183
1184
1185
1186

1187
1188
1189
1190
1191
1192
1193
    void (*tk_CreateOldPhotoImageFormat) (const Tk_PhotoImageFormat *formatPtr); /* 273 */
    int (*tk_AlwaysShowSelection) (Tk_Window tkwin); /* 274 */
    unsigned (*tk_GetButtonMask) (unsigned button); /* 275 */
    int (*tk_GetDoublePixelsFromObj) (Tcl_Interp *interp, Tk_Window tkwin, Tcl_Obj *objPtr, double *doublePtr); /* 276 */
    Tcl_Obj * (*tk_NewWindowObj) (Tk_Window tkwin); /* 277 */
    void (*tk_SendVirtualEvent) (Tk_Window tkwin, const char *eventName, Tcl_Obj *detail); /* 278 */
    Tcl_Obj * (*tk_FontGetDescription) (Tk_Font tkfont); /* 279 */

} TkStubs;

extern const TkStubs *tkStubsPtr;

#ifdef __cplusplus
}
#endif







>







1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
    void (*tk_CreateOldPhotoImageFormat) (const Tk_PhotoImageFormat *formatPtr); /* 273 */
    int (*tk_AlwaysShowSelection) (Tk_Window tkwin); /* 274 */
    unsigned (*tk_GetButtonMask) (unsigned button); /* 275 */
    int (*tk_GetDoublePixelsFromObj) (Tcl_Interp *interp, Tk_Window tkwin, Tcl_Obj *objPtr, double *doublePtr); /* 276 */
    Tcl_Obj * (*tk_NewWindowObj) (Tk_Window tkwin); /* 277 */
    void (*tk_SendVirtualEvent) (Tk_Window tkwin, const char *eventName, Tcl_Obj *detail); /* 278 */
    Tcl_Obj * (*tk_FontGetDescription) (Tk_Font tkfont); /* 279 */
    void (*tk_CreatePhotoImageFormatVersion3) (const Tk_PhotoImageFormatVersion3 *formatPtr); /* 280 */
} TkStubs;

extern const TkStubs *tkStubsPtr;

#ifdef __cplusplus
}
#endif
1752
1753
1754
1755
1756
1757
1758


1759
1760
1761
1762
1763
1764
1765
	(tkStubsPtr->tk_GetDoublePixelsFromObj) /* 276 */
#define Tk_NewWindowObj \
	(tkStubsPtr->tk_NewWindowObj) /* 277 */
#define Tk_SendVirtualEvent \
	(tkStubsPtr->tk_SendVirtualEvent) /* 278 */
#define Tk_FontGetDescription \
	(tkStubsPtr->tk_FontGetDescription) /* 279 */



#endif /* defined(USE_TK_STUBS) */

/* !END!: Do not edit above this line. */

/* Functions that don't belong in the stub table */
#undef Tk_MainEx







>
>







1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
	(tkStubsPtr->tk_GetDoublePixelsFromObj) /* 276 */
#define Tk_NewWindowObj \
	(tkStubsPtr->tk_NewWindowObj) /* 277 */
#define Tk_SendVirtualEvent \
	(tkStubsPtr->tk_SendVirtualEvent) /* 278 */
#define Tk_FontGetDescription \
	(tkStubsPtr->tk_FontGetDescription) /* 279 */
#define Tk_CreatePhotoImageFormatVersion3 \
	(tkStubsPtr->tk_CreatePhotoImageFormatVersion3) /* 280 */

#endif /* defined(USE_TK_STUBS) */

/* !END!: Do not edit above this line. */

/* Functions that don't belong in the stub table */
#undef Tk_MainEx

Changes to generic/tkImage.c.

1
2
3
4
5
6
7
8
9
10
11
12
13

14
15
16
17
18
19
20
/*
 * tkImage.c --
 *
 *	This module implements the image protocol, which allows lots of
 *	different kinds of images to be used in lots of different widgets.
 *
 * Copyright (c) 1994 The Regents of the University of California.
 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */


#include "tkInt.h"

/*
 * Each call to Tk_GetImage returns a pointer to one of the following
 * structures, which is used as a token by clients (widgets) that display
 * images.
 */













>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
 * tkImage.c --
 *
 *	This module implements the image protocol, which allows lots of
 *	different kinds of images to be used in lots of different widgets.
 *
 * Copyright (c) 1994 The Regents of the University of California.
 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkImgPhoto.h"
#include "tkInt.h"

/*
 * Each call to Tk_GetImage returns a pointer to one of the following
 * structures, which is used as a token by clients (widgets) that display
 * images.
 */
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
Tk_ImageObjCmd(
    ClientData clientData,	/* Main window associated with interpreter. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument strings. */
{
    static const char *const imageOptions[] = {
	"create", "delete", "height", "inuse", "names", "type", "types",
	"width", NULL
    };
    enum options {
	IMAGE_CREATE, IMAGE_DELETE, IMAGE_HEIGHT, IMAGE_INUSE, IMAGE_NAMES,
	IMAGE_TYPE, IMAGE_TYPES, IMAGE_WIDTH
    };
    TkWindow *winPtr = (TkWindow *)clientData;
    int i, isNew, firstOption, index;
    Tk_ImageType *typePtr;
    ImageModel *modelPtr;
    Image *imagePtr;
    Tcl_HashEntry *hPtr;







|
|


|
|







206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
Tk_ImageObjCmd(
    ClientData clientData,	/* Main window associated with interpreter. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument strings. */
{
    static const char *const imageOptions[] = {
	"create", "delete", "height", "inuse", "metadata", 
        "names", "type", "types", "width", NULL
    };
    enum options {
	IMAGE_CREATE, IMAGE_DELETE, IMAGE_HEIGHT, IMAGE_INUSE, IMAGE_METADATA,
        IMAGE_NAMES, IMAGE_TYPE, IMAGE_TYPES, IMAGE_WIDTH
    };
    TkWindow *winPtr = (TkWindow *)clientData;
    int i, isNew, firstOption, index;
    Tk_ImageType *typePtr;
    ImageModel *modelPtr;
    Image *imagePtr;
    Tcl_HashEntry *hPtr;
439
440
441
442
443
444
445
















































































































446
447
448
449
450
451
452
	for (typePtr = tsdPtr->oldImageTypeList; typePtr != NULL;
		typePtr = typePtr->nextPtr) {
	    Tcl_ListObjAppendElement(NULL, resultObj, Tcl_NewStringObj(
		    typePtr->name, -1));
	}
	Tcl_SetObjResult(interp, resultObj);
	break;

















































































































    case IMAGE_HEIGHT:
    case IMAGE_INUSE:
    case IMAGE_TYPE:
    case IMAGE_WIDTH:
	/*
	 * These operations all parse virtually identically. First check to







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







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
	for (typePtr = tsdPtr->oldImageTypeList; typePtr != NULL;
		typePtr = typePtr->nextPtr) {
	    Tcl_ListObjAppendElement(NULL, resultObj, Tcl_NewStringObj(
		    typePtr->name, -1));
	}
	Tcl_SetObjResult(interp, resultObj);
	break;

    case IMAGE_METADATA: {
        int w = 0;
        int h = 0;
        Tcl_Channel chan;
        Tcl_Obj *metadataOutObj;
        Tk_PhotoImageFormat *imageFormat;
        Tk_PhotoImageFormatVersion3 *imageFormatVersion3;
        int oldformat;
        Tcl_DictSearch search;
        Tcl_Obj *key, *value;
        int done;
        char * xbmData;
        const char * fmt = "Unknown";
        int x_hot, y_hot;
        int foundImage = 0;
        const char * option;
        TkSizeT length;
        Tcl_Obj *dataObj = NULL;
        const char *fileName = NULL;

	if (objc < 4) {
	    Tcl_WrongNumArgs(interp, 2, objv, "?-file name? ?-data string?");
	    return TCL_ERROR;
	}
        option = TkGetStringFromObj(objv[2], &length);
	if (length <= 1 || option[0] != '-') {
	    Tcl_WrongNumArgs(interp, 2, objv, "?-file name? ?-data string?");
	    return TCL_ERROR;
        }
        if (length > 1) {
            if (option[1] == 'f' && (strncmp(option, "-file", length) == 0)) {
                fileName = Tcl_GetString(objv[3]);
            } else if (option[1] == 'd' && (strcmp(option, "-data") == 0)) {
                dataObj = objv[3];
            }
        }
        if (dataObj == NULL && fileName == NULL) {
	    Tcl_WrongNumArgs(interp, 2, objv, "?-file name? ?-data string?");
	    return TCL_ERROR;
        }

        metadataOutObj = Tcl_NewDictObj();
	Tcl_IncrRefCount(metadataOutObj);

        if (fileName != NULL) {
            xbmData = TkGetBitmapData(interp, NULL, fileName, &w, &h, &x_hot, &y_hot);
        } else {
            xbmData = TkGetBitmapData(interp, Tcl_GetString(dataObj), NULL, &w, &h, &x_hot, &y_hot);
        }
        if (xbmData != NULL) {
            foundImage = 1;
            fmt = "xbm"; 
        }

        if (!foundImage) {
            if (fileName != NULL) {
                chan = Tcl_OpenFileChannel(interp, fileName, "r", 0);
                if (chan == NULL) {
                    return TCL_ERROR;
                }
                if (Tcl_SetChannelOption(interp, chan, "-translation", "binary") != TCL_OK) {
                    Tcl_Close(NULL, chan);
                    return TCL_ERROR;
                }
                if (Tcl_SetChannelOption(interp, chan, "-encoding", "binary") != TCL_OK) {
                    Tcl_Close(NULL, chan);
                    return TCL_ERROR;
                }
                if (TkImgPhotoMatchFileFormat(
                        interp, chan, fileName, NULL, NULL, metadataOutObj,
                        &imageFormat, &imageFormatVersion3,
                        &w, &h, &oldformat) == TCL_OK) {
                    foundImage = 1;
                }
                Tcl_Close(NULL, chan);
            } else {
                if (TkImgMatchStringFormat(
                        interp, dataObj, NULL, NULL, metadataOutObj,
                        &imageFormat, &imageFormatVersion3,
                        &w, &h, &oldformat) == TCL_OK) {
                    foundImage = 1;
                }
            }
            if (foundImage) {
                if (imageFormat) {
                    fmt = imageFormat->name;
                }
                if (imageFormatVersion3) {
                    fmt = imageFormatVersion3->name;
                }
            }
        }

	resultObj = Tcl_NewDictObj();
        if (foundImage) {
	    Tcl_DictObjPut(interp, resultObj, Tcl_NewStringObj("format", -1), Tcl_NewStringObj(fmt, -1));
	    Tcl_DictObjPut(interp, resultObj, Tcl_NewStringObj("width",  -1), Tcl_NewWideIntObj(w));
	    Tcl_DictObjPut(interp, resultObj, Tcl_NewStringObj("height", -1), Tcl_NewWideIntObj(h));

	    if (Tcl_DictObjFirst(interp, metadataOutObj, &search, &key, &value, &done) != TCL_OK) {
		return TCL_ERROR;
	    }
	    for (; !done ; Tcl_DictObjNext(&search, &key, &value, &done)) {
		Tcl_DictObjPut(interp, resultObj, key, value);
	    }
	    Tcl_DictObjDone(&search); 
	}
	Tcl_DecrRefCount(metadataOutObj);
	Tcl_SetObjResult(interp, resultObj);
	break;
    }

    case IMAGE_HEIGHT:
    case IMAGE_INUSE:
    case IMAGE_TYPE:
    case IMAGE_WIDTH:
	/*
	 * These operations all parse virtually identically. First check to

Changes to generic/tkImgGIF.c.

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
typedef size_t (WriteBytesFunc) (ClientData clientData, const char *bytes,
			    size_t byteCount);

/*
 * The format record for the GIF file format:
 */

static int		FileMatchGIF(Tcl_Channel chan, const char *fileName,
			    Tcl_Obj *format, int *widthPtr, int *heightPtr,
			    Tcl_Interp *interp);

static int		FileReadGIF(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		StringMatchGIF(Tcl_Obj *dataObj, Tcl_Obj *format,

			    int *widthPtr, int *heightPtr, Tcl_Interp *interp);

static int		StringReadGIF(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 int		FileWriteGIF(Tcl_Interp *interp, const char *filename,

			    Tcl_Obj *format, Tk_PhotoImageBlock *blockPtr);
static int		StringWriteGIF(Tcl_Interp *interp, Tcl_Obj *format,

			    Tk_PhotoImageBlock *blockPtr);
static int		CommonWriteGIF(Tcl_Interp *interp, ClientData clientData,

			    WriteBytesFunc *writeProc, Tcl_Obj *format,

			    Tk_PhotoImageBlock *blockPtr);

Tk_PhotoImageFormat tkImgFmtGIF = {
    "gif",		/* name */
    FileMatchGIF,	/* fileMatchProc */
    StringMatchGIF,	/* stringMatchProc */
    FileReadGIF,	/* fileReadProc */
    StringReadGIF,	/* stringReadProc */
    FileWriteGIF,	/* fileWriteProc */
    StringWriteGIF,	/* stringWriteProc */







|
|
|
>


|
|
>
|
>
|
>

>
|

|

>
|

>

|
>

>


|







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
typedef size_t (WriteBytesFunc) (ClientData clientData, const char *bytes,
			    size_t byteCount);

/*
 * The format record for the GIF file format:
 */

static int		FileMatchGIF(Tcl_Interp *interp, Tcl_Channel chan,
			    const char *fileName, Tcl_Obj *format,
			    Tcl_Obj *metadataInObj, int *widthPtr,
			    int *heightPtr, Tcl_Obj *metadataOutObj);
static int		FileReadGIF(Tcl_Interp *interp, Tcl_Channel chan,
			    const char *fileName, Tcl_Obj *format,
			    Tcl_Obj *metadataInObj, Tk_PhotoHandle imageHandle,
			    int destX, int destY, int width, int height,
			    int srcX, int srcY, Tcl_Obj *metadataOutObj);
static int		StringMatchGIF(Tcl_Interp *interp, Tcl_Obj *dataObj,
			    Tcl_Obj *format, Tcl_Obj *metadataInObj,
			    int *widthPtr, int *heightPtr,
			    Tcl_Obj *metadataOutObj);
static int		StringReadGIF(Tcl_Interp *interp, Tcl_Obj *dataObj,
			    Tcl_Obj *format, Tcl_Obj *metadataInObj,
			    Tk_PhotoHandle imageHandle,
			    int destX, int destY, int width, int height,
			    int srcX, int srcY, Tcl_Obj *metadataOutObj);
static int		FileWriteGIF(Tcl_Interp *interp, const char *filename,
			    Tcl_Obj *format, Tcl_Obj *metadataInObj,
			    Tk_PhotoImageBlock *blockPtr);
static int		StringWriteGIF(Tcl_Interp *interp, Tcl_Obj *format,
			    Tcl_Obj *metadataInObj,
			    Tk_PhotoImageBlock *blockPtr);
static int		CommonWriteGIF(Tcl_Interp *interp,
			    ClientData clientData,
			    WriteBytesFunc *writeProc, Tcl_Obj *format,
			    Tcl_Obj *metadataInObj,
			    Tk_PhotoImageBlock *blockPtr);

Tk_PhotoImageFormatVersion3 tkImgFmtGIF = {
    "gif",		/* name */
    FileMatchGIF,	/* fileMatchProc */
    StringMatchGIF,	/* stringMatchProc */
    FileReadGIF,	/* fileReadProc */
    StringReadGIF,	/* stringReadProc */
    FileWriteGIF,	/* fileWriteProc */
    StringWriteGIF,	/* stringWriteProc */
161
162
163
164
165
166
167


168
169
170
171
172
173
174
175
176
177
#define MAX_LWZ_BITS		12
#define LM_to_uint(a,b)		(((b)<<8)|(a))

/*
 * Prototypes for local functions defined in this file:
 */



static int		DoExtension(GIFImageConfig *gifConfPtr,
			    Tcl_Channel chan, int label, unsigned char *buffer,
			    int *transparent);
static int		GetCode(Tcl_Channel chan, int code_size, int flag,
			    GIFImageConfig *gifConfPtr);
static int		GetDataBlock(GIFImageConfig *gifConfPtr,
			    Tcl_Channel chan, unsigned char *buf);
static int		ReadColorMap(GIFImageConfig *gifConfPtr,
			    Tcl_Channel chan, int number,
			    unsigned char buffer[MAXCOLORMAPSIZE][4]);







>
>


|







170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#define MAX_LWZ_BITS		12
#define LM_to_uint(a,b)		(((b)<<8)|(a))

/*
 * Prototypes for local functions defined in this file:
 */

static int		ReadOneByte(Tcl_Interp *interp,
			    GIFImageConfig *gifConfPtr, Tcl_Channel chan);
static int		DoExtension(GIFImageConfig *gifConfPtr,
			    Tcl_Channel chan, int label, unsigned char *buffer,
			    int *transparent, Tcl_Obj *metadataOutObj);
static int		GetCode(Tcl_Channel chan, int code_size, int flag,
			    GIFImageConfig *gifConfPtr);
static int		GetDataBlock(GIFImageConfig *gifConfPtr,
			    Tcl_Channel chan, unsigned char *buf);
static int		ReadColorMap(GIFImageConfig *gifConfPtr,
			    Tcl_Channel chan, int number,
			    unsigned char buffer[MAXCOLORMAPSIZE][4]);
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
 *	The access position in f may change.
 *
 *----------------------------------------------------------------------
 */

static int
FileMatchGIF(

    Tcl_Channel chan,		/* The image file, open for reading. */
    const char *fileName,	/* The name of the image file. */
    Tcl_Obj *format,		/* User-specified format object, or NULL. */

    int *widthPtr, int *heightPtr,
				/* The dimensions of the image are returned
				 * here if the file is a valid raw GIF file. */
    Tcl_Interp *dummy)		/* not used */
{
    GIFImageConfig gifConf;
    (void)fileName;
    (void)format;
    (void)dummy;

    memset(&gifConf, 0, sizeof(GIFImageConfig));
    return ReadGIFHeader(&gifConf, chan, widthPtr, heightPtr);
}

/*
 *----------------------------------------------------------------------







>

|
|
>



|


<
<
<







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
 *	The access position in f may change.
 *
 *----------------------------------------------------------------------
 */

static int
FileMatchGIF(
    TCL_UNUSED(Tcl_Interp *),		/* not used */
    Tcl_Channel chan,		/* The image file, open for reading. */
    TCL_UNUSED(const char *),	/* The name of the image file. */
    TCL_UNUSED(Tcl_Obj *),		/* User-specified format object, or NULL. */
    TCL_UNUSED(Tcl_Obj *),	/* metadata input, may be NULL */
    int *widthPtr, int *heightPtr,
				/* The dimensions of the image are returned
				 * here if the file is a valid raw GIF file. */
    TCL_UNUSED(Tcl_Obj *))	/* metadata return dict, may be NULL */
{
    GIFImageConfig gifConf;




    memset(&gifConf, 0, sizeof(GIFImageConfig));
    return ReadGIFHeader(&gifConf, chan, widthPtr, heightPtr);
}

/*
 *----------------------------------------------------------------------
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

static int
FileReadGIF(
    Tcl_Interp *interp,		/* Interpreter to use for reporting errors. */
    Tcl_Channel chan,		/* The image file, open for reading. */
    const char *fileName,	/* The name of the image file. */
    Tcl_Obj *format,		/* User-specified format object, or NULL. */

    Tk_PhotoHandle imageHandle,	/* The photo image to write into. */
    int destX, int destY,	/* Coordinates of top-left pixel in photo
				 * image to be written to. */
    int width, int height,	/* Dimensions of block of photo image to be
				 * written to. */
    int srcX, int srcY)		/* Coordinates of top-left pixel to be used in
				 * image being read. */

{
    int fileWidth, fileHeight, imageWidth, imageHeight;
    unsigned int nBytes;
    int index = 0, argc = 0, i, result = TCL_ERROR;
    Tcl_Obj **objv;
    unsigned char buf[100];
    unsigned char *trashBuffer = NULL;
    int bitPixel;

    unsigned char colorMap[MAXCOLORMAPSIZE][4];
    int transparent = -1;
    static const char *const optionStrings[] = {
	"-index", NULL
    };
    GIFImageConfig gifConf, *gifConfPtr = &gifConf;








>





|

>








>







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

static int
FileReadGIF(
    Tcl_Interp *interp,		/* Interpreter to use for reporting errors. */
    Tcl_Channel chan,		/* The image file, open for reading. */
    const char *fileName,	/* The name of the image file. */
    Tcl_Obj *format,		/* User-specified format object, or NULL. */
    TCL_UNUSED(Tcl_Obj *),	/* metadata input, may be NULL */
    Tk_PhotoHandle imageHandle,	/* The photo image to write into. */
    int destX, int destY,	/* Coordinates of top-left pixel in photo
				 * image to be written to. */
    int width, int height,	/* Dimensions of block of photo image to be
				 * 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 */
{
    int fileWidth, fileHeight, imageWidth, imageHeight;
    unsigned int nBytes;
    int index = 0, argc = 0, i, result = TCL_ERROR;
    Tcl_Obj **objv;
    unsigned char buf[100];
    unsigned char *trashBuffer = NULL;
    int bitPixel;
    int gifLabel;
    unsigned char colorMap[MAXCOLORMAPSIZE][4];
    int transparent = -1;
    static const char *const optionStrings[] = {
	"-index", NULL
    };
    GIFImageConfig gifConf, *gifConfPtr = &gifConf;

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

    if (Tk_PhotoExpand(interp, imageHandle,
	    destX + width, destY + height) != TCL_OK) {
	return TCL_ERROR;
    }







    /*
     * Search for the frame from the GIF to display.
     */

    while (1) {
	if (Fread(gifConfPtr, buf, 1, 1, chan) != 1) {
	    /*
	     * Premature end of image.
	     */

	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "premature end of image data for this index", -1));
	    Tcl_SetErrorCode(interp, "TK", "IMAGE", "GIF", "PREMATURE_END",
		    NULL);
	    goto error;
	}

	switch (buf[0]) {
	case GIF_TERMINATOR:
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "no image data for this index", -1));
	    Tcl_SetErrorCode(interp, "TK", "IMAGE", "GIF", "NO_DATA", NULL);
	    goto error;

	case GIF_EXTENSION:
	    /*
	     * This is a GIF extension.
	     */

	    if (Fread(gifConfPtr, buf, 1, 1, chan) != 1) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj(
			"error reading extension function code in GIF image",
			-1));
		Tcl_SetErrorCode(interp, "TK", "IMAGE", "GIF", "BAD_EXT",
			NULL);
		goto error;
	    }
	    if (DoExtension(gifConfPtr, chan, buf[0],
		    gifConfPtr->workingBuffer, &transparent) < 0) {

		Tcl_SetObjResult(interp, Tcl_NewStringObj(
			"error reading extension in GIF image", -1));
		Tcl_SetErrorCode(interp, "TK", "IMAGE", "GIF", "BAD_EXT",
			NULL);
		goto error;
	    }
	    continue;







>
>
>
>
>
>





<
<
<
<
|
<
<
<
<



|











|
<
<
<
<
<


|
|
>







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

    if (Tk_PhotoExpand(interp, imageHandle,
	    destX + width, destY + height) != TCL_OK) {
	return TCL_ERROR;
    }

    /*
     * -------------------------------------------------------------------------
     * From here on, go to error to not leave memory leaks
     * -------------------------------------------------------------------------
     */

    /*
     * Search for the frame from the GIF to display.
     */

    while (1) {




	if (-1 == (gifLabel = ReadOneByte( interp, gifConfPtr, chan ) ) ) {




	    goto error;
	}

	switch (gifLabel) {
	case GIF_TERMINATOR:
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "no image data for this index", -1));
	    Tcl_SetErrorCode(interp, "TK", "IMAGE", "GIF", "NO_DATA", NULL);
	    goto error;

	case GIF_EXTENSION:
	    /*
	     * This is a GIF extension.
	     */

	    if (-1 == (gifLabel = ReadOneByte( interp, gifConfPtr, chan ) ) ) {





		goto error;
	    }
	    if (DoExtension(gifConfPtr, chan, gifLabel,
		    gifConfPtr->workingBuffer, &transparent, metadataOutObj)
		    < 0) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj(
			"error reading extension in GIF image", -1));
		Tcl_SetErrorCode(interp, "TK", "IMAGE", "GIF", "BAD_EXT",
			NULL);
		goto error;
	    }
	    continue;
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
	ckfree(block.pixelPtr);
    }

    /*
     * We've successfully read the GIF frame (or there was nothing to read,
     * which suits as well). We're done.
     */










































    Tcl_SetObjResult(interp, Tcl_NewStringObj(tkImgFmtGIF.name, -1));
    result = TCL_OK;

  error:

    /*
     * If a trash buffer has been allocated, free it now.
     */

    if (trashBuffer != NULL) {
	ckfree(trashBuffer);
    }
    return result;
}








































/*
 *----------------------------------------------------------------------
 *
 * StringMatchGIF --
 *
 *	This function is invoked by the photo image type to see if an object
 *	contains image data in GIF format.
 *
 * Results:
 *	The return value is 1 if the first characters in the data are like GIF
 *	data, and 0 otherwise.
 *
 * Side effects:
 *	The size of the image is placed in widthPtr and heightPtr.
 *
 *----------------------------------------------------------------------
 */


static int
StringMatchGIF(

    Tcl_Obj *dataObj,		/* the object containing the image data */
    Tcl_Obj *format,		/* the image format object, or NULL */

    int *widthPtr,		/* where to put the string width */
    int *heightPtr,		/* where to put the string height */
    Tcl_Interp *dummy)		/* not used */

{
    unsigned char *data, header[10];
    TkSizeT got, length;
    MFile handle;
    (void)format;
    (void)dummy;

    data = TkGetByteArrayFromObj(dataObj, &length);

    /*
     * Header is a minimum of 10 bytes.
     */









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



|
>










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

















>



>

|
>


<
>




<
<







721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850

851
852
853
854
855


856
857
858
859
860
861
862
	ckfree(block.pixelPtr);
    }

    /*
     * We've successfully read the GIF frame (or there was nothing to read,
     * which suits as well). We're done.
     */

    while (1) {
	if (-1 == (gifLabel = ReadOneByte( interp, gifConfPtr, chan ) ) ) {
	    goto error;
	}
	switch (gifLabel) {
	case GIF_TERMINATOR:
	    break;

	case GIF_EXTENSION:
	    /*
	     * This is a GIF extension.
	     */

	    if (-1 == (gifLabel = ReadOneByte( interp, gifConfPtr, chan ) ) ) {
		goto error;
	    }
	    if (DoExtension(gifConfPtr, chan, gifLabel,
		    gifConfPtr->workingBuffer, &transparent, metadataOutObj)
		    < 0) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj(
			"error reading extension in GIF image", -1));
		Tcl_SetErrorCode(interp, "TK", "IMAGE", "GIF", "BAD_EXT",
			NULL);
		goto error;
	    }
	    continue;
	case GIF_START:
	    /*
	     * There should not be a second image block - bail out without error
	     */
	    break;
	default:
	    /*
	     * Not a valid start character; ignore it.
	     */

	    continue;
	}
	break;
    }

    Tcl_SetObjResult(interp, Tcl_NewStringObj(tkImgFmtGIF.name, -1));
    result = TCL_OK;

error:
    
    /*
     * If a trash buffer has been allocated, free it now.
     */

    if (trashBuffer != NULL) {
	ckfree(trashBuffer);
    }
    return result;
}


/*
 *----------------------------------------------------------------------
 *
 * Read one Byte --
 *
 *	Read one byte (label byte) from the image stream.
 *
 * Results:
 *	The return value is 1 if the first characters in the data are like GIF
 *	data, and 0 otherwise.
 *
 * Side effects:
 *	The access position in the source is incremented.
 *
 *----------------------------------------------------------------------
 */

static int
ReadOneByte(
    Tcl_Interp *interp,		/* Interpreter to use for reporting errors. */
    GIFImageConfig *gifConfPtr,
    Tcl_Channel chan		/* The image file, open for reading. */
    )
{
    unsigned char buf[2];
    if (Fread(gifConfPtr, buf, 1, 1, chan) != 1) {
        /*
         * Premature end of image.
         */

        Tcl_SetObjResult(interp, Tcl_NewStringObj(
		"premature end of image data", -1));
	Tcl_SetErrorCode(interp, "TK", "IMAGE", "GIF", "PREMATURE_END", NULL);
	return -1;
    }
    return buf[0];
}

/*
 *----------------------------------------------------------------------
 *
 * StringMatchGIF --
 *
 *	This function is invoked by the photo image type to see if an object
 *	contains image data in GIF format.
 *
 * Results:
 *	The return value is 1 if the first characters in the data are like GIF
 *	data, and 0 otherwise.
 *
 * Side effects:
 *	The size of the image is placed in widthPtr and heightPtr.
 *
 *----------------------------------------------------------------------
 */


static int
StringMatchGIF(
    TCL_UNUSED(Tcl_Interp *),		/* not used */
    Tcl_Obj *dataObj,		/* the object containing the image data */
    TCL_UNUSED(Tcl_Obj *),		/* the image format object, or NULL */
    TCL_UNUSED(Tcl_Obj *),	/* metadata input, may be NULL */
    int *widthPtr,		/* where to put the string width */
    int *heightPtr,		/* where to put the string height */

    TCL_UNUSED(Tcl_Obj *))	/* metadata return dict, may be NULL */
{
    unsigned char *data, header[10];
    TkSizeT got, length;
    MFile handle;



    data = TkGetByteArrayFromObj(dataObj, &length);

    /*
     * Header is a minimum of 10 bytes.
     */

821
822
823
824
825
826
827

828
829
830
831

832
833
834
835
836
837
838
 */

static int
StringReadGIF(
    Tcl_Interp *interp,		/* interpreter for reporting errors in */
    Tcl_Obj *dataObj,		/* object containing the image */
    Tcl_Obj *format,		/* format object, or 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)

{
    MFile handle, *hdlPtr = &handle;
    TkSizeT length;
    const char *xferFormat;
    unsigned char *data = TkGetByteArrayFromObj(dataObj, &length);

    mInit(data, hdlPtr, length);







>



|
>







910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
 */

static int
StringReadGIF(
    Tcl_Interp *interp,		/* interpreter for reporting errors in */
    Tcl_Obj *dataObj,		/* object containing the image */
    Tcl_Obj *format,		/* format object, or 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 *metadataOutObj)	/* metadata return dict, may be NULL */
{
    MFile handle, *hdlPtr = &handle;
    TkSizeT length;
    const char *xferFormat;
    unsigned char *data = TkGetByteArrayFromObj(dataObj, &length);

    mInit(data, hdlPtr, length);
853
854
855
856
857
858
859
860

861
862
863
864
865
866
867

    /*
     * Fall through to the file reader now that we have a correctly-configured
     * pseudo-channel to pull the data from.
     */

    return FileReadGIF(interp, (Tcl_Channel) hdlPtr, xferFormat, format,
	    imageHandle, destX, destY, width, height, srcX, srcY);

}

/*
 *----------------------------------------------------------------------
 *
 * ReadGIFHeader --
 *







|
>







944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959

    /*
     * Fall through to the file reader now that we have a correctly-configured
     * pseudo-channel to pull the data from.
     */

    return FileReadGIF(interp, (Tcl_Channel) hdlPtr, xferFormat, format,
	    metadataInObj, imageHandle, destX, destY, width, height, srcX, srcY,
	    metadataOutObj);
}

/*
 *----------------------------------------------------------------------
 *
 * ReadGIFHeader --
 *
932
933
934
935
936
937
938





















939
940
941
942
943
944
945

946
947





948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969





970





971
972
973

974







975
976



















977
978
979
980
981
982
983
984
985
986
987
	    buffer[i][CM_BLUE] = rgb[2];
	    buffer[i][CM_ALPHA] = 255;
	}
    }
    return 1;
}






















static int
DoExtension(
    GIFImageConfig *gifConfPtr,
    Tcl_Channel chan,
    int label,
    unsigned char *buf,
    int *transparent)

{
    int count;






    switch (label) {
    case 0x01:			/* Plain Text Extension */
	break;

    case 0xff:			/* Application Extension */
	break;

    case 0xfe:			/* Comment Extension */
	do {
	    count = GetDataBlock(gifConfPtr, chan, buf);
	} while (count > 0);
	return count;

    case 0xf9:			/* Graphic Control Extension */
	count = GetDataBlock(gifConfPtr, chan, buf);
	if (count < 0) {
	    return 1;
	}
	if ((buf[0] & 0x1) != 0) {
	    *transparent = buf[3];
	}











	do {
	    count = GetDataBlock(gifConfPtr, chan, buf);
	} while (count > 0);

	return count;







    }




















    do {
	count = GetDataBlock(gifConfPtr, chan, buf);
    } while (count > 0);
    return count;
}

static int
GetDataBlock(
    GIFImageConfig *gifConfPtr,
    Tcl_Channel chan,
    unsigned char *buf)







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





|
|
>


>
>
>
>
>



<
|
<

<
<
<
<
<
<
<



|




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

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



|







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
	    buffer[i][CM_BLUE] = rgb[2];
	    buffer[i][CM_ALPHA] = 255;
	}
    }
    return 1;
}

/*
*----------------------------------------------------------------------
*
* DoExtension --
*
*	Process a GIF extension block
*
* Results:
*	-1 to trigger an extension read error
*       >= 0 ok
*
* 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
*         - Comment extension in key "comment"
*       Plain text extensions are currently ignored.
*
*----------------------------------------------------------------------
*/

static int
DoExtension(
    GIFImageConfig *gifConfPtr,
    Tcl_Channel chan,
    int label,
    unsigned char *buf, /* defined as 280 byte working buffer */
    int *transparent,
    Tcl_Obj *metadataOutObj)
{
    int count;
    /* Prepare extension name
     * Maximum string size: "comment" + Code(3) + trailing zero
     */
    char extensionStreamName[8];
    extensionStreamName[0] = '\0';

    switch (label) {
    case 0x01:			/* Plain Text Extension */

        /* this extension is ignored, skip below */

	break;







    case 0xf9:			/* Graphic Control Extension */
	count = GetDataBlock(gifConfPtr, chan, buf);
	if (count < 0) {
	    return -1;
	}
	if ((buf[0] & 0x1) != 0) {
	    *transparent = buf[3];
	}
	break;
    case 0xfe:			/* Comment Extension */
	strcpy(extensionStreamName,"comment");
        /* copy the extension data below */
	break;
    }
    /* Add extension to dict */
    if (NULL != metadataOutObj
	    && extensionStreamName[0] != '\0' ) {
	Tcl_Obj *ValueObj;
	int length = 0;
	for (;;) {
	    count = GetDataBlock(gifConfPtr, chan, buf);
	    switch (count) {
	    case -1: /* error */
		return -1;
	    case 0: /* end of data */
		if (length > 0) {
		    if ( TCL_OK != Tcl_DictObjPut(NULL, metadataOutObj,
			    Tcl_NewByteArrayObj(
				(unsigned char *)extensionStreamName,
			    strlen(extensionStreamName)), ValueObj)) {
			return -1;
		    }
		}
		/* return success */
		return 0;
	    default: /* block received */
		if (length == 0) {
		    /* first block */
		    ValueObj = Tcl_NewByteArrayObj(buf, count);
		    length = count;
		} else {
		    /* consecutive block */
		    unsigned char *bytePtr;
		    bytePtr = Tcl_SetByteArrayLength(ValueObj, length+count);
		    memcpy(bytePtr+length,buf,count);
		    length += count;
		}
		break;
	    }
	} /* for */
    }
    /* skip eventual remaining data block bytes */
    do {
	count = GetDataBlock(gifConfPtr, chan, buf);
    } while (count > 0);
    return count; /* this may be -1 for error or 0 */
}

static int
GetDataBlock(
    GIFImageConfig *gifConfPtr,
    Tcl_Channel chan,
    unsigned char *buf)
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
ReadImage(
    GIFImageConfig *gifConfPtr,
    Tcl_Interp *interp,
    unsigned char *imagePtr,
    Tcl_Channel chan,
    int len, int rows,
    unsigned char cmap[MAXCOLORMAPSIZE][4],
    int srcX, int srcY,

    int interlace,
    int transparent)
{
    unsigned char initialCodeSize;
    int xpos = 0, ypos = 0, pass = 0, i, count;
    unsigned char *pixelPtr;
    static const int interlaceStep[] = { 8, 8, 4, 2 };
    static const int interlaceStart[] = { 0, 4, 2, 1 };
    unsigned short prefix[(1 << MAX_LWZ_BITS)];
    unsigned char append[(1 << MAX_LWZ_BITS)];
    unsigned char stack[(1 << MAX_LWZ_BITS)*2];
    unsigned char *top;
    int codeSize, clearCode, inCode, endCode, oldCode, maxCode;
    int code, firstCode, v;
    (void)srcX;
    (void)srcY;

    /*
     * Initialize the decoder
     */

    if (((size_t)Fread(gifConfPtr, &initialCodeSize, 1, 1, chan) + 1) < 2) {
	Tcl_SetObjResult(interp, Tcl_ObjPrintf(







|
>














<
<







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
ReadImage(
    GIFImageConfig *gifConfPtr,
    Tcl_Interp *interp,
    unsigned char *imagePtr,
    Tcl_Channel chan,
    int len, int rows,
    unsigned char cmap[MAXCOLORMAPSIZE][4],
	TCL_UNUSED(int),
	TCL_UNUSED(int),
    int interlace,
    int transparent)
{
    unsigned char initialCodeSize;
    int xpos = 0, ypos = 0, pass = 0, i, count;
    unsigned char *pixelPtr;
    static const int interlaceStep[] = { 8, 8, 4, 2 };
    static const int interlaceStart[] = { 0, 4, 2, 1 };
    unsigned short prefix[(1 << MAX_LWZ_BITS)];
    unsigned char append[(1 << MAX_LWZ_BITS)];
    unsigned char stack[(1 << MAX_LWZ_BITS)*2];
    unsigned char *top;
    int codeSize, clearCode, inCode, endCode, oldCode, maxCode;
    int code, firstCode, v;



    /*
     * Initialize the decoder
     */

    if (((size_t)Fread(gifConfPtr, &initialCodeSize, 1, 1, chan) + 1) < 2) {
	Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1633
1634
1635
1636
1637
1638
1639

1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655

1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667

1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682


static int
FileWriteGIF(
    Tcl_Interp *interp,		/* Interpreter to use for reporting errors. */
    const char *filename,
    Tcl_Obj *format,

    Tk_PhotoImageBlock *blockPtr)
{
    Tcl_Channel chan = NULL;
    int result;

    chan = Tcl_OpenFileChannel(interp, (char *) filename, "w", 0644);
    if (!chan) {
	return TCL_ERROR;
    }
    if (Tcl_SetChannelOption(interp, chan, "-translation",
	    "binary") != TCL_OK) {
	Tcl_Close(NULL, chan);
	return TCL_ERROR;
    }

    result = CommonWriteGIF(interp, chan, WriteToChannel, format, blockPtr);


    if (Tcl_Close(interp, chan) == TCL_ERROR) {
	return TCL_ERROR;
    }
    return result;
}

static int
StringWriteGIF(
    Tcl_Interp *interp,		/* Interpreter to use for reporting errors and
				 * returning the GIF data. */
    Tcl_Obj *format,

    Tk_PhotoImageBlock *blockPtr)
{
    int result;
    Tcl_Obj *objPtr = Tcl_NewObj();

    Tcl_IncrRefCount(objPtr);
    result = CommonWriteGIF(interp, objPtr, WriteToByteArray, format,
	    blockPtr);
    if (result == TCL_OK) {
	Tcl_SetObjResult(interp, objPtr);
    }
    Tcl_DecrRefCount(objPtr);
    return result;
}








>















|
>












>







|







1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831


static int
FileWriteGIF(
    Tcl_Interp *interp,		/* Interpreter to use for reporting errors. */
    const char *filename,
    Tcl_Obj *format,
    Tcl_Obj *metadataInObj,
    Tk_PhotoImageBlock *blockPtr)
{
    Tcl_Channel chan = NULL;
    int result;

    chan = Tcl_OpenFileChannel(interp, (char *) filename, "w", 0644);
    if (!chan) {
	return TCL_ERROR;
    }
    if (Tcl_SetChannelOption(interp, chan, "-translation",
	    "binary") != TCL_OK) {
	Tcl_Close(NULL, chan);
	return TCL_ERROR;
    }

    result = CommonWriteGIF(interp, chan, WriteToChannel, format, metadataInObj,
	    blockPtr);

    if (Tcl_Close(interp, chan) == TCL_ERROR) {
	return TCL_ERROR;
    }
    return result;
}

static int
StringWriteGIF(
    Tcl_Interp *interp,		/* Interpreter to use for reporting errors and
				 * returning the GIF data. */
    Tcl_Obj *format,
    Tcl_Obj *metadataInObj,
    Tk_PhotoImageBlock *blockPtr)
{
    int result;
    Tcl_Obj *objPtr = Tcl_NewObj();

    Tcl_IncrRefCount(objPtr);
    result = CommonWriteGIF(interp, objPtr, WriteToByteArray, format,
	    metadataInObj, blockPtr);
    if (result == TCL_OK) {
	Tcl_SetObjResult(interp, objPtr);
    }
    Tcl_DecrRefCount(objPtr);
    return result;
}

1707
1708
1709
1710
1711
1712
1713

1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
}

static int
CommonWriteGIF(
    Tcl_Interp *interp,
    ClientData handle,
    WriteBytesFunc *writeProc,

    Tcl_Obj *format,
    Tk_PhotoImageBlock *blockPtr)
{
    GifWriterState state;
    int resolution;
    long width, height, x;
    unsigned char c;
    unsigned int top, left;
    (void)format;

    top = 0;
    left = 0;

    memset(&state, 0, sizeof(state));

    state.pixelSize = blockPtr->pixelSize;







>
|







<







1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871

1872
1873
1874
1875
1876
1877
1878
}

static int
CommonWriteGIF(
    Tcl_Interp *interp,
    ClientData handle,
    WriteBytesFunc *writeProc,
    TCL_UNUSED(Tcl_Obj *),
    Tcl_Obj *metadataInObj,
    Tk_PhotoImageBlock *blockPtr)
{
    GifWriterState state;
    int resolution;
    long width, height, x;
    unsigned char c;
    unsigned int top, left;


    top = 0;
    left = 0;

    memset(&state, 0, sizeof(state));

    state.pixelSize = blockPtr->pixelSize;
1838
1839
1840
1841
1842
1843
1844












































1845
1846
1847
1848
1849
1850
1851

    state.ssize = state.rsize = blockPtr->width;
    state.csize = blockPtr->height;
    Compress(resolution+1, handle, writeProc, ReadValue, &state);

    c = 0;
    writeProc(handle, (char *) &c, 1);












































    c = GIF_TERMINATOR;
    writeProc(handle, (char *) &c, 1);

    return TCL_OK;
}

static int







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







1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044

    state.ssize = state.rsize = blockPtr->width;
    state.csize = blockPtr->height;
    Compress(resolution+1, handle, writeProc, ReadValue, &state);

    c = 0;
    writeProc(handle, (char *) &c, 1);
    /*
     * Check for metadata keys to add to file
     */
    if (NULL != metadataInObj) {
	Tcl_Obj *itemData;
	
	/*
	 * Check and code comment block
	 */
	
	if (TCL_ERROR == Tcl_DictObjGet(interp, metadataInObj,
		Tcl_NewStringObj("comment",-1),
		&itemData)) {
	    return TCL_ERROR;
	}
	if (itemData != NULL) {
	    int length;
	    unsigned char *comment;
	    comment = Tcl_GetByteArrayFromObj(itemData, &length);
	    if (length > 0) {
		/* write comment header */
		writeProc(handle, (char *) "\x21\xfe", 2);
		/* write comment blocks */
		for (;length > 0;) {
		    int blockLength;
		    unsigned char blockLengthChar;
		    if (length > 255) {
			length -=255;
			blockLength = 255;
		    } else {
			blockLength = length;
			length = 0;
		    }
		    blockLengthChar = (unsigned char) blockLength;
		    writeProc(handle, (char *) &blockLengthChar, 1);
		    writeProc(handle, (char *) comment, blockLength);
		    comment += blockLength;
		}
		/* Block terminator */
		c = 0;
		writeProc(handle, (char *) &c, 1);
	    }
	}
    }
    c = GIF_TERMINATOR;
    writeProc(handle, (char *) &c, 1);

    return TCL_OK;
}

static int

Changes to generic/tkImgPNG.c.

171
172
173
174
175
176
177









178
179
180
181
182
183
184

    Tcl_ZlibStream stream;	/* Inflating or deflating stream; this one is
				 * not bound to a Tcl command. */
    Tcl_Obj *lastLineObj;	/* Last line of pixels, for unfiltering. */
    Tcl_Obj *thisLineObj;	/* Current line of pixels to process. */
    int lineSize;		/* Number of bytes in a PNG line. */
    int phaseSize;		/* Number of bytes/line in current phase. */









} PNGImage;

/*
 * Maximum size of various chunks.
 */

#define	PNG_PLTE_MAXSZ 768	/* 3 bytes/RGB entry, 256 entries max */







>
>
>
>
>
>
>
>
>







171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193

    Tcl_ZlibStream stream;	/* Inflating or deflating stream; this one is
				 * not bound to a Tcl command. */
    Tcl_Obj *lastLineObj;	/* Last line of pixels, for unfiltering. */
    Tcl_Obj *thisLineObj;	/* Current line of pixels to process. */
    int lineSize;		/* Number of bytes in a PNG line. */
    int phaseSize;		/* Number of bytes/line in current phase. */


    /*
     * Physical size: pHYS chunks.
     */
    
    double DPI;
    double aspect;

} PNGImage;

/*
 * Maximum size of various chunks.
 */

#define	PNG_PLTE_MAXSZ 768	/* 3 bytes/RGB entry, 256 entries max */
194
195
196
197
198
199
200
201

202
203
204

205
206
207
208

209

210
211
212
213
214
215
216
217
			    unsigned long calculated);
static void		CleanupPNGImage(PNGImage *pngPtr);
static int		DecodeLine(Tcl_Interp *interp, PNGImage *pngPtr);
static int		DecodePNG(Tcl_Interp *interp, PNGImage *pngPtr,
			    Tcl_Obj *fmtObj, Tk_PhotoHandle imageHandle,
			    int destX, int destY);
static int		EncodePNG(Tcl_Interp *interp,
			    Tk_PhotoImageBlock *blockPtr, PNGImage *pngPtr);

static int		FileMatchPNG(Tcl_Channel chan, const char *fileName,
			    Tcl_Obj *fmtObj, int *widthPtr, int *heightPtr,
			    Tcl_Interp *interp);

static int		FileReadPNG(Tcl_Interp *interp, Tcl_Channel chan,
			    const char *fileName, Tcl_Obj *fmtObj,
			    Tk_PhotoHandle imageHandle, int destX, int destY,
			    int width, int height, int srcX, int srcY);

static int		FileWritePNG(Tcl_Interp *interp, const char *filename,

			    Tcl_Obj *fmtObj, Tk_PhotoImageBlock *blockPtr);
static int		InitPNGImage(Tcl_Interp *interp, PNGImage *pngPtr,
			    Tcl_Channel chan, Tcl_Obj *objPtr, int dir);
static inline unsigned char Paeth(int a, int b, int c);
static int		ParseFormat(Tcl_Interp *interp, Tcl_Obj *fmtObj,
			    PNGImage *pngPtr);
static int		ReadBase64(Tcl_Interp *interp, PNGImage *pngPtr,
			    unsigned char *destPtr, size_t destSz,







|
>
|
|
|
>


|
|
>

>
|







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
			    unsigned long calculated);
static void		CleanupPNGImage(PNGImage *pngPtr);
static int		DecodeLine(Tcl_Interp *interp, PNGImage *pngPtr);
static int		DecodePNG(Tcl_Interp *interp, PNGImage *pngPtr,
			    Tcl_Obj *fmtObj, Tk_PhotoHandle imageHandle,
			    int destX, int destY);
static int		EncodePNG(Tcl_Interp *interp,
			    Tk_PhotoImageBlock *blockPtr, PNGImage *pngPtr,
			    Tcl_Obj *metadataInObj);
static int		FileMatchPNG(Tcl_Interp *interp, Tcl_Channel chan,
			    const char *fileName, Tcl_Obj *fmtObj,
			    Tcl_Obj *metadataInObj, int *widthPtr,
			    int *heightPtr, Tcl_Obj *metadataOut);
static int		FileReadPNG(Tcl_Interp *interp, Tcl_Channel chan,
			    const char *fileName, Tcl_Obj *fmtObj,
			    Tcl_Obj *metadataInObj, Tk_PhotoHandle imageHandle,
			    int destX, int destY, int width, int height,
			    int srcX, int srcY, Tcl_Obj *metadataOutPtr);
static int		FileWritePNG(Tcl_Interp *interp, const char *filename,
			    Tcl_Obj *fmtObj, Tcl_Obj *metadataInObj,
			    Tk_PhotoImageBlock *blockPtr);
static int		InitPNGImage(Tcl_Interp *interp, PNGImage *pngPtr,
			    Tcl_Channel chan, Tcl_Obj *objPtr, int dir);
static inline unsigned char Paeth(int a, int b, int c);
static int		ParseFormat(Tcl_Interp *interp, Tcl_Obj *fmtObj,
			    PNGImage *pngPtr);
static int		ReadBase64(Tcl_Interp *interp, PNGImage *pngPtr,
			    unsigned char *destPtr, size_t destSz,
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
			    unsigned long *resultPtr, unsigned long *crcPtr);
static int		ReadPLTE(Tcl_Interp *interp, PNGImage *pngPtr,
			    int chunkSz, unsigned long crc);
static int		ReadTRNS(Tcl_Interp *interp, PNGImage *pngPtr,
			    int chunkSz, unsigned long crc);
static int		SkipChunk(Tcl_Interp *interp, PNGImage *pngPtr,
			    int chunkSz, unsigned long crc);
static int		StringMatchPNG(Tcl_Obj *dataObj, Tcl_Obj *fmtObj,

			    int *widthPtr, int *heightPtr,
			    Tcl_Interp *interp);
static int		StringReadPNG(Tcl_Interp *interp, Tcl_Obj *dataObj,

			    Tcl_Obj *fmtObj, Tk_PhotoHandle imageHandle,
			    int destX, int destY, int width, int height,
			    int srcX, int srcY);

static int		StringWritePNG(Tcl_Interp *interp, Tcl_Obj *fmtObj,

			    Tk_PhotoImageBlock *blockPtr);
static int		UnfilterLine(Tcl_Interp *interp, PNGImage *pngPtr);
static inline int	WriteByte(Tcl_Interp *interp, PNGImage *pngPtr,
			    unsigned char c, unsigned long *crcPtr);
static inline int	WriteChunk(Tcl_Interp *interp, PNGImage *pngPtr,
			    unsigned long chunkType,
			    const unsigned char *dataPtr, size_t dataSize);
static int		WriteData(Tcl_Interp *interp, PNGImage *pngPtr,
			    const unsigned char *srcPtr, size_t srcSz,
			    unsigned long *crcPtr);
static int		WriteExtraChunks(Tcl_Interp *interp,
			    PNGImage *pngPtr);
static int		WriteIHDR(Tcl_Interp *interp, PNGImage *pngPtr,
			    Tk_PhotoImageBlock *blockPtr);
static int		WriteIDAT(Tcl_Interp *interp, PNGImage *pngPtr,
			    Tk_PhotoImageBlock *blockPtr);
static inline int	WriteInt32(Tcl_Interp *interp, PNGImage *pngPtr,
			    unsigned long l, unsigned long *crcPtr);

/*
 * The format record for the PNG file format:
 */

Tk_PhotoImageFormat tkImgFmtPNG = {
    "png",			/* name */
    FileMatchPNG,		/* fileMatchProc */
    StringMatchPNG,		/* stringMatchProc */
    FileReadPNG,		/* fileReadProc */
    StringReadPNG,		/* stringReadProc */
    FileWritePNG,		/* fileWriteProc */
    StringWritePNG,		/* stringWriteProc */







|
>

|
|
>
|

|
>

>











|











|







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
			    unsigned long *resultPtr, unsigned long *crcPtr);
static int		ReadPLTE(Tcl_Interp *interp, PNGImage *pngPtr,
			    int chunkSz, unsigned long crc);
static int		ReadTRNS(Tcl_Interp *interp, PNGImage *pngPtr,
			    int chunkSz, unsigned long crc);
static int		SkipChunk(Tcl_Interp *interp, PNGImage *pngPtr,
			    int chunkSz, unsigned long crc);
static int		StringMatchPNG(Tcl_Interp *interp, Tcl_Obj *pObjData,
			    Tcl_Obj *fmtObj, Tcl_Obj *metadataInObj,
			    int *widthPtr, int *heightPtr,
			    Tcl_Obj *metadataOutObj);
static int		StringReadPNG(Tcl_Interp *interp, Tcl_Obj *pObjData,
			    Tcl_Obj *fmtObj, Tcl_Obj *metadataInObj,
			    Tk_PhotoHandle imageHandle,
			    int destX, int destY, int width, int height,
			    int srcX, int srcY, Tcl_Obj *metadataOutObj);

static int		StringWritePNG(Tcl_Interp *interp, Tcl_Obj *fmtObj,
			    Tcl_Obj *metadataInObj,
			    Tk_PhotoImageBlock *blockPtr);
static int		UnfilterLine(Tcl_Interp *interp, PNGImage *pngPtr);
static inline int	WriteByte(Tcl_Interp *interp, PNGImage *pngPtr,
			    unsigned char c, unsigned long *crcPtr);
static inline int	WriteChunk(Tcl_Interp *interp, PNGImage *pngPtr,
			    unsigned long chunkType,
			    const unsigned char *dataPtr, size_t dataSize);
static int		WriteData(Tcl_Interp *interp, PNGImage *pngPtr,
			    const unsigned char *srcPtr, size_t srcSz,
			    unsigned long *crcPtr);
static int		WriteExtraChunks(Tcl_Interp *interp,
			    PNGImage *pngPtr, Tcl_Obj *metadataInObj);
static int		WriteIHDR(Tcl_Interp *interp, PNGImage *pngPtr,
			    Tk_PhotoImageBlock *blockPtr);
static int		WriteIDAT(Tcl_Interp *interp, PNGImage *pngPtr,
			    Tk_PhotoImageBlock *blockPtr);
static inline int	WriteInt32(Tcl_Interp *interp, PNGImage *pngPtr,
			    unsigned long l, unsigned long *crcPtr);

/*
 * The format record for the PNG file format:
 */

Tk_PhotoImageFormatVersion3 tkImgFmtPNG = {
    "png",			/* name */
    FileMatchPNG,		/* fileMatchProc */
    StringMatchPNG,		/* stringMatchProc */
    FileReadPNG,		/* fileReadProc */
    StringReadPNG,		/* stringReadProc */
    FileWritePNG,		/* fileWriteProc */
    StringWritePNG,		/* stringWriteProc */
340
341
342
343
344
345
346







347
348
349
350
351
352
353
	    Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "ZLIB_INIT", NULL);
	}
	if (objPtr) {
	    Tcl_DecrRefCount(objPtr);
	}
	return TCL_ERROR;
    }








    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *







>
>
>
>
>
>
>







357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
	    Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "ZLIB_INIT", NULL);
	}
	if (objPtr) {
	    Tcl_DecrRefCount(objPtr);
	}
	return TCL_ERROR;
    }
    
    /*
     * Initialize physical size pHYS values
     */
    
    pngPtr->DPI = -1;
    pngPtr->aspect = -1;

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
929
930
931
932
933
934
935

936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
	    /*
	     * These chunk types are required and/or supported.
	     */

	case CHUNK_IDAT:
	case CHUNK_IEND:
	case CHUNK_IHDR:

	case CHUNK_PLTE:
	case CHUNK_tRNS:
	    break;

	    /*
	     * These chunk types are part of the standard, but are not used by
	     * this implementation (at least not yet). Note that these are all
	     * ancillary chunks (lowercase first letter).
	     */

	case CHUNK_bKGD:
	case CHUNK_cHRM:
	case CHUNK_gAMA:
	case CHUNK_hIST:
	case CHUNK_iCCP:
	case CHUNK_iTXt:
	case CHUNK_oFFs:
	case CHUNK_pCAL:
	case CHUNK_pHYs:
	case CHUNK_sBIT:
	case CHUNK_sCAL:
	case CHUNK_sPLT:
	case CHUNK_sRGB:
	case CHUNK_tEXt:
	case CHUNK_tIME:
	case CHUNK_zTXt:







>


















<







953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978

979
980
981
982
983
984
985
	    /*
	     * These chunk types are required and/or supported.
	     */

	case CHUNK_IDAT:
	case CHUNK_IEND:
	case CHUNK_IHDR:
	case CHUNK_pHYs:
	case CHUNK_PLTE:
	case CHUNK_tRNS:
	    break;

	    /*
	     * These chunk types are part of the standard, but are not used by
	     * this implementation (at least not yet). Note that these are all
	     * ancillary chunks (lowercase first letter).
	     */

	case CHUNK_bKGD:
	case CHUNK_cHRM:
	case CHUNK_gAMA:
	case CHUNK_hIST:
	case CHUNK_iCCP:
	case CHUNK_iTXt:
	case CHUNK_oFFs:
	case CHUNK_pCAL:

	case CHUNK_sBIT:
	case CHUNK_sCAL:
	case CHUNK_sPLT:
	case CHUNK_sRGB:
	case CHUNK_tEXt:
	case CHUNK_tIME:
	case CHUNK_zTXt:
1636
1637
1638
1639
1640
1641
1642














































































1643
1644
1645
1646
1647
1648
1649
	pngPtr->useTRNS = 1;
	break;
    }

    return TCL_OK;
}















































































/*
 *----------------------------------------------------------------------
 *
 * Paeth --
 *
 *	Utility function for applying the Paeth filter to a pixel. The Paeth
 *	filter is a linear function of the pixel to be filtered and the pixels







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







1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
	pngPtr->useTRNS = 1;
	break;
    }

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ReadPHYS --
 *
 *	This function reads the PHYS (physical size) chunk data from
 *	the PNG file and populates the fields in the PNGImage
 *	structure.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if an I/O error occurs or the PHYS chunk is
 *	invalid.
 *
 * Side effects:
 *	The access position in f advances.
 *
 *----------------------------------------------------------------------
 */

static int
ReadPHYS(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    int chunkSz,
    unsigned long crc)
{
    unsigned long PPUx, PPUy;
    char unitSpecifier;

    /*
     * Check chunk size equal 9 bytes
     */

    if (chunkSz != 9) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj(
		"invalid physical chunk size", -1));
	Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "BAD_PHYS", NULL);
	return TCL_ERROR;
    }

    /*
     * Read the chunk data
     * 4 bytes: Pixels per unit, x axis
     * 4 bytes: Pixels per unit, y axis
     * 1 byte: unit specifier
     */
    
    if (ReadInt32(interp, pngPtr, &PPUx, &crc) == TCL_ERROR) {
	return TCL_ERROR;
    }
    if (ReadInt32(interp, pngPtr, &PPUy, &crc) == TCL_ERROR) {
	return TCL_ERROR;
    }
    if (ReadData(interp, pngPtr, (unsigned char *)&unitSpecifier, 1, &crc) == TCL_ERROR) {
	return TCL_ERROR;
    }

    if (CheckCRC(interp, pngPtr, crc) == TCL_ERROR) {
	return TCL_ERROR;
    }
    
    if ( PPUx > 2147483647 || PPUy > 2147483647
	    || unitSpecifier > 1 ) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj(
		"invalid physical size value", -1));
	Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "BAD_PHYS", NULL);
	return TCL_ERROR;
    }

    if (PPUx > 0) {
	pngPtr->aspect = ((double) PPUy) / ((double) PPUx);
    }
    if (1 == unitSpecifier) {
	pngPtr->DPI = ((double) PPUx) * 0.0254;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * Paeth --
 *
 *	Utility function for applying the Paeth filter to a pixel. The Paeth
 *	filter is a linear function of the pixel to be filtered and the pixels
2410
2411
2412
2413
2414
2415
2416























2417
2418
2419
2420
2421
2422
2423
     * PLTE is mandatory for color type 3 and forbidden for 2 and 6
     */

    if (ReadChunkHeader(interp, pngPtr, &chunkSz, &chunkType,
	    &crc) == TCL_ERROR) {
	return TCL_ERROR;
    }
























    if (CHUNK_PLTE == chunkType) {
	/*
	 * Finish parsing the PLTE chunk.
	 */

	if (ReadPLTE(interp, pngPtr, chunkSz, crc) == TCL_ERROR) {







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







2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
     * PLTE is mandatory for color type 3 and forbidden for 2 and 6
     */

    if (ReadChunkHeader(interp, pngPtr, &chunkSz, &chunkType,
	    &crc) == TCL_ERROR) {
	return TCL_ERROR;
    }

    /*
     * Physical header may be present here so try to parse it
     */
    
    if (CHUNK_pHYs == chunkType) {
	/*
	 * Finish parsing the PHYS chunk.
	 */

	if (ReadPHYS(interp, pngPtr, chunkSz, crc) == TCL_ERROR) {
	    return TCL_ERROR;
	}

	/*
	 * Begin the next chunk.
	 */

	if (ReadChunkHeader(interp, pngPtr, &chunkSz, &chunkType,
		&crc) == TCL_ERROR) {
	    return TCL_ERROR;
	}
    }

    if (CHUNK_PLTE == chunkType) {
	/*
	 * Finish parsing the PLTE chunk.
	 */

	if (ReadPLTE(interp, pngPtr, chunkSz, crc) == TCL_ERROR) {
2450
2451
2452
2453
2454
2455
2456























2457
2458
2459
2460
2461
2462
2463
	/*
	 * Finish parsing the tRNS chunk.
	 */

	if (ReadTRNS(interp, pngPtr, chunkSz, crc) == TCL_ERROR) {
	    return TCL_ERROR;
	}
























	/*
	 * Begin the next chunk.
	 */

	if (ReadChunkHeader(interp, pngPtr, &chunkSz, &chunkType,
		&crc) == TCL_ERROR) {







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







2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
	/*
	 * Finish parsing the tRNS chunk.
	 */

	if (ReadTRNS(interp, pngPtr, chunkSz, crc) == TCL_ERROR) {
	    return TCL_ERROR;
	}

	/*
	 * Begin the next chunk.
	 */

	if (ReadChunkHeader(interp, pngPtr, &chunkSz, &chunkType,
		&crc) == TCL_ERROR) {
	    return TCL_ERROR;
	}
    }

    /*
     * Physical header may be present here so try to parse it
     */
    
    if (CHUNK_pHYs == chunkType) {
	/*
	 * Finish parsing the PHYS chunk.
	 */

	if (ReadPHYS(interp, pngPtr, chunkSz, crc) == TCL_ERROR) {
	    return TCL_ERROR;
	}

	/*
	 * Begin the next chunk.
	 */

	if (ReadChunkHeader(interp, pngPtr, &chunkSz, &chunkType,
		&crc) == TCL_ERROR) {
2663
2664
2665
2666
2667
2668
2669

2670
2671

2672
2673
2674


2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
 *	The access position in f may change.
 *
 *----------------------------------------------------------------------
 */

static int
FileMatchPNG(

    Tcl_Channel chan,
    const char *fileName,

    Tcl_Obj *fmtObj,
    int *widthPtr,
    int *heightPtr,


    Tcl_Interp *interp)
{
    PNGImage png;
    int match = 0;
    (void)fileName;
    (void)fmtObj;

    InitPNGImage(NULL, &png, chan, NULL, TCL_ZLIB_STREAM_INFLATE);

    if (ReadIHDR(interp, &png) == TCL_OK) {
	*widthPtr = png.block.width;
	*heightPtr = png.block.height;
	match = 1;







>
|
|
>
|
|
<
>
>
|



<
<







2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823

2824
2825
2826
2827
2828
2829


2830
2831
2832
2833
2834
2835
2836
 *	The access position in f may change.
 *
 *----------------------------------------------------------------------
 */

static int
FileMatchPNG(
    Tcl_Interp *interp,		/* Interpreter to use for reporting errors. */
    Tcl_Channel chan,		/* The image file, open for reading. */
    TCL_UNUSED(const char *),	/* The name of the image file. */
    TCL_UNUSED(Tcl_Obj *),		/* User-specified format object, or NULL. */
    TCL_UNUSED(Tcl_Obj *),	/* metadata input, may be NULL */
    int *widthPtr, int *heightPtr,

				/* The dimensions of the image are returned
				 * here if the file is a valid raw GIF file. */
    TCL_UNUSED(Tcl_Obj *))	/* metadata return dict, may be NULL */
{
    PNGImage png;
    int match = 0;



    InitPNGImage(NULL, &png, chan, NULL, TCL_ZLIB_STREAM_INFLATE);

    if (ReadIHDR(interp, &png) == TCL_OK) {
	*widthPtr = png.block.width;
	*heightPtr = png.block.height;
	match = 1;
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719

2720
2721
2722


2723
2724

2725
2726

2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740












2741
2742
2743
2744
2745
2746
2747
 *	image given by imageHandle.
 *
 *----------------------------------------------------------------------
 */

static int
FileReadPNG(
    Tcl_Interp *interp,
    Tcl_Channel chan,
    const char *fileName,
    Tcl_Obj *fmtObj,

    Tk_PhotoHandle imageHandle,
    int destX,
    int destY,


    int width,
    int height,

    int srcX,
    int srcY)

{
    PNGImage png;
    int result = TCL_ERROR;
    (void)fileName;
    (void)width;
    (void)height;
    (void)srcX;
    (void)srcY;

    result = InitPNGImage(interp, &png, chan, NULL, TCL_ZLIB_STREAM_INFLATE);

    if (TCL_OK == result) {
	result = DecodePNG(interp, &png, fmtObj, imageHandle, destX, destY);
    }













    CleanupPNGImage(&png);
    return result;
}

/*
 *----------------------------------------------------------------------







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



<
<
<
<
<






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







2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871

2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882





2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
 *	image given by imageHandle.
 *
 *----------------------------------------------------------------------
 */

static int
FileReadPNG(
    Tcl_Interp *interp,		/* Interpreter to use for reporting errors. */
    Tcl_Channel chan,		/* The image file, open for reading. */
    TCL_UNUSED(const char *),	/* The name of the image file. */
    Tcl_Obj *fmtObj,		/* User-specified format object, or NULL. */
    TCL_UNUSED(Tcl_Obj *),	/* metadata input, may be NULL */
    Tk_PhotoHandle imageHandle,	/* The photo image to write into. */
    int destX, int destY,	/* Coordinates of top-left pixel in photo

				 * image to be written to. */
    TCL_UNUSED(int),	/* Dimensions of block of photo image to be
				 * written to. */
    TCL_UNUSED(int),
    TCL_UNUSED(int),		/* Coordinates of top-left pixel to be used in
				 * image being read. */
    TCL_UNUSED(int),
    Tcl_Obj *metadataOutObj)	/* metadata return dict, may be NULL */
{
    PNGImage png;
    int result = TCL_ERROR;






    result = InitPNGImage(interp, &png, chan, NULL, TCL_ZLIB_STREAM_INFLATE);

    if (TCL_OK == result) {
	result = DecodePNG(interp, &png, fmtObj, imageHandle, destX, destY);
    }

    if (TCL_OK == result && metadataOutObj != NULL && png.DPI != -1) {
	result = Tcl_DictObjPut(NULL, metadataOutObj,
		Tcl_NewStringObj("DPI",-1),
		Tcl_NewDoubleObj(png.DPI));
    }

    if (TCL_OK == result && metadataOutObj != NULL && png.aspect != -1) {
	result = Tcl_DictObjPut(NULL, metadataOutObj,
		Tcl_NewStringObj("aspect",-1),
		Tcl_NewDoubleObj(png.aspect));
    }

    CleanupPNGImage(&png);
    return result;
}

/*
 *----------------------------------------------------------------------
2759
2760
2761
2762
2763
2764
2765

2766

2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
 *	The size of the image is placed in widthPre and heightPtr.
 *
 *----------------------------------------------------------------------
 */

static int
StringMatchPNG(

    Tcl_Obj *pObjData,

    Tcl_Obj *fmtObj,
    int *widthPtr,
    int *heightPtr,
    Tcl_Interp *interp)
{
    PNGImage png;
    int match = 0;
    (void)fmtObj;

    InitPNGImage(NULL, &png, NULL, pObjData, TCL_ZLIB_STREAM_INFLATE);

    png.strDataBuf = TkGetByteArrayFromObj(pObjData, &png.strDataLen);

    if (ReadIHDR(interp, &png) == TCL_OK) {
	*widthPtr = png.block.width;







>
|
>
|
|
|
|



<







2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935

2936
2937
2938
2939
2940
2941
2942
 *	The size of the image is placed in widthPre and heightPtr.
 *
 *----------------------------------------------------------------------
 */

static int
StringMatchPNG(
    Tcl_Interp *interp,		/* Interpreter to use for reporting errors. */
    Tcl_Obj *pObjData,		/* the object containing the image data */
    TCL_UNUSED(Tcl_Obj *),		/* the image format object, or NULL */
    TCL_UNUSED(Tcl_Obj *),	/* metadata input, may be NULL */
    int *widthPtr,		/* where to put the string width */
    int *heightPtr,		/* where to put the string height */
    TCL_UNUSED(Tcl_Obj *))	/* metadata return dict, may be NULL */
{
    PNGImage png;
    int match = 0;


    InitPNGImage(NULL, &png, NULL, pObjData, TCL_ZLIB_STREAM_INFLATE);

    png.strDataBuf = TkGetByteArrayFromObj(pObjData, &png.strDataLen);

    if (ReadIHDR(interp, &png) == TCL_OK) {
	*widthPtr = png.block.width;
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812

2813
2814
2815
2816
2817
2818
2819

2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833












2834
2835
2836
2837
2838
2839
2840
 *	New data is added to the image given by imageHandle.
 *
 *----------------------------------------------------------------------
 */

static int
StringReadPNG(
    Tcl_Interp *interp,
    Tcl_Obj *pObjData,
    Tcl_Obj *fmtObj,

    Tk_PhotoHandle imageHandle,
    int destX,
    int destY,
    int width,
    int height,
    int srcX,
    int srcY)

{
    PNGImage png;
    int result = TCL_ERROR;
    (void)width;
    (void)height;
    (void)srcX;
    (void)srcY;

    result = InitPNGImage(interp, &png, NULL, pObjData,
	    TCL_ZLIB_STREAM_INFLATE);

    if (TCL_OK == result) {
	result = DecodePNG(interp, &png, fmtObj, imageHandle, destX, destY);
    }













    CleanupPNGImage(&png);
    return result;
}

/*
 *----------------------------------------------------------------------







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



<
<
<
<







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







2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978

2979
2980
2981
2982
2983
2984




2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
 *	New data is added to the image given by imageHandle.
 *
 *----------------------------------------------------------------------
 */

static int
StringReadPNG(
    Tcl_Interp *interp,		/* interpreter for reporting errors in */
    Tcl_Obj *pObjData,		/* object containing the image */
    Tcl_Obj *fmtObj,		/* format object, or NULL */
    TCL_UNUSED(Tcl_Obj *),	/* metadata input, may be NULL */
    Tk_PhotoHandle imageHandle,	/* the image to write this data into */
    int destX, int destY,	/* The rectangular region of the */
    TCL_UNUSED(int),	/* image to copy */
    TCL_UNUSED(int),

    TCL_UNUSED(int),
    TCL_UNUSED(int),
    Tcl_Obj *metadataOutObj)	/* metadata return dict, may be NULL */
{
    PNGImage png;
    int result = TCL_ERROR;





    result = InitPNGImage(interp, &png, NULL, pObjData,
	    TCL_ZLIB_STREAM_INFLATE);

    if (TCL_OK == result) {
	result = DecodePNG(interp, &png, fmtObj, imageHandle, destX, destY);
    }

    if (TCL_OK == result && metadataOutObj != NULL && png.DPI != -1) {
	result = Tcl_DictObjPut(NULL, metadataOutObj,
		Tcl_NewStringObj("DPI",-1),
		Tcl_NewDoubleObj(png.DPI));
    }

    if (TCL_OK == result && metadataOutObj != NULL && png.aspect != -1) {
	result = Tcl_DictObjPut(NULL, metadataOutObj,
		Tcl_NewStringObj("aspect",-1),
		Tcl_NewDoubleObj(png.aspect));
    }

    CleanupPNGImage(&png);
    return result;
}

/*
 *----------------------------------------------------------------------
2914
2915
2916
2917
2918
2919
2920




























2921
2922
2923
2924
2925
2926
2927
{
    return WriteData(interp, pngPtr, &c, 1, crcPtr);
}

/*
 *----------------------------------------------------------------------
 *




























 * WriteInt32 --
 *
 *	This function writes a 32-bit integer value out to the PNG image as
 *	four bytes in network byte order.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if the write fails.







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







3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
{
    return WriteData(interp, pngPtr, &c, 1, crcPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * LongToInt32 --
 *
 *	This function transforms to a 32-bit integer value as
 *	four bytes in network byte order.
 *
 * Results:
 *	None
 *
 * Side effects:
 *	Buffer will be modified.
 *
 *----------------------------------------------------------------------
 */

static inline void
LongToInt32(
    unsigned long l,
    unsigned char *pc)
{
    pc[0] = (unsigned char) ((l & 0xff000000) >> 24);
    pc[1] = (unsigned char) ((l & 0x00ff0000) >> 16);
    pc[2] = (unsigned char) ((l & 0x0000ff00) >> 8);
    pc[3] = (unsigned char) ((l & 0x000000ff) >> 0);
}

/*
 *----------------------------------------------------------------------
 *
 * WriteInt32 --
 *
 *	This function writes a 32-bit integer value out to the PNG image as
 *	four bytes in network byte order.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if the write fails.
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
WriteInt32(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    unsigned long l,
    unsigned long *crcPtr)
{
    unsigned char pc[4];

    pc[0] = (unsigned char) ((l & 0xff000000) >> 24);
    pc[1] = (unsigned char) ((l & 0x00ff0000) >> 16);
    pc[2] = (unsigned char) ((l & 0x0000ff00) >> 8);
    pc[3] = (unsigned char) ((l & 0x000000ff) >> 0);

    return WriteData(interp, pngPtr, pc, 4, crcPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * WriteChunk --







|
<
<
<
<
<







3134
3135
3136
3137
3138
3139
3140
3141





3142
3143
3144
3145
3146
3147
3148
WriteInt32(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    unsigned long l,
    unsigned long *crcPtr)
{
    unsigned char pc[4];
    LongToInt32(l,pc);





    return WriteData(interp, pngPtr, pc, 4, crcPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * WriteChunk --
3260
3261
3262
3263
3264
3265
3266
3267

3268
3269
3270
3271
3272
3273
3274
 *
 *----------------------------------------------------------------------
 */

static int
WriteExtraChunks(
    Tcl_Interp *interp,
    PNGImage *pngPtr)

{
    static const unsigned char sBIT_contents[] = {
	8, 8, 8, 8
    };
    int sBIT_length = 4;
    Tcl_DString buf;








|
>







3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
 *
 *----------------------------------------------------------------------
 */

static int
WriteExtraChunks(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    Tcl_Obj *metadataInObj)
{
    static const unsigned char sBIT_contents[] = {
	8, 8, 8, 8
    };
    int sBIT_length = 4;
    Tcl_DString buf;

3311
3312
3313
3314
3315
3316
3317
3318









































































3319
3320
3321
3322
3323
3324
3325
    if (WriteChunk(interp, pngPtr, CHUNK_tEXt,
	    (unsigned char *) Tcl_DStringValue(&buf),
	    Tcl_DStringLength(&buf)) != TCL_OK) {
	Tcl_DStringFree(&buf);
	return TCL_ERROR;
    }
    Tcl_DStringFree(&buf);










































































    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * EncodePNG --







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







3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
    if (WriteChunk(interp, pngPtr, CHUNK_tEXt,
	    (unsigned char *) Tcl_DStringValue(&buf),
	    Tcl_DStringLength(&buf)) != TCL_OK) {
	Tcl_DStringFree(&buf);
	return TCL_ERROR;
    }
    Tcl_DStringFree(&buf);
    
    /*
     * Add a pHYs chunk if there is metadata for DPI and/or aspect
     * aspect = PPUy / PPUx
     * DPI = PPUx * 0.0254
     * The physical chunc consists of:
     * - Points per meter in x direction (32 bit)
     * - Points per meter in x direction (32 bit)
     * - Unit specifier: 0: no unit (only aspect), 1: Points per meter
     */
    
    if (metadataInObj != NULL) {
	
	Tcl_Obj *aspectObj, *DPIObj;
	double aspectValue=-1, DPIValue=-1;
	unsigned long PPUx = 65536, PPUy = 65536;
	char unitSpecifier;
	
	if (TCL_ERROR == Tcl_DictObjGet(interp, metadataInObj,
		Tcl_NewStringObj("aspect",-1),
		&aspectObj) ||
	    TCL_ERROR == Tcl_DictObjGet(interp, metadataInObj,
		Tcl_NewStringObj("DPI",-1),
		&DPIObj) ) {
	    return TCL_ERROR;
	}
	if (DPIObj != NULL) {
	    if (TCL_ERROR == Tcl_GetDoubleFromObj(interp, DPIObj, &DPIValue))
	    {
		return TCL_ERROR;
	    }
	    PPUx = (unsigned long)floor(DPIValue / 0.0254+0.5);
	    if (aspectObj == NULL) {
		PPUy = PPUx;
	    }
	    unitSpecifier = 1;
	}
	if (aspectObj != NULL) {
	    if (TCL_ERROR == Tcl_GetDoubleFromObj(interp, aspectObj,
		    &aspectValue)) {
		return TCL_ERROR;
	    }

	    /*
	     * aspect = PPUy / PPUx
	     */
	    
	    if (DPIObj == NULL) {
		unitSpecifier = 0;
		PPUx = 65536;
		PPUy = (unsigned long)floor(65536.0 * aspectValue+0.5);
	    } else {
		PPUy = (unsigned long)floor(DPIValue * aspectValue / 0.0254+0.5);
	    }
	}
	if (DPIObj != NULL || aspectObj != NULL) {
	    unsigned char buffer[9];

	    if ( PPUx > 2147483647 || PPUy > 2147483647 ) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj(
			"DPI or aspect out of range", -1));
		Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "PHYS", NULL);
		return TCL_ERROR;
	    }
	    
	    LongToInt32(PPUx, buffer);
	    LongToInt32(PPUy, buffer+4);
	    buffer[8] = unitSpecifier;
	    if (WriteChunk(interp, pngPtr, CHUNK_pHYs, buffer, 9)
		    != TCL_OK) {
		return TCL_ERROR;
	    }
	}
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * EncodePNG --
3337
3338
3339
3340
3341
3342
3343
3344

3345
3346
3347
3348
3349
3350
3351
 *----------------------------------------------------------------------
 */

static int
EncodePNG(
    Tcl_Interp *interp,
    Tk_PhotoImageBlock *blockPtr,
    PNGImage *pngPtr)

{
    int greenOffset, blueOffset, alphaOffset;

    /*
     * Determine appropriate color type based on color usage (e.g., only red
     * and maybe alpha channel = grayscale).
     *







|
>







3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
 *----------------------------------------------------------------------
 */

static int
EncodePNG(
    Tcl_Interp *interp,
    Tk_PhotoImageBlock *blockPtr,
    PNGImage *pngPtr,
    Tcl_Obj *metadataInObj)
{
    int greenOffset, blueOffset, alphaOffset;

    /*
     * Determine appropriate color type based on color usage (e.g., only red
     * and maybe alpha channel = grayscale).
     *
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
    }

    /*
     * Write out the extra chunks containing metadata that is of interest to
     * other programs more than us.
     */

    if (WriteExtraChunks(interp, pngPtr) == TCL_ERROR) {
	return TCL_ERROR;
    }

    /*
     * Write out the image pixels in the IDAT (data) chunk.
     */








|







3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
    }

    /*
     * Write out the extra chunks containing metadata that is of interest to
     * other programs more than us.
     */

    if (WriteExtraChunks(interp, pngPtr, metadataInObj) == TCL_ERROR) {
	return TCL_ERROR;
    }

    /*
     * Write out the image pixels in the IDAT (data) chunk.
     */

3461
3462
3463
3464
3465
3466
3467

3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
 *----------------------------------------------------------------------
 */

static int
FileWritePNG(
    Tcl_Interp *interp,
    const char *filename,

    Tcl_Obj *fmtObj,
    Tk_PhotoImageBlock *blockPtr)
{
    Tcl_Channel chan;
    PNGImage png;
    int result = TCL_ERROR;
    (void)fmtObj;

    /*
     * Open a Tcl file channel where the image data will be stored. Tk ought
     * to take care of this, and just provide a channel, but it doesn't.
     */

    chan = Tcl_OpenFileChannel(interp, filename, "w", 0644);







>
|





<







3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742

3743
3744
3745
3746
3747
3748
3749
 *----------------------------------------------------------------------
 */

static int
FileWritePNG(
    Tcl_Interp *interp,
    const char *filename,
    TCL_UNUSED(Tcl_Obj *),
    Tcl_Obj *metadataInObj,
    Tk_PhotoImageBlock *blockPtr)
{
    Tcl_Channel chan;
    PNGImage png;
    int result = TCL_ERROR;


    /*
     * Open a Tcl file channel where the image data will be stored. Tk ought
     * to take care of this, and just provide a channel, but it doesn't.
     */

    chan = Tcl_OpenFileChannel(interp, filename, "w", 0644);
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
	goto cleanup;
    }

    /*
     * Write the raw PNG data out to the file.
     */

    result = EncodePNG(interp, blockPtr, &png);

  cleanup:
    Tcl_Close(interp, chan);
    CleanupPNGImage(&png);
    return result;
}








|







3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
	goto cleanup;
    }

    /*
     * Write the raw PNG data out to the file.
     */

    result = EncodePNG(interp, blockPtr, &png, metadataInObj);

  cleanup:
    Tcl_Close(interp, chan);
    CleanupPNGImage(&png);
    return result;
}

3532
3533
3534
3535
3536
3537
3538

3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
 *
 *----------------------------------------------------------------------
 */

static int
StringWritePNG(
    Tcl_Interp *interp,

    Tcl_Obj *fmtObj,
    Tk_PhotoImageBlock *blockPtr)
{
    Tcl_Obj *resultObj = Tcl_NewObj();
    PNGImage png;
    int result = TCL_ERROR;
    (void)fmtObj;

    /*
     * Initalize PNGImage instance for encoding.
     */

    if (InitPNGImage(interp, &png, NULL, resultObj,
	    TCL_ZLIB_STREAM_DEFLATE) == TCL_ERROR) {
	goto cleanup;
    }

    /*
     * Write the raw PNG data into the prepared Tcl_Obj buffer. Set the result
     * back to the interpreter if successful.
     */

    result = EncodePNG(interp, blockPtr, &png);

    if (TCL_OK == result) {
	Tcl_SetObjResult(interp, png.objDataPtr);
    }

  cleanup:
    CleanupPNGImage(&png);







>
|





<















|







3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813

3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
 *
 *----------------------------------------------------------------------
 */

static int
StringWritePNG(
    Tcl_Interp *interp,
    TCL_UNUSED(Tcl_Obj *),
    Tcl_Obj *metadataInObj,
    Tk_PhotoImageBlock *blockPtr)
{
    Tcl_Obj *resultObj = Tcl_NewObj();
    PNGImage png;
    int result = TCL_ERROR;


    /*
     * Initalize PNGImage instance for encoding.
     */

    if (InitPNGImage(interp, &png, NULL, resultObj,
	    TCL_ZLIB_STREAM_DEFLATE) == TCL_ERROR) {
	goto cleanup;
    }

    /*
     * Write the raw PNG data into the prepared Tcl_Obj buffer. Set the result
     * back to the interpreter if successful.
     */

    result = EncodePNG(interp, blockPtr, &png, metadataInObj);

    if (TCL_OK == result) {
	Tcl_SetObjResult(interp, png.objDataPtr);
    }

  cleanup:
    CleanupPNGImage(&png);

Changes to generic/tkImgPhoto.c.

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
    int toX2, toY2;		/* Second coordinate pair for -to option. */
    int zoomX, zoomY;		/* Values specified for -zoom option. */
    int subsampleX, subsampleY;	/* Values specified for -subsample option. */
    Tcl_Obj *format;		/* Value specified for -format option. */
    XColor *background;		/* Value specified for -background option. */
    int compositingRule;	/* Value specified for -compositingrule
				 * option. */

};

/*
 * Bit definitions for use with ParseSubcommandOptions: each bit is set in the
 * allowedOptions parameter on a call to ParseSubcommandOptions if that option
 * is allowed for the current photo image subcommand. On return, the bit is
 * set in the options field of the SubcommandOptions structure if that option
 * was specified.
 *
 * OPT_ALPHA:			Set if -alpha option allowed/specified.
 * OPT_BACKGROUND:		Set if -format option allowed/specified.
 * OPT_COMPOSITE:		Set if -compositingrule option allowed/spec'd.
 * OPT_FORMAT:			Set if -format option allowed/specified.
 * OPT_FROM:			Set if -from option allowed/specified.
 * OPT_GRAYSCALE:		Set if -grayscale option allowed/specified.

 * OPT_SHRINK:			Set if -shrink option allowed/specified.
 * OPT_SUBSAMPLE:		Set if -subsample option allowed/spec'd.
 * OPT_TO:			Set if -to option allowed/specified.
 * OPT_WITHALPHA:		Set if -withalpha option allowed/specified.
 * OPT_ZOOM:			Set if -zoom option allowed/specified.
 */

#define OPT_ALPHA	1
#define OPT_BACKGROUND	2
#define OPT_COMPOSITE	4
#define OPT_FORMAT	8
#define OPT_FROM	0x10
#define OPT_GRAYSCALE	0x20

#define OPT_SHRINK	0x40
#define OPT_SUBSAMPLE	0x80
#define OPT_TO		0x100
#define OPT_WITHALPHA	0x200
#define OPT_ZOOM	0x400

/*
 * List of option names. The order here must match the order of declarations
 * of the OPT_* constants above.
 */

static const char *const optionNames[] = {
    "-alpha",
    "-background",
    "-compositingrule",
    "-format",
    "-from",
    "-grayscale",

    "-shrink",
    "-subsample",
    "-to",
    "-withalpha",
    "-zoom",
    NULL
};







>















>













>
|
|
|
|
|













>







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
    int toX2, toY2;		/* Second coordinate pair for -to option. */
    int zoomX, zoomY;		/* Values specified for -zoom option. */
    int subsampleX, subsampleY;	/* Values specified for -subsample option. */
    Tcl_Obj *format;		/* Value specified for -format option. */
    XColor *background;		/* Value specified for -background option. */
    int compositingRule;	/* Value specified for -compositingrule
				 * option. */
    Tcl_Obj *metadata;		/* Value specified for -metadata option. */
};

/*
 * Bit definitions for use with ParseSubcommandOptions: each bit is set in the
 * allowedOptions parameter on a call to ParseSubcommandOptions if that option
 * is allowed for the current photo image subcommand. On return, the bit is
 * set in the options field of the SubcommandOptions structure if that option
 * was specified.
 *
 * OPT_ALPHA:			Set if -alpha option allowed/specified.
 * OPT_BACKGROUND:		Set if -format option allowed/specified.
 * OPT_COMPOSITE:		Set if -compositingrule option allowed/spec'd.
 * OPT_FORMAT:			Set if -format option allowed/specified.
 * OPT_FROM:			Set if -from option allowed/specified.
 * OPT_GRAYSCALE:		Set if -grayscale option allowed/specified.
 * OPT_METADATA:		Set if -metadata option allowed/specified.
 * OPT_SHRINK:			Set if -shrink option allowed/specified.
 * OPT_SUBSAMPLE:		Set if -subsample option allowed/spec'd.
 * OPT_TO:			Set if -to option allowed/specified.
 * OPT_WITHALPHA:		Set if -withalpha option allowed/specified.
 * OPT_ZOOM:			Set if -zoom option allowed/specified.
 */

#define OPT_ALPHA	1
#define OPT_BACKGROUND	2
#define OPT_COMPOSITE	4
#define OPT_FORMAT	8
#define OPT_FROM	0x10
#define OPT_GRAYSCALE	0x20
#define OPT_METADATA	0x40
#define OPT_SHRINK	0x80
#define OPT_SUBSAMPLE	0x100
#define OPT_TO		0x200
#define OPT_WITHALPHA	0x400
#define OPT_ZOOM	0x800

/*
 * List of option names. The order here must match the order of declarations
 * of the OPT_* constants above.
 */

static const char *const optionNames[] = {
    "-alpha",
    "-background",
    "-compositingrule",
    "-format",
    "-from",
    "-grayscale",
    "-metadata",
    "-shrink",
    "-subsample",
    "-to",
    "-withalpha",
    "-zoom",
    NULL
};
136
137
138
139
140
141
142



143
144
145
146
147
148
149
				/* Pointer to the first in the list of known
				 * photo image formats.*/
#if !defined(TK_NO_DEPRECATED) && TCL_MAJOR_VERSION < 9
    Tk_PhotoImageFormat *oldFormatList;
				/* Pointer to the first in the list of known
				 * photo image formats.*/
#endif



    int initialized;		/* Set to 1 if we've initialized the
				 * structure. */
} ThreadSpecificData;
static Tcl_ThreadDataKey dataKey;

/*
 * Default configuration







>
>
>







140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
				/* Pointer to the first in the list of known
				 * photo image formats.*/
#if !defined(TK_NO_DEPRECATED) && TCL_MAJOR_VERSION < 9
    Tk_PhotoImageFormat *oldFormatList;
				/* Pointer to the first in the list of known
				 * photo image formats.*/
#endif
    Tk_PhotoImageFormatVersion3 *formatListVersion3;
				/* Pointer to the first in the list of known
				 * photo image formats in Version3 format.*/
    int initialized;		/* Set to 1 if we've initialized the
				 * structure. */
} ThreadSpecificData;
static Tcl_ThreadDataKey dataKey;

/*
 * Default configuration
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
			    Tcl_Obj *const objv[], int flags);
static int		ToggleComplexAlphaIfNeeded(PhotoModel *mPtr);
static int		ImgPhotoSetSize(PhotoModel *modelPtr, int width,
			    int height);
static char *		ImgGetPhoto(PhotoModel *modelPtr,
			    Tk_PhotoImageBlock *blockPtr,
			    struct SubcommandOptions *optPtr);
static int		MatchFileFormat(Tcl_Interp *interp, Tcl_Channel chan,
			    const char *fileName, Tcl_Obj *formatString,
			    Tk_PhotoImageFormat **imageFormatPtr,
			    int *widthPtr, int *heightPtr, int *oldformat);
static int		MatchStringFormat(Tcl_Interp *interp, Tcl_Obj *data,
			    Tcl_Obj *formatString,
			    Tk_PhotoImageFormat **imageFormatPtr,
			    int *widthPtr, int *heightPtr, int *oldformat);
static const char *	GetExtension(const char *path);

/*
 *----------------------------------------------------------------------
 *
 * PhotoFormatThreadExitProc --
 *
 *	Clean up the registered list of photo formats.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The thread's linked lists of photo image formats is deleted.
 *
 *----------------------------------------------------------------------
 */

static void
PhotoFormatThreadExitProc(
    ClientData dummy)	/* not used */
{
    Tk_PhotoImageFormat *freePtr;

    ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
	    Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
    (void)dummy;

#if !defined(TK_NO_DEPRECATED) && TCL_MAJOR_VERSION < 9
    while (tsdPtr->oldFormatList != NULL) {
	freePtr = tsdPtr->oldFormatList;
	tsdPtr->oldFormatList = tsdPtr->oldFormatList->nextPtr;
	ckfree(freePtr);
    }
#endif
    while (tsdPtr->formatList != NULL) {
	freePtr = tsdPtr->formatList;
	tsdPtr->formatList = tsdPtr->formatList->nextPtr;
	ckfree((char *)freePtr->name);
	ckfree(freePtr);
    }






}

/*
 *----------------------------------------------------------------------
 *
 * Tk_CreateOldPhotoImageFormat, Tk_CreatePhotoImageFormat --

 *
 *	This function is invoked by an image file handler to register a new
 *	photo image format and the functions that handle the new format. The
 *	function is typically invoked during Tcl_AppInit.
 *
 * Results:
 *	None.







<
<
<
<
<
<
<
<




















|


>


<














>
>
>
>
>
>





|
>







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
			    Tcl_Obj *const objv[], int flags);
static int		ToggleComplexAlphaIfNeeded(PhotoModel *mPtr);
static int		ImgPhotoSetSize(PhotoModel *modelPtr, int width,
			    int height);
static char *		ImgGetPhoto(PhotoModel *modelPtr,
			    Tk_PhotoImageBlock *blockPtr,
			    struct SubcommandOptions *optPtr);








static const char *	GetExtension(const char *path);

/*
 *----------------------------------------------------------------------
 *
 * PhotoFormatThreadExitProc --
 *
 *	Clean up the registered list of photo formats.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The thread's linked lists of photo image formats is deleted.
 *
 *----------------------------------------------------------------------
 */

static void
PhotoFormatThreadExitProc(
    TCL_UNUSED(void *))	/* not used */
{
    Tk_PhotoImageFormat *freePtr;
    Tk_PhotoImageFormatVersion3 *freePtrVersion3;
    ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
	    Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));


#if !defined(TK_NO_DEPRECATED) && TCL_MAJOR_VERSION < 9
    while (tsdPtr->oldFormatList != NULL) {
	freePtr = tsdPtr->oldFormatList;
	tsdPtr->oldFormatList = tsdPtr->oldFormatList->nextPtr;
	ckfree(freePtr);
    }
#endif
    while (tsdPtr->formatList != NULL) {
	freePtr = tsdPtr->formatList;
	tsdPtr->formatList = tsdPtr->formatList->nextPtr;
	ckfree((char *)freePtr->name);
	ckfree(freePtr);
    }
    while (tsdPtr->formatListVersion3 != NULL) {
	freePtrVersion3 = tsdPtr->formatListVersion3;
	tsdPtr->formatListVersion3 = tsdPtr->formatListVersion3->nextPtr;
	ckfree((char *)freePtrVersion3->name);
	ckfree(freePtrVersion3);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * Tk_CreateOldPhotoImageFormat, Tk_CreatePhotoImageFormat,
 * Tk_CreatePhotoImageFormatVersion3 --
 *
 *	This function is invoked by an image file handler to register a new
 *	photo image format and the functions that handle the new format. The
 *	function is typically invoked during Tcl_AppInit.
 *
 * Results:
 *	None.
313
314
315
316
317
318
319


























320
321
322
323
324
325
326
	char *name = (char *)ckalloc(strlen(formatPtr->name) + 1);
	strcpy(name, formatPtr->name);
	copyPtr->name = name;
	copyPtr->nextPtr = tsdPtr->formatList;
	tsdPtr->formatList = copyPtr;
    }
}



























/*
 *----------------------------------------------------------------------
 *
 * ImgPhotoCreate --
 *
 *	This function is called by the Tk image code to create a new photo







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







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
	char *name = (char *)ckalloc(strlen(formatPtr->name) + 1);
	strcpy(name, formatPtr->name);
	copyPtr->name = name;
	copyPtr->nextPtr = tsdPtr->formatList;
	tsdPtr->formatList = copyPtr;
    }
}
void
Tk_CreatePhotoImageFormatVersion3(
    const Tk_PhotoImageFormatVersion3 *formatPtr)
				/* Structure describing the format. All of the
				 * fields except "nextPtr" must be filled in
				 * by caller. */
{
    Tk_PhotoImageFormatVersion3 *copyPtr;
    char *name;
    ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
	    Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));

    if (!tsdPtr->initialized) {
	tsdPtr->initialized = 1;
	Tcl_CreateThreadExitHandler(PhotoFormatThreadExitProc, NULL);
    }
    copyPtr = (Tk_PhotoImageFormatVersion3 *)
	    ckalloc(sizeof(Tk_PhotoImageFormatVersion3));
    *copyPtr = *formatPtr;
    /* for compatibility with aMSN: make a copy of formatPtr->name */
    name = (char *)ckalloc(strlen(formatPtr->name) + 1);
    strcpy(name, formatPtr->name);
    copyPtr->name = name;
    copyPtr->nextPtr = tsdPtr->formatListVersion3;
    tsdPtr->formatListVersion3 = copyPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * ImgPhotoCreate --
 *
 *	This function is called by the Tk image code to create a new photo
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
ImgPhotoCreate(
    Tcl_Interp *interp,		/* Interpreter for application containing
				 * image. */
    const char *name,		/* Name to use for image. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[],	/* Argument objects for options (doesn't
				 * include image name or type). */
    const Tk_ImageType *typePtr,/* Pointer to our type record (not used). */
    Tk_ImageModel model,	/* Token for image, to be used by us in later
				 * callbacks. */
    ClientData *clientDataPtr)	/* Store manager's token for image here; it
				 * will be returned in later callbacks. */
{
    PhotoModel *modelPtr;
    (void)typePtr;

    /*
     * Allocate and initialize the photo image model record.
     */

    modelPtr = (PhotoModel *)ckalloc(sizeof(PhotoModel));
    memset(modelPtr, 0, sizeof(PhotoModel));







|






<







371
372
373
374
375
376
377
378
379
380
381
382
383
384

385
386
387
388
389
390
391
ImgPhotoCreate(
    Tcl_Interp *interp,		/* Interpreter for application containing
				 * image. */
    const char *name,		/* Name to use for image. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[],	/* Argument objects for options (doesn't
				 * include image name or type). */
    TCL_UNUSED(const Tk_ImageType *),/* Pointer to our type record (not used). */
    Tk_ImageModel model,	/* Token for image, to be used by us in later
				 * callbacks. */
    ClientData *clientDataPtr)	/* Store manager's token for image here; it
				 * will be returned in later callbacks. */
{
    PhotoModel *modelPtr;


    /*
     * Allocate and initialize the photo image model record.
     */

    modelPtr = (PhotoModel *)ckalloc(sizeof(PhotoModel));
    memset(modelPtr, 0, sizeof(PhotoModel));
417
418
419
420
421
422
423

424
425
426
427
428
429
430

    PhotoModel *modelPtr = (PhotoModel *)clientData;
    int result, index, x, y, width, height;
    struct SubcommandOptions options;
    unsigned char *pixelPtr;
    Tk_PhotoImageBlock block;
    Tk_PhotoImageFormat *imageFormat;

    TkSizeT length;
    int imageWidth, imageHeight, matched, oldformat = 0;
    Tcl_Channel chan;
    Tk_PhotoHandle srcHandle;
    ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
	    Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));








>







448
449
450
451
452
453
454
455
456
457
458
459
460
461
462

    PhotoModel *modelPtr = (PhotoModel *)clientData;
    int result, index, x, y, width, height;
    struct SubcommandOptions options;
    unsigned char *pixelPtr;
    Tk_PhotoImageBlock block;
    Tk_PhotoImageFormat *imageFormat;
    Tk_PhotoImageFormatVersion3 *imageFormatVersion3;
    TkSizeT length;
    int imageWidth, imageHeight, matched, oldformat = 0;
    Tcl_Channel chan;
    Tk_PhotoHandle srcHandle;
    ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
	    Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));

464
465
466
467
468
469
470




471
472
473
474
475
476
477
	    if (modelPtr->dataString) {
		Tcl_SetObjResult(interp, modelPtr->dataString);
	    }
	} else if (strncmp(arg,"-format", length) == 0) {
	    if (modelPtr->format) {
		Tcl_SetObjResult(interp, modelPtr->format);
	    }




	} else {
	    Tk_ConfigureValue(interp, Tk_MainWindow(interp), configSpecs,
		    (char *) modelPtr, Tcl_GetString(objv[2]), 0);
	}
	return TCL_OK;
    }








>
>
>
>







496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
	    if (modelPtr->dataString) {
		Tcl_SetObjResult(interp, modelPtr->dataString);
	    }
	} else if (strncmp(arg,"-format", length) == 0) {
	    if (modelPtr->format) {
		Tcl_SetObjResult(interp, modelPtr->format);
	    }
	} else if (strncmp(arg, "-metadata", length) == 0) {
	    if (modelPtr->metadata) {
		Tcl_SetObjResult(interp, modelPtr->metadata);
	    }
	} else {
	    Tk_ConfigureValue(interp, Tk_MainWindow(interp), configSpecs,
		    (char *) modelPtr, Tcl_GetString(objv[2]), 0);
	}
	return TCL_OK;
    }

497
498
499
500
501
502
503







504
505
506
507
508
509
510
	    }
	    Tcl_ListObjAppendElement(interp, obj, subobj);
	    subobj = Tcl_NewStringObj("-format {} {} {}", 16);
	    if (modelPtr->format) {
		Tcl_ListObjAppendElement(NULL, subobj, modelPtr->format);
	    } else {
		Tcl_AppendStringsToObj(subobj, " {}", NULL);







	    }
	    Tcl_ListObjAppendElement(interp, obj, subobj);
	    Tcl_ListObjAppendList(interp, obj, Tcl_GetObjResult(interp));
	    Tcl_SetObjResult(interp, obj);
	    return TCL_OK;

	} else if (objc == 3) {







>
>
>
>
>
>
>







533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
	    }
	    Tcl_ListObjAppendElement(interp, obj, subobj);
	    subobj = Tcl_NewStringObj("-format {} {} {}", 16);
	    if (modelPtr->format) {
		Tcl_ListObjAppendElement(NULL, subobj, modelPtr->format);
	    } else {
		Tcl_AppendStringsToObj(subobj, " {}", NULL);
	    }
	    Tcl_ListObjAppendElement(interp, obj, subobj);
	    subobj = Tcl_NewStringObj("-metadata {} {} {}", 16);
	    if (modelPtr->metadata) {
		Tcl_ListObjAppendElement(NULL, subobj, modelPtr->metadata);
	    } else {
		Tcl_AppendStringsToObj(subobj, " {}", NULL);
	    }
	    Tcl_ListObjAppendElement(interp, obj, subobj);
	    Tcl_ListObjAppendList(interp, obj, Tcl_GetObjResult(interp));
	    Tcl_SetObjResult(interp, obj);
	    return TCL_OK;

	} else if (objc == 3) {
529
530
531
532
533
534
535














536
537
538
539
540
541
542
		if (modelPtr->format) {
		    /*
		     * TODO: Modifying result is bad!
		     */

		    Tcl_ListObjAppendElement(NULL, Tcl_GetObjResult(interp),
			    modelPtr->format);














		} else {
		    Tcl_AppendResult(interp, " {}", NULL);
		}
		return TCL_OK;
	    } else {
		return Tk_ConfigureInfo(interp, Tk_MainWindow(interp),
			configSpecs, (char *) modelPtr, arg, 0);







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







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
		if (modelPtr->format) {
		    /*
		     * TODO: Modifying result is bad!
		     */

		    Tcl_ListObjAppendElement(NULL, Tcl_GetObjResult(interp),
			    modelPtr->format);
		} else {
		    Tcl_AppendResult(interp, " {}", NULL);
		}
		return TCL_OK;
	    } else if (length > 1 &&
		!strncmp(arg, "-metadata", length)) {
		Tcl_AppendResult(interp, "-metadata {} {} {}", NULL);
		if (modelPtr->metadata) {
		    /*
		     * TODO: Modifying result is bad!
		     */

		    Tcl_ListObjAppendElement(NULL, Tcl_GetObjResult(interp),
			modelPtr->metadata);
		} else {
		    Tcl_AppendResult(interp, " {}", NULL);
		}
		return TCL_OK;
	    } else {
		return Tk_ConfigureInfo(interp, Tk_MainWindow(interp),
			configSpecs, (char *) modelPtr, arg, 0);
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
	    Tk_FreeColor(options.background);
	}
	return result;

    case PHOTO_DATA: {
        char *data = NULL;
        Tcl_Obj *freeObj = NULL;


	/*
	 * photo data command - first parse and check any options given.
	 */

	Tk_ImageStringWriteProc *stringWriteProc = NULL;


	index = 1;
	memset(&options, 0, sizeof(options));
	options.name = NULL;
	options.format = NULL;

	options.fromX = 0;
	options.fromY = 0;
	if (ParseSubcommandOptions(&options, interp,
		OPT_FORMAT | OPT_FROM | OPT_GRAYSCALE | OPT_BACKGROUND,

		&index, objc, objv) != TCL_OK) {
	    return TCL_ERROR;
	}
	if ((options.name == NULL) || (index < objc)) {
	    Tcl_WrongNumArgs(interp, 2, objv, "?-option value ...?");
	    return TCL_ERROR;
	}







>






>





>



|
>







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
	    Tk_FreeColor(options.background);
	}
	return result;

    case PHOTO_DATA: {
        char *data = NULL;
        Tcl_Obj *freeObj = NULL;
	Tcl_Obj *metadataIn;

	/*
	 * photo data command - first parse and check any options given.
	 */

	Tk_ImageStringWriteProc *stringWriteProc = NULL;
	Tk_ImageStringWriteProcVersion3 *stringWriteProcVersion3 = NULL;

	index = 1;
	memset(&options, 0, sizeof(options));
	options.name = NULL;
	options.format = NULL;
	options.metadata = NULL;
	options.fromX = 0;
	options.fromY = 0;
	if (ParseSubcommandOptions(&options, interp,
		OPT_FORMAT | OPT_FROM | OPT_GRAYSCALE | OPT_BACKGROUND
		| OPT_METADATA,
		&index, objc, objv) != TCL_OK) {
	    return TCL_ERROR;
	}
	if ((options.name == NULL) || (index < objc)) {
	    Tcl_WrongNumArgs(interp, 2, objv, "?-option value ...?");
	    return TCL_ERROR;
	}
720
721
722
723
724
725
726










727
728
729
730
731
732
733
	    options.fromX2 = modelPtr->width;
	    options.fromY2 = modelPtr->height;
	}
	if (!(options.options & OPT_FORMAT)) {
            options.format = Tcl_NewStringObj("default", -1);
            freeObj = options.format;
	}











	/*
	 * Search for an appropriate image string format handler.
	 */

	matched = 0;
	for (imageFormat = tsdPtr->formatList; imageFormat != NULL;







>
>
>
>
>
>
>
>
>
>







781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
	    options.fromX2 = modelPtr->width;
	    options.fromY2 = modelPtr->height;
	}
	if (!(options.options & OPT_FORMAT)) {
            options.format = Tcl_NewStringObj("default", -1);
            freeObj = options.format;
	}
	
	/*
	 * Use argument metadata if specified, otherwise the model metadata
	 */
	
	if (NULL != options.metadata) {
	    metadataIn = options.metadata;
	} else {
	    metadataIn = modelPtr->metadata;
	}

	/*
	 * Search for an appropriate image string format handler.
	 */

	matched = 0;
	for (imageFormat = tsdPtr->formatList; imageFormat != NULL;
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
                        break;
                    }
                }
	    }
	}
#endif
	if (stringWriteProc == NULL) {

















	    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
                    "image string format \"%s\" is %s",
                    Tcl_GetString(options.format),
                    (matched ? "not supported" : "unknown")));
	    Tcl_SetErrorCode(interp, "TK", "LOOKUP", "PHOTO_FORMAT",
                    Tcl_GetString(options.format), NULL);
	    goto dataErrorExit;
	}

	/*
	 * Call the handler's string write function to write out the image.
	 */

	data = ImgGetPhoto(modelPtr, &block, &options);




	if (oldformat) {
	    Tcl_DString buffer;
	    typedef int (*OldStringWriteProc)(Tcl_Interp *interp,
		    Tcl_DString *dataPtr, const char *formatString,
		    Tk_PhotoImageBlock *blockPtr);

	    Tcl_DStringInit(&buffer);
	    result = ((OldStringWriteProc)(void *)stringWriteProc)(interp, &buffer,







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

|
|
|

|









>
>
>
|







826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
                        break;
                    }
                }
	    }
	}
#endif
	if (stringWriteProc == NULL) {
	    oldformat = 0;
	    for (imageFormatVersion3 = tsdPtr->formatListVersion3;
		    imageFormatVersion3 != NULL;
		    imageFormatVersion3 = imageFormatVersion3->nextPtr) {
		if ((strncasecmp(Tcl_GetString(options.format),
			imageFormatVersion3->name,
			strlen(imageFormatVersion3->name)) == 0)) {
		    matched = 1;
		    if (imageFormatVersion3->stringWriteProc != NULL) {
			stringWriteProcVersion3 =
				imageFormatVersion3->stringWriteProc;
			break;
		    }
		}
	    }
	}
	if (stringWriteProc == NULL && stringWriteProcVersion3 == NULL) {
	    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		    "image string format \"%s\" is %s",
		    Tcl_GetString(options.format),
		    (matched ? "not supported" : "unknown")));
	    Tcl_SetErrorCode(interp, "TK", "LOOKUP", "PHOTO_FORMAT",
		    Tcl_GetString(options.format), NULL);
	    goto dataErrorExit;
	}

	/*
	 * Call the handler's string write function to write out the image.
	 */

	data = ImgGetPhoto(modelPtr, &block, &options);

	if (stringWriteProc == NULL) {
	    result = (stringWriteProcVersion3)(interp,
		    options.format, metadataIn, &block);
	} else if (oldformat) {
	    Tcl_DString buffer;
	    typedef int (*OldStringWriteProc)(Tcl_Interp *interp,
		    Tcl_DString *dataPtr, const char *formatString,
		    Tk_PhotoImageBlock *blockPtr);

	    Tcl_DStringInit(&buffer);
	    result = ((OldStringWriteProc)(void *)stringWriteProc)(interp, &buffer,
877
878
879
880
881
882
883

884

885
886
887
888
889
890
891
892
893
894
895
896
897

898

899
900
901
902
903
904
905
	 * photo put command - first parse the options.
	 */

	index = 2;
	memset(&options, 0, sizeof(options));
	options.name = NULL;
	options.format = NULL;

	if (ParseSubcommandOptions(&options, interp, OPT_TO|OPT_FORMAT,

		&index, objc, objv) != TCL_OK) {
	    return TCL_ERROR;
	}
	if ((options.name == NULL) || (index < objc)) {
	    Tcl_WrongNumArgs(interp, 2, objv, "data ?-option value ...?");
	    return TCL_ERROR;
	}

	/*
	 * See if there's a format that can read the data
	 */

	if (MatchStringFormat(interp, objv[2], options.format, &imageFormat,

		&imageWidth, &imageHeight, &oldformat) != TCL_OK) {

	    return TCL_ERROR;
	}

	if (!(options.options & OPT_TO) || (options.toX2 < 0)) {
	    options.toX2 = options.toX + imageWidth;
	    options.toY2 = options.toY + imageHeight;
	}







>
|
>












|
>
|
>







968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
	 * photo put command - first parse the options.
	 */

	index = 2;
	memset(&options, 0, sizeof(options));
	options.name = NULL;
	options.format = NULL;
	options.metadata = NULL;
	if (ParseSubcommandOptions(&options, interp,
		OPT_TO|OPT_FORMAT|OPT_METADATA,
		&index, objc, objv) != TCL_OK) {
	    return TCL_ERROR;
	}
	if ((options.name == NULL) || (index < objc)) {
	    Tcl_WrongNumArgs(interp, 2, objv, "data ?-option value ...?");
	    return TCL_ERROR;
	}

	/*
	 * See if there's a format that can read the data
	 */

	if (TkImgMatchStringFormat(interp, objv[2], options.format,
		options.metadata, NULL, &imageFormat,
		&imageFormatVersion3, &imageWidth, &imageHeight, &oldformat)
		!= TCL_OK) {
	    return TCL_ERROR;
	}

	if (!(options.options & OPT_TO) || (options.toX2 < 0)) {
	    options.toX2 = options.toX + imageWidth;
	    options.toY2 = options.toY + imageHeight;
	}
914
915
916
917
918
919
920

921
922
923
924
925
926












927
928
929
930
931
932
933
934
935
936
937
938

939
940
941
942
943
944
945
946
947

948
949
950
951
952
953
954
955
956
	if (oldformat) {
	    if (format) {
		format = (Tcl_Obj *) Tcl_GetString(format);
	    }
	    data = (Tcl_Obj *) Tcl_GetString(data);
	}


	if (imageFormat->stringReadProc(interp, data, format,
		(Tk_PhotoHandle) modelPtr, options.toX, options.toY,
		options.toX2 - options.toX,
		options.toY2 - options.toY, 0, 0) != TCL_OK) {
	    return TCL_ERROR;
	}












	/*
	 * SB: is the next line really needed? The stringReadProc
	 * writes image data with Tk_PhotoPutBlock(), which in turn
	 * takes care to notify the changed image and to set/unset the
	 * IMAGE_CHANGED bit.
	 */
	modelPtr->flags |= IMAGE_CHANGED;

	return TCL_OK;
    }
    case PHOTO_READ: {
	Tcl_Obj *format;


	/*
	 * photo read command - first parse the options specified.
	 */

	index = 2;
	memset(&options, 0, sizeof(options));
	options.name = NULL;
	options.format = NULL;

	if (ParseSubcommandOptions(&options, interp,
		OPT_FORMAT | OPT_FROM | OPT_TO | OPT_SHRINK,
		&index, objc, objv) != TCL_OK) {
	    return TCL_ERROR;
	}
	if ((options.name == NULL) || (index < objc)) {
	    Tcl_WrongNumArgs(interp, 2, objv, "fileName ?-option value ...?");
	    return TCL_ERROR;
	}







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












>









>

|







1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
	if (oldformat) {
	    if (format) {
		format = (Tcl_Obj *) Tcl_GetString(format);
	    }
	    data = (Tcl_Obj *) Tcl_GetString(data);
	}

	if (imageFormat != NULL) {
	    if (imageFormat->stringReadProc(interp, data, format,
		    (Tk_PhotoHandle) modelPtr, options.toX, options.toY,
		    options.toX2 - options.toX,
		    options.toY2 - options.toY, 0, 0) != TCL_OK) {
		return TCL_ERROR;
	    }
	} else {
	    if (imageFormatVersion3->stringReadProc(interp, data, format,
		    options.metadata,
		    (Tk_PhotoHandle) modelPtr, options.toX, options.toY,
		    options.toX2 - options.toX,
		    options.toY2 - options.toY, 0, 0,
		    NULL)
		    != TCL_OK) {
		return TCL_ERROR;
	    }
	}

	/*
	 * SB: is the next line really needed? The stringReadProc
	 * writes image data with Tk_PhotoPutBlock(), which in turn
	 * takes care to notify the changed image and to set/unset the
	 * IMAGE_CHANGED bit.
	 */
	modelPtr->flags |= IMAGE_CHANGED;

	return TCL_OK;
    }
    case PHOTO_READ: {
	Tcl_Obj *format;
	int result;

	/*
	 * photo read command - first parse the options specified.
	 */

	index = 2;
	memset(&options, 0, sizeof(options));
	options.name = NULL;
	options.format = NULL;
	options.metadata = NULL;
	if (ParseSubcommandOptions(&options, interp,
		OPT_FORMAT | OPT_FROM | OPT_TO | OPT_SHRINK | OPT_METADATA,
		&index, objc, objv) != TCL_OK) {
	    return TCL_ERROR;
	}
	if ((options.name == NULL) || (index < objc)) {
	    Tcl_WrongNumArgs(interp, 2, objv, "fileName ?-option value ...?");
	    return TCL_ERROR;
	}
982
983
984
985
986
987
988
989
990

991
992

993

994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008

1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030

1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042

1043
1044
1045
1046








1047
1048
1049
1050
1051
1052
1053
	}
	if (Tcl_SetChannelOption(interp, chan, "-encoding", "binary")
		!= TCL_OK) {
	    Tcl_Close(NULL, chan);
	    return TCL_ERROR;
	}

	if (MatchFileFormat(interp, chan,
		Tcl_GetString(options.name), options.format, &imageFormat,

		&imageWidth, &imageHeight, &oldformat) != TCL_OK) {
	    Tcl_Close(NULL, chan);

	    return TCL_ERROR;

	}

	/*
	 * Check the values given for the -from option.
	 */

	if ((options.fromX > imageWidth) || (options.fromY > imageHeight)
		|| (options.fromX2 > imageWidth)
		|| (options.fromY2 > imageHeight)) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "coordinates for -from option extend outside source image",
		    -1));
	    Tcl_SetErrorCode(interp, "TK", "IMAGE", "PHOTO", "BAD_FROM", NULL);
	    Tcl_Close(NULL, chan);
	    return TCL_ERROR;

	}
	if (!(options.options & OPT_FROM) || (options.fromX2 < 0)) {
	    width = imageWidth - options.fromX;
	    height = imageHeight - options.fromY;
	} else {
	    width = options.fromX2 - options.fromX;
	    height = options.fromY2 - options.fromY;
	}

	/*
	 * If the -shrink option was specified, set the size of the image.
	 */

	if (options.options & OPT_SHRINK) {
	    if (ImgPhotoSetSize(modelPtr, options.toX + width,
		    options.toY + height) != TCL_OK) {
		Tcl_ResetResult(interp);
		Tcl_SetObjResult(interp, Tcl_NewStringObj(
			TK_PHOTO_ALLOC_FAILURE_MESSAGE, -1));
		Tcl_SetErrorCode(interp, "TK", "MALLOC", NULL);
		Tcl_Close(NULL, chan);
		return TCL_ERROR;

	    }
	}

	/*
	 * Call the handler's file read function to read the data into the
	 * image.
	 */

	format = options.format;
	if (oldformat && format) {
	    format = (Tcl_Obj *) Tcl_GetString(format);
	}

	result = imageFormat->fileReadProc(interp, chan,
		Tcl_GetString(options.name),
		format, (Tk_PhotoHandle) modelPtr, options.toX,
		options.toY, width, height, options.fromX, options.fromY);








	if (chan != NULL) {
	    Tcl_Close(NULL, chan);
	}
	return result;
    }

    case PHOTO_REDITHER:







|
|
>
|
<
>
|
>













<
|
>




















<
|
>












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







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
	}
	if (Tcl_SetChannelOption(interp, chan, "-encoding", "binary")
		!= TCL_OK) {
	    Tcl_Close(NULL, chan);
	    return TCL_ERROR;
	}

	if (TkImgPhotoMatchFileFormat(interp, chan,
		Tcl_GetString(options.name), options.format,
		options.metadata, NULL, &imageFormat,
		&imageFormatVersion3, &imageWidth, &imageHeight, &oldformat)

		!= TCL_OK) {
	    result = TCL_ERROR;
	    goto readCleanup;
	}

	/*
	 * Check the values given for the -from option.
	 */

	if ((options.fromX > imageWidth) || (options.fromY > imageHeight)
		|| (options.fromX2 > imageWidth)
		|| (options.fromY2 > imageHeight)) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "coordinates for -from option extend outside source image",
		    -1));
	    Tcl_SetErrorCode(interp, "TK", "IMAGE", "PHOTO", "BAD_FROM", NULL);

	    result = TCL_ERROR;
	    goto readCleanup;
	}
	if (!(options.options & OPT_FROM) || (options.fromX2 < 0)) {
	    width = imageWidth - options.fromX;
	    height = imageHeight - options.fromY;
	} else {
	    width = options.fromX2 - options.fromX;
	    height = options.fromY2 - options.fromY;
	}

	/*
	 * If the -shrink option was specified, set the size of the image.
	 */

	if (options.options & OPT_SHRINK) {
	    if (ImgPhotoSetSize(modelPtr, options.toX + width,
		    options.toY + height) != TCL_OK) {
		Tcl_ResetResult(interp);
		Tcl_SetObjResult(interp, Tcl_NewStringObj(
			TK_PHOTO_ALLOC_FAILURE_MESSAGE, -1));
		Tcl_SetErrorCode(interp, "TK", "MALLOC", NULL);

		result = TCL_ERROR;
		goto readCleanup;
	    }
	}

	/*
	 * Call the handler's file read function to read the data into the
	 * image.
	 */

	format = options.format;
	if (oldformat && format) {
	    format = (Tcl_Obj *) Tcl_GetString(format);
	}
	if (imageFormat != NULL) {
	    result = imageFormat->fileReadProc(interp, chan,
		    Tcl_GetString(options.name),
		    format, (Tk_PhotoHandle) modelPtr, options.toX,
		    options.toY, width, height, options.fromX, options.fromY);
	} else {
	    result = imageFormatVersion3->fileReadProc(interp, chan,
		    Tcl_GetString(options.name),
		    format, options.metadata, (Tk_PhotoHandle) modelPtr,
		    options.toX, options.toY, width, height, options.fromX,
		    options.fromY, NULL);
	}
readCleanup:
	if (chan != NULL) {
	    Tcl_Close(NULL, chan);
	}
	return result;
    }

    case PHOTO_REDITHER:
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
	}
	Tcl_Panic("unexpected fallthrough");
    }

    case PHOTO_WRITE: {
	char *data;
	const char *fmtString;
	Tcl_Obj *format;
	int usedExt;

	/*
	 * Prevent file system access in safe interpreters.
	 */

	if (Tcl_IsSafe(interp)) {







|







1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
	}
	Tcl_Panic("unexpected fallthrough");
    }

    case PHOTO_WRITE: {
	char *data;
	const char *fmtString;
	Tcl_Obj *format, *metadataIn;
	int usedExt;

	/*
	 * Prevent file system access in safe interpreters.
	 */

	if (Tcl_IsSafe(interp)) {
1291
1292
1293
1294
1295
1296
1297

1298
1299

1300
1301
1302
1303
1304
1305
1306
	 * photo write command - first parse and check any options given.
	 */

	index = 2;
	memset(&options, 0, sizeof(options));
	options.name = NULL;
	options.format = NULL;

	if (ParseSubcommandOptions(&options, interp,
		OPT_FORMAT | OPT_FROM | OPT_GRAYSCALE | OPT_BACKGROUND,

		&index, objc, objv) != TCL_OK) {
	    return TCL_ERROR;
	}
	if ((options.name == NULL) || (index < objc)) {
	    Tcl_WrongNumArgs(interp, 2, objv, "fileName ?-option value ...?");
	    return TCL_ERROR;
	}







>

|
>







1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
	 * photo write command - first parse and check any options given.
	 */

	index = 2;
	memset(&options, 0, sizeof(options));
	options.name = NULL;
	options.format = NULL;
	options.metadata = NULL;
	if (ParseSubcommandOptions(&options, interp,
		OPT_FORMAT | OPT_FROM | OPT_GRAYSCALE | OPT_BACKGROUND
		| OPT_METADATA,
		&index, objc, objv) != TCL_OK) {
	    return TCL_ERROR;
	}
	if ((options.name == NULL) || (index < objc)) {
	    Tcl_WrongNumArgs(interp, 2, objv, "fileName ?-option value ...?");
	    return TCL_ERROR;
	}
1328
1329
1330
1331
1332
1333
1334











1335
1336
1337
1338
1339
1340
1341

1342
1343
1344
1345
1346
1347
1348
	    fmtString = GetExtension(Tcl_GetString(options.name));
	    usedExt = (fmtString != NULL);
	} else {
	    fmtString = Tcl_GetString(options.format);
	    usedExt = 0;
	}












	/*
	 * Search for an appropriate image file format handler, and give an
	 * error if none is found.
	 */

	matched = 0;
    redoFormatLookup:

	for (imageFormat = tsdPtr->formatList; imageFormat != NULL;
		imageFormat = imageFormat->nextPtr) {
	    if ((fmtString == NULL)
		    || (strncasecmp(fmtString, imageFormat->name,
			    strlen(imageFormat->name)) == 0)) {
		matched = 1;
		if (imageFormat->fileWriteProc != NULL) {







>
>
>
>
>
>
>
>
>
>
>







>







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
	    fmtString = GetExtension(Tcl_GetString(options.name));
	    usedExt = (fmtString != NULL);
	} else {
	    fmtString = Tcl_GetString(options.format);
	    usedExt = 0;
	}

	
	/*
	 * Use argument metadata if specified, otherwise the model metadata
	 */
	
	if (NULL != options.metadata) {
	    metadataIn = options.metadata;
	} else {
	    metadataIn = modelPtr->metadata;
	}

	/*
	 * Search for an appropriate image file format handler, and give an
	 * error if none is found.
	 */

	matched = 0;
    redoFormatLookup:
	imageFormatVersion3 = NULL;
	for (imageFormat = tsdPtr->formatList; imageFormat != NULL;
		imageFormat = imageFormat->nextPtr) {
	    if ((fmtString == NULL)
		    || (strncasecmp(fmtString, imageFormat->name,
			    strlen(imageFormat->name)) == 0)) {
		matched = 1;
		if (imageFormat->fileWriteProc != NULL) {
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
		    matched = 1;
		    if (imageFormat->fileWriteProc != NULL) {
			break;
		    }
		}
	    }
	}















#endif
	if (usedExt && !matched) {
	    /*
	     * If we didn't find one and we're using file extensions as the
	     * basis for the guessing, go back and look again without
	     * prejudice. Supports old broken code.
	     */

	    usedExt = 0;
	    fmtString = NULL;
	    goto redoFormatLookup;
	}
	if (imageFormat == NULL) {
	    if (fmtString == NULL) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj(
			"no available image file format has file writing"
			" capability", -1));
	    } else if (!matched) {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf(
			"image file format \"%s\" is unknown", fmtString));







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












|







1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
		    matched = 1;
		    if (imageFormat->fileWriteProc != NULL) {
			break;
		    }
		}
	    }
	}
	if (imageFormat == NULL) {
	    oldformat = 0;
	    for (imageFormatVersion3 = tsdPtr->formatListVersion3;
		    imageFormatVersion3 != NULL;
		    imageFormatVersion3 = imageFormatVersion3->nextPtr) {
		if ((fmtString == NULL)
			|| (strncasecmp(fmtString, imageFormatVersion3->name,
				strlen(imageFormatVersion3->name)) == 0)) {
		    matched = 1;
		    if (imageFormatVersion3->fileWriteProc != NULL) {
			break;
		    }
		}
	    }
	}
#endif
	if (usedExt && !matched) {
	    /*
	     * If we didn't find one and we're using file extensions as the
	     * basis for the guessing, go back and look again without
	     * prejudice. Supports old broken code.
	     */

	    usedExt = 0;
	    fmtString = NULL;
	    goto redoFormatLookup;
	}
	if (imageFormat == NULL && imageFormatVersion3 == NULL) {
	    if (fmtString == NULL) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj(
			"no available image file format has file writing"
			" capability", -1));
	    } else if (!matched) {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf(
			"image file format \"%s\" is unknown", fmtString));
1400
1401
1402
1403
1404
1405
1406

1407
1408





1409
1410
1411
1412
1413
1414
1415
	 */

	data = ImgGetPhoto(modelPtr, &block, &options);
	format = options.format;
	if (oldformat && format) {
	    format = (Tcl_Obj *) Tcl_GetString(options.format);
	}

	result = imageFormat->fileWriteProc(interp,
		Tcl_GetString(options.name), format, &block);





	if (options.background) {
	    Tk_FreeColor(options.background);
	}
	if (data) {
	    ckfree(data);
	}
	return result;







>
|
|
>
>
>
>
>







1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
	 */

	data = ImgGetPhoto(modelPtr, &block, &options);
	format = options.format;
	if (oldformat && format) {
	    format = (Tcl_Obj *) Tcl_GetString(options.format);
	}
	if (imageFormat != NULL) {
	    result = imageFormat->fileWriteProc(interp,
		    Tcl_GetString(options.name), format, &block);
	} else {
	    result = imageFormatVersion3->fileWriteProc(interp,
		    Tcl_GetString(options.name), format, metadataIn,
		    &block);
	}
	if (options.background) {
	    Tk_FreeColor(options.background);
	}
	if (data) {
	    ckfree(data);
	}
	return result;
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
/*
 *----------------------------------------------------------------------
 *
 * ParseSubcommandOptions --
 *
 *	This function is invoked to process one of the options which may be
 *	specified for the photo image subcommands, namely, -from, -to, -zoom,
 *	-subsample, -format, -shrink, -compositingrule, -alpha, -boolean and
 *	-withalpha.
 *	Parsing starts at the index in *optIndexPtr and stops at the end of
 *	objv[] or at the first value that does not belong to an option.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:







|
|







1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
/*
 *----------------------------------------------------------------------
 *
 * ParseSubcommandOptions --
 *
 *	This function is invoked to process one of the options which may be
 *	specified for the photo image subcommands, namely, -from, -to, -zoom,
 *	-subsample, -format, -shrink, -compositingrule, -alpha, -boolean,
 *	-withalpha and -metadata.
 *	Parsing starts at the index in *optIndexPtr and stops at the end of
 *	objv[] or at the first value that does not belong to an option.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
1572
1573
1574
1575
1576
1577
1578











1579
1580
1581
1582
1583
1584
1585
	     */

	    if (index + 1 >= objc) {
		goto oneValueRequired;
	    }
	    *optIndexPtr = ++index;
	    optPtr->format = objv[index];











	} else if (bit == OPT_COMPOSITE) {
	    /*
	     * The -compositingrule option takes a single value from a
	     * well-known set.
	     */

	    if (index + 1 >= objc) {







>
>
>
>
>
>
>
>
>
>
>







1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
	     */

	    if (index + 1 >= objc) {
		goto oneValueRequired;
	    }
	    *optIndexPtr = ++index;
	    optPtr->format = objv[index];
	} else if (bit == OPT_METADATA) {
	    /*
	    * The -metadata option takes a single dict value. Note that
	    * parsing this is outside the scope of this function.
	    */

	    if (index + 1 >= objc) {
		goto oneValueRequired;
	    }
	    *optIndexPtr = ++index;
	    optPtr->metadata = objv[index];
	} else if (bit == OPT_COMPOSITE) {
	    /*
	     * The -compositingrule option takes a single value from a
	     * well-known set.
	     */

	    if (index + 1 >= objc) {
1768
1769
1770
1771
1772
1773
1774
1775

1776
1777
1778
1779
1780
1781

1782
1783
1784
1785
1786
1787
1788
    int objc,			/* Number of entries in objv. */
    Tcl_Obj *const objv[],	/* Pairs of configuration options for image. */
    int flags)			/* Flags to pass to Tk_ConfigureWidget, such
				 * as TK_CONFIG_ARGV_ONLY. */
{
    PhotoInstance *instancePtr;
    const char *oldFileString, *oldPaletteString;
    Tcl_Obj *oldData, *data = NULL, *oldFormat, *format = NULL;

    Tcl_Obj *tempdata, *tempformat;
    TkSizeT length;
    int i, j, result, imageWidth, imageHeight, oldformat;
    double oldGamma;
    Tcl_Channel chan;
    Tk_PhotoImageFormat *imageFormat;

    const char **args;

    args = (const char **)ckalloc((objc + 1) * sizeof(char *));
    for (i = 0, j = 0; i < objc; i++,j++) {
	args[j] = TkGetStringFromObj(objv[i], &length);
	if ((length > 1) && (args[j][0] == '-')) {
	    if ((args[j][1] == 'd') &&







|
>






>







1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
    int objc,			/* Number of entries in objv. */
    Tcl_Obj *const objv[],	/* Pairs of configuration options for image. */
    int flags)			/* Flags to pass to Tk_ConfigureWidget, such
				 * as TK_CONFIG_ARGV_ONLY. */
{
    PhotoInstance *instancePtr;
    const char *oldFileString, *oldPaletteString;
    Tcl_Obj *oldData, *data = NULL, *oldFormat, *format = NULL,
	    *metadataInObj = NULL, *metadataOutObj = NULL;
    Tcl_Obj *tempdata, *tempformat;
    TkSizeT length;
    int i, j, result, imageWidth, imageHeight, oldformat;
    double oldGamma;
    Tcl_Channel chan;
    Tk_PhotoImageFormat *imageFormat;
    Tk_PhotoImageFormatVersion3 *imageFormatVersion3;
    const char **args;

    args = (const char **)ckalloc((objc + 1) * sizeof(char *));
    for (i = 0, j = 0; i < objc; i++,j++) {
	args[j] = TkGetStringFromObj(objv[i], &length);
	if ((length > 1) && (args[j][0] == '-')) {
	    if ((args[j][1] == 'd') &&
1806
1807
1808
1809
1810
1811
1812













1813
1814
1815
1816
1817
1818
1819
		} else {
		    ckfree(args);
		    Tcl_SetObjResult(interp, Tcl_NewStringObj(
			    "value for \"-format\" missing", -1));
		    Tcl_SetErrorCode(interp, "TK", "IMAGE", "PHOTO",
			    "MISSING_VALUE", NULL);
		    return TCL_ERROR;













		}
	    }
	}
    }

    /*
     * Save the current values for fileString and dataString, so we can tell







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







1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
		} else {
		    ckfree(args);
		    Tcl_SetObjResult(interp, Tcl_NewStringObj(
			    "value for \"-format\" missing", -1));
		    Tcl_SetErrorCode(interp, "TK", "IMAGE", "PHOTO",
			    "MISSING_VALUE", NULL);
		    return TCL_ERROR;
		}
	    } else if ((args[j][1] == 'm') &&
		!strncmp(args[j], "-metadata", length)) {
		if (++i < objc) {
		    metadataInObj = objv[i];
		    j--;
		} else {
		    ckfree(args);
		    Tcl_SetObjResult(interp, Tcl_NewStringObj(
			"value for \"-metadata\" missing", -1));
		    Tcl_SetErrorCode(interp, "TK", "IMAGE", "PHOTO",
			"MISSING_VALUE", NULL);
		    return TCL_ERROR;
		}
	    }
	}
    }

    /*
     * Save the current values for fileString and dataString, so we can tell
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
	    j, args, (char *) modelPtr, flags) != TCL_OK) {
	ckfree(args);
	goto errorExit;
    }
    ckfree(args);

    /*
     * Regard the empty string for -file, -data or -format as the null value.
     */

    if ((modelPtr->fileString != NULL) && (modelPtr->fileString[0] == 0)) {
	ckfree(modelPtr->fileString);
	modelPtr->fileString = NULL;
    }
    if (data) {







|







2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
	    j, args, (char *) modelPtr, flags) != TCL_OK) {
	ckfree(args);
	goto errorExit;
    }
    ckfree(args);

    /*
     * Regard the empty string for -file, -data, -format or -metadata as the null value.
     */

    if ((modelPtr->fileString != NULL) && (modelPtr->fileString[0] == 0)) {
	ckfree(modelPtr->fileString);
	modelPtr->fileString = NULL;
    }
    if (data) {
1888
1889
1890
1891
1892
1893
1894


























1895
1896
1897
1898
1899
1900
1901
	    format = NULL;
	}
	if (modelPtr->format) {
	    Tcl_DecrRefCount(modelPtr->format);
	}
	modelPtr->format = format;
    }


























    /*
     * Set the image to the user-requested size, if any, and make sure storage
     * is correctly allocated for this image.
     */

    if (ImgPhotoSetSize(modelPtr, modelPtr->width,
	    modelPtr->height) != TCL_OK) {







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







2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
	    format = NULL;
	}
	if (modelPtr->format) {
	    Tcl_DecrRefCount(modelPtr->format);
	}
	modelPtr->format = format;
    }
    if (metadataInObj) {
	/*
	 * make -metadata a dict.
	 * Take also empty metadatas as this may be a sign to replace
	 * existing metadata.
	 */
	int dictSize;

	if (TCL_OK != Tcl_DictObjSize(interp,metadataInObj, &dictSize)) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "value for \"-metadata\" not a dict", -1));
	    Tcl_SetErrorCode(interp, "TK", "IMAGE", "PHOTO",
		    "UNRECOGNIZED_DATA", NULL);
	    return TCL_ERROR;
	}

	if (dictSize > 0) {
	    Tcl_IncrRefCount(metadataInObj);
	} else {
	    metadataInObj = NULL;
	}
	if (modelPtr->metadata) {
	    Tcl_DecrRefCount(modelPtr->metadata);
	}
	modelPtr->metadata = metadataInObj;
    }
    /*
     * Set the image to the user-requested size, if any, and make sure storage
     * is correctly allocated for this image.
     */

    if (ImgPhotoSetSize(modelPtr, modelPtr->width,
	    modelPtr->height) != TCL_OK) {
1909
1910
1911
1912
1913
1914
1915

1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933







1934
1935
1936
1937
1938
1939
1940

1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957

1958
1959

1960








1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973







1974

1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992

1993
1994
1995
1996
1997

1998







1999
2000
2001











































2002
2003
2004
2005
2006
2007
2008
     * Read in the image from the file or string if the user has specified the
     * -file or -data option.
     */

    if ((modelPtr->fileString != NULL)
	    && ((modelPtr->fileString != oldFileString)
	    || (modelPtr->format != oldFormat))) {

	/*
	 * Prevent file system access in a safe interpreter.
	 */

	if (Tcl_IsSafe(interp)) {
	    Tcl_ResetResult(interp);
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "can't get image from a file in a safe interpreter",
		    -1));
	    Tcl_SetErrorCode(interp, "TK", "SAFE", "PHOTO_FILE", NULL);
	    goto errorExit;
	}

	chan = Tcl_OpenFileChannel(interp, modelPtr->fileString, "r", 0);
	if (chan == NULL) {
	    goto errorExit;
	}








	/*
	 * -translation binary also sets -encoding binary
	 */

	if ((Tcl_SetChannelOption(interp, chan,
		"-translation", "binary") != TCL_OK) ||
		(MatchFileFormat(interp, chan, modelPtr->fileString,

			modelPtr->format, &imageFormat, &imageWidth,
			&imageHeight, &oldformat) != TCL_OK)) {
	    Tcl_Close(NULL, chan);
	    goto errorExit;
	}
	result = ImgPhotoSetSize(modelPtr, imageWidth, imageHeight);
	if (result != TCL_OK) {
	    Tcl_Close(NULL, chan);
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    TK_PHOTO_ALLOC_FAILURE_MESSAGE, -1));
	    Tcl_SetErrorCode(interp, "TK", "MALLOC", NULL);
	    goto errorExit;
	}
	tempformat = modelPtr->format;
	if (oldformat && tempformat) {
	    tempformat = (Tcl_Obj *) Tcl_GetString(tempformat);
	}

	result = imageFormat->fileReadProc(interp, chan,
		modelPtr->fileString, tempformat, (Tk_PhotoHandle) modelPtr,

		0, 0, imageWidth, imageHeight, 0, 0);








	Tcl_Close(NULL, chan);
	if (result != TCL_OK) {
	    goto errorExit;
	}

	Tcl_ResetResult(interp);
	modelPtr->flags |= IMAGE_CHANGED;
    }

    if ((modelPtr->fileString == NULL) && (modelPtr->dataString != NULL)
	    && ((modelPtr->dataString != oldData)
		    || (modelPtr->format != oldFormat))) {








	if (MatchStringFormat(interp, modelPtr->dataString,

		modelPtr->format, &imageFormat, &imageWidth,
		&imageHeight, &oldformat) != TCL_OK) {
	    goto errorExit;
	}
	if (ImgPhotoSetSize(modelPtr, imageWidth, imageHeight) != TCL_OK) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    TK_PHOTO_ALLOC_FAILURE_MESSAGE, -1));
	    Tcl_SetErrorCode(interp, "TK", "MALLOC", NULL);
	    goto errorExit;
	}
	tempformat = modelPtr->format;
	tempdata = modelPtr->dataString;
	if (oldformat) {
	    if (tempformat) {
		tempformat = (Tcl_Obj *) Tcl_GetString(tempformat);
	    }
	    tempdata = (Tcl_Obj *) Tcl_GetString(tempdata);
	}

	if (imageFormat->stringReadProc(interp, tempdata, tempformat,
		(Tk_PhotoHandle) modelPtr, 0, 0, imageWidth, imageHeight,
		0, 0) != TCL_OK) {
	    goto errorExit;
	}









	Tcl_ResetResult(interp);
	modelPtr->flags |= IMAGE_CHANGED;
    }












































    /*
     * Enforce a reasonable value for gamma.
     */

    if (modelPtr->gamma <= 0) {
	modelPtr->gamma = 1.0;







>


















>
>
>
>
>
>
>






|
>
|
|















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













>
>
>
>
>
>
>
|
>
|

















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



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







2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
     * Read in the image from the file or string if the user has specified the
     * -file or -data option.
     */

    if ((modelPtr->fileString != NULL)
	    && ((modelPtr->fileString != oldFileString)
	    || (modelPtr->format != oldFormat))) {

	/*
	 * Prevent file system access in a safe interpreter.
	 */

	if (Tcl_IsSafe(interp)) {
	    Tcl_ResetResult(interp);
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "can't get image from a file in a safe interpreter",
		    -1));
	    Tcl_SetErrorCode(interp, "TK", "SAFE", "PHOTO_FILE", NULL);
	    goto errorExit;
	}

	chan = Tcl_OpenFileChannel(interp, modelPtr->fileString, "r", 0);
	if (chan == NULL) {
	    goto errorExit;
	}

	/*
	 * Flag that we want the metadata result dict
	 */

	metadataOutObj = Tcl_NewDictObj();
	Tcl_IncrRefCount(metadataOutObj);

	/*
	 * -translation binary also sets -encoding binary
	 */

	if ((Tcl_SetChannelOption(interp, chan,
		"-translation", "binary") != TCL_OK) ||
		(TkImgPhotoMatchFileFormat(interp, chan, modelPtr->fileString,
			modelPtr->format, modelPtr->metadata, metadataOutObj,
			&imageFormat, &imageFormatVersion3,
			&imageWidth, &imageHeight, &oldformat) != TCL_OK)) {
	    Tcl_Close(NULL, chan);
	    goto errorExit;
	}
	result = ImgPhotoSetSize(modelPtr, imageWidth, imageHeight);
	if (result != TCL_OK) {
	    Tcl_Close(NULL, chan);
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    TK_PHOTO_ALLOC_FAILURE_MESSAGE, -1));
	    Tcl_SetErrorCode(interp, "TK", "MALLOC", NULL);
	    goto errorExit;
	}
	tempformat = modelPtr->format;
	if (oldformat && tempformat) {
	    tempformat = (Tcl_Obj *) Tcl_GetString(tempformat);
	}
	if (imageFormat != NULL) {
	    result = imageFormat->fileReadProc(interp, chan,
		    modelPtr->fileString, tempformat,
		    (Tk_PhotoHandle) modelPtr,
		    0, 0, imageWidth, imageHeight, 0, 0);
	} else {
	    result = imageFormatVersion3->fileReadProc(interp, chan,
		    modelPtr->fileString, tempformat, modelPtr->metadata,
		    (Tk_PhotoHandle) modelPtr,
		    0, 0, imageWidth, imageHeight, 0, 0,
		    metadataOutObj);
	}

	Tcl_Close(NULL, chan);
	if (result != TCL_OK) {
	    goto errorExit;
	}

	Tcl_ResetResult(interp);
	modelPtr->flags |= IMAGE_CHANGED;
    }

    if ((modelPtr->fileString == NULL) && (modelPtr->dataString != NULL)
	    && ((modelPtr->dataString != oldData)
		    || (modelPtr->format != oldFormat))) {

	/*
	 * Flag that we want the metadata result dict
	 */

	metadataOutObj = Tcl_NewDictObj();
	Tcl_IncrRefCount(metadataOutObj);

	if (TkImgMatchStringFormat(interp, modelPtr->dataString,
		modelPtr->format, modelPtr->metadata, metadataOutObj,
		&imageFormat, &imageFormatVersion3, &imageWidth,
		&imageHeight, &oldformat) != TCL_OK) {
	    goto errorExit;
	}
	if (ImgPhotoSetSize(modelPtr, imageWidth, imageHeight) != TCL_OK) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    TK_PHOTO_ALLOC_FAILURE_MESSAGE, -1));
	    Tcl_SetErrorCode(interp, "TK", "MALLOC", NULL);
	    goto errorExit;
	}
	tempformat = modelPtr->format;
	tempdata = modelPtr->dataString;
	if (oldformat) {
	    if (tempformat) {
		tempformat = (Tcl_Obj *) Tcl_GetString(tempformat);
	    }
	    tempdata = (Tcl_Obj *) Tcl_GetString(tempdata);
	}
	if (imageFormat != NULL) {
	    if (imageFormat->stringReadProc(interp, tempdata, tempformat,
		    (Tk_PhotoHandle) modelPtr, 0, 0, imageWidth, imageHeight,
		    0, 0) != TCL_OK) {
		goto errorExit;
	    }
	} else {
	    
	    if (imageFormatVersion3->stringReadProc(interp, tempdata, tempformat,
		    modelPtr->metadata, (Tk_PhotoHandle) modelPtr, 0, 0,
		    imageWidth, imageHeight, 0, 0, metadataOutObj) != TCL_OK) {
		goto errorExit;
	    }
	}

	Tcl_ResetResult(interp);
	modelPtr->flags |= IMAGE_CHANGED;
    }

    /*
     * Merge driver returned metadata and model metadata
     */
    if (metadataOutObj != NULL) {
	int dictSize;
	if (TCL_OK != Tcl_DictObjSize(interp,metadataOutObj, &dictSize)) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "driver metadata not a dict", -1));
	    Tcl_SetErrorCode(interp, "TK", "IMAGE", "PHOTO",
		    "UNRECOGNIZED_DATA", NULL);
	    goto errorExit;
	}
	if (dictSize > 0) {

	    /*
	     * We have driver return metadata
	     */
	    
	    if (modelPtr->metadata == NULL) {
		modelPtr->metadata = metadataOutObj;
		metadataOutObj = NULL;
	    } else {
		Tcl_DictSearch search;
		Tcl_Obj *key, *value;
		int done;

		if (Tcl_IsShared(modelPtr->metadata)) {
		    Tcl_DecrRefCount(modelPtr->metadata);
		    modelPtr->metadata = Tcl_DuplicateObj(modelPtr->metadata);
		    Tcl_IncrRefCount(modelPtr->metadata);
		}

		if (Tcl_DictObjFirst(interp, metadataOutObj, &search, &key,
			&value, &done) != TCL_OK) {
		    goto errorExit;
		}
		for (; !done ; Tcl_DictObjNext(&search, &key, &value, &done)) {
		    Tcl_DictObjPut(interp, modelPtr->metadata, key, value);
		}
	    }
	}
    }

    /*
     * Enforce a reasonable value for gamma.
     */

    if (modelPtr->gamma <= 0) {
	modelPtr->gamma = 1.0;
2034
2035
2036
2037
2038
2039
2040



2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052



2053
2054
2055
2056
2057
2058
2059

    if (oldData != NULL) {
	Tcl_DecrRefCount(oldData);
    }
    if (oldFormat != NULL) {
	Tcl_DecrRefCount(oldFormat);
    }




    ToggleComplexAlphaIfNeeded(modelPtr);

    return TCL_OK;

  errorExit:
    if (oldData != NULL) {
	Tcl_DecrRefCount(oldData);
    }
    if (oldFormat != NULL) {
	Tcl_DecrRefCount(oldFormat);
    }



    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * ToggleComplexAlphaIfNeeded --







>
>
>












>
>
>







2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352

    if (oldData != NULL) {
	Tcl_DecrRefCount(oldData);
    }
    if (oldFormat != NULL) {
	Tcl_DecrRefCount(oldFormat);
    }
    if (metadataOutObj != NULL) {
	Tcl_DecrRefCount(metadataOutObj);
    }

    ToggleComplexAlphaIfNeeded(modelPtr);

    return TCL_OK;

  errorExit:
    if (oldData != NULL) {
	Tcl_DecrRefCount(oldData);
    }
    if (oldFormat != NULL) {
	Tcl_DecrRefCount(oldFormat);
    }
    if (metadataOutObj != NULL) {
	Tcl_DecrRefCount(metadataOutObj);
    }
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * ToggleComplexAlphaIfNeeded --
2143
2144
2145
2146
2147
2148
2149



2150
2151
2152
2153
2154
2155
2156
    }
    if (modelPtr->dataString != NULL) {
	Tcl_DecrRefCount(modelPtr->dataString);
    }
    if (modelPtr->format != NULL) {
	Tcl_DecrRefCount(modelPtr->format);
    }



    Tk_FreeOptions(configSpecs, (char *) modelPtr, NULL, 0);
    ckfree(modelPtr);
}

/*
 *----------------------------------------------------------------------
 *







>
>
>







2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
    }
    if (modelPtr->dataString != NULL) {
	Tcl_DecrRefCount(modelPtr->dataString);
    }
    if (modelPtr->format != NULL) {
	Tcl_DecrRefCount(modelPtr->format);
    }
    if (modelPtr->metadata != NULL) {
	Tcl_DecrRefCount(modelPtr->metadata);
    }
    Tk_FreeOptions(configSpecs, (char *) modelPtr, NULL, 0);
    ckfree(modelPtr);
}

/*
 *----------------------------------------------------------------------
 *
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401


2402
2403
2404





2405
2406
2407
2408
2409
2410
2411
2412

2413
2414
2415
2416
2417
2418
2419

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * MatchFileFormat --
 *
 *	This function is called to find a photo image file format handler
 *	which can parse the image data in the given file. If a user-specified
 *	format string is provided, only handlers whose names match a prefix of
 *	the format string are tried.
 *
 * Results:
 *	A standard TCL return value. If the return value is TCL_OK, a pointer
 *	to the image format record is returned in *imageFormatPtr, and the
 *	width and height of the image are returned in *widthPtr and
 *	*heightPtr.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
MatchFileFormat(
    Tcl_Interp *interp,		/* Interpreter to use for reporting errors. */
    Tcl_Channel chan,		/* The image file, open for reading. */
    const char *fileName,	/* The name of the image file. */
    Tcl_Obj *formatObj,		/* User-specified format string, or NULL. */


    Tk_PhotoImageFormat **imageFormatPtr,
				/* A pointer to the photo image format record
				 * is returned here. */





    int *widthPtr, int *heightPtr,
				/* The dimensions of the image are returned
				 * here. */
    int *oldformat)		/* Returns 1 if the old image API is used. */
{
    int matched = 0;
    int useoldformat = 0;
    Tk_PhotoImageFormat *formatPtr;

    ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
	    Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
    const char *formatString = NULL;

    if (formatObj) {
	formatString = Tcl_GetString(formatObj);
    }







|








|
|
|







|
|




>
>


|
>
>
>
>
>








>







2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * TkImgPhotoMatchFileFormat --
 *
 *	This function is called to find a photo image file format handler
 *	which can parse the image data in the given file. If a user-specified
 *	format string is provided, only handlers whose names match a prefix of
 *	the format string are tried.
 *
 * Results:
 *	A standard TCL return value. If the return value is TCL_OK, a pointer
 *	to the image format record is returned in *imageFormatPtr or
 *	*imageFormatVersion3Ptr, and the width and height of the image are
 *	returned in *widthPtr and *heightPtr.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TkImgPhotoMatchFileFormat(
    Tcl_Interp *interp,		/* Interpreter to use for reporting errors. */
    Tcl_Channel chan,		/* The image file, open for reading. */
    const char *fileName,	/* The name of the image file. */
    Tcl_Obj *formatObj,		/* User-specified format string, or NULL. */
    Tcl_Obj *metadataInObj,	/* User-specified metadata, may be NULL */
    Tcl_Obj *metadataOutObj,	/* metadata to return, may be NULL */
    Tk_PhotoImageFormat **imageFormatPtr,
				/* A pointer to the photo image format record
				 * is returned here. For formatVersion3, this is
				 * set to NULL */
    Tk_PhotoImageFormatVersion3 **imageFormatVersion3Ptr,
				/* A pointer to the photo image formatVersion3
				 * record is returned here. For non
				 * formatVersion3, this is set to NULL*/
    int *widthPtr, int *heightPtr,
				/* The dimensions of the image are returned
				 * here. */
    int *oldformat)		/* Returns 1 if the old image API is used. */
{
    int matched = 0;
    int useoldformat = 0;
    Tk_PhotoImageFormat *formatPtr;
    Tk_PhotoImageFormatVersion3 *formatVersion3Ptr;
    ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
	    Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
    const char *formatString = NULL;

    if (formatObj) {
	formatString = Tcl_GetString(formatObj);
    }
2488
2489
2490
2491
2492
2493
2494




2495









































































2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544


2545
2546
2547





2548
2549
2550
2551
2552
2553
2554

2555
2556
2557
2558
2559
2560
2561
		    break;
		}
	    }
	}
    }
#endif





    if (formatPtr == NULL) {









































































	if ((formatObj != NULL) && !matched) {
	    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		    "image file format \"%s\" is not supported",
		    formatString));
	    Tcl_SetErrorCode(interp, "TK", "LOOKUP", "PHOTO_FORMAT",
		    formatString, NULL);
	} else {
	    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		    "couldn't recognize data in image file \"%s\"",
		    fileName));
	    Tcl_SetErrorCode(interp, "TK", "PHOTO", "IMAGE",
		    "UNRECOGNIZED_DATA", NULL);
	}
	return TCL_ERROR;
    }

    *imageFormatPtr = formatPtr;
    *oldformat = useoldformat;
    (void) Tcl_Seek(chan, Tcl_LongAsWide(0L), SEEK_SET);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * MatchStringFormat --
 *
 *	This function is called to find a photo image file format handler
 *	which can parse the image data in the given string. If a
 *	user-specified format string is provided, only handlers whose names
 *	match a prefix of the format string are tried.
 *
 * Results:
 *	A standard TCL return value. If the return value is TCL_OK, a pointer
 *	to the image format record is returned in *imageFormatPtr, and the
 *	width and height of the image are returned in *widthPtr and
 *	*heightPtr.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
MatchStringFormat(
    Tcl_Interp *interp,		/* Interpreter to use for reporting errors. */
    Tcl_Obj *data,		/* Object containing the image data. */
    Tcl_Obj *formatObj,		/* User-specified format string, or NULL. */


    Tk_PhotoImageFormat **imageFormatPtr,
				/* A pointer to the photo image format record
				 * is returned here. */





    int *widthPtr, int *heightPtr,
				/* The dimensions of the image are returned
				 * here. */
    int *oldformat)		/* Returns 1 if the old image API is used. */
{
    int matched = 0, useoldformat = 0;
    Tk_PhotoImageFormat *formatPtr, *defaultFormatPtr = NULL;

    ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
	    Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
    const char *formatString = NULL;

    if (formatObj) {
	formatString = Tcl_GetString(formatObj);
    }







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





|








|
|
|







|
|



>
>


|
>
>
>
>
>







>







2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890






2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
		    break;
		}
	    }
	}
    }
#endif

    /*
     * For old and not version 3 format, exit now with success
     */

    if (formatPtr != NULL) {
	*imageFormatPtr = formatPtr;
	*imageFormatVersion3Ptr = NULL;
	*oldformat = useoldformat;
	(void) Tcl_Seek(chan, Tcl_LongAsWide(0L), SEEK_SET);
	return TCL_OK;
    }

    /*
     * Scan through the table of file format version 3 handlers to find one
     * which can handle the image.
     */

    for (formatVersion3Ptr = tsdPtr->formatListVersion3;
	    formatVersion3Ptr != NULL;
	    formatVersion3Ptr = formatVersion3Ptr->nextPtr) {
	if (formatObj != NULL) {
	    if (strncasecmp(formatString,
		    formatVersion3Ptr->name, strlen(formatVersion3Ptr->name))
		    != 0) {
		continue;
	    }
	    matched = 1;
	    if (formatVersion3Ptr->fileMatchProc == NULL) {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf(
			"-file option isn't supported for %s images",
			formatString));
		Tcl_SetErrorCode(interp, "TK", "IMAGE", "PHOTO",
			"NOT_FILE_FORMAT", NULL);
		return TCL_ERROR;
	    }
	}
	if (formatVersion3Ptr->fileMatchProc != NULL) {
	    (void) Tcl_Seek(chan, Tcl_LongAsWide(0L), SEEK_SET);

	    if (formatVersion3Ptr->fileMatchProc(interp, chan, fileName,
		    formatObj, metadataInObj, widthPtr, heightPtr,
		    metadataOutObj)) {
		if (*widthPtr < 1) {
		    *widthPtr = 1;
		}
		if (*heightPtr < 1) {
		    *heightPtr = 1;
		}
		*imageFormatVersion3Ptr = formatVersion3Ptr;
		*imageFormatPtr = NULL;
		*oldformat = 0;
		(void) Tcl_Seek(chan, Tcl_LongAsWide(0L), SEEK_SET);
		return TCL_OK;
	    }

	    /*
	     * Clear eventual set keys in the metadata object
	     */

	    if (metadataOutObj != NULL) {
		int dictSize;
		if (TCL_OK != Tcl_DictObjSize(interp,metadataOutObj, &dictSize)
			|| dictSize > 0) {
		    /*
		     * Driver has modified the metadata dict, so clear it
		     */
		    Tcl_DecrRefCount(metadataOutObj);
		    metadataOutObj = Tcl_NewDictObj();
		    Tcl_IncrRefCount(metadataOutObj);
		}
	    }
	}
    }
    
    /*
     * No matching format found
     */

    if ((formatObj != NULL) && !matched) {
        Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		"image file format \"%s\" is not supported",
		formatString));
	Tcl_SetErrorCode(interp, "TK", "LOOKUP", "PHOTO_FORMAT",
		formatString, NULL);
    } else {
	Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		"couldn't recognize data in image file \"%s\"",
		fileName));
	Tcl_SetErrorCode(interp, "TK", "PHOTO", "IMAGE",
		"UNRECOGNIZED_DATA", NULL);
    }
    return TCL_ERROR;






}

/*
 *----------------------------------------------------------------------
 *
 * TkImgMatchStringFormat --
 *
 *	This function is called to find a photo image file format handler
 *	which can parse the image data in the given string. If a
 *	user-specified format string is provided, only handlers whose names
 *	match a prefix of the format string are tried.
 *
 * Results:
 *	A standard TCL return value. If the return value is TCL_OK, a pointer
 *	to the image format record is returned in *imageFormatPtr or
 *	*imageFormatVersion3Ptr, and the width and height of the image are
 *	returned in *widthPtr and *heightPtr.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TkImgMatchStringFormat(
    Tcl_Interp *interp,		/* Interpreter to use for reporting errors. */
    Tcl_Obj *data,		/* Object containing the image data. */
    Tcl_Obj *formatObj,		/* User-specified format string, or NULL. */
    Tcl_Obj *metadataInObj,	/* User-specified metadata, may be NULL */
    Tcl_Obj *metadataOutObj,	/* metadata output dict, may be NULL */
    Tk_PhotoImageFormat **imageFormatPtr,
				/* A pointer to the photo image format record
				 * is returned here. For formatVersion3, this is
				 * set to NULL*/
    Tk_PhotoImageFormatVersion3 **imageFormatVersion3Ptr,
				/* A pointer to the photo image formatVersion3
				 * record is returned here. For non
				 * formatVersion3, this is set to NULL*/
    int *widthPtr, int *heightPtr,
				/* The dimensions of the image are returned
				 * here. */
    int *oldformat)		/* Returns 1 if the old image API is used. */
{
    int matched = 0, useoldformat = 0;
    Tk_PhotoImageFormat *formatPtr, *defaultFormatPtr = NULL;
    Tk_PhotoImageFormatVersion3 *formatVersion3Ptr = NULL;
    ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
	    Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
    const char *formatString = NULL;

    if (formatObj) {
	formatString = Tcl_GetString(formatObj);
    }
2639
2640
2641
2642
2643
2644
2645
















































2646
2647
2648
2649
2650
2651
2652
		break;
	    }
	}
    }
#endif

    if (formatPtr == NULL) {
















































	/*
	 * Try the default format as last resort (only if no -format option
	 * was passed).
	 */

	if ( formatObj == NULL && defaultFormatPtr == NULL) {
	    Tcl_Panic("default image format handler not registered");







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







3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
		break;
	    }
	}
    }
#endif

    if (formatPtr == NULL) {
	useoldformat = 0;
	for (formatVersion3Ptr = tsdPtr->formatListVersion3;
		formatVersion3Ptr != NULL;
		formatVersion3Ptr = formatVersion3Ptr->nextPtr) {
	    if (formatObj != NULL) {
		if (strncasecmp(formatString,
			formatVersion3Ptr->name, strlen(formatVersion3Ptr->name)
			) != 0) {
		    continue;
		}
		matched = 1;
		if (formatVersion3Ptr->stringMatchProc == NULL) {
		    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
			    "-data option isn't supported for %s images",
			    formatString));
		    Tcl_SetErrorCode(interp, "TK", "IMAGE", "PHOTO",
			    "NOT_DATA_FORMAT", NULL);
		    return TCL_ERROR;
		}
	    }
	    if ((formatVersion3Ptr->stringMatchProc != NULL)
		    && (formatVersion3Ptr->stringReadProc != NULL)
		    && formatVersion3Ptr->stringMatchProc(interp, data,
			    formatObj, metadataInObj, widthPtr, heightPtr,
			    metadataOutObj)) {
		break;
	    }

	    /*
	     * Clear eventual set keys in the metadata object
	     */

	    if (metadataOutObj != NULL) {
		int dictSize;
		if (TCL_OK != Tcl_DictObjSize(interp,metadataOutObj, &dictSize)
			|| dictSize > 0) {
		    /*
		     * Driver has modified the metadata dict, so clear it
		     */
		    Tcl_DecrRefCount(metadataOutObj);
		    metadataOutObj = Tcl_NewDictObj();
		    Tcl_IncrRefCount(metadataOutObj);
		}
	    }
	}
    }

    if (formatPtr == NULL && formatVersion3Ptr == NULL) {
	/*
	 * Try the default format as last resort (only if no -format option
	 * was passed).
	 */

	if ( formatObj == NULL && defaultFormatPtr == NULL) {
	    Tcl_Panic("default image format handler not registered");
2679
2680
2681
2682
2683
2684
2685

2686
2687
2688
2689
2690
2691
2692
		        "UNRECOGNIZED_DATA", NULL);
            }
	    return TCL_ERROR;
	}
    }

    *imageFormatPtr = formatPtr;

    *oldformat = useoldformat;

    /*
     * Some stringMatchProc might have left error messages and error codes in
     * interp.	Clear them before return.
     */
    Tcl_ResetResult(interp);







>







3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
		        "UNRECOGNIZED_DATA", NULL);
            }
	    return TCL_ERROR;
	}
    }

    *imageFormatPtr = formatPtr;
    *imageFormatVersion3Ptr = formatVersion3Ptr;
    *oldformat = useoldformat;

    /*
     * Some stringMatchProc might have left error messages and error codes in
     * interp.	Clear them before return.
     */
    Tcl_ResetResult(interp);
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
 *--------------------------------------------------------------
 */

static int
ImgPhotoPostscript(
    ClientData clientData,	/* Handle for the photo image. */
    Tcl_Interp *interp,		/* Interpreter. */
    Tk_Window tkwin,		/* (unused) */
    Tk_PostscriptInfo psInfo,	/* Postscript info. */
    int x, int y,		/* First pixel to output. */
    int width, int height,	/* Width and height of area. */
    int prepass)		/* (unused) */
{
    Tk_PhotoImageBlock block;
    (void)tkwin;
    (void)prepass;

    Tk_PhotoGetImage(clientData, &block);
    block.pixelPtr += y * block.pitch + x * block.pixelSize;

    return Tk_PostscriptPhoto(interp, &block, psInfo, width, height);
}








|



|


<
<







4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506


4507
4508
4509
4510
4511
4512
4513
 *--------------------------------------------------------------
 */

static int
ImgPhotoPostscript(
    ClientData clientData,	/* Handle for the photo image. */
    Tcl_Interp *interp,		/* Interpreter. */
    TCL_UNUSED(Tk_Window),		/* (unused) */
    Tk_PostscriptInfo psInfo,	/* Postscript info. */
    int x, int y,		/* First pixel to output. */
    int width, int height,	/* Width and height of area. */
    TCL_UNUSED(int))		/* (unused) */
{
    Tk_PhotoImageBlock block;



    Tk_PhotoGetImage(clientData, &block);
    block.pixelPtr += y * block.pitch + x * block.pixelSize;

    return Tk_PostscriptPhoto(interp, &block, psInfo, width, height);
}


Changes to generic/tkImgPhoto.h.

162
163
164
165
166
167
168


169
170
171
172
173
174
175
    Tk_Uid palette;		/* User-specified default palette for
				 * instances of this image. */
    double gamma;		/* Display gamma value to correct for. */
    char *fileString;		/* Name of file to read into image. */
    Tcl_Obj *dataString;	/* Object to use as contents of image. */
    Tcl_Obj *format;		/* User-specified format of data in image file
				 * or string value. */


    unsigned char *pix32;	/* Local storage for 32-bit image. */
    int ditherX, ditherY;	/* Location of first incorrectly dithered
				 * pixel in image. */
    TkRegion validRegion;	/* Tk region indicating which parts of the
				 * image have valid image data. */
    PhotoInstance *instancePtr;	/* First in the list of instances associated
				 * with this model. */







>
>







162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
    Tk_Uid palette;		/* User-specified default palette for
				 * instances of this image. */
    double gamma;		/* Display gamma value to correct for. */
    char *fileString;		/* Name of file to read into image. */
    Tcl_Obj *dataString;	/* Object to use as contents of image. */
    Tcl_Obj *format;		/* User-specified format of data in image file
				 * or string value. */
    Tcl_Obj *metadata;		/* User-specified metadata dict or read from
				 * image file */
    unsigned char *pix32;	/* Local storage for 32-bit image. */
    int ditherX, ditherY;	/* Location of first incorrectly dithered
				 * pixel in image. */
    TkRegion validRegion;	/* Tk region indicating which parts of the
				 * image have valid image data. */
    PhotoInstance *instancePtr;	/* First in the list of instances associated
				 * with this model. */
260
261
262
263
264
265
266















267
268
269
270
271
272
273
274
MODULE_SCOPE void	TkImgPhotoDisplay(ClientData clientData,
			    Display *display, Drawable drawable,
			    int imageX, int imageY, int width, int height,
			    int drawableX, int drawableY);
MODULE_SCOPE void	TkImgPhotoFree(ClientData clientData,
			    Display *display);
MODULE_SCOPE void	TkImgResetDither(PhotoInstance *instancePtr);
















/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 4
 * fill-column: 78
 * End:
 */







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








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
MODULE_SCOPE void	TkImgPhotoDisplay(ClientData clientData,
			    Display *display, Drawable drawable,
			    int imageX, int imageY, int width, int height,
			    int drawableX, int drawableY);
MODULE_SCOPE void	TkImgPhotoFree(ClientData clientData,
			    Display *display);
MODULE_SCOPE void	TkImgResetDither(PhotoInstance *instancePtr);

MODULE_SCOPE int	TkImgPhotoMatchFileFormat(Tcl_Interp *interp, Tcl_Channel chan,
			    const char *fileName, Tcl_Obj *formatString,
			    Tcl_Obj *metadataInObj,
			    Tcl_Obj *metadataOutObj,
			    Tk_PhotoImageFormat **imageFormatPtr,
			    Tk_PhotoImageFormatVersion3 **imageFormatVersion3Ptr,
			    int *widthPtr, int *heightPtr, int *oldformat);
MODULE_SCOPE int	TkImgMatchStringFormat(Tcl_Interp *interp, Tcl_Obj *data,
			    Tcl_Obj *formatString,
			    Tcl_Obj *metadataInObj,
			    Tcl_Obj *metadataOutObj,
			    Tk_PhotoImageFormat **imageFormatPtr,
			    Tk_PhotoImageFormatVersion3 **imageFormatVersion3Ptr,
			    int *widthPtr, int *heightPtr, int *oldformat);

/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 4
 * fill-column: 78
 * End:
 */

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 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 and the tcl extension files from
 * https://github.com/auriocus/tksvg
 *
 */

#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 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 and the tcl extension files from
 * https://github.com/auriocus/tksvg
 *
 */

#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;
}

















































































































































































Changes to generic/tkInt.h.

1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
/*
 * Miscellaneous variables shared among Tk modules but not exported to the
 * outside world:
 */

MODULE_SCOPE const Tk_SmoothMethod tkBezierSmoothMethod;
MODULE_SCOPE Tk_ImageType	tkBitmapImageType;
MODULE_SCOPE Tk_PhotoImageFormat tkImgFmtGIF;
MODULE_SCOPE void		(*tkHandleEventProc) (XEvent* eventPtr);
MODULE_SCOPE Tk_PhotoImageFormat tkImgFmtDefault;
MODULE_SCOPE Tk_PhotoImageFormat tkImgFmtPNG;
MODULE_SCOPE Tk_PhotoImageFormat tkImgFmtPPM;
MODULE_SCOPE Tk_PhotoImageFormat tkImgFmtSVGnano;
MODULE_SCOPE TkMainInfo		*tkMainWindowList;
MODULE_SCOPE Tk_ImageType	tkPhotoImageType;
MODULE_SCOPE Tcl_HashTable	tkPredefBitmapTable;

MODULE_SCOPE const char *const tkWebColors[20];







|


|







1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
/*
 * Miscellaneous variables shared among Tk modules but not exported to the
 * outside world:
 */

MODULE_SCOPE const Tk_SmoothMethod tkBezierSmoothMethod;
MODULE_SCOPE Tk_ImageType	tkBitmapImageType;
MODULE_SCOPE Tk_PhotoImageFormatVersion3 tkImgFmtGIF;
MODULE_SCOPE void		(*tkHandleEventProc) (XEvent* eventPtr);
MODULE_SCOPE Tk_PhotoImageFormat tkImgFmtDefault;
MODULE_SCOPE Tk_PhotoImageFormatVersion3 tkImgFmtPNG;
MODULE_SCOPE Tk_PhotoImageFormat tkImgFmtPPM;
MODULE_SCOPE Tk_PhotoImageFormat tkImgFmtSVGnano;
MODULE_SCOPE TkMainInfo		*tkMainWindowList;
MODULE_SCOPE Tk_ImageType	tkPhotoImageType;
MODULE_SCOPE Tcl_HashTable	tkPredefBitmapTable;

MODULE_SCOPE const char *const tkWebColors[20];

Changes to generic/tkStubInit.c.

1321
1322
1323
1324
1325
1326
1327

1328
1329
1330
1331
1332
1333
1334
    Tk_CreateOldPhotoImageFormat, /* 273 */
    Tk_AlwaysShowSelection, /* 274 */
    Tk_GetButtonMask, /* 275 */
    Tk_GetDoublePixelsFromObj, /* 276 */
    Tk_NewWindowObj, /* 277 */
    Tk_SendVirtualEvent, /* 278 */
    Tk_FontGetDescription, /* 279 */

};

/* !END!: Do not edit above this line. */


#ifdef __CYGWIN__
void *Tk_GetHINSTANCE(void)







>







1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
    Tk_CreateOldPhotoImageFormat, /* 273 */
    Tk_AlwaysShowSelection, /* 274 */
    Tk_GetButtonMask, /* 275 */
    Tk_GetDoublePixelsFromObj, /* 276 */
    Tk_NewWindowObj, /* 277 */
    Tk_SendVirtualEvent, /* 278 */
    Tk_FontGetDescription, /* 279 */
    Tk_CreatePhotoImageFormatVersion3, /* 280 */
};

/* !END!: Do not edit above this line. */


#ifdef __CYGWIN__
void *Tk_GetHINSTANCE(void)

Changes to generic/tkWindow.c.

330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
	Tk_CreateImageType(&tkBitmapImageType);
	Tk_CreateImageType(&tkPhotoImageType);

	/*
	 * Create built-in photo image formats.
	 */

        Tk_CreatePhotoImageFormat(&tkImgFmtDefault);
	Tk_CreatePhotoImageFormat(&tkImgFmtGIF);
	Tk_CreatePhotoImageFormat(&tkImgFmtPNG);
	Tk_CreatePhotoImageFormat(&tkImgFmtPPM);
	Tk_CreatePhotoImageFormat(&tkImgFmtSVGnano);
    }

    if ((parent != NULL) && (screenName != NULL) && (screenName[0] == '\0')) {
	dispPtr = ((TkWindow *) parent)->dispPtr;
	screenId = Tk_ScreenNumber(parent);







|
|
|







330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
	Tk_CreateImageType(&tkBitmapImageType);
	Tk_CreateImageType(&tkPhotoImageType);

	/*
	 * Create built-in photo image formats.
	 */

	Tk_CreatePhotoImageFormat(&tkImgFmtDefault);
	Tk_CreatePhotoImageFormatVersion3(&tkImgFmtGIF);
	Tk_CreatePhotoImageFormatVersion3(&tkImgFmtPNG);
	Tk_CreatePhotoImageFormat(&tkImgFmtPPM);
	Tk_CreatePhotoImageFormat(&tkImgFmtSVGnano);
    }

    if ((parent != NULL) && (screenName != NULL) && (screenName[0] == '\0')) {
	dispPtr = ((TkWindow *) parent)->dispPtr;
	screenId = Tk_ScreenNumber(parent);

Changes to tests/earth.gif.

cannot compute difference between binary files

Changes to tests/image.test.

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35


test image-1.1 {Tk_ImageCmd procedure, "create" option} -body {
    image
} -returnCodes error -result {wrong # args: should be "image option ?args?"}
test image-1.2 {Tk_ImageCmd procedure, "create" option} -body {
    image gorp
} -returnCodes error -result {bad option "gorp": must be create, delete, height, inuse, names, type, types, or width}
test image-1.3 {Tk_ImageCmd procedure, "create" option} -body {
    image create
} -returnCodes error -result {wrong # args: should be "image create type ?name? ?-option value ...?"}
test image-1.4 {Tk_ImageCmd procedure, "create" option} -body {
    image c bad_type
} -returnCodes error -result {image type "bad_type" doesn't exist}
test image-1.5 {Tk_ImageCmd procedure, "create" option} -constraints {







|







21
22
23
24
25
26
27
28
29
30
31
32
33
34
35


test image-1.1 {Tk_ImageCmd procedure, "create" option} -body {
    image
} -returnCodes error -result {wrong # args: should be "image option ?args?"}
test image-1.2 {Tk_ImageCmd procedure, "create" option} -body {
    image gorp
} -returnCodes error -result {bad option "gorp": must be create, delete, height, inuse, metadata, names, type, types, or width}
test image-1.3 {Tk_ImageCmd procedure, "create" option} -body {
    image create
} -returnCodes error -result {wrong # args: should be "image create type ?name? ?-option value ...?"}
test image-1.4 {Tk_ImageCmd procedure, "create" option} -body {
    image c bad_type
} -returnCodes error -result {image type "bad_type" doesn't exist}
test image-1.5 {Tk_ImageCmd procedure, "create" option} -constraints {
636
637
638
639
640
641
642




























643
644
645
646
647
648
649
650
651
652
653
    lappend x [imageNames]
    image create photo foo -width 20 -height 20
    lappend x [.c bbox i1] [imageNames]
} -cleanup {
    .c delete all
    imageCleanup
} -result {10 10 20 20 foo {} {10 10 30 30} foo}





























destroy .c
imageFinish

# cleanup
cleanupTests
return

# Local variables:
# mode: tcl
# End:







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











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
    lappend x [imageNames]
    image create photo foo -width 20 -height 20
    lappend x [.c bbox i1] [imageNames]
} -cleanup {
    .c delete all
    imageCleanup
} -result {10 10 20 20 foo {} {10 10 30 30} foo}

# Tests 16.x: Basic usage of "image metadata".
# Format specific "image metadata" tests are in the corresponding test files.

test image-16.1 {Tk_ImageCmd procedure, "metadata" option} -body {
    image metadata
} -returnCodes error -result {wrong # args: should be "image metadata ?-file name? ?-data string?"}

test image-16.2 {Tk_ImageCmd procedure, "metadata" option} -body {
    image metadata -gorp
} -returnCodes error -result {wrong # args: should be "image metadata ?-file name? ?-data string?"}

test image-16.3 {Tk_ImageCmd procedure, "metadata" option} -body {
    image metadata -file
} -returnCodes error -result {wrong # args: should be "image metadata ?-file name? ?-data string?"}

test image-16.4 {Tk_ImageCmd procedure, "metadata" option} -body {
    image metadata -data
} -returnCodes error -result {wrong # args: should be "image metadata ?-file name? ?-data string?"}

test image-16.5 {Tk_ImageCmd procedure, "metadata" No image file} -setup {
    imageCleanup
} -body {
    image metadata -file all.tcl
} -cleanup {
    imageCleanup
} -result {}


destroy .c
imageFinish

# cleanup
cleanupTests
return

# Local variables:
# mode: tcl
# End:

Changes to tests/imgBmap.test.

495
496
497
498
499
500
501
502
503
504
505
506
507


















508
509
510
511
512
513
514
    image create bitmap i2 -file foo.bm -maskfile foo2.bm
    rename i2 newi2
    set x [list [info command i2] [info command new*] [newi2 cget -file]]
    image delete i2
    lappend x [info command new*]
} -result {{} newi2 foo.bm {}}


test imageBmap-12.1 {ImgBmapCmdDeletedProc procedure} -body {
    image create bitmap i2 -file foo.bm -maskfile foo2.bm
    rename i2 {}
    list [lsearch -exact [imageNames] i2] [catch {i2 foo} msg] $msg
} -result {-1 1 {invalid command name "i2"}}



















removeFile foo.bm
removeFile foo2.bm
imageFinish

# cleanup
cleanupTests







<





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







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
    image create bitmap i2 -file foo.bm -maskfile foo2.bm
    rename i2 newi2
    set x [list [info command i2] [info command new*] [newi2 cget -file]]
    image delete i2
    lappend x [info command new*]
} -result {{} newi2 foo.bm {}}


test imageBmap-12.1 {ImgBmapCmdDeletedProc procedure} -body {
    image create bitmap i2 -file foo.bm -maskfile foo2.bm
    rename i2 {}
    list [lsearch -exact [imageNames] i2] [catch {i2 foo} msg] $msg
} -result {-1 1 {invalid command name "i2"}}

# Tests 13.x: Use "image metadata" with XBM image files and image data.

test imageBmp-13.1 {image metadata -file} -setup {
    imageCleanup
} -body {
    image metadata -file face.xbm
} -cleanup {
    imageCleanup
} -result {format xbm width 108 height 144}

test imageBmp-13.2 {image metadata -data} -setup {
    imageCleanup
} -body {
    image metadata -data $data1
} -cleanup {
    imageCleanup
} -result {format xbm width 16 height 16}

removeFile foo.bm
removeFile foo2.bm
imageFinish

# cleanup
cleanupTests

Changes to tests/imgPNG.test.

1052
1053
1054
1055
1056
1057
1058



1059
1060
1061
1062
1063
1064
1065
1066
PmSgZc0hPNhvYAruYN27V8n2gtXV8fOShnq5O9t+492kG9n2LQv65KWAaWAMUDPhEaG0oIFyOMgkhy
YOaz2HKRVHc4lqQbf3LMisUrWjrl9XhhBCkwnWnNLiFDVCParR5BeeRJE47aungOASE1gueu+OTh76
0dt3Gzx47dvzRUnHNQ8Cf2yQZE7mg+XtslqVWi5XocjlDu7K0pgS+dfbs2V8tFotPlUqlr+ZyuXNO+
duFtaSrZF3pfCpiGjN2imToJJ39m6BjG1XZRwrkAI8YUKSZWlEZQDAIrNArHnyvpXtmM/B7wJeAbwO
fBcxKuQMrzfLdBoz29fX9led5v6u1XnBJW7vnr/YlrXEoNo22LRYOYlxZ1S6rkOfDcLvPAY/hGmWC7
H68uFI+x0oSPg2MAN/L5/M/vtqSED/T5cMu9J4Wf7HMGsB/4TEv/DFwe3Y/NPN57VXh+5BWApwFLlh
r661tV1eju/ne8YJrkWtES0tmRe2VOviv2j2aBp5nHihiRaz/A4oCnsAsje/+AAAAAElFTkSuQmCC"



    }

# $encoded(basn0g08), $encoded(basn2c08), $encoded(basn3p08), $encoded(basn6a08)
test imgPNG-1.1 {reading basic images; grayscale} -setup {
    catch {rename foo ""}
} -body {
    image create photo foo -data $encoded(basn0g08)
    list [image width foo] [image height foo]







>
>
>
|







1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
PmSgZc0hPNhvYAruYN27V8n2gtXV8fOShnq5O9t+492kG9n2LQv65KWAaWAMUDPhEaG0oIFyOMgkhy
YOaz2HKRVHc4lqQbf3LMisUrWjrl9XhhBCkwnWnNLiFDVCParR5BeeRJE47aungOASE1gueu+OTh76
0dt3Gzx47dvzRUnHNQ8Cf2yQZE7mg+XtslqVWi5XocjlDu7K0pgS+dfbs2V8tFotPlUqlr+ZyuXNO+
duFtaSrZF3pfCpiGjN2imToJJ39m6BjG1XZRwrkAI8YUKSZWlEZQDAIrNArHnyvpXtmM/B7wJeAbwO
fBcxKuQMrzfLdBoz29fX9led5v6u1XnBJW7vnr/YlrXEoNo22LRYOYlxZ1S6rkOfDcLvPAY/hGmWC7
H68uFI+x0oSPg2MAN/L5/M/vtqSED/T5cMu9J4Wf7HMGsB/4TEv/DFwe3Y/NPN57VXh+5BWApwFLlh
r661tV1eju/ne8YJrkWtES0tmRe2VOviv2j2aBp5nHihiRaz/A4oCnsAsje/+AAAAAElFTkSuQmCC"
    dpi100aspect2
"iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAACXBIWXMAAA9hAAAewgEw8YEEAAAA
FklEQVR4nGP4+vXrP11lJgYGhj9xSQAzOwXsETZ69QAAAABJRU5ErkJggg=="
	}

# $encoded(basn0g08), $encoded(basn2c08), $encoded(basn3p08), $encoded(basn6a08)
test imgPNG-1.1 {reading basic images; grayscale} -setup {
    catch {rename foo ""}
} -body {
    image create photo foo -data $encoded(basn0g08)
    list [image width foo] [image height foo]
1110
1111
1112
1113
1114
1115
1116
1117






1118


































































1119
1120
1121
1122
1123
1124
1125
1126
1127
    # the image contains an unknown chunk iDOT
    # since the name of this chunk starts with a lowercase letter,
    # it's an ancillary chunk that shall not trigger an error
    catch {set i [image create photo -file $fileName]}
} -cleanup {
    image delete $i
} -result 0







}


































































namespace delete png
imageFinish
cleanupTests
return

# Local Variables:
# mode: tcl
# fill-column: 78
# End:







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









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
    # the image contains an unknown chunk iDOT
    # since the name of this chunk starts with a lowercase letter,
    # it's an ancillary chunk that shall not trigger an error
    catch {set i [image create photo -file $fileName]}
} -cleanup {
    image delete $i
} -result 0

test imgPNG-4.1 {data image with metadata} -body {
    image create photo i1 -data $encoded(dpi100aspect2)
    i1 cget -metadata
} -cleanup {
    image delete i1
} -result {DPI 99.9998 aspect 2.0}

test imgPNG-4.2 {file image with metadata} -setup {
    set path [file join [configure -tmpdir] test.png]
    set h [open $path "WRONLY BINARY CREAT"]
    puts -nonewline $h [binary decode base64 $encoded(dpi100aspect2)]
    close $h
} -body {
    image create photo i1 -file $path
    i1 cget -metadata
} -cleanup {
    image delete i1
    file delete $path
} -result {DPI 99.9998 aspect 2.0}

test imgPNG-4.3 {data output with metadata} -setup {
    image create photo i1 -data $encoded(dpi100aspect2)
} -body {
    set imgData [i1 data -format png]
    image delete i1
    image create photo i1 -data $imgData
    i1 cget -metadata
} -cleanup {
    image delete i1
} -result {DPI 99.9998 aspect 2.0}

test imgPNG-4.4 {file output with metadata} -setup {
    image create photo i1 -data $encoded(dpi100aspect2)
    set path [file join [configure -tmpdir] test.png]
} -body {
    i1 write $path -format png
    image delete i1
    image create photo i1 -file $path
    i1 cget -metadata
} -cleanup {
    image delete i1
    file delete $path
} -result {DPI 99.9998 aspect 2.0}

# Tests 5.x: Use "image metadata" with PNG image files and image data.

# Note, that extracting addtional metadata like resolution is not
# yet implemented for PNG images.

test imgPNG-5.1 {image metadata -file} -setup {
    imageCleanup
    set path [file join [configure -tmpdir] test.png]
    set h [open $path "WRONLY BINARY CREAT"]
    puts -nonewline $h [binary decode base64 $encoded(dpi100aspect2)]
    close $h
} -body {
    image metadata -file $path
} -cleanup {
    file delete $path
    imageCleanup
} -result {format png width 2 height 2}

test imgPNG-5.2 {image metadata -data} -setup {
    imageCleanup
} -body {
    image metadata -data $encoded(dpi100aspect2)
} -cleanup {
    imageCleanup
} -result {format png width 2 height 2}

}


namespace delete png
imageFinish
cleanupTests
return

# Local Variables:
# mode: tcl
# fill-column: 78
# End:

Changes to tests/imgPPM.test.

222
223
224
225
226
227
228



















229
230
231
232
233
234
235
    image create photo ppm
} -body {
    ppm put "P6\n5 4\n150\n012345678901234567890123456789012345678901234567890123456789"
    list [image width ppm] [image height ppm]
} -cleanup {
    image delete ppm
} -result {5 4}




















imageFinish

# cleanup
catch {file delete test.ppm}
cleanupTests
return







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







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
    image create photo ppm
} -body {
    ppm put "P6\n5 4\n150\n012345678901234567890123456789012345678901234567890123456789"
    list [image width ppm] [image height ppm]
} -cleanup {
    image delete ppm
} -result {5 4}

# Tests 6.x: Use "image metadata" with PPM image files and image data.

test imgPPM-6.1 {image metadata -file} -setup {
    imageCleanup
} -body {
    image metadata -file teapot.ppm
} -cleanup {
    imageCleanup
} -result {format ppm width 256 height 256}

test imgPPM-6.2 {image metadata -data} -setup {
    imageCleanup
} -body {
    image metadata -data "P6\n5 4\n150\n012345678901234567890123456789012345678901234567890123456789"
} -cleanup {
    imageCleanup
} -result {format ppm width 5 height 4}


imageFinish

# cleanup
catch {file delete test.ppm}
cleanupTests
return

Changes to tests/imgPhoto.test.

53
54
55
56
57
58
59


60
61
62
63
64
65
66
# ImgPostscriptPhoto                    no tests
# Tk_PhotoPutBlock_NoComposite          no tests, probably none needed
# Tk_PhotoPutZoomedBlock_NoComposite    no tests, probably none needed
# Tk_PhotoExpand_Panic                  no tests, probably none needed
# Tk_PhotoPutBlock_Panic                no tests, probably none needed
# Tk_PhotoPutZoomedBlock_Panic          no tests, probably none needed
# Tk_PhotoSetSize_Panic                 no tests, probably none needed


#--------------------------------------------------------------------------
#

#
# Some tests are not specific to a function in tkImgPhoto.c. They are:
#








>
>







53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# ImgPostscriptPhoto                    no tests
# Tk_PhotoPutBlock_NoComposite          no tests, probably none needed
# Tk_PhotoPutZoomedBlock_NoComposite    no tests, probably none needed
# Tk_PhotoExpand_Panic                  no tests, probably none needed
# Tk_PhotoPutBlock_Panic                no tests, probably none needed
# Tk_PhotoPutZoomedBlock_Panic          no tests, probably none needed
# Tk_PhotoSetSize_Panic                 no tests, probably none needed
# Tk_PhotoGetMetadata:                  imgPhoto-19.*
# Tk_PhotoSetMetadata:                  imgPhoto-20.*
#--------------------------------------------------------------------------
#

#
# Some tests are not specific to a function in tkImgPhoto.c. They are:
#

190
191
192
193
194
195
196



197
198
199
200
201
202
203
    image create photo photo1
} -body {
    photo1 put {{blue green}}
    photo1 get 1 0 -withalpha
} -cleanup {
    imageCleanup
} -result {0 128 0 255}




test imgPhoto-2.1 {ImgPhotoCreate procedure} -setup {
    imageCleanup
} -body {
    catch {image create photo -blah blah}
    imageNames
} -result {}







>
>
>







192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
    image create photo photo1
} -body {
    photo1 put {{blue green}}
    photo1 get 1 0 -withalpha
} -cleanup {
    imageCleanup
} -result {0 128 0 255}
test imgPhoto-1.14 {options for photo images - error case} -body {
    image create photo photo1 -metadata
} -returnCodes error -result {value for "-metadata" missing}

test imgPhoto-2.1 {ImgPhotoCreate procedure} -setup {
    imageCleanup
} -body {
    catch {image create photo -blah blah}
    imageNames
} -result {}
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
} -result {25 30}
test imgPhoto-4.6 {ImgPhotoCmd procedure: configure option} -setup {
    image create photo photo1
} -body {
    llength [photo1 configure]
} -cleanup {
    image delete photo1
} -result 7
test imgPhoto-4.7 {ImgPhotoCmd procedure: configure option} -setup {
    image create photo photo1
} -body {
    photo1 conf -palette 3/4/2
    photo1 configure -palette
} -cleanup {
    image delete photo1







|







330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
} -result {25 30}
test imgPhoto-4.6 {ImgPhotoCmd procedure: configure option} -setup {
    image create photo photo1
} -body {
    llength [photo1 configure]
} -cleanup {
    image delete photo1
} -result 8
test imgPhoto-4.7 {ImgPhotoCmd procedure: configure option} -setup {
    image create photo photo1
} -body {
    photo1 conf -palette 3/4/2
    photo1 configure -palette
} -cleanup {
    image delete photo1
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
    hasTeapotPhoto
} -setup {
    image create photo photo1
} -body {
    photo1 read $teapotPhotoFile -zoom 2
} -returnCodes error -cleanup {
    image delete photo1
} -result {unrecognized option "-zoom": must be -format, -from, -shrink, or -to}
test imgPhoto-4.32 {ImgPhotoCmd procedure: read option} -setup {
    image create photo photo1
} -body {
    list [catch {photo1 read bogus} err] [string tolower $err]
} -cleanup {
    image delete photo1
} -result {1 {couldn't open "bogus": no such file or directory}}







|







572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
    hasTeapotPhoto
} -setup {
    image create photo photo1
} -body {
    photo1 read $teapotPhotoFile -zoom 2
} -returnCodes error -cleanup {
    image delete photo1
} -result {unrecognized option "-zoom": must be -format, -from, -metadata, -shrink, or -to}
test imgPhoto-4.32 {ImgPhotoCmd procedure: read option} -setup {
    image create photo photo1
} -body {
    list [catch {photo1 read bogus} err] [string tolower $err]
} -cleanup {
    image delete photo1
} -result {1 {couldn't open "bogus": no such file or directory}}
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
test imgPhoto-4.90 {ImgPhotoCmd put: existing but not allowed opt} -setup {
    image create photo photo1
} -body {
    photo1 put yellow -from 0 0 1 1
} -cleanup {
    imageCleanup
} -returnCodes error -result \
    {unrecognized option "-from": must be -format, or -to}
test imgPhoto-4.91 {ImgPhotoCmd put: invalid option} -setup {
    image create photo photo1
} -body {
    photo1 put {{0 1 2 3}} -bogus x
} -returnCodes error -result \
    {unrecognized option "-bogus": must be -format, or -to}
test imgPhoto-4.92 {ImgPhotocmd put: missing data} -setup {
    image create photo photo1
} -body {
    photo1 put -to 0 0
} -returnCodes error -result \
    {wrong # args: should be "photo1 put data ?-option value ...?"}
test imgPhoto-4.93 {ImgPhotoCmd put: data in ppm format} -constraints {







|





|







1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
test imgPhoto-4.90 {ImgPhotoCmd put: existing but not allowed opt} -setup {
    image create photo photo1
} -body {
    photo1 put yellow -from 0 0 1 1
} -cleanup {
    imageCleanup
} -returnCodes error -result \
    {unrecognized option "-from": must be -format, -metadata, or -to}
test imgPhoto-4.91 {ImgPhotoCmd put: invalid option} -setup {
    image create photo photo1
} -body {
    photo1 put {{0 1 2 3}} -bogus x
} -returnCodes error -result \
    {unrecognized option "-bogus": must be -format, -metadata, or -to}
test imgPhoto-4.92 {ImgPhotocmd put: missing data} -setup {
    image create photo photo1
} -body {
    photo1 put -to 0 0
} -returnCodes error -result \
    {wrong # args: should be "photo1 put data ?-option value ...?"}
test imgPhoto-4.93 {ImgPhotoCmd put: data in ppm format} -constraints {
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
test imgPhoto-4.104 {ImgPhotoCmd data: existing but not accepted opt} -setup {
    image create photo photo1
} -body {
    photo1 data -to
} -cleanup {
    imageCleanup
} -returnCodes error -result \
{unrecognized option "-to": must be -background, -format, -from, or -grayscale}
test imgPhoto-4.105 {ImgPhotoCmd data: invalid option} -setup {
    image create photo photo1
} -body {
    photo1 data -bogus
} -cleanup {
    imageCleanup
} -returnCodes error -result \
{unrecognized option "-bogus": must be -background, -format, -from, or -grayscale}
test imgPhoto-4.106 {ImgPhotoCmd data: extra arg before options} -setup {
    image create photo photo1
} -body {
    photo1 data bogus -grayscale
} -cleanup {
    imageCleanup
} -returnCodes error -result \







|







|







1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
test imgPhoto-4.104 {ImgPhotoCmd data: existing but not accepted opt} -setup {
    image create photo photo1
} -body {
    photo1 data -to
} -cleanup {
    imageCleanup
} -returnCodes error -result \
{unrecognized option "-to": must be -background, -format, -from, -grayscale, or -metadata}
test imgPhoto-4.105 {ImgPhotoCmd data: invalid option} -setup {
    image create photo photo1
} -body {
    photo1 data -bogus
} -cleanup {
    imageCleanup
} -returnCodes error -result \
{unrecognized option "-bogus": must be -background, -format, -from, -grayscale, or -metadata}
test imgPhoto-4.106 {ImgPhotoCmd data: extra arg before options} -setup {
    image create photo photo1
} -body {
    photo1 data bogus -grayscale
} -cleanup {
    imageCleanup
} -returnCodes error -result \
2066
2067
2068
2069
2070
2071
2072











































































































































































































































































































































































































































































2073
2074
2075
2076
2077
2078
2079
test imgPhoto-20.12 {Valid GIF (file)} -setup {
    set fileName [file join [file dirname [info script]] red.gif]
} -body {
    image create photo gif1 -file $fileName
} -cleanup {
    catch {image delete gif1}
} -result gif1












































































































































































































































































































































































































































































catch {rename foreachPixel {}}
catch {rename checkImgTrans {}}
catch {rename checkImgTransLoop {}}
imageFinish

# cleanup







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







2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
test imgPhoto-20.12 {Valid GIF (file)} -setup {
    set fileName [file join [file dirname [info script]] red.gif]
} -body {
    image create photo gif1 -file $fileName
} -cleanup {
    catch {image delete gif1}
} -result gif1

# imgPhoto-21.x : Tk_PhotoGetMetadata

test imgPhoto-21.1 {option -metadata, get configure list} -setup {
    image create photo photo1 -metadata {dpi 100}
} -body {
    photo1 configure -metadata
} -cleanup {
    catch {image delete photo1}
} -result {-metadata {} {} {} {dpi 100}}

test imgPhoto-21.2 {option -metadata, get value} -setup {
    image create photo photo1 -metadata {dpi 100}
} -body {
    photo1 cget -metadata
} -cleanup {
    catch {image delete photo1}
} -result {dpi 100}

test imgPhoto-21.3 {option -metadata, get default value} -setup {
    image create photo photo1
} -body {
    photo1 cget -metadata
} -cleanup {
    catch {image delete photo1}
} -result {}

# imgPhoto-22.x : Tk_PhotoSetMetadata

test imgPhoto-22.1 {option -metadata, set value} -setup {
    image create photo photo1
} -body {
    photo1 configure -metadata {dpi 100}
    photo1 cget -metadata
} -cleanup {
    catch {image delete photo1}
} -result {dpi 100}

test imgPhoto-22.2 {option -metadata, change value} -setup {
    image create photo photo1 -metadata {dpi 200}
} -body {
    photo1 configure -metadata {dpi 100}
    photo1 cget -metadata
} -cleanup {
    catch {image delete photo1}
} -result {dpi 100}

test imgPhoto-22.3 {option -metadata, clear value} -setup {
    image create photo photo1 -metadata {dpi 200}
} -body {
    photo1 configure -metadata {}
    photo1 cget -metadata
} -cleanup {
    catch {image delete photo1}
} -result {}

# 23.x GIF images with metadata

# The following gif core data is used by the following data.
# N.B. this is the same image as test imgPhoto-18.10

# size 16x16, global color table size: 8
set gifstart "GIF89a\x10\x00\x10\x00\xc2\x07\x00"
# color table
append gifstart "\x00\x00\x00\x33\x33\xff\xff\x33\x33\xff\x33\xff\x33\xff\x33\x33\xff\xff\xff\xff\x33\xff\xff\xff"
# Graphic control extension: Transparent color index: 7 (not needed here)
# append gifdata "\x21\xf9\x04\x01\x0a\x00\x07\x00"
# Image descriptor: 16x16, no local color table
set gifdata "\x2c\x00\x00\x00\x00\x10\x00\x10\x00\x00"
# Image data
append gifdata "\x03\x21\x78\xba\xdc\x2d\x30\x42\x77\xa4\x15\xef\xda\xa5\xb5\xea\xd7\x07\x4a\xe2\x38\x55\xe6\x99\xaa\x6b\x69\x72\x2f\x33\x52\x1d\x65\x37\x09\x00"
set gifend "\x3b"

test imgPhoto-23.1 {GIF comment before image data (-data)} -setup {
    set data $::gifstart
    # Append a comment extension block with data "ABCD"
    append data "\x21\xfe\x04" "ABCD" "\x0"
    # Trailer
    append data $::gifdata $::gifend
} -body {
    image create photo gif1 -data $data
    gif1 cget -metadata
} -cleanup {
    catch {image delete gif1}
} -result {comment ABCD}

test imgPhoto-23.2 {GIF file comment before image data (-file)} -setup {
    set data $::gifstart
    # Append a comment extension block with data "ABCD"
    append data "\x21\xfe\x04" "ABCD" "\x0"
    # Trailer
    append data $::gifdata $::gifend
    set path [file join [configure -tmpdir] test.gif]
    set h [open $path "WRONLY BINARY CREAT"]
    puts -nonewline $h $data
    close $h
} -body {
    image create photo gif1 -file $path
    gif1 cget -metadata
} -cleanup {
    catch {image delete gif1}
    file delete $path
} -result {comment ABCD}

test imgPhoto-23.3 {GIF comment after image data (-data)} -setup {
    set data $::gifstart
    append data $::gifdata
    # Append a comment extension block with data "ABCD"
    append data "\x21\xfe\x04" "ABCD" "\x0"
    # Trailer
    append data $::gifend
} -body {
    image create photo gif1 -data $data
    gif1 cget -metadata
} -cleanup {
    catch {image delete gif1}
} -result {comment ABCD}

test imgPhoto-23.4 {GIF comment after image data (-file)} -setup {
    set data $::gifstart
    append data $::gifdata
    # Append a comment extension block with data "ABCD"
    append data "\x21\xfe\x04" "ABCD" "\x0"
    # Trailer
    append data $::gifend
    set path [file join [configure -tmpdir] test.gif]
    set h [open $path "WRONLY BINARY CREAT"]
    puts $h $data
    close $h
} -body {
    image create photo gif1 -file $path
    gif1 cget -metadata
} -cleanup {
    catch {image delete gif1}
    file delete $path
} -result {comment ABCD}

test imgPhoto-23.5 {Two GIF comment blocks (-data)} -setup {
    set data $::gifstart
    # Append a comment extension block with data "1234"
    append data "\x21\xfe\x04" "1234" "\x0"
    append data $::gifdata
    # Append a comment extension block with data "ABCD"
    append data "\x21\xfe\x04" "ABCD" "\x0"
    # Trailer
    append data $::gifend
} -body {
    image create photo gif1 -data $data
    gif1 cget -metadata
} -cleanup {
    catch {image delete gif1}
} -result {comment ABCD}

test imgPhoto-23.6 {Two GIF comment blocks (-file)} -setup {
    set data $::gifstart
    # Append a comment extension block with data "1234"
    append data "\x21\xfe\x04" "1234" "\x0"
    append data $::gifdata
    # Append a comment extension block with data "ABCD"
    append data "\x21\xfe\x04" "ABCD" "\x0"
    # Trailer
    append data $::gifend
    set path [file join [configure -tmpdir] test.gif]
    set h [open $path "WRONLY BINARY CREAT"]
    puts $h $data
    close $h
} -body {
    image create photo gif1 -file $path
    gif1 cget -metadata
} -cleanup {
    catch {image delete gif1}
    file delete $path
} -result {comment ABCD}

test imgPhoto-23.7 {create: test if shared metadata object is not preserved\
	(-data)}\
-setup {
    set data $::gifstart
    # Append a comment extension block with data "ABCD"
    append data "\x21\xfe\x04" "ABCD" "\x0"
    # Trailer
    append data $::gifdata $::gifend
} -body {
    set metadataDict [dict create A 1]
    set metadataDict2 $metadataDict
    image create photo gif1 -data $data -metadata $metadataDict
    list [dict get [gif1 cget -metadata]] $metadataDict $metadataDict2
} -cleanup {
    catch {image delete gif1}
} -result {{A 1 comment ABCD} {A 1} {A 1}}

test imgPhoto-23.8 {create: test if shared metadata object is not preserved\
	(-file)}\
-setup {
    set data $::gifstart
    # Append a comment extension block with data "ABCD"
    append data "\x21\xfe\x04" "ABCD" "\x0"
    # Trailer
    append data $::gifdata $::gifend

    set path [file join [configure -tmpdir] test.gif]
    set h [open $path "WRONLY BINARY CREAT"]
    puts $h $data
    close $h
} -body {
    set metadataDict [dict create A 1]
    set metadataDict2 $metadataDict
    image create photo gif1 -file $path -metadata $metadataDict
    list [dict get [gif1 cget -metadata]] $metadataDict $metadataDict2
} -cleanup {
    catch {image delete gif1}
    file delete $path
} -result {{A 1 comment ABCD} {A 1} {A 1}}

test imgPhoto-23.9 {configure: test if shared metadata object is not\
	preserved (empty image, -data)}\
-setup {
    set data $::gifstart
    # Append a comment extension block with data "ABCD"
    append data "\x21\xfe\x04" "ABCD" "\x0"
    # Trailer
    append data $::gifdata $::gifend
} -body {
    image create photo gif1
    set metadataDict [dict create A 1]
    set metadataDict2 $metadataDict
    gif1 configure -data $data -format gif -metadata $metadataDict
    list [dict get [gif1 cget -metadata]] $metadataDict $metadataDict2
} -cleanup {
    catch {image delete gif1}
} -result {{A 1 comment ABCD} {A 1} {A 1}}

test imgPhoto-23.10 {configure: test if shared metadata object is not preserved\
	(empty image, -file)}\
-setup {
    set data $::gifstart
    # Append a comment extension block with data "ABCD"
    append data "\x21\xfe\x04" "ABCD" "\x0"
    # Trailer
    append data $::gifdata $::gifend

    set path [file join [configure -tmpdir] test.gif]
    set h [open $path "WRONLY BINARY CREAT"]
    puts $h $data
    close $h
} -body {
    image create photo gif1
    set metadataDict [dict create A 1]
    set metadataDict2 $metadataDict
    gif1 configure -file $path -format gif -metadata $metadataDict
    list [dict get [gif1 cget -metadata]] $metadataDict $metadataDict2
} -cleanup {
    catch {image delete gif1}
    file delete $path
} -result {{A 1 comment ABCD} {A 1} {A 1}}

test imgPhoto-23.11 {configure: test if shared metadata object is not preserved\
	(metadata replace, -data}\
-setup {
    set data $::gifstart
    # Append a comment extension block with data "ABCD"
    append data "\x21\xfe\x04" "ABCD" "\x0"
    # Trailer
    append data $::gifdata $::gifend
} -body {
    image create photo gif1 -data "$::gifstart$::gifdata$::gifend"
    set metadataDict [dict create A 1]
    set metadataDict2 $metadataDict
    gif1 configure -data $data -format gif -metadata $metadataDict
    list [dict get [gif1 cget -metadata]] $metadataDict $metadataDict2
} -cleanup {
    catch {image delete gif1}
} -result {{A 1 comment ABCD} {A 1} {A 1}}

test imgPhoto-23.12 {configure: test if shared metadata object is not preserved\
	(metadata replace, -file}\
-setup {
    set data $::gifstart
    # Append a comment extension block with data "ABCD"
    append data "\x21\xfe\x04" "ABCD" "\x0"
    # Trailer
    append data $::gifdata $::gifend

    set path [file join [configure -tmpdir] test.gif]
    set h [open $path "WRONLY BINARY CREAT"]
    puts $h $data
    close $h
} -body {
    image create photo gif1 -data "$::gifstart$::gifdata$::gifend"
    set metadataDict [dict create A 1]
    set metadataDict2 $metadataDict
    gif1 configure -file $path -format gif -metadata $metadataDict
    list [dict get [gif1 cget -metadata]] $metadataDict $metadataDict2
} -cleanup {
    catch {image delete gif1}
    file delete $path
} -result {{A 1 comment ABCD} {A 1} {A 1}}

test imgPhoto-23.13 {configure: test if shared metadata object is not preserved\
	(-data)}\
-setup {
    set data $::gifstart$::gifdata$::gifend
} -body {
    image create photo gif1 -data $data
    set metadataDict [dict create A 1]
    set metadataDict2 $metadataDict
    set data $::gifstart
    # Append a comment extension block with data "ABCD"
    append data "\x21\xfe\x04" "ABCD" "\x0"
    # Trailer
    append data $::gifdata $::gifend
    gif1 configure -data $data -format gif -metadata $metadataDict
    list [dict get [gif1 cget -metadata]] $metadataDict $metadataDict2
} -cleanup {
    catch {image delete gif1}
} -result {{A 1 comment ABCD} {A 1} {A 1}}

test imgPhoto-23.14 {configure: test if shared metadata object is not preserved\
	(-file)}\
-setup {
    set data $::gifstart
    # Append a comment extension block with data "ABCD"
    append data "\x21\xfe\x04" "ABCD" "\x0"
    # Trailer
    append data $::gifdata $::gifend

    set path [file join [configure -tmpdir] test.gif]
    set h [open $path "WRONLY BINARY CREAT"]
    puts $h $data
    close $h
} -body {
    image create photo gif1 -data "$::gifstart$::gifdata$::gifend"
    set metadataDict [dict create A 1]
    set metadataDict2 $metadataDict
    gif1 configure -file $path -format gif -metadata $metadataDict
    list [dict get [gif1 cget -metadata]] $metadataDict $metadataDict2
} -cleanup {
    catch {image delete gif1}
    file delete $path
} -result {{A 1 comment ABCD} {A 1} {A 1}}

test imgPhoto-23.15 {output data with comment (from -metadata argument)}\
-setup {
    set data $::gifstart$::gifdata$::gifend
} -body {
    image create photo gif1 -data $data
    set gifData [gif1 data -format gif -metadata [dict create comment ABCD]]
} -cleanup {
    catch {image delete gif1}
} -match glob -result {*ABCD*}

test imgPhoto-23.22 {output file with comment (from -metadata argument)}\
-setup {
    set data $::gifstart$::gifdata$::gifend
    set path [file join [configure -tmpdir] test.gif]
} -body {
    image create photo gif1 -data $data
    gif1 write $path -format gif -metadata [dict create comment ABCD]
    image delete gif1
    image create photo gif1 -file $path
    dict get [gif1 cget -metadata] comment
} -cleanup {
    catch {image delete gif1}
    file delete $path
} -result {ABCD}

test imgPhoto-23.16 {output data with comment (from -metadata property)}\
-setup {
    set data $::gifstart$::gifdata$::gifend
} -body {
    image create photo gif1 -data $data
    gif1 configure -metadata [dict create comment ABCD]
    set gifData [gif1 data -format gif]
} -cleanup {
    catch {image delete gif1}
} -match glob -result {*ABCD*}

test imgPhoto-23.17 {output file with comment (from -metadata property)}\
-setup {
    set data $::gifstart$::gifdata$::gifend
    set path [file join [configure -tmpdir] test.gif]
} -body {
    image create photo gif1 -data $data
    gif1 configure -metadata [dict create comment ABCD]
    gif1 write $path -format gif
    image delete gif1
    image create photo gif1 -file $path
    dict get [gif1 cget -metadata] comment
} -cleanup {
    catch {image delete gif1}
    file delete $path
} -result {ABCD}

test imgPhoto-23.18 {configure: empty metadata parameter overwrites image metadata} -setup {
    image create photo gif1 -data $::gifstart$::gifdata$::gifend\
	    -metadata {foo bar}
    set data $::gifstart
    # Append a comment extension block with data "ABCD"
    append data "\x21\xfe\x04" "ABCD" "\x0"
    # Trailer
    append data $::gifdata $::gifend
} -body {
    gif1 configure -data $data -metadata {}
    gif1 cget -metadata
} -cleanup {
    catch {image delete gif1}
} -result {comment ABCD}

test imgPhoto-23.19 {write: empty metadata parameter overwrites image metadata} -setup {
    image create photo gif1 -data $::gifstart$::gifdata$::gifend\
	    -metadata {comment bar}
    set path [file join [configure -tmpdir] test.gif]
} -body {
    gif1 write $path -format gif -metadata {}
    image delete gif1
    image create photo gif1 -file $path
    dict size [gif1 cget -metadata]
} -cleanup {
    catch {image delete gif1}
    file delete $path
} -result {0}

test imgPhoto-23.20 {data: empty metadata parameter overwrites image metadata} -setup {
    image create photo gif1 -data $::gifstart$::gifdata$::gifend\
	    -metadata {comment bar}
} -body {
    set data [gif1 data -format gif -metadata {}]
    image delete gif1
    image create photo gif1 -data $data
    dict size [gif1 cget -metadata]
} -cleanup {
    catch {image delete gif1}
    file delete $path
} -result {0}

# Tests 24.x: Use "image metadata" with GIF image files and image data.

test imgPhoto-24.1 {image metadata -file} -setup {
    imageCleanup
} -body {
    image metadata -file earth.gif
} -cleanup {
    imageCleanup
} -result {format gif width 320 height 200}

# Note, that extracting addtional metadata like "comment" is not
# yet implemented for GIF images.
test imgPhoto-24.2 {image metadata -data} -setup {
    set data $::gifstart
    append data "\x21\xfe\x04" "ABCD" "\x0"
    append data $::gifdata $::gifend
} -body {
    image metadata -data $data
} -cleanup {
    imageCleanup
} -result {format gif width 16 height 16}

unset -nocomplain gifstart gifdata gifend


catch {rename foreachPixel {}}
catch {rename checkImgTrans {}}
catch {rename checkImgTransLoop {}}
imageFinish

# cleanup

Changes to tests/imgSVGnano.test.

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
    foo configure -format "svg -scale 2"
    lappend res [image width foo] [image height foo]
} -cleanup {
    rename foo ""
    unset res
} -result {100 100 200 200}


test imgSVGnano-4.2 {error on file not accessible on reread due to configure} -setup {
    catch {rename foo ""}
    tcltest::makeFile $data(plus) tmpplus.svg
    image create photo foo -file [file join [tcltest::configure -tmpdir] tmpplus.svg]
    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}




































};# end of namespace svgnano

namespace delete svgnano
imageFinish
cleanupTests
return







<











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







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
    foo configure -format "svg -scale 2"
    lappend res [image width foo] [image height foo]
} -cleanup {
    rename foo ""
    unset res
} -result {100 100 200 200}


test imgSVGnano-4.2 {error on file not accessible on reread due to configure} -setup {
    catch {rename foo ""}
    tcltest::makeFile $data(plus) tmpplus.svg
    image create photo foo -file [file join [tcltest::configure -tmpdir] tmpplus.svg]
    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}

# Tests 5.x: Use "image metadata" with SVG image files and image data.

test imgSVGnano-5.1 {image metadata -file} -setup {
    imageCleanup
} -body {
    image metadata -file $data(plusFilePath)
} -cleanup {
    imageCleanup
} -result {format svg width 100 height 100}

test imgSVGnano-5.2 {image metadata -data} -setup {
    imageCleanup
} -body {
    image metadata -data $data(plus)
} -cleanup {
    imageCleanup
} -result {format svg width 100 height 100}

test imgSVGnano-5.3 {image metadata -file} -setup {
    imageCleanup
} -body {
    image metadata -file $data(badFilePath)
} -cleanup {
    imageCleanup
} -result {}

test imgSVGnano-5.4 {image metadata -data} -setup {
    imageCleanup
} -body {
    image metadata -data $data(bad)
} -cleanup {
    imageCleanup
} -result {}


};# end of namespace svgnano

namespace delete svgnano
imageFinish
cleanupTests
return