Debian Codegraph @

pTk/mTk/generic/tkImgPhoto.c

raw symbols SCIP
1 /*
2 * tkImgPhoto.c --
3 *
4 * Implements images of type "photo" for Tk. Photo images are
5 * stored in full color (32 bits per pixel including alpha channel)
6 * and displayed using dithering if necessary.
7 *
8 * Copyright (c) 1994 The Australian National University.
9 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
10 * Copyright (c) 2002 Donal K. Fellows
11 * Copyright (c) 2003 ActiveState Corporation.
12 *
13 * See the file "license.terms" for information on usage and redistribution
14 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
15 *
16 * Author: Paul Mackerras ([email protected]),
17 * Department of Computer Science,
18 * Australian National University.
19 *
20 * RCS: @(#) $Id: tkImgPhoto.c,v 1.36.2.3 2003/11/11 00:05:19 hobbs Exp $
21 */
22
23 #include "Lang.h"
24 #include "tkPort.h"
25 #include "tkInt.h"
26 #include "tclMath.h"
27 #include <ctype.h>
28
29 #ifdef __WIN32__
30 #include "tkWinInt.h"
31 #endif
32
33 /*
34 * Declaration for internal Xlib function used here:
35 */
36 extern int _XInitImageFuncPtrs _ANSI_ARGS_((XImage *image));
37 #include "tkImgPhoto.h"
38 #include <math.h>
39 #include <ctype.h>
40
41
42
43 /*
44 * A signed 8-bit integral type. If chars are unsigned and the compiler
45 * isn't an ANSI one, then we have to use short instead (which wastes
46 * space) to get signed behavior.
47 */
48
49 #if defined(__STDC__) || defined(ANSI_SIGNED_CHAR) || defined(_AIX)
50 typedef signed char schar;
51 #else
52 # ifndef __CHAR_UNSIGNED__
53 typedef char schar;
54 # else
55 typedef short schar;
56 # endif
57 #endif
58
59 /*
60 * An unsigned 32-bit integral type, used for pixel values.
61 * We use int rather than long here to accommodate those systems
62 * where longs are 64 bits.
63 */
64
65 typedef unsigned int pixel;
66
67 /*
68 * The maximum number of pixels to transmit to the server in a
69 * single XPutImage call.
70 */
71
72 #define MAX_PIXELS 65536
73
74 /*
75 * The set of colors required to display a photo image in a window depends on:
76 * - the visual used by the window
77 * - the palette, which specifies how many levels of each primary
78 * color to use, and
79 * - the gamma value for the image.
80 *
81 * Pixel values allocated for specific colors are valid only for the
82 * colormap in which they were allocated. Sets of pixel values
83 * allocated for displaying photos are re-used in other windows if
84 * possible, that is, if the display, colormap, palette and gamma
85 * values match. A hash table is used to locate these sets of pixel
86 * values, using the following data structure as key:
87 */
88
89 typedef struct {
90 Display *display; /* Qualifies the colormap resource ID */
91 Colormap colormap; /* Colormap that the windows are using. */
92 double gamma; /* Gamma exponent value for images. */
93 Tk_Uid palette; /* Specifies how many shades of each primary
94 * we want to allocate. */
95 } ColorTableId;
96
97 /*
98 * For a particular (display, colormap, palette, gamma) combination,
99 * a data structure of the following type is used to store the allocated
100 * pixel values and other information:
101 */
102
103 typedef struct ColorTable {
104 ColorTableId id; /* Information used in selecting this
105 * color table. */
106 int flags; /* See below. */
107 int refCount; /* Number of instances using this map. */
108 int liveRefCount; /* Number of instances which are actually
109 * in use, using this map. */
110 int numColors; /* Number of colors allocated for this map. */
111
112 XVisualInfo visualInfo; /* Information about the visual for windows
113 * using this color table. */
114
115 pixel redValues[256]; /* Maps 8-bit values of red intensity
116 * to a pixel value or index in pixelMap. */
117 pixel greenValues[256]; /* Ditto for green intensity */
118 pixel blueValues[256]; /* Ditto for blue intensity */
119 unsigned long *pixelMap; /* Actual pixel values allocated. */
120
121 unsigned char colorQuant[3][256];
122 /* Maps 8-bit intensities to quantized
123 * intensities. The first index is 0 for
124 * red, 1 for green, 2 for blue. */
125 } ColorTable;
126
127 /*
128 * Bit definitions for the flags field of a ColorTable.
129 * BLACK_AND_WHITE: 1 means only black and white colors are
130 * available.
131 * COLOR_WINDOW: 1 means a full 3-D color cube has been
132 * allocated.
133 * DISPOSE_PENDING: 1 means a call to DisposeColorTable has
134 * been scheduled as an idle handler, but it
135 * hasn't been invoked yet.
136 * MAP_COLORS: 1 means pixel values should be mapped
137 * through pixelMap.
138 */
139 #ifdef COLOR_WINDOW
140 #undef COLOR_WINDOW
141 #endif
142
143 #define BLACK_AND_WHITE 1
144 #define COLOR_WINDOW 2
145 #define DISPOSE_PENDING 4
146 #define MAP_COLORS 8
147
148 /*
149 * Definition of the data associated with each photo image master.
150 */
151
152 typedef struct PhotoMaster {
153 Tk_ImageMaster tkMaster; /* Tk's token for image master. NULL means
154 * the image is being deleted. */
155 Tcl_Interp *interp; /* Interpreter associated with the
156 * application using this image. */
157 Tcl_Command imageCmd; /* Token for image command (used to delete
158 * it when the image goes away). NULL means
159 * the image command has already been
160 * deleted. */
161 int flags; /* Sundry flags, defined below. */
162 int width, height; /* Dimensions of image. */
163 int userWidth, userHeight; /* User-declared image dimensions. */
164 Tk_Uid palette; /* User-specified default palette for
165 * instances of this image. */
166 double gamma; /* Display gamma value to correct for. */
167 Tcl_Obj *fileString; /* Name of file to read into image. */
168 Tcl_Obj *dataString; /* Object to use as contents of image. */
169 Tcl_Obj *format; /* User-specified format of data in image
170 * file or string value. */
171 unsigned char *pix32; /* Local storage for 32-bit image. */
172 int ditherX, ditherY; /* Location of first incorrectly
173 * dithered pixel in image. */
174 TkRegion validRegion; /* Tk region indicating which parts of
175 * the image have valid image data. */
176 struct PhotoInstance *instancePtr;
177 /* First in the list of instances
178 * associated with this master. */
179 } PhotoMaster;
180
181 /*
182 * Bit definitions for the flags field of a PhotoMaster.
183 * COLOR_IMAGE: 1 means that the image has different color
184 * components.
185 * IMAGE_CHANGED: 1 means that the instances of this image
186 * need to be redithered.
187 * COMPLEX_ALPHA: 1 means that the instances of this image
188 * have alpha values that aren't 0 or 255.
189 */
190
191 #define COLOR_IMAGE 1
192 #define IMAGE_CHANGED 2
193 #define COMPLEX_ALPHA 4
194
195 /*
196 * The following data structure represents all of the instances of
197 * a photo image in windows on a given screen that are using the
198 * same colormap.
199 */
200
201 typedef struct PhotoInstance {
202 PhotoMaster *masterPtr; /* Pointer to master for image. */
203 Display *display; /* Display for windows using this instance. */
204 Colormap colormap; /* The image may only be used in windows with
205 * this particular colormap. */
206 struct PhotoInstance *nextPtr;
207 /* Pointer to the next instance in the list
208 * of instances associated with this master. */
209 int refCount; /* Number of instances using this structure. */
210 Tk_Uid palette; /* Palette for these particular instances. */
211 double gamma; /* Gamma value for these instances. */
212 Tk_Uid defaultPalette; /* Default palette to use if a palette
213 * is not specified for the master. */
214 ColorTable *colorTablePtr; /* Pointer to information about colors
215 * allocated for image display in windows
216 * like this one. */
217 Pixmap pixels; /* X pixmap containing dithered image. */
218 int width, height; /* Dimensions of the pixmap. */
219 schar *error; /* Error image, used in dithering. */
220 XImage *imagePtr; /* Image structure for converted pixels. */
221 XVisualInfo visualInfo; /* Information about the visual that these
222 * windows are using. */
223 GC gc; /* Graphics context for writing images
224 * to the pixmap. */
225 } PhotoInstance;
226
227 /*
228 * The following data structure is used to return information
229 * from ParseSubcommandOptions:
230 */
231
232 struct SubcommandOptions {
233 int options; /* Individual bits indicate which
234 * options were specified - see below. */
235 Tcl_Obj *name; /* Name specified without an option. */
236 int fromX, fromY; /* Values specified for -from option. */
237 int fromX2, fromY2; /* Second coordinate pair for -from option. */
238 int toX, toY; /* Values specified for -to option. */
239 int toX2, toY2; /* Second coordinate pair for -to option. */
240 int zoomX, zoomY; /* Values specified for -zoom option. */
241 int subsampleX, subsampleY; /* Values specified for -subsample option. */
242 Tcl_Obj *format; /* Value specified for -format option. */
243 XColor *background; /* Value specified for -background option. */
244 int compositingRule; /* Value specified for -compositingrule opt */
245 };
246
247 /*
248 * Bit definitions for use with ParseSubcommandOptions:
249 * Each bit is set in the allowedOptions parameter on a call to
250 * ParseSubcommandOptions if that option is allowed for the current
251 * photo image subcommand. On return, the bit is set in the options
252 * field of the SubcommandOptions structure if that option was specified.
253 *
254 * OPT_BACKGROUND: Set if -format option allowed/specified.
255 * OPT_COMPOSITE: Set if -compositingrule option allowed/spec'd.
256 * OPT_FORMAT: Set if -format option allowed/specified.
257 * OPT_FROM: Set if -from option allowed/specified.
258 * OPT_GRAYSCALE: Set if -grayscale option allowed/specified.
259 * OPT_SHRINK: Set if -shrink option allowed/specified.
260 * OPT_SUBSAMPLE: Set if -subsample option allowed/spec'd.
261 * OPT_TO: Set if -to option allowed/specified.
262 * OPT_ZOOM: Set if -zoom option allowed/specified.
263 */
264
265 #define OPT_BACKGROUND 1
266 #define OPT_COMPOSITE 2
267 #define OPT_FORMAT 4
268 #define OPT_FROM 8
269 #define OPT_GRAYSCALE 0x10
270 #define OPT_SHRINK 0x20
271 #define OPT_SUBSAMPLE 0x40
272 #define OPT_TO 0x80
273 #define OPT_ZOOM 0x100
274
275 /*
276 * List of option names. The order here must match the order of
277 * declarations of the OPT_* constants above.
278 */
279
280 static char *optionNames[] = {
281 "-background",
282 "-compositingrule",
283 "-format",
284 "-from",
285 "-grayscale",
286 "-shrink",
287 "-subsample",
288 "-to",
289 "-zoom",
290 (char *) NULL
291 };
292
293 /*
294 * Message to generate when an attempt to resize an image fails due
295 * to memory problems.
296 */
297 #define TK_PHOTO_ALLOC_FAILURE_MESSAGE \
298 "not enough free memory for image buffer"
299
300 /*
301 * Functions used in the type record for photo images.
302 */
303
304 static int ImgPhotoCreate _ANSI_ARGS_((Tcl_Interp *interp,
305 char *name, int objc, Tcl_Obj *CONST objv[],
306 Tk_ImageType *typePtr, Tk_ImageMaster master,
307 ClientData *clientDataPtr));
308 static ClientData ImgPhotoGet _ANSI_ARGS_((Tk_Window tkwin,
309 ClientData clientData));
310 static void ImgPhotoDisplay _ANSI_ARGS_((ClientData clientData,
311 Display *display, Drawable drawable,
312 int imageX, int imageY, int width, int height,
313 int drawableX, int drawableY));
314 static void ImgPhotoFree _ANSI_ARGS_((ClientData clientData,
315 Display *display));
316 static void ImgPhotoDelete _ANSI_ARGS_((ClientData clientData));
317 static int ImgPhotoPostscript _ANSI_ARGS_((ClientData clientData,
318 Tcl_Interp *interp, Tk_Window tkwin,
319 Tk_PostscriptInfo psInfo, int x, int y, int width,
320 int height, int prepass));
321
322 /*
323 * The type record itself for photo images:
324 */
325
326 Tk_ImageType tkPhotoImageType = {
327 "photo", /* name */
328 ImgPhotoCreate, /* createProc */
329 ImgPhotoGet, /* getProc */
330 ImgPhotoDisplay, /* displayProc */
331 ImgPhotoFree, /* freeProc */
332 ImgPhotoDelete, /* deleteProc */
333 ImgPhotoPostscript, /* postscriptProc */
334 (Tk_ImageType *) NULL /* nextPtr */
335 };
336
337 typedef struct ThreadSpecificData {
338 Tk_PhotoImageFormat *formatList; /* Pointer to the first in the
339 * list of known photo image formats.*/
340 Tk_PhotoImageFormat *oldFormatList; /* Pointer to the first in the
341 * list of known photo image formats.*/
342 int initialized; /* set to 1 if we've initialized the strucuture */
343 } ThreadSpecificData;
344 static Tcl_ThreadDataKey dataKey;
345
346 /*
347 * Default configuration
348 */
349
350 #define DEF_PHOTO_GAMMA "1"
351 #define DEF_PHOTO_HEIGHT "0"
352 #define DEF_PHOTO_PALETTE ""
353 #define DEF_PHOTO_WIDTH "0"
354
355 /*
356 * Information used for parsing configuration specifications:
357 */
358 static Tk_ConfigSpec configSpecs[] = {
359 {TK_CONFIG_LANGARG, "-data", (char *) NULL, (char *) NULL,
360 (char *) NULL, Tk_Offset(PhotoMaster, dataString), TK_CONFIG_NULL_OK},
361 {TK_CONFIG_LANGARG, "-format", (char *) NULL, (char *) NULL,
362 (char *) NULL, Tk_Offset(PhotoMaster, format), TK_CONFIG_NULL_OK},
363 {TK_CONFIG_LANGARG, "-file", (char *) NULL, (char *) NULL,
364 (char *) NULL, Tk_Offset(PhotoMaster, fileString), TK_CONFIG_NULL_OK},
365 {TK_CONFIG_DOUBLE, "-gamma", "gamma", "Gamma",
366 DEF_PHOTO_GAMMA, Tk_Offset(PhotoMaster, gamma), 0},
367 {TK_CONFIG_INT, "-height", (char *) NULL, (char *) NULL,
368 DEF_PHOTO_HEIGHT, Tk_Offset(PhotoMaster, userHeight), 0},
369 {TK_CONFIG_UID, "-palette", "palette", "Palette",
370 DEF_PHOTO_PALETTE, Tk_Offset(PhotoMaster, palette), 0},
371 {TK_CONFIG_INT, "-width", (char *) NULL, (char *) NULL,
372 DEF_PHOTO_WIDTH, Tk_Offset(PhotoMaster, userWidth), 0},
373 {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL,
374 (char *) NULL, 0, 0}
375 };
376
377 /*
378 * Hash table used to hash from (display, colormap, palette, gamma)
379 * to ColorTable address.
380 */
381
382 static Tcl_HashTable imgPhotoColorHash;
383 static int imgPhotoColorHashInitialized;
384 #define N_COLOR_HASH (sizeof(ColorTableId) / sizeof(int))
385
386 /*
387 * Forward declarations
388 */
389
390 static void PhotoFormatThreadExitProc _ANSI_ARGS_((
391 ClientData clientData));
392 static int ImgPhotoCmd _ANSI_ARGS_((ClientData clientData,
393 Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]));
394 static int ParseSubcommandOptions _ANSI_ARGS_((
395 struct SubcommandOptions *optPtr,
396 Tcl_Interp *interp, int allowedOptions,
397 int *indexPtr, int objc, Tcl_Obj *CONST objv[]));
398 static void ImgPhotoCmdDeletedProc _ANSI_ARGS_((
399 ClientData clientData));
400 static int ImgPhotoConfigureMaster _ANSI_ARGS_((
401 Tcl_Interp *interp, PhotoMaster *masterPtr,
402 int objc, Tcl_Obj *CONST objv[], int flags));
403 static void ImgPhotoConfigureInstance _ANSI_ARGS_((
404 PhotoInstance *instancePtr));
405 static int ToggleComplexAlphaIfNeeded _ANSI_ARGS_((
406 PhotoMaster *mPtr));
407 static void ImgPhotoBlendComplexAlpha _ANSI_ARGS_((
408 XImage *bgImg, PhotoInstance *iPtr,
409 int xOffset, int yOffset, int width, int height));
410 static int ImgPhotoSetSize _ANSI_ARGS_((PhotoMaster *masterPtr,
411 int width, int height));
412 static void ImgPhotoInstanceSetSize _ANSI_ARGS_((
413 PhotoInstance *instancePtr));
414 static int ImgStringWrite _ANSI_ARGS_((Tcl_Interp *interp,
415 Tcl_Obj *formatString,
416 Tk_PhotoImageBlock *blockPtr));
417 static char * ImgGetPhoto _ANSI_ARGS_((PhotoMaster *masterPtr,
418 Tk_PhotoImageBlock *blockPtr,
419 struct SubcommandOptions *optPtr));
420 static int IsValidPalette _ANSI_ARGS_((PhotoInstance *instancePtr,
421 CONST char *palette));
422 static int CountBits _ANSI_ARGS_((pixel mask));
423 static void GetColorTable _ANSI_ARGS_((PhotoInstance *instancePtr));
424 static void FreeColorTable _ANSI_ARGS_((ColorTable *colorPtr,
425 int force));
426 static void AllocateColors _ANSI_ARGS_((ColorTable *colorPtr));
427 static void DisposeColorTable _ANSI_ARGS_((ClientData clientData));
428 static void DisposeInstance _ANSI_ARGS_((ClientData clientData));
429 static int ReclaimColors _ANSI_ARGS_((ColorTableId *id,
430 int numColors));
431 static int MatchFileFormat _ANSI_ARGS_((Tcl_Interp *interp,
432 Tcl_Channel chan, Tcl_Obj *fileName, Tcl_Obj *formatString,
433 Tk_PhotoImageFormat **imageFormatPtr,
434 int *widthPtr, int *heightPtr, int *oldformat));
435 static int MatchStringFormat _ANSI_ARGS_((Tcl_Interp *interp,
436 Tcl_Obj *data, Tcl_Obj *formatString,
437 Tk_PhotoImageFormat **imageFormatPtr,
438 int *widthPtr, int *heightPtr, int *oldformat));
439 static Tcl_ObjCmdProc * PhotoOptionFind _ANSI_ARGS_((Tcl_Interp * interp,
440 Tcl_Obj *obj));
441 static void DitherInstance _ANSI_ARGS_((PhotoInstance *instancePtr,
442 int x, int y, int width, int height));
443 static void PhotoOptionCleanupProc _ANSI_ARGS_((
444 ClientData clientData, Tcl_Interp *interp));
445
446 #undef MIN
447 #define MIN(a, b) ((a) < (b)? (a): (b))
448 #undef MAX
449 #define MAX(a, b) ((a) > (b)? (a): (b))
450
451 /*
452 *----------------------------------------------------------------------
453 *
454 * Tk_CreateOldPhotoImageFormat, Tk_CreatePhotoImageFormat --
455 *
456 * This procedure is invoked by an image file handler to register
457 * a new photo image format and the procedures that handle the
458 * new format. The procedure is typically invoked during
459 * Tcl_AppInit.
460 *
461 * Results:
462 * None.
463 *
464 * Side effects:
465 * The new image file format is entered into a table used in the
466 * photo image "read" and "write" subcommands.
467 *
468 *----------------------------------------------------------------------
469 */
470
471 static void
472 PhotoFormatThreadExitProc(clientData)
473 ClientData clientData; /* not used */
474 {
475 Tk_PhotoImageFormat *freePtr;
476 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
477 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
478
479 while (tsdPtr->oldFormatList != NULL) {
480 freePtr = tsdPtr->oldFormatList;
481 tsdPtr->oldFormatList = tsdPtr->oldFormatList->nextPtr;
482 ckfree((char *) freePtr->name);
483 ckfree((char *) freePtr);
484 }
485 while (tsdPtr->formatList != NULL) {
486 freePtr = tsdPtr->formatList;
487 tsdPtr->formatList = tsdPtr->formatList->nextPtr;
488 ckfree((char *) freePtr->name);
489 ckfree((char *) freePtr);
490 }
491 }
492
493 /*
494 *----------------------------------------------------------------------
495 *
496 * Tk_CreateOldPhotoImageFormat, Tk_CreatePhotoImageFormat --
497 *
498 * This procedure is invoked by an image file handler to register
499 * a new photo image format and the procedures that handle the
500 * new format. The procedure is typically invoked during
501 * Tcl_AppInit.
502 *
503 * Results:
504 * None.
505 *
506 * Side effects:
507 * The new image file format is entered into a table used in the
508 * photo image "read" and "write" subcommands.
509 *
510 *----------------------------------------------------------------------
511 */
512 void
513 Tk_CreateOldPhotoImageFormat(formatPtr)
514 Tk_PhotoImageFormat *formatPtr;
515 /* Structure describing the format. All of
516 * the fields except "nextPtr" must be filled
517 * in by caller. Must not have been passed
518 * to Tk_CreatePhotoImageFormat previously. */
519 {
520 Tk_PhotoImageFormat *copyPtr;
521 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
522 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
523
524 if (!tsdPtr->initialized) {
525 tsdPtr->initialized = 1;
526 Tcl_CreateThreadExitHandler(PhotoFormatThreadExitProc, NULL);
527 }
528 copyPtr = (Tk_PhotoImageFormat *) ckalloc(sizeof(Tk_PhotoImageFormat));
529 *copyPtr = *formatPtr;
530 copyPtr->name = (char *) ckalloc((unsigned) (strlen(formatPtr->name) + 1));
531 strcpy(copyPtr->name, formatPtr->name);
532 copyPtr->nextPtr = tsdPtr->oldFormatList;
533 tsdPtr->oldFormatList = copyPtr;
534 }
535
536 void
537 Tk_CreatePhotoImageFormat(formatPtr)
538 Tk_PhotoImageFormat *formatPtr;
539 /* Structure describing the format. All of
540 * the fields except "nextPtr" must be filled
541 * in by caller. Must not have been passed
542 * to Tk_CreatePhotoImageFormat previously. */
543 {
544 Tk_PhotoImageFormat *copyPtr;
545 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
546 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
547
548 if (!tsdPtr->initialized) {
549 tsdPtr->initialized = 1;
550 Tcl_CreateThreadExitHandler(PhotoFormatThreadExitProc, NULL);
551 }
552 copyPtr = (Tk_PhotoImageFormat *) ckalloc(sizeof(Tk_PhotoImageFormat));
553 *copyPtr = *formatPtr;
554 copyPtr->name = (char *) ckalloc((unsigned) (strlen(formatPtr->name) + 1));
555 strcpy(copyPtr->name, formatPtr->name);
556 if (0 && isupper((unsigned char) *formatPtr->name)) {
557 copyPtr->nextPtr = tsdPtr->oldFormatList;
558 tsdPtr->oldFormatList = copyPtr;
559 } else {
560 copyPtr->nextPtr = tsdPtr->formatList;
561 tsdPtr->formatList = copyPtr;
562 }
563 }
564
565 /*
566 *----------------------------------------------------------------------
567 *
568 * ImgPhotoCreate --
569 *
570 * This procedure is called by the Tk image code to create
571 * a new photo image.
572 *
573 * Results:
574 * A standard Tcl result.
575 *
576 * Side effects:
577 * The data structure for a new photo image is allocated and
578 * initialized.
579 *
580 *----------------------------------------------------------------------
581 */
582
583 static int
584 ImgPhotoCreate(interp, name, objc, objv, typePtr, master, clientDataPtr)
585 Tcl_Interp *interp; /* Interpreter for application containing
586 * image. */
587 char *name; /* Name to use for image. */
588 int objc; /* Number of arguments. */
589 Tcl_Obj *CONST objv[]; /* Argument objects for options (doesn't
590 * include image name or type). */
591 Tk_ImageType *typePtr; /* Pointer to our type record (not used). */
592 Tk_ImageMaster master; /* Token for image, to be used by us in
593 * later callbacks. */
594 ClientData *clientDataPtr; /* Store manager's token for image here;
595 * it will be returned in later callbacks. */
596 {
597 PhotoMaster *masterPtr;
598
599 /*
600 * Allocate and initialize the photo image master record.
601 */
602
603 masterPtr = (PhotoMaster *) ckalloc(sizeof(PhotoMaster));
604 memset((void *) masterPtr, 0, sizeof(PhotoMaster));
605 masterPtr->tkMaster = master;
606 masterPtr->interp = interp;
607 masterPtr->imageCmd = Lang_CreateImage(interp, name, ImgPhotoCmd,
608 (ClientData) masterPtr, ImgPhotoCmdDeletedProc, typePtr);
609 masterPtr->palette = NULL;
610 masterPtr->pix32 = NULL;
611 masterPtr->instancePtr = NULL;
612 masterPtr->validRegion = TkCreateRegion();
613
614
615 /*
616 * Process configuration options given in the image create command.
617 */
618
619
620 if (ImgPhotoConfigureMaster(interp, masterPtr, objc, objv, 0) != TCL_OK) {
621 ImgPhotoDelete((ClientData) masterPtr);
622 return TCL_ERROR;
623 }
624
625 *clientDataPtr = (ClientData) masterPtr;
626 return TCL_OK;
627 }
628
629 /*
630 *----------------------------------------------------------------------
631 *
632 * ImgPhotoCmd --
633 *
634 * This procedure is invoked to process the Tcl command that
635 * corresponds to a photo image. See the user documentation
636 * for details on what it does.
637 *
638 * Results:
639 * A standard Tcl result.
640 *
641 * Side effects:
642 * See the user documentation.
643 *
644 *----------------------------------------------------------------------
645 */
646
647 static int
648 ImgPhotoCmd(clientData, interp, objc, objv)
649 ClientData clientData; /* Information about photo master. */
650 Tcl_Interp *interp; /* Current interpreter. */
651 int objc; /* Number of arguments. */
652 Tcl_Obj *CONST objv[]; /* Argument objects. */
653 {
654 int oldformat = 0;
655 static CONST char *photoOptions[] = {
656 "blank", "cget", "configure", "copy", "data", "get", "put",
657 "read", "redither", "transparency", "write", "formats", (char *) NULL
658 };
659 enum options {
660 PHOTO_BLANK, PHOTO_CGET, PHOTO_CONFIGURE, PHOTO_COPY, PHOTO_DATA,
661 PHOTO_GET, PHOTO_PUT, PHOTO_READ, PHOTO_REDITHER, PHOTO_TRANS,
662 PHOTO_WRITE, PHOTO_FORMATS
663 };
664
665 PhotoMaster *masterPtr = (PhotoMaster *) clientData;
666 int result, index;
667 int x, y, width, height;
668 int dataWidth = 0, dataHeight;
669 struct SubcommandOptions options;
670 int listArgc;
671 Tcl_Obj * *listArgv;
672 Tcl_Obj * *srcArgv;
673 unsigned char *pixelPtr = NULL;
674 Tk_PhotoImageBlock block;
675 Tk_Window tkwin;
676 XColor color;
677 Tk_PhotoImageFormat *imageFormat;
678 int imageWidth, imageHeight;
679 int matched;
680 Tcl_Channel chan;
681 Tk_PhotoHandle srcHandle;
682 size_t length;
683 Tcl_Obj *obj;
684 int c;
685 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
686 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
687
688
689
690 if (objc < 2) {
691 Tcl_WrongNumArgs(interp, 1, objv, "option ?arg arg ...?");
692 return TCL_ERROR;
693 }
694
695 if (Tcl_GetIndexFromObj(interp, objv[1], photoOptions, "option", 0,
696 &index) != TCL_OK) {
697 Tcl_ObjCmdProc *proc;
698 proc = PhotoOptionFind(interp, objv[1]);
699 if (proc == (Tcl_ObjCmdProc *) NULL) {
700 return TCL_ERROR;
701 }
702 return proc(clientData, interp, objc, objv);
703 }
704
705 switch ((enum options) index) {
706 case PHOTO_BLANK:
707 /*
708 * photo blank command - just call Tk_PhotoBlank.
709 */
710
711 if (objc == 2) {
712 Tk_PhotoBlank(masterPtr);
713 return TCL_OK;
714 } else {
715 Tcl_WrongNumArgs(interp, 2, objv, (char *) NULL);
716 return TCL_ERROR;
717 }
718
719 case PHOTO_CGET: {
720 char *arg;
721
722 if (objc != 3) {
723 Tcl_WrongNumArgs(interp, 2, objv, "option");
724 return TCL_ERROR;
725 }
726 arg = Tcl_GetStringFromObj(objv[2], (int *) &length);
727 if (strncmp(arg,"-data", length) == 0) {
728 if (masterPtr->dataString) {
729 Tcl_SetObjResult(interp, masterPtr->dataString);
730 }
731 } else if (strncmp(arg,"-format", length) == 0) {
732 if (masterPtr->format) {
733 Tcl_SetObjResult(interp, masterPtr->format);
734 }
735 } else {
736 Tk_ConfigureValue(interp, Tk_MainWindow(interp), configSpecs,
737 (char *) masterPtr, Tcl_GetString(objv[2]), 0);
738 }
739 return TCL_OK;
740 }
741
742 case PHOTO_CONFIGURE:
743 /*
744 * photo configure command - handle this in the standard way.
745 */
746
747 if (objc == 2) {
748 Tcl_Obj *obj, *subobj;
749 result = Tk_ConfigureInfo(interp, Tk_MainWindow(interp),
750 configSpecs, (char *) masterPtr, (char *) NULL, 0);
751 if (result != TCL_OK) {
752 return result;
753 }
754 subobj = Tcl_NewStringObj("-data {} {} {}", 14);
755 if (masterPtr->dataString) {
756 Tcl_ListObjAppendElement(interp, subobj, masterPtr->dataString);
757 } else {
758 Tcl_ListObjAppendElement(interp, subobj, Tcl_NewStringObj("",0));
759 }
760 Tcl_ListObjAppendElement(interp, Tcl_GetObjResult(interp), subobj);
761 subobj = Tcl_NewStringObj("-format {} {} {}", 16);
762 if (masterPtr->format) {
763 Tcl_ListObjAppendElement(interp, subobj, masterPtr->format);
764 } else {
765 Tcl_ListObjAppendElement(interp, subobj, Tcl_NewStringObj("",0));
766 }
767 Tcl_ListObjAppendElement(interp, Tcl_GetObjResult(interp), subobj);
768 return TCL_OK;
769 }
770 if (objc == 3) {
771 char *arg = Tcl_GetStringFromObj(objv[2], (int *) &length);
772 if (!strncmp(arg, "-data", length)) {
773 Tcl_Obj *subobj = Tcl_NewStringObj("-data {} {} {}", 14);
774 if (masterPtr->dataString) {
775 Tcl_ListObjAppendElement(interp, subobj, masterPtr->dataString);
776 } else {
777 Tcl_ListObjAppendElement(interp, subobj, Tcl_NewStringObj("",0));
778 }
779 Tcl_SetObjResult(interp,subobj);
780 return TCL_OK;
781 } else if (!strncmp(arg, "-format", length)) {
782 Tcl_Obj *subobj = Tcl_NewStringObj("-format {} {} {}", 16);
783 if (masterPtr->format) {
784 Tcl_ListObjAppendElement(interp, subobj, masterPtr->format);
785 } else {
786 Tcl_ListObjAppendElement(interp, subobj, Tcl_NewStringObj("",0));
787 }
788 Tcl_SetObjResult(interp,subobj);
789 return TCL_OK;
790 } else {
791 return Tk_ConfigureInfo(interp, Tk_MainWindow(interp),
792 configSpecs, (char *) masterPtr, arg, 0);
793 }
794 }
795 return ImgPhotoConfigureMaster(interp, masterPtr, objc-2, objv+2,
796 TK_CONFIG_ARGV_ONLY);
797
798 case PHOTO_COPY:
799 /*
800 * photo copy command - first parse options.
801 */
802
803 index = 2;
804 memset((VOID *) &options, 0, sizeof(options));
805 options.zoomX = options.zoomY = 1;
806 options.subsampleX = options.subsampleY = 1;
807 options.name = NULL;
808 options.compositingRule = TK_PHOTO_COMPOSITE_OVERLAY;
809 if (ParseSubcommandOptions(&options, interp,
810 OPT_FROM | OPT_TO | OPT_ZOOM | OPT_SUBSAMPLE | OPT_SHRINK |
811 OPT_COMPOSITE, &index, objc, objv) != TCL_OK) {
812 return TCL_ERROR;
813 }
814 if (options.name == NULL || index < objc) {
815 Tcl_WrongNumArgs(interp, 2, objv,
816 "source-image ?-compositingrule rule? ?-from x1 y1 x2 y2? ?-to x1 y1 x2 y2? ?-zoom x y? ?-subsample x y?");
817 return TCL_ERROR;
818 }
819
820 /*
821 * Look for the source image and get a pointer to its image data.
822 * Check the values given for the -from option.
823 */
824
825 srcHandle = Tk_FindPhoto(interp, Tcl_GetString(options.name));
826 if (srcHandle == NULL) {
827 Tcl_AppendResult(interp, "image \"",
828 Tcl_GetString(options.name), "\" doesn't",
829 " exist or is not a photo image", (char *) NULL);
830 return TCL_ERROR;
831 }
832 Tk_PhotoGetImage(srcHandle, &block);
833 if ((options.fromX2 > block.width) || (options.fromY2 > block.height)
834 || (options.fromX2 > block.width)
835 || (options.fromY2 > block.height)) {
836 Tcl_AppendResult(interp, "coordinates for -from option extend ",
837 "outside source image", (char *) NULL);
838 return TCL_ERROR;
839 }
840
841 /*
842 * Fill in default values for unspecified parameters.
843 */
844
845 if (!(options.options & OPT_FROM) || (options.fromX2 < 0)) {
846 options.fromX2 = block.width;
847 options.fromY2 = block.height;
848 }
849 if (!(options.options & OPT_TO) || (options.toX2 < 0)) {
850 width = options.fromX2 - options.fromX;
851 if (options.subsampleX > 0) {
852 width = (width + options.subsampleX - 1) / options.subsampleX;
853 } else if (options.subsampleX == 0) {
854 width = 0;
855 } else {
856 width = (width - options.subsampleX - 1) / -options.subsampleX;
857 }
858 options.toX2 = options.toX + width * options.zoomX;
859
860 height = options.fromY2 - options.fromY;
861 if (options.subsampleY > 0) {
862 height = (height + options.subsampleY - 1)
863 / options.subsampleY;
864 } else if (options.subsampleY == 0) {
865 height = 0;
866 } else {
867 height = (height - options.subsampleY - 1)
868 / -options.subsampleY;
869 }
870 options.toY2 = options.toY + height * options.zoomY;
871 }
872
873 /*
874 * Set the destination image size if the -shrink option was specified.
875 */
876
877 if (options.options & OPT_SHRINK) {
878 if (ImgPhotoSetSize(masterPtr, options.toX2,
879 options.toY2) != TCL_OK) {
880 Tcl_ResetResult(interp);
881 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
882 TK_PHOTO_ALLOC_FAILURE_MESSAGE, (char *) NULL);
883 return TCL_ERROR;
884 }
885 }
886
887 /*
888 * Copy the image data over using Tk_PhotoPutZoomedBlock.
889 */
890
891 block.pixelPtr += options.fromX * block.pixelSize
892 + options.fromY * block.pitch;
893 block.width = options.fromX2 - options.fromX;
894 block.height = options.fromY2 - options.fromY;
895 Tk_PhotoPutZoomedBlock((Tk_PhotoHandle) masterPtr, &block,
896 options.toX, options.toY, options.toX2 - options.toX,
897 options.toY2 - options.toY, options.zoomX, options.zoomY,
898 options.subsampleX, options.subsampleY,
899 options.compositingRule);
900 return TCL_OK;
901
902 case PHOTO_DATA: {
903 char *data;
904
905 /*
906 * photo data command - first parse and check any options given.
907 */
908 Tk_ImageStringWriteProc *stringWriteProc = NULL;
909
910 index = 2;
911 memset((VOID *) &options, 0, sizeof(options));
912 options.name = NULL;
913 options.format = NULL;
914 options.fromX = 0;
915 options.fromY = 0;
916 if (ParseSubcommandOptions(&options, interp,
917 OPT_FORMAT | OPT_FROM | OPT_GRAYSCALE | OPT_BACKGROUND,
918 &index, objc, objv) != TCL_OK) {
919 return TCL_ERROR;
920 }
921 if ((options.name != NULL) || (index < objc)) {
922 Tcl_WrongNumArgs(interp, 2, objv, "?options?");
923 return TCL_ERROR;
924 }
925 if ((options.fromX > masterPtr->width)
926 || (options.fromY > masterPtr->height)
927 || (options.fromX2 > masterPtr->width)
928 || (options.fromY2 > masterPtr->height)) {
929 Tcl_AppendResult(interp, "coordinates for -from option extend ",
930 "outside image", (char *) NULL);
931 return TCL_ERROR;
932 }
933
934 /*
935 * Fill in default values for unspecified parameters.
936 */
937
938 if (((options.options & OPT_FROM) == 0) || (options.fromX2 < 0)) {
939 options.fromX2 = masterPtr->width;
940 options.fromY2 = masterPtr->height;
941 }
942
943 /*
944 * Search for an appropriate image string format handler.
945 */
946
947 if (options.options & OPT_FORMAT) {
948 for (imageFormat = tsdPtr->formatList; imageFormat != NULL;
949 imageFormat = imageFormat->nextPtr) {
950 if ((strncasecmp(Tcl_GetString(options.format),
951 imageFormat->name, strlen(imageFormat->name)) == 0)) {
952 if (imageFormat->stringWriteProc != NULL) {
953 stringWriteProc = imageFormat->stringWriteProc;
954 break;
955 }
956 }
957 }
958 if (stringWriteProc == NULL) {
959 Tcl_AppendResult(interp, "image string format \"",
960 Tcl_GetString(options.format),
961 "\" is not supported", (char *) NULL);
962 return TCL_ERROR;
963 }
964 } else {
965 stringWriteProc = ImgStringWrite;
966 }
967
968 /*
969 * Call the handler's string write procedure to write out
970 * the image.
971 */
972
973 data = ImgGetPhoto(masterPtr, &block, &options);
974 result = stringWriteProc(interp, options.format, &block);
975 if (options.background) {
976 Tk_FreeColor(options.background);
977 }
978 if (data) {
979 ckfree(data);
980 }
981 return result;
982 }
983 case PHOTO_FORMATS: {
984 Tk_PhotoImageFormat *format = tsdPtr->formatList;
985 for (format = tsdPtr->formatList; format; format = format->nextPtr) {
986 Tcl_ListObjAppendElement(interp, Tcl_GetObjResult(interp), Tcl_NewStringObj(format->name,-1));
987 }
988 for (format = tsdPtr->oldFormatList; format; format = format->nextPtr) {
989 Tcl_ListObjAppendElement(interp, Tcl_GetObjResult(interp), Tcl_NewStringObj(format->name,-1));
990 }
991 return TCL_OK;
992 break;
993 }
994
995 case PHOTO_GET: {
996 /*
997 * photo get command - first parse and check parameters.
998 */
999
1000 char string[TCL_INTEGER_SPACE * 3];
1001
1002 if (objc != 4) {
1003 Tcl_WrongNumArgs(interp, 2, objv, "x y");
1004 return TCL_ERROR;
1005 }
1006 if ((Tcl_GetIntFromObj(interp, objv[2], &x) != TCL_OK)
1007 || (Tcl_GetIntFromObj(interp, objv[3], &y) != TCL_OK)) {
1008 return TCL_ERROR;
1009 }
1010 if ((x < 0) || (x >= masterPtr->width)
1011 || (y < 0) || (y >= masterPtr->height)) {
1012 Tcl_AppendResult(interp, Tcl_GetString(objv[0]), " get: ",
1013 "coordinates out of range", (char *) NULL);
1014 return TCL_ERROR;
1015 }
1016
1017 /*
1018 * Extract the value of the desired pixel and format it as a string.
1019 */
1020
1021 pixelPtr = masterPtr->pix32 + (y * masterPtr->width + x) * 4;
1022 obj = Tcl_NewListObj(0,NULL);
1023 for (c=0; c < 3; c++) {
1024 Tcl_ListObjAppendElement(interp, obj, Tcl_NewIntObj(pixelPtr[c]));
1025 }
1026 Tcl_SetObjResult(interp, obj);
1027 return TCL_OK;
1028 }
1029
1030 case PHOTO_PUT:
1031 /*
1032 * photo put command - first parse the options and colors specified.
1033 */
1034
1035 index = 2;
1036 memset((VOID *) &options, 0, sizeof(options));
1037 options.name = NULL;
1038 if (ParseSubcommandOptions(&options, interp, OPT_TO|OPT_FORMAT,
1039 &index, objc, objv) != TCL_OK) {
1040 return TCL_ERROR;
1041 }
1042 if ((options.name == NULL) || (index < objc)) {
1043 Tcl_WrongNumArgs(interp, 2, objv, "data ?options?");
1044 return TCL_ERROR;
1045 }
1046
1047 if (MatchStringFormat(interp, options.name ? objv[2]:NULL,
1048 options.format, &imageFormat, &imageWidth,
1049 &imageHeight, &oldformat) == TCL_OK) {
1050 Tcl_Obj *format, *data;
1051
1052 if (((options.options & OPT_TO) == 0) || (options.toX2 < 0)) {
1053 options.toX2 = options.toX + imageWidth;
1054 options.toY2 = options.toY + imageHeight;
1055 }
1056 if (imageWidth > options.toX2 - options.toX) {
1057 imageWidth = options.toX2 - options.toX;
1058 }
1059 if (imageHeight > options.toY2 - options.toY) {
1060 imageHeight = options.toY2 - options.toY;
1061 }
1062 format = options.format;
1063 data = objv[2];
1064 if (oldformat) {
1065 if (format) {
1066 format = (Tcl_Obj *) Tcl_GetString(format);
1067 }
1068 data = (Tcl_Obj *) Tcl_GetString(data);
1069 }
1070 if ((*imageFormat->stringReadProc)(interp, data,
1071 format, (Tk_PhotoHandle) masterPtr,
1072 options.toX, options.toY, imageWidth, imageHeight,
1073 0, 0) != TCL_OK) {
1074 return TCL_ERROR;
1075 }
1076 masterPtr->flags |= IMAGE_CHANGED;
1077 return TCL_OK;
1078 }
1079 if (options.options & OPT_FORMAT) {
1080 return TCL_ERROR;
1081 }
1082 Tcl_ResetResult(interp);
1083 if (Tcl_ListObjGetElements(interp, options.name, &dataHeight, &srcArgv) != TCL_OK) {
1084 return TCL_ERROR;
1085 }
1086 tkwin = Tk_MainWindow(interp);
1087 block.pixelPtr = NULL;
1088 dataWidth = 0;
1089 pixelPtr = NULL;
1090 for (y = 0; y < dataHeight; ++y) {
1091 if (Tcl_ListObjGetElements(interp, srcArgv[y], &listArgc, &listArgv) != TCL_OK) {
1092 break;
1093 }
1094 if (y == 0) {
1095 if (listArgc == 0) {
1096 /*
1097 * Lines must be non-empty...
1098 */
1099 break;
1100 }
1101 dataWidth = listArgc;
1102 pixelPtr = (unsigned char *)
1103 ckalloc((unsigned) dataWidth * dataHeight * 3);
1104 block.pixelPtr = pixelPtr;
1105 } else if (listArgc != dataWidth) {
1106 Tcl_AppendResult(interp, "all elements of color list must",
1107 " have the same number of elements", (char *) NULL);
1108 break;
1109 }
1110 for (x = 0; x < dataWidth; ++x) {
1111 if (!XParseColor(Tk_Display(tkwin), Tk_Colormap(tkwin),
1112 Tcl_GetString(listArgv[x]), &color)) {
1113 Tcl_AppendResult(interp, "can't parse color \"",
1114 Tcl_GetString(listArgv[x]), "\"", (char *) NULL);
1115 break;
1116 }
1117 *pixelPtr++ = color.red >> 8;
1118 *pixelPtr++ = color.green >> 8;
1119 *pixelPtr++ = color.blue >> 8;
1120 }
1121 if (x < dataWidth) {
1122 break;
1123 }
1124 }
1125 if (y < dataHeight || dataHeight == 0 || dataWidth == 0) {
1126 if (block.pixelPtr != NULL) {
1127 ckfree((char *) block.pixelPtr);
1128 }
1129 if (y < dataHeight) {
1130 return TCL_ERROR;
1131 }
1132 return TCL_OK;
1133 }
1134
1135 /*
1136 * Fill in default values for the -to option, then
1137 * copy the block in using Tk_PhotoPutBlock.
1138 */
1139
1140 if (!(options.options & OPT_TO) || (options.toX2 < 0)) {
1141 options.toX2 = options.toX + dataWidth;
1142 options.toY2 = options.toY + dataHeight;
1143 }
1144 block.width = dataWidth;
1145 block.height = dataHeight;
1146 block.pitch = dataWidth * 3;
1147 block.pixelSize = 3;
1148 block.offset[0] = 0;
1149 block.offset[1] = 1;
1150 block.offset[2] = 2;
1151 block.offset[3] = 0;
1152 Tk_PhotoPutBlock((ClientData)masterPtr, &block,
1153 options.toX, options.toY, options.toX2 - options.toX,
1154 options.toY2 - options.toY, TK_PHOTO_COMPOSITE_SET);
1155 ckfree((char *) block.pixelPtr);
1156 return TCL_OK;
1157
1158 case PHOTO_READ: {
1159 Tcl_Obj *format;
1160
1161 /*
1162 * photo read command - first parse the options specified.
1163 */
1164
1165 index = 2;
1166 memset((VOID *) &options, 0, sizeof(options));
1167 options.name = NULL;
1168 options.format = NULL;
1169 if (ParseSubcommandOptions(&options, interp,
1170 OPT_FORMAT | OPT_FROM | OPT_TO | OPT_SHRINK,
1171 &index, objc, objv) != TCL_OK) {
1172 return TCL_ERROR;
1173 }
1174 if ((options.name == NULL) || (index < objc)) {
1175 Tcl_WrongNumArgs(interp, 2, objv, "fileName ?options?");
1176 return TCL_ERROR;
1177 }
1178
1179 /*
1180 * Prevent file system access in safe interpreters.
1181 */
1182
1183 if (Tcl_IsSafe(interp)) {
1184 Tcl_AppendResult(interp, "can't get image from a file in a",
1185 " safe interpreter", (char *) NULL);
1186 return TCL_ERROR;
1187 }
1188
1189 /*
1190 * Open the image file and look for a handler for it.
1191 */
1192
1193 chan = Tcl_OpenFileChannel(interp,
1194 Tcl_GetString(options.name), "r", 0);
1195 if (chan == NULL) {
1196 return TCL_ERROR;
1197 }
1198 if (Tcl_SetChannelOption(interp, chan, "-translation", "binary")
1199 != TCL_OK) {
1200 Tcl_Close(NULL, chan);
1201 return TCL_ERROR;
1202 }
1203 if (Tcl_SetChannelOption(interp, chan, "-encoding", "binary")
1204 != TCL_OK) {
1205 Tcl_Close(NULL, chan);
1206 return TCL_ERROR;
1207 }
1208
1209 if (MatchFileFormat(interp, chan,
1210 options.name, options.format,
1211 &imageFormat, &imageWidth, &imageHeight, &oldformat) != TCL_OK) {
1212 Tcl_Close(NULL, chan);
1213 return TCL_ERROR;
1214 }
1215
1216 /*
1217 * Check the values given for the -from option.
1218 */
1219
1220 if ((options.fromX > imageWidth) || (options.fromY > imageHeight)
1221 || (options.fromX2 > imageWidth)
1222 || (options.fromY2 > imageHeight)) {
1223 Tcl_AppendResult(interp, "coordinates for -from option extend ",
1224 "outside source image", (char *) NULL);
1225 Tcl_Close(NULL, chan);
1226 return TCL_ERROR;
1227 }
1228 if (((options.options & OPT_FROM) == 0) || (options.fromX2 < 0)) {
1229 width = imageWidth - options.fromX;
1230 height = imageHeight - options.fromY;
1231 } else {
1232 width = options.fromX2 - options.fromX;
1233 height = options.fromY2 - options.fromY;
1234 }
1235
1236 /*
1237 * If the -shrink option was specified, set the size of the image.
1238 */
1239
1240 if (options.options & OPT_SHRINK) {
1241 if (ImgPhotoSetSize(masterPtr, options.toX + width,
1242 options.toY + height) != TCL_OK) {
1243 Tcl_ResetResult(interp);
1244 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
1245 TK_PHOTO_ALLOC_FAILURE_MESSAGE, (char *) NULL);
1246 return TCL_ERROR;
1247 }
1248 }
1249
1250 /*
1251 * Call the handler's file read procedure to read the data
1252 * into the image.
1253 */
1254
1255 format = options.format;
1256 if (oldformat && format) {
1257 format = (Tcl_Obj *) Tcl_GetString(format);
1258 }
1259 result = (*imageFormat->fileReadProc)(interp, chan,
1260 options.name,
1261 format, (Tk_PhotoHandle) masterPtr, options.toX,
1262 options.toY, width, height, options.fromX, options.fromY);
1263 if (chan != NULL) {
1264 Tcl_Close(NULL, chan);
1265 }
1266 return result;
1267 }
1268
1269 case PHOTO_REDITHER:
1270 if (objc != 2) {
1271 Tcl_WrongNumArgs(interp, 2, objv, (char *) NULL);
1272 return TCL_ERROR;
1273 }
1274
1275 /*
1276 * Call Dither if any part of the image is not correctly
1277 * dithered at present.
1278 */
1279
1280 x = masterPtr->ditherX;
1281 y = masterPtr->ditherY;
1282 if (masterPtr->ditherX != 0) {
1283 Tk_DitherPhoto((Tk_PhotoHandle) masterPtr, x, y,
1284 masterPtr->width - x, 1);
1285 }
1286 if (masterPtr->ditherY < masterPtr->height) {
1287 x = 0;
1288 Tk_DitherPhoto((Tk_PhotoHandle)masterPtr, 0,
1289 masterPtr->ditherY, masterPtr->width,
1290 masterPtr->height - masterPtr->ditherY);
1291 }
1292
1293 if (y < masterPtr->height) {
1294 /*
1295 * Tell the core image code that part of the image has changed.
1296 */
1297
1298 Tk_ImageChanged(masterPtr->tkMaster, x, y,
1299 (masterPtr->width - x), (masterPtr->height - y),
1300 masterPtr->width, masterPtr->height);
1301 }
1302 return TCL_OK;
1303
1304 case PHOTO_TRANS: {
1305 static CONST char *photoTransOptions[] = {
1306 "get", "set", (char *) NULL
1307 };
1308 enum transOptions {
1309 PHOTO_TRANS_GET, PHOTO_TRANS_SET
1310 };
1311
1312 if (objc < 3) {
1313 Tcl_WrongNumArgs(interp, 2, objv, "option ?arg arg ...?");
1314 return TCL_ERROR;
1315 }
1316 if (Tcl_GetIndexFromObj(interp, objv[2], photoTransOptions, "option",
1317 0, &index) != TCL_OK) {
1318 return TCL_ERROR;
1319 }
1320
1321 switch ((enum transOptions) index) {
1322 case PHOTO_TRANS_GET: {
1323 XRectangle testBox;
1324 TkRegion testRegion;
1325
1326 if (objc != 5) {
1327 Tcl_WrongNumArgs(interp, 3, objv, "x y");
1328 return TCL_ERROR;
1329 }
1330 if ((Tcl_GetIntFromObj(interp, objv[3], &x) != TCL_OK)
1331 || (Tcl_GetIntFromObj(interp, objv[4], &y) != TCL_OK)) {
1332 return TCL_ERROR;
1333 }
1334 if ((x < 0) || (x >= masterPtr->width)
1335 || (y < 0) || (y >= masterPtr->height)) {
1336 Tcl_AppendResult(interp, Tcl_GetString(objv[0]),
1337 " transparency get: coordinates out of range",
1338 (char *) NULL);
1339 return TCL_ERROR;
1340 }
1341
1342 testBox.x = x;
1343 testBox.y = y;
1344 testBox.width = 1;
1345 testBox.height = 1;
1346 /* What a way to do a test! */
1347 testRegion = TkCreateRegion();
1348 TkUnionRectWithRegion(&testBox, testRegion, testRegion);
1349 TkIntersectRegion(testRegion, masterPtr->validRegion, testRegion);
1350 TkClipBox(testRegion, &testBox);
1351 TkDestroyRegion(testRegion);
1352
1353 Tcl_SetBooleanObj(Tcl_GetObjResult(interp),
1354 (testBox.width==0 && testBox.height==0));
1355 return TCL_OK;
1356 }
1357
1358 case PHOTO_TRANS_SET: {
1359 int transFlag;
1360 XRectangle setBox;
1361
1362 if (objc != 6) {
1363 Tcl_WrongNumArgs(interp, 3, objv, "x y boolean");
1364 return TCL_ERROR;
1365 }
1366 if ((Tcl_GetIntFromObj(interp, objv[3], &x) != TCL_OK)
1367 || (Tcl_GetIntFromObj(interp, objv[4], &y) != TCL_OK)
1368 || (Tcl_GetBooleanFromObj(interp, objv[5],
1369 &transFlag) != TCL_OK)) {
1370 return TCL_ERROR;
1371 }
1372 if ((x < 0) || (x >= masterPtr->width)
1373 || (y < 0) || (y >= masterPtr->height)) {
1374 Tcl_AppendResult(interp, Tcl_GetString(objv[0]),
1375 " transparency set: coordinates out of range",
1376 (char *) NULL);
1377 return TCL_ERROR;
1378 }
1379
1380 setBox.x = x;
1381 setBox.y = y;
1382 setBox.width = 1;
1383 setBox.height = 1;
1384 pixelPtr = masterPtr->pix32 + (y * masterPtr->width + x) * 4;
1385
1386 if (transFlag) {
1387 /*
1388 * Make pixel transparent.
1389 */
1390 TkRegion clearRegion = TkCreateRegion();
1391
1392 TkUnionRectWithRegion(&setBox, clearRegion, clearRegion);
1393 TkSubtractRegion(masterPtr->validRegion, clearRegion,
1394 masterPtr->validRegion);
1395 TkDestroyRegion(clearRegion);
1396 /*
1397 * Set the alpha value correctly.
1398 */
1399 pixelPtr[3] = 0;
1400 } else {
1401 /*
1402 * Make pixel opaque.
1403 */
1404 TkUnionRectWithRegion(&setBox, masterPtr->validRegion,
1405 masterPtr->validRegion);
1406 pixelPtr[3] = 255;
1407 }
1408
1409 /*
1410 * Inform the generic image code that the image
1411 * has (potentially) changed.
1412 */
1413
1414 Tk_ImageChanged(masterPtr->tkMaster, x, y, 1, 1,
1415 masterPtr->width, masterPtr->height);
1416 masterPtr->flags &= ~IMAGE_CHANGED;
1417 return TCL_OK;
1418 }
1419 }
1420
1421 panic("unexpected fallthrough");
1422 }
1423
1424 case PHOTO_WRITE: {
1425 char *data;
1426 Tcl_Obj *format;
1427
1428 /*
1429 * Prevent file system access in safe interpreters.
1430 */
1431
1432 if (Tcl_IsSafe(interp)) {
1433 Tcl_AppendResult(interp, "can't write image to a file in a",
1434 " safe interpreter", (char *) NULL);
1435 return TCL_ERROR;
1436 }
1437
1438 /*
1439 * photo write command - first parse and check any options given.
1440 */
1441
1442 index = 2;
1443 memset((VOID *) &options, 0, sizeof(options));
1444 options.name = NULL;
1445 options.format = NULL;
1446 if (ParseSubcommandOptions(&options, interp,
1447 OPT_FORMAT | OPT_FROM | OPT_GRAYSCALE | OPT_BACKGROUND,
1448 &index, objc, objv) != TCL_OK) {
1449 return TCL_ERROR;
1450 }
1451 if ((options.name == NULL) || (index < objc)) {
1452 Tcl_WrongNumArgs(interp, 2, objv, "fileName ?options?");
1453 return TCL_ERROR;
1454 }
1455 if ((options.fromX > masterPtr->width)
1456 || (options.fromY > masterPtr->height)
1457 || (options.fromX2 > masterPtr->width)
1458 || (options.fromY2 > masterPtr->height)) {
1459 Tcl_AppendResult(interp, "coordinates for -from option extend ",
1460 "outside image", (char *) NULL);
1461 return TCL_ERROR;
1462 }
1463
1464 /*
1465 * Fill in default values for unspecified parameters.
1466 */
1467
1468 if (!(options.options & OPT_FROM) || (options.fromX2 < 0)) {
1469 options.fromX2 = masterPtr->width;
1470 options.fromY2 = masterPtr->height;
1471 }
1472
1473 /*
1474 * Search for an appropriate image file format handler,
1475 * and give an error if none is found.
1476 */
1477
1478 matched = 0;
1479 for (imageFormat = tsdPtr->formatList; imageFormat != NULL;
1480 imageFormat = imageFormat->nextPtr) {
1481 if ((options.format == NULL)
1482 || (strncasecmp(Tcl_GetString(options.format),
1483 imageFormat->name, strlen(imageFormat->name)) == 0)) {
1484 matched = 1;
1485 if (imageFormat->fileWriteProc != NULL) {
1486 break;
1487 }
1488 }
1489 }
1490 if (imageFormat == NULL) {
1491 oldformat = 1;
1492 for (imageFormat = tsdPtr->oldFormatList; imageFormat != NULL;
1493 imageFormat = imageFormat->nextPtr) {
1494 if ((options.format == NULL)
1495 || (strncasecmp(Tcl_GetString(options.format),
1496 imageFormat->name, strlen(imageFormat->name)) == 0)) {
1497 matched = 1;
1498 if (imageFormat->fileWriteProc != NULL) {
1499 break;
1500 }
1501 }
1502 }
1503 }
1504 if (imageFormat == NULL) {
1505 if (options.format == NULL) {
1506 Tcl_AppendResult(interp, "no available image file format ",
1507 "has file writing capability", (char *) NULL);
1508 } else if (!matched) {
1509 Tcl_AppendResult(interp, "image file format \"",
1510 Tcl_GetString(options.format),
1511 "\" is unknown", (char *) NULL);
1512 } else {
1513 Tcl_AppendResult(interp, "image file format \"",
1514 Tcl_GetString(options.format),
1515 "\" has no file writing capability",
1516 (char *) NULL);
1517 }
1518 return TCL_ERROR;
1519 }
1520
1521 /*
1522 * Call the handler's file write procedure to write out
1523 * the image.
1524 */
1525
1526 data = ImgGetPhoto(masterPtr, &block, &options);
1527 format = options.format;
1528 if (oldformat && format) {
1529 format = (Tcl_Obj *) Tcl_GetString(options.format);
1530 }
1531 result = (*imageFormat->fileWriteProc)(interp,
1532 Tcl_GetString(options.name), format, &block);
1533 if (options.background) {
1534 Tk_FreeColor(options.background);
1535 }
1536 if (data) {
1537 ckfree(data);
1538 }
1539 return result;
1540 }
1541
1542 }
1543 panic("unexpected fallthrough");
1544 return TCL_ERROR; /* NOT REACHED */
1545 }
1546
1547 /*
1548 *----------------------------------------------------------------------
1549 *
1550 * ParseSubcommandOptions --
1551 *
1552 * This procedure is invoked to process one of the options
1553 * which may be specified for the photo image subcommands,
1554 * namely, -from, -to, -zoom, -subsample, -format, -shrink,
1555 * and -compositingrule.
1556 *
1557 * Results:
1558 * A standard Tcl result.
1559 *
1560 * Side effects:
1561 * Fields in *optPtr get filled in.
1562 *
1563 *----------------------------------------------------------------------
1564 */
1565
1566 static int
1567 ParseSubcommandOptions(optPtr, interp, allowedOptions, optIndexPtr, objc, objv)
1568 struct SubcommandOptions *optPtr;
1569 /* Information about the options specified
1570 * and the values given is returned here. */
1571 Tcl_Interp *interp; /* Interpreter to use for reporting errors. */
1572 int allowedOptions; /* Indicates which options are valid for
1573 * the current command. */
1574 int *optIndexPtr; /* Points to a variable containing the
1575 * current index in objv; this variable is
1576 * updated by this procedure. */
1577 int objc; /* Number of arguments in objv[]. */
1578 Tcl_Obj *CONST objv[]; /* Arguments to be parsed. */
1579 {
1580 int index, c, bit, currentBit;
1581 int length;
1582 char *option, **listPtr;
1583 int values[4];
1584 int numValues, maxValues, argIndex;
1585
1586 for (index = *optIndexPtr; index < objc; *optIndexPtr = ++index) {
1587 /*
1588 * We can have one value specified without an option;
1589 * it goes into optPtr->name.
1590 */
1591
1592 option = Tcl_GetStringFromObj(objv[index], &length);
1593 if (option[0] != '-') {
1594 if (optPtr->name == NULL) {
1595 optPtr->name = objv[index];
1596 continue;
1597 }
1598 break;
1599 }
1600
1601 /*
1602 * Work out which option this is.
1603 */
1604
1605 c = option[0];
1606 bit = 0;
1607 currentBit = 1;
1608 for (listPtr = optionNames; *listPtr != NULL; ++listPtr) {
1609 if ((c == *listPtr[0])
1610 && (strncmp(option, *listPtr, (size_t) length) == 0)) {
1611 if (bit != 0) {
1612 bit = 0; /* An ambiguous option. */
1613 break;
1614 }
1615 bit = currentBit;
1616 }
1617 currentBit <<= 1;
1618 }
1619
1620 /*
1621 * If this option is not recognized and allowed, put
1622 * an error message in the interpreter and return.
1623 */
1624
1625 if ((allowedOptions & bit) == 0) {
1626 Tcl_AppendResult(interp, "unrecognized option \"",
1627 Tcl_GetString(objv[index]),
1628 "\": must be ", (char *)NULL);
1629 bit = 1;
1630 for (listPtr = optionNames; *listPtr != NULL; ++listPtr) {
1631 if ((allowedOptions & bit) != 0) {
1632 if ((allowedOptions & (bit - 1)) != 0) {
1633 Tcl_AppendResult(interp, ", ", (char *) NULL);
1634 if ((allowedOptions & ~((bit << 1) - 1)) == 0) {
1635 Tcl_AppendResult(interp, "or ", (char *) NULL);
1636 }
1637 }
1638 Tcl_AppendResult(interp, *listPtr, (char *) NULL);
1639 }
1640 bit <<= 1;
1641 }
1642 return TCL_ERROR;
1643 }
1644
1645 /*
1646 * For the -from, -to, -zoom and -subsample options,
1647 * parse the values given. Report an error if too few
1648 * or too many values are given.
1649 */
1650
1651 if (bit == OPT_BACKGROUND) {
1652 /*
1653 * The -background option takes a single XColor value.
1654 */
1655
1656 if (index + 1 < objc) {
1657 *optIndexPtr = ++index;
1658 optPtr->background = Tk_GetColor(interp, Tk_MainWindow(interp),
1659 Tk_GetUid(Tcl_GetString(objv[index])));
1660 if (!optPtr->background) {
1661 return TCL_ERROR;
1662 }
1663 } else {
1664 Tcl_AppendResult(interp, "the \"-background\" option ",
1665 "requires a value", (char *) NULL);
1666 return TCL_ERROR;
1667 }
1668 } else if (bit == OPT_FORMAT) {
1669 /*
1670 * The -format option takes a single string value. Note
1671 * that parsing this is outside the scope of this
1672 * function.
1673 */
1674
1675 if (index + 1 < objc) {
1676 *optIndexPtr = ++index;
1677 optPtr->format = objv[index];
1678 } else {
1679 Tcl_AppendResult(interp, "the \"-format\" option ",
1680 "requires a value", (char *) NULL);
1681 return TCL_ERROR;
1682 }
1683 } else if (bit == OPT_COMPOSITE) {
1684 /*
1685 * The -compositingrule option takes a single value from
1686 * a well-known set.
1687 */
1688
1689 if (index + 1 < objc) {
1690 /*
1691 * Note that these must match the TK_PHOTO_COMPOSITE_*
1692 * constants.
1693 */
1694 static CONST char *compositingRules[] = {
1695 "overlay", "set",
1696 NULL
1697 };
1698
1699 index++;
1700 if (Tcl_GetIndexFromObj(interp, objv[index], compositingRules,
1701 "compositing rule", 0, &optPtr->compositingRule)
1702 != TCL_OK) {
1703 return TCL_ERROR;
1704 }
1705 *optIndexPtr = index;
1706 } else {
1707 Tcl_AppendResult(interp, "the \"-compositingrule\" option ",
1708 "requires a value", (char *) NULL);
1709 return TCL_ERROR;
1710 }
1711 } else if ((bit != OPT_SHRINK) && (bit != OPT_GRAYSCALE)) {
1712 char *val;
1713 maxValues = ((bit == OPT_FROM) || (bit == OPT_TO))? 4: 2;
1714 argIndex = index + 1;
1715 for (numValues = 0; numValues < maxValues; ++numValues) {
1716 if (argIndex >= objc) {
1717 break;
1718 }
1719 val = Tcl_GetString(objv[argIndex]);
1720 if ((argIndex < objc) && (isdigit(UCHAR(val[0]))
1721 || ((val[0] == '-') && isdigit(UCHAR(val[1]))))) {
1722 if (Tcl_GetIntFromObj(interp, objv[argIndex], &values[numValues])
1723 != TCL_OK) {
1724 return TCL_ERROR;
1725 }
1726 } else {
1727 break;
1728 }
1729 ++argIndex;
1730 }
1731
1732 if (numValues == 0) {
1733 Tcl_AppendResult(interp, "the \"", option, "\" option ",
1734 "requires one ", maxValues == 2? "or two": "to four",
1735 " integer values", (char *) NULL);
1736 return TCL_ERROR;
1737 }
1738 *optIndexPtr = (index += numValues);
1739
1740 /*
1741 * Y values default to the corresponding X value if not specified.
1742 */
1743
1744 if (numValues == 1) {
1745 values[1] = values[0];
1746 }
1747 if (numValues == 3) {
1748 values[3] = values[2];
1749 }
1750
1751 /*
1752 * Check the values given and put them in the appropriate
1753 * field of the SubcommandOptions structure.
1754 */
1755
1756 switch (bit) {
1757 case OPT_FROM:
1758 if ((values[0] < 0) || (values[1] < 0) || ((numValues > 2)
1759 && ((values[2] < 0) || (values[3] < 0)))) {
1760 Tcl_AppendResult(interp, "value(s) for the -from",
1761 " option must be non-negative", (char *) NULL);
1762 return TCL_ERROR;
1763 }
1764 if (numValues <= 2) {
1765 optPtr->fromX = values[0];
1766 optPtr->fromY = values[1];
1767 optPtr->fromX2 = -1;
1768 optPtr->fromY2 = -1;
1769 } else {
1770 optPtr->fromX = MIN(values[0], values[2]);
1771 optPtr->fromY = MIN(values[1], values[3]);
1772 optPtr->fromX2 = MAX(values[0], values[2]);
1773 optPtr->fromY2 = MAX(values[1], values[3]);
1774 }
1775 break;
1776 case OPT_SUBSAMPLE:
1777 optPtr->subsampleX = values[0];
1778 optPtr->subsampleY = values[1];
1779 break;
1780 case OPT_TO:
1781 if ((values[0] < 0) || (values[1] < 0) || ((numValues > 2)
1782 && ((values[2] < 0) || (values[3] < 0)))) {
1783 Tcl_AppendResult(interp, "value(s) for the -to",
1784 " option must be non-negative", (char *) NULL);
1785 return TCL_ERROR;
1786 }
1787 if (numValues <= 2) {
1788 optPtr->toX = values[0];
1789 optPtr->toY = values[1];
1790 optPtr->toX2 = -1;
1791 optPtr->toY2 = -1;
1792 } else {
1793 optPtr->toX = MIN(values[0], values[2]);
1794 optPtr->toY = MIN(values[1], values[3]);
1795 optPtr->toX2 = MAX(values[0], values[2]);
1796 optPtr->toY2 = MAX(values[1], values[3]);
1797 }
1798 break;
1799 case OPT_ZOOM:
1800 if ((values[0] <= 0) || (values[1] <= 0)) {
1801 Tcl_AppendResult(interp, "value(s) for the -zoom",
1802 " option must be positive", (char *) NULL);
1803 return TCL_ERROR;
1804 }
1805 optPtr->zoomX = values[0];
1806 optPtr->zoomY = values[1];
1807 break;
1808 }
1809 }
1810
1811 /*
1812 * Remember that we saw this option.
1813 */
1814
1815 optPtr->options |= bit;
1816 }
1817
1818 return TCL_OK;
1819 }
1820
1821 /*
1822 *----------------------------------------------------------------------
1823 *
1824 * ImgPhotoConfigureMaster --
1825 *
1826 * This procedure is called when a photo image is created or
1827 * reconfigured. It processes configuration options and resets
1828 * any instances of the image.
1829 *
1830 * Results:
1831 * A standard Tcl return value. If TCL_ERROR is returned then
1832 * an error message is left in the masterPtr->interp's result.
1833 *
1834 * Side effects:
1835 * Existing instances of the image will be redisplayed to match
1836 * the new configuration options.
1837 *
1838 *----------------------------------------------------------------------
1839 */
1840
1841 static int
1842 ImgPhotoConfigureMaster(interp, masterPtr, objc, objv, flags)
1843 Tcl_Interp *interp; /* Interpreter to use for reporting errors. */
1844 PhotoMaster *masterPtr; /* Pointer to data structure describing
1845 * overall photo image to (re)configure. */
1846 int objc; /* Number of entries in objv. */
1847 Tcl_Obj *CONST objv[]; /* Pairs of configuration options for image. */
1848 int flags; /* Flags to pass to Tk_ConfigureWidget,
1849 * such as TK_CONFIG_ARGV_ONLY. */
1850 {
1851 PhotoInstance *instancePtr;
1852 Tcl_Obj *oldFileString;
1853 CONST char *oldPaletteString;
1854 Tcl_Obj *oldData, *data = NULL, *oldFormat, *format = NULL;
1855 int length, i, j;
1856 double oldGamma;
1857 int result;
1858 Tcl_Channel chan;
1859 Tk_PhotoImageFormat *imageFormat;
1860 int imageWidth, imageHeight;
1861 CONST char **args;
1862 int oldformat;
1863 Tcl_Obj *tempdata, *tempformat;
1864
1865 args = (CONST char **) ckalloc((objc + 1) * sizeof(char *));
1866 for (i = 0, j = 0; i < objc; i++,j++) {
1867 args[j] = Tcl_GetStringFromObj(objv[i], &length);
1868 if ((length > 1) && (args[j][0] == '-')) {
1869 if ((args[j][1] == 'd') &&
1870 !strncmp(args[j], "-data", (size_t) length)) {
1871 if (++i < objc) {
1872 data = objv[i];
1873 j--;
1874 } else {
1875 Tcl_AppendResult(interp,
1876 "value for \"-data\" missing", (char *) NULL);
1877 return TCL_ERROR;
1878 }
1879 } else if ((args[j][1] == 'f') &&
1880 !strncmp(args[j], "-format", (size_t) length)) {
1881 if (++i < objc) {
1882 format = objv[i];
1883 j--;
1884 } else {
1885 Tcl_AppendResult(interp,
1886 "value for \"-format\" missing", (char *) NULL);
1887 return TCL_ERROR;
1888 }
1889 }
1890 }
1891 }
1892
1893 /*
1894 * Save the current values for fileString and dataString, so we
1895 * can tell if the user specifies them anew.
1896 * IMPORTANT: if the format changes we have to interpret
1897 * "-file" and "-data" again as well!!!!!!! It might be
1898 * that the format string influences how "-data" or "-file"
1899 * is interpreted.
1900 */
1901
1902 oldFileString = masterPtr->fileString;
1903 if (oldFileString == NULL) {
1904 oldData = masterPtr->dataString;
1905 if (oldData != NULL) {
1906 Tcl_IncrRefCount(oldData);
1907 }
1908 } else {
1909 oldData = NULL;
1910 }
1911 oldFormat = masterPtr->format;
1912 if (oldFormat != NULL) {
1913 Tcl_IncrRefCount(oldFormat);
1914 }
1915 oldPaletteString = masterPtr->palette;
1916 oldGamma = masterPtr->gamma;
1917
1918 /*
1919 * Process the configuration options specified.
1920 */
1921
1922 if (Tk_ConfigureWidget(interp, Tk_MainWindow(interp), configSpecs,
1923 objc, objv, (char *) masterPtr, flags) != TCL_OK) {
1924 ckfree((char *) args);
1925 goto errorExit;
1926 }
1927 ckfree((char *) args);
1928
1929 /*
1930 * Regard the empty string for -file, -data or -format as the null
1931 * value.
1932 */
1933
1934 if ((masterPtr->fileString != NULL) && (Tcl_GetString(masterPtr->fileString)[0] == 0)) {
1935 Tcl_DecrRefCount(masterPtr->fileString);
1936 masterPtr->fileString = NULL;
1937 }
1938 if (data) {
1939 if (TclObjLength(data)
1940 || (TclObjGetType(data) == Tcl_GetObjType("bytearray")
1941 && TclObjInternal(data)->otherValuePtr != NULL)) {
1942 Tcl_IncrRefCount(data);
1943 } else {
1944 data = NULL;
1945 }
1946 }
1947 if (masterPtr->dataString != NULL) {
1948 Tcl_GetStringFromObj(masterPtr->dataString, &length);
1949 if (!length) {
1950 Tcl_DecrRefCount(masterPtr->dataString);
1951 masterPtr->dataString = NULL;
1952 }
1953 }
1954 if (masterPtr->format != NULL) {
1955 Tcl_GetStringFromObj(masterPtr->format, &length);
1956 if (!length) {
1957 Tcl_DecrRefCount(masterPtr->format);
1958 masterPtr->format = NULL;
1959 }
1960 }
1961 /*
1962 * Set the image to the user-requested size, if any,
1963 * and make sure storage is correctly allocated for this image.
1964 */
1965
1966 if (ImgPhotoSetSize(masterPtr, masterPtr->width,
1967 masterPtr->height) != TCL_OK) {
1968 Tcl_ResetResult(interp);
1969 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
1970 TK_PHOTO_ALLOC_FAILURE_MESSAGE, (char *) NULL);
1971 goto errorExit;
1972 }
1973
1974 /*
1975 * Read in the image from the file or string if the user has
1976 * specified the -file or -data option.
1977 */
1978
1979 if ((masterPtr->fileString != NULL)
1980 && ((masterPtr->fileString != oldFileString)
1981 || (masterPtr->format != oldFormat))) {
1982
1983 /*
1984 * Prevent file system access in a safe interpreter.
1985 */
1986
1987 if (Tcl_IsSafe(interp)) {
1988 Tcl_ResetResult(interp);
1989 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
1990 "can't get image from a file in a safe interpreter",
1991 (char *) NULL);
1992 goto errorExit;
1993 }
1994
1995 chan = Tcl_OpenFileChannel(interp, Tcl_GetString(masterPtr->fileString), "r", 0);
1996 if (chan == NULL) {
1997 goto errorExit;
1998 }
1999 /*
2000 * -translation binary also sets -encoding binary
2001 */
2002 if ((Tcl_SetChannelOption(interp, chan,
2003 "-translation", "binary") != TCL_OK) ||
2004 (MatchFileFormat(interp, chan, masterPtr->fileString,
2005 masterPtr->format, &imageFormat, &imageWidth,
2006 &imageHeight, &oldformat) != TCL_OK)) {
2007 Tcl_Close(NULL, chan);
2008 goto errorExit;
2009 }
2010 result = ImgPhotoSetSize(masterPtr, imageWidth, imageHeight);
2011 if (result != TCL_OK) {
2012 Tcl_Close(NULL, chan);
2013 Tcl_ResetResult(interp);
2014 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
2015 TK_PHOTO_ALLOC_FAILURE_MESSAGE, (char *) NULL);
2016 goto errorExit;
2017 }
2018 tempformat = masterPtr->format;
2019 if (oldformat && tempformat) {
2020 tempformat = (Tcl_Obj *) Tcl_GetString(tempformat);
2021 }
2022 result = (*imageFormat->fileReadProc)(interp, chan,
2023 masterPtr->fileString, tempformat,
2024 (Tk_PhotoHandle) masterPtr, 0, 0,
2025 imageWidth, imageHeight, 0, 0);
2026 Tcl_Close(NULL, chan);
2027 if (result != TCL_OK) {
2028 goto errorExit;
2029 }
2030
2031 Tcl_ResetResult(interp);
2032 masterPtr->flags |= IMAGE_CHANGED;
2033 }
2034
2035 if ((masterPtr->fileString == NULL) && (masterPtr->dataString != NULL)
2036 && ((masterPtr->dataString != oldData)
2037 || (masterPtr->format != oldFormat))) {
2038
2039 if (MatchStringFormat(interp, masterPtr->dataString,
2040 masterPtr->format, &imageFormat, &imageWidth,
2041 &imageHeight, &oldformat) != TCL_OK) {
2042 goto errorExit;
2043 }
2044 if (ImgPhotoSetSize(masterPtr, imageWidth, imageHeight) != TCL_OK) {
2045 Tcl_ResetResult(interp);
2046 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
2047 TK_PHOTO_ALLOC_FAILURE_MESSAGE, (char *) NULL);
2048 goto errorExit;
2049 }
2050 tempformat = masterPtr->format;
2051 tempdata = masterPtr->dataString;
2052 if (oldformat) {
2053 if (tempformat) {
2054 tempformat = (Tcl_Obj *) Tcl_GetString(tempformat);
2055 }
2056 tempdata = (Tcl_Obj *) Tcl_GetString(tempdata);
2057 }
2058 if ((*imageFormat->stringReadProc)(interp, tempdata,
2059 tempformat, (Tk_PhotoHandle) masterPtr,
2060 0, 0, imageWidth, imageHeight, 0, 0) != TCL_OK) {
2061 goto errorExit;
2062 }
2063
2064 Tcl_ResetResult(interp);
2065 masterPtr->flags |= IMAGE_CHANGED;
2066 }
2067
2068 /*
2069 * Enforce a reasonable value for gamma.
2070 */
2071
2072 if (masterPtr->gamma <= 0) {
2073 masterPtr->gamma = 1.0;
2074 }
2075
2076 if ((masterPtr->gamma != oldGamma)
2077 || (masterPtr->palette != oldPaletteString)) {
2078 masterPtr->flags |= IMAGE_CHANGED;
2079 }
2080
2081 /*
2082 * Cycle through all of the instances of this image, regenerating
2083 * the information for each instance. Then force the image to be
2084 * redisplayed everywhere that it is used.
2085 */
2086
2087 for (instancePtr = masterPtr->instancePtr; instancePtr != NULL;
2088 instancePtr = instancePtr->nextPtr) {
2089 ImgPhotoConfigureInstance(instancePtr);
2090 }
2091
2092 /*
2093 * Inform the generic image code that the image
2094 * has (potentially) changed.
2095 */
2096
2097 Tk_ImageChanged(masterPtr->tkMaster, 0, 0, masterPtr->width,
2098 masterPtr->height, masterPtr->width, masterPtr->height);
2099 masterPtr->flags &= ~IMAGE_CHANGED;
2100
2101 if (oldData != NULL) {
2102 Tcl_DecrRefCount(oldData);
2103 }
2104 if (oldFormat != NULL) {
2105 Tcl_DecrRefCount(oldFormat);
2106 }
2107
2108 ToggleComplexAlphaIfNeeded(masterPtr);
2109
2110 return TCL_OK;
2111
2112 errorExit:
2113 if (oldData != NULL) {
2114 Tcl_DecrRefCount(oldData);
2115 }
2116 if (oldFormat != NULL) {
2117 Tcl_DecrRefCount(oldFormat);
2118 }
2119 return TCL_ERROR;
2120 }
2121
2122 /*
2123 *----------------------------------------------------------------------
2124 *
2125 * ImgPhotoConfigureInstance --
2126 *
2127 * This procedure is called to create displaying information for
2128 * a photo image instance based on the configuration information
2129 * in the master. It is invoked both when new instances are
2130 * created and when the master is reconfigured.
2131 *
2132 * Results:
2133 * None.
2134 *
2135 * Side effects:
2136 * Generates errors via Tcl_BackgroundError if there are problems
2137 * in setting up the instance.
2138 *
2139 *----------------------------------------------------------------------
2140 */
2141
2142 static void
2143 ImgPhotoConfigureInstance(instancePtr)
2144 PhotoInstance *instancePtr; /* Instance to reconfigure. */
2145 {
2146 PhotoMaster *masterPtr = instancePtr->masterPtr;
2147 XImage *imagePtr;
2148 int bitsPerPixel;
2149 ColorTable *colorTablePtr;
2150 XRectangle validBox;
2151
2152 /*
2153 * If the -palette configuration option has been set for the master,
2154 * use the value specified for our palette, but only if it is
2155 * a valid palette for our windows. Use the gamma value specified
2156 * the master.
2157 */
2158
2159 if ((masterPtr->palette && masterPtr->palette[0])
2160 && IsValidPalette(instancePtr, masterPtr->palette)) {
2161 instancePtr->palette = masterPtr->palette;
2162 } else {
2163 instancePtr->palette = instancePtr->defaultPalette;
2164 }
2165 instancePtr->gamma = masterPtr->gamma;
2166
2167 /*
2168 * If we don't currently have a color table, or if the one we
2169 * have no longer applies (e.g. because our palette or gamma
2170 * has changed), get a new one.
2171 */
2172
2173 colorTablePtr = instancePtr->colorTablePtr;
2174 if ((colorTablePtr == NULL)
2175 || (instancePtr->colormap != colorTablePtr->id.colormap)
2176 || (instancePtr->palette != colorTablePtr->id.palette)
2177 || (instancePtr->gamma != colorTablePtr->id.gamma)) {
2178 /*
2179 * Free up our old color table, and get a new one.
2180 */
2181
2182 if (colorTablePtr != NULL) {
2183 colorTablePtr->liveRefCount -= 1;
2184 FreeColorTable(colorTablePtr, 0);
2185 }
2186 GetColorTable(instancePtr);
2187
2188 /*
2189 * Create a new XImage structure for sending data to
2190 * the X server, if necessary.
2191 */
2192
2193 if (instancePtr->colorTablePtr->flags & BLACK_AND_WHITE) {
2194 bitsPerPixel = 1;
2195 } else {
2196 bitsPerPixel = instancePtr->visualInfo.depth;
2197 }
2198
2199 if ((instancePtr->imagePtr == NULL)
2200 || (instancePtr->imagePtr->bits_per_pixel != bitsPerPixel)) {
2201 if (instancePtr->imagePtr != NULL) {
2202 XFree((char *) instancePtr->imagePtr);
2203 }
2204 imagePtr = XCreateImage(instancePtr->display,
2205 instancePtr->visualInfo.visual, (unsigned) bitsPerPixel,
2206 (bitsPerPixel > 1? ZPixmap: XYBitmap), 0, (char *) NULL,
2207 1, 1, 32, 0);
2208 instancePtr->imagePtr = imagePtr;
2209
2210 /*
2211 * Determine the endianness of this machine.
2212 * We create images using the local host's endianness, rather
2213 * than the endianness of the server; otherwise we would have
2214 * to byte-swap any 16 or 32 bit values that we store in the
2215 * image in those situations where the server's endianness
2216 * is different from ours.
2217 *
2218 * FIXME: use autoconf to figure this out.
2219 */
2220
2221 if (imagePtr != NULL) {
2222 union {
2223 int i;
2224 char c[sizeof(int)];
2225 } kludge;
2226
2227 imagePtr->bitmap_unit = sizeof(pixel) * NBBY;
2228 kludge.i = 0;
2229 kludge.c[0] = 1;
2230 imagePtr->byte_order = (kludge.i == 1) ? LSBFirst : MSBFirst;
2231 _XInitImageFuncPtrs(imagePtr);
2232 }
2233 }
2234 }
2235
2236 /*
2237 * If the user has specified a width and/or height for the master
2238 * which is different from our current width/height, set the size
2239 * to the values specified by the user. If we have no pixmap, we
2240 * do this also, since it has the side effect of allocating a
2241 * pixmap for us.
2242 */
2243
2244 if ((instancePtr->pixels == None) || (instancePtr->error == NULL)
2245 || (instancePtr->width != masterPtr->width)
2246 || (instancePtr->height != masterPtr->height)) {
2247 ImgPhotoInstanceSetSize(instancePtr);
2248 }
2249
2250 /*
2251 * Redither this instance if necessary.
2252 */
2253
2254 if ((masterPtr->flags & IMAGE_CHANGED)
2255 || (instancePtr->colorTablePtr != colorTablePtr)) {
2256 TkClipBox(masterPtr->validRegion, &validBox);
2257 if ((validBox.width > 0) && (validBox.height > 0)) {
2258 DitherInstance(instancePtr, validBox.x, validBox.y,
2259 validBox.width, validBox.height);
2260 }
2261 }
2262 }
2263
2264 /*
2265 *----------------------------------------------------------------------
2266 *
2267 * ImgPhotoGet --
2268 *
2269 * This procedure is called for each use of a photo image in a
2270 * widget.
2271 *
2272 * Results:
2273 * The return value is a token for the instance, which is passed
2274 * back to us in calls to ImgPhotoDisplay and ImgPhotoFree.
2275 *
2276 * Side effects:
2277 * A data structure is set up for the instance (or, an existing
2278 * instance is re-used for the new one).
2279 *
2280 *----------------------------------------------------------------------
2281 */
2282
2283 static ClientData
2284 ImgPhotoGet(tkwin, masterData)
2285 Tk_Window tkwin; /* Window in which the instance will be
2286 * used. */
2287 ClientData masterData; /* Pointer to our master structure for the
2288 * image. */
2289 {
2290 PhotoMaster *masterPtr = (PhotoMaster *) masterData;
2291 PhotoInstance *instancePtr;
2292 Colormap colormap;
2293 int mono, nRed, nGreen, nBlue;
2294 XVisualInfo visualInfo, *visInfoPtr;
2295 char buf[TCL_INTEGER_SPACE * 3];
2296 int numVisuals;
2297 XColor *white, *black;
2298 XGCValues gcValues;
2299
2300 /*
2301 * Table of "best" choices for palette for PseudoColor displays
2302 * with between 3 and 15 bits/pixel.
2303 */
2304
2305 static int paletteChoice[13][3] = {
2306 /* #red, #green, #blue */
2307 {2, 2, 2, /* 3 bits, 8 colors */},
2308 {2, 3, 2, /* 4 bits, 12 colors */},
2309 {3, 4, 2, /* 5 bits, 24 colors */},
2310 {4, 5, 3, /* 6 bits, 60 colors */},
2311 {5, 6, 4, /* 7 bits, 120 colors */},
2312 {7, 7, 4, /* 8 bits, 198 colors */},
2313 {8, 10, 6, /* 9 bits, 480 colors */},
2314 {10, 12, 8, /* 10 bits, 960 colors */},
2315 {14, 15, 9, /* 11 bits, 1890 colors */},
2316 {16, 20, 12, /* 12 bits, 3840 colors */},
2317 {20, 24, 16, /* 13 bits, 7680 colors */},
2318 {26, 30, 20, /* 14 bits, 15600 colors */},
2319 {32, 32, 30, /* 15 bits, 30720 colors */}
2320 };
2321
2322 /*
2323 * See if there is already an instance for windows using
2324 * the same colormap. If so then just re-use it.
2325 */
2326
2327 colormap = Tk_Colormap(tkwin);
2328 for (instancePtr = masterPtr->instancePtr; instancePtr != NULL;
2329 instancePtr = instancePtr->nextPtr) {
2330 if ((colormap == instancePtr->colormap)
2331 && (Tk_Display(tkwin) == instancePtr->display)) {
2332
2333 /*
2334 * Re-use this instance.
2335 */
2336
2337 if (instancePtr->refCount == 0) {
2338 /*
2339 * We are resurrecting this instance.
2340 */
2341
2342 Tcl_CancelIdleCall(DisposeInstance, (ClientData) instancePtr);
2343 if (instancePtr->colorTablePtr != NULL) {
2344 FreeColorTable(instancePtr->colorTablePtr, 0);
2345 }
2346 GetColorTable(instancePtr);
2347 }
2348 instancePtr->refCount++;
2349 return (ClientData) instancePtr;
2350 }
2351 }
2352
2353 /*
2354 * The image isn't already in use in a window with the same colormap.
2355 * Make a new instance of the image.
2356 */
2357
2358 instancePtr = (PhotoInstance *) ckalloc(sizeof(PhotoInstance));
2359 instancePtr->masterPtr = masterPtr;
2360 instancePtr->display = Tk_Display(tkwin);
2361 instancePtr->colormap = Tk_Colormap(tkwin);
2362 Tk_PreserveColormap(instancePtr->display, instancePtr->colormap);
2363 instancePtr->refCount = 1;
2364 instancePtr->colorTablePtr = NULL;
2365 instancePtr->pixels = None;
2366 instancePtr->error = NULL;
2367 instancePtr->width = 0;
2368 instancePtr->height = 0;
2369 instancePtr->imagePtr = 0;
2370 instancePtr->nextPtr = masterPtr->instancePtr;
2371 masterPtr->instancePtr = instancePtr;
2372
2373 /*
2374 * Obtain information about the visual and decide on the
2375 * default palette.
2376 */
2377
2378 visualInfo.screen = Tk_ScreenNumber(tkwin);
2379 visualInfo.visualid = XVisualIDFromVisual(Tk_Visual(tkwin));
2380 visInfoPtr = XGetVisualInfo(Tk_Display(tkwin),
2381 VisualScreenMask | VisualIDMask, &visualInfo, &numVisuals);
2382 nRed = 2;
2383 nGreen = nBlue = 0;
2384 mono = 1;
2385 if (visInfoPtr != NULL) {
2386 instancePtr->visualInfo = *visInfoPtr;
2387 switch (visInfoPtr->class) {
2388 case DirectColor:
2389 case TrueColor:
2390 nRed = 1 << CountBits(visInfoPtr->red_mask);
2391 nGreen = 1 << CountBits(visInfoPtr->green_mask);
2392 nBlue = 1 << CountBits(visInfoPtr->blue_mask);
2393 mono = 0;
2394 break;
2395 case PseudoColor:
2396 case StaticColor:
2397 if (visInfoPtr->depth > 15) {
2398 nRed = 32;
2399 nGreen = 32;
2400 nBlue = 32;
2401 mono = 0;
2402 } else if (visInfoPtr->depth >= 3) {
2403 int *ip = paletteChoice[visInfoPtr->depth - 3];
2404
2405 nRed = ip[0];
2406 nGreen = ip[1];
2407 nBlue = ip[2];
2408 mono = 0;
2409 }
2410 break;
2411 case GrayScale:
2412 case StaticGray:
2413 nRed = 1 << visInfoPtr->depth;
2414 break;
2415 }
2416 XFree((char *) visInfoPtr);
2417
2418 } else {
2419 panic("ImgPhotoGet couldn't find visual for window");
2420 }
2421
2422 sprintf(buf, ((mono) ? "%d": "%d/%d/%d"), nRed, nGreen, nBlue);
2423 instancePtr->defaultPalette = Tk_GetUid(buf);
2424
2425 /*
2426 * Make a GC with background = black and foreground = white.
2427 */
2428
2429 white = Tk_GetColor(masterPtr->interp, tkwin, "white");
2430 black = Tk_GetColor(masterPtr->interp, tkwin, "black");
2431 gcValues.foreground = (white != NULL)? white->pixel:
2432 WhitePixelOfScreen(Tk_Screen(tkwin));
2433 gcValues.background = (black != NULL)? black->pixel:
2434 BlackPixelOfScreen(Tk_Screen(tkwin));
2435 gcValues.graphics_exposures = False;
2436 instancePtr->gc = Tk_GetGC(tkwin,
2437 GCForeground|GCBackground|GCGraphicsExposures, &gcValues);
2438
2439 /*
2440 * Set configuration options and finish the initialization of the instance.
2441 * This will also dither the image if necessary.
2442 */
2443
2444 ImgPhotoConfigureInstance(instancePtr);
2445
2446 /*
2447 * If this is the first instance, must set the size of the image.
2448 */
2449
2450 if (instancePtr->nextPtr == NULL) {
2451 Tk_ImageChanged(masterPtr->tkMaster, 0, 0, 0, 0,
2452 masterPtr->width, masterPtr->height);
2453 }
2454
2455 return (ClientData) instancePtr;
2456 }
2457
2458 /*
2459 *----------------------------------------------------------------------
2460 *
2461 * ToggleComplexAlphaIfNeeded --
2462 *
2463 * This procedure is called when an image is modified to
2464 * check if any partially transparent pixels exist, which
2465 * requires blending instead of straight copy.
2466 *
2467 * Results:
2468 * None.
2469 *
2470 * Side effects:
2471 * (Re)sets COMPLEX_ALPHA flag of master.
2472 *
2473 *----------------------------------------------------------------------
2474 */
2475
2476 static int
2477 ToggleComplexAlphaIfNeeded(PhotoMaster *mPtr)
2478 {
2479 size_t len = MAX(mPtr->userWidth, mPtr->width) *
2480 MAX(mPtr->userHeight, mPtr->height) * 4;
2481 unsigned char *c = mPtr->pix32;
2482 unsigned char *end = c + len;
2483
2484 /*
2485 * Set the COMPLEX_ALPHA flag if we have an image with partially
2486 * transparent bits.
2487 */
2488 mPtr->flags &= ~COMPLEX_ALPHA;
2489 c += 3; /* start at first alpha byte */
2490 for (; c < end; c += 4) {
2491 if (*c && *c != 255) {
2492 mPtr->flags |= COMPLEX_ALPHA;
2493 break;
2494 }
2495 }
2496 return (mPtr->flags & COMPLEX_ALPHA);
2497 }
2498
2499 /*
2500 *----------------------------------------------------------------------
2501 *
2502 * ImgPhotoBlendComplexAlpha --
2503 *
2504 * This procedure is called when an image with partially
2505 * transparent pixels must be drawn over another image.
2506 *
2507 * Results:
2508 * None.
2509 *
2510 * Side effects:
2511 * Background image passed in gets drawn over with image data.
2512 *
2513 *----------------------------------------------------------------------
2514 */
2515 /*
2516 * This should work on all platforms that set mask and shift data properly
2517 * from the visualInfo.
2518 * RGB is really only a 24+ bpp version whereas RGB15 is the correct version
2519 * and works for 15bpp+, but it slower, so it's only used for 15bpp+.
2520 */
2521 #ifndef __WIN32__
2522 #define GetRValue(rgb) (UCHAR((rgb & red_mask) >> red_shift))
2523 #define GetGValue(rgb) (UCHAR((rgb & green_mask) >> green_shift))
2524 #define GetBValue(rgb) (UCHAR((rgb & blue_mask) >> blue_shift))
2525 #define RGB(r,g,b) ((unsigned)((UCHAR(r)<<red_shift)|(UCHAR(g)<<green_shift)|(UCHAR(b)<<blue_shift)))
2526 #define RGB15(r,g,b) ((unsigned)(((r*red_mask/255)&red_mask)|((g*green_mask/255)&green_mask)|((b*blue_mask/255)&blue_mask)))
2527 #endif
2528
2529 static void ImgPhotoBlendComplexAlpha (
2530 XImage *bgImg, /* background image to draw on */
2531 PhotoInstance *iPtr, /* image instance to draw */
2532 int xOffset, int yOffset, /* X & Y offset into image instance to draw */
2533 int width, int height /* width & height of image to draw */
2534 )
2535 {
2536 int x, y, line;
2537 unsigned long pixel;
2538 unsigned char r, g, b, alpha, unalpha;
2539 unsigned char *alphaAr = iPtr->masterPtr->pix32;
2540 unsigned char *masterPtr;
2541
2542 #ifndef __WIN32__
2543 /*
2544 * We have to get the mask and shift info from the visual.
2545 * This might be cached for better performance.
2546 */
2547 unsigned long red_mask, green_mask, blue_mask;
2548 unsigned long red_shift, green_shift, blue_shift;
2549 Visual *visual = iPtr->visualInfo.visual;
2550
2551 red_mask = visual->red_mask;
2552 green_mask = visual->green_mask;
2553 blue_mask = visual->blue_mask;
2554 red_shift = 0;
2555 green_shift = 0;
2556 blue_shift = 0;
2557 while ((0x0001 & (red_mask >> red_shift)) == 0) red_shift++;
2558 while ((0x0001 & (green_mask >> green_shift)) == 0) green_shift++;
2559 while ((0x0001 & (blue_mask >> blue_shift)) == 0) blue_shift++;
2560 #endif
2561
2562 #define ALPHA_BLEND(bgPix, imgPix, alpha, unalpha) \
2563 ((bgPix * unalpha + imgPix * alpha) / 255)
2564
2565 #if !(defined(__WIN32__) || defined(MAC_OSX_TK))
2566 /*
2567 * Only unix requires the special case for <24bpp. It varies with
2568 * 3 extra shifts and uses RGB15. The 24+bpp version could also
2569 * then be further optimized.
2570 */
2571 if (bgImg->depth < 24) {
2572 unsigned char red_mlen, green_mlen, blue_mlen;
2573
2574 red_mlen = 8 - CountBits(red_mask >> red_shift);
2575 green_mlen = 8 - CountBits(green_mask >> green_shift);
2576 blue_mlen = 8 - CountBits(blue_mask >> blue_shift);
2577 for (y = 0; y < height; y++) {
2578 line = (y + yOffset) * iPtr->masterPtr->width;
2579 for (x = 0; x < width; x++) {
2580 masterPtr = alphaAr + ((line + x + xOffset) * 4);
2581 alpha = masterPtr[3];
2582 /*
2583 * Ignore pixels that are fully transparent
2584 */
2585 if (alpha) {
2586 /*
2587 * We could perhaps be more efficient than XGetPixel for
2588 * 24 and 32 bit displays, but this seems "fast enough".
2589 */
2590 r = masterPtr[0];
2591 g = masterPtr[1];
2592 b = masterPtr[2];
2593 if (alpha != 255) {
2594 /*
2595 * Only blend pixels that have some transparency
2596 */
2597 unsigned char ra, ga, ba;
2598
2599 pixel = XGetPixel(bgImg, x, y);
2600 ra = GetRValue(pixel) << red_mlen;
2601 ga = GetGValue(pixel) << green_mlen;
2602 ba = GetBValue(pixel) << blue_mlen;
2603 unalpha = 255 - alpha;
2604 r = ALPHA_BLEND(ra, r, alpha, unalpha);
2605 g = ALPHA_BLEND(ga, g, alpha, unalpha);
2606 b = ALPHA_BLEND(ba, b, alpha, unalpha);
2607 }
2608 XPutPixel(bgImg, x, y, RGB15(r, g, b));
2609 }
2610 }
2611 }
2612 } else
2613 #endif
2614 for (y = 0; y < height; y++) {
2615 line = (y + yOffset) * iPtr->masterPtr->width;
2616 for (x = 0; x < width; x++) {
2617 masterPtr = alphaAr + ((line + x + xOffset) * 4);
2618 alpha = masterPtr[3];
2619 /*
2620 * Ignore pixels that are fully transparent
2621 */
2622 if (alpha) {
2623 /*
2624 * We could perhaps be more efficient than XGetPixel for
2625 * 24 and 32 bit displays, but this seems "fast enough".
2626 */
2627 r = masterPtr[0];
2628 g = masterPtr[1];
2629 b = masterPtr[2];
2630 if (alpha != 255) {
2631 /*
2632 * Only blend pixels that have some transparency
2633 */
2634 unsigned char ra, ga, ba;
2635
2636 pixel = XGetPixel(bgImg, x, y);
2637 ra = GetRValue(pixel);
2638 ga = GetGValue(pixel);
2639 ba = GetBValue(pixel);
2640 unalpha = 255 - alpha;
2641 r = ALPHA_BLEND(ra, r, alpha, unalpha);
2642 g = ALPHA_BLEND(ga, g, alpha, unalpha);
2643 b = ALPHA_BLEND(ba, b, alpha, unalpha);
2644 }
2645 XPutPixel(bgImg, x, y, RGB(r, g, b));
2646 }
2647 }
2648 }
2649 #undef ALPHA_BLEND
2650 }
2651
2652 /*
2653 *----------------------------------------------------------------------
2654 *
2655 * ImgPhotoDisplay --
2656 *
2657 * This procedure is invoked to draw a photo image.
2658 *
2659 * Results:
2660 * None.
2661 *
2662 * Side effects:
2663 * A portion of the image gets rendered in a pixmap or window.
2664 *
2665 *----------------------------------------------------------------------
2666 */
2667
2668 static void
2669 ImgPhotoDisplay(clientData, display, drawable, imageX, imageY, width,
2670 height, drawableX, drawableY)
2671 ClientData clientData; /* Pointer to PhotoInstance structure for
2672 * for instance to be displayed. */
2673 Display *display; /* Display on which to draw image. */
2674 Drawable drawable; /* Pixmap or window in which to draw image. */
2675 int imageX, imageY; /* Upper-left corner of region within image
2676 * to draw. */
2677 int width, height; /* Dimensions of region within image to draw. */
2678 int drawableX, drawableY; /* Coordinates within drawable that
2679 * correspond to imageX and imageY. */
2680 {
2681 PhotoInstance *instancePtr = (PhotoInstance *) clientData;
2682 XVisualInfo visInfo = instancePtr->visualInfo;
2683
2684 /*
2685 * If there's no pixmap, it means that an error occurred
2686 * while creating the image instance so it can't be displayed.
2687 */
2688
2689 if (instancePtr->pixels == None) {
2690 return;
2691 }
2692
2693 if (
2694 #if defined(MAC_TCL) || defined(MAC_OSX_TK)
2695 /*
2696 * The retrieval of bgImg is currently not functional on OSX
2697 * (and likely not OS9 either), so skip attempts to alpha blend.
2698 */
2699 0 &&
2700 #endif
2701 (instancePtr->masterPtr->flags & COMPLEX_ALPHA)
2702 && visInfo.depth >= 15
2703 && (visInfo.class == DirectColor || visInfo.class == TrueColor)) {
2704 Tk_ErrorHandler handler;
2705 XImage *bgImg = NULL;
2706
2707 /*
2708 * Create an error handler to suppress the case where the input was
2709 * not properly constrained, which can cause an X error. [Bug 979239]
2710 * Fix put in perl/tk by Franck Aniere, with help from George Peter
2711 * Staplin.
2712 */
2713
2714 handler = Tk_CreateErrorHandler(display, -1, -1, -1,
2715 (Tk_ErrorProc *) NULL, (ClientData) NULL);
2716
2717 /*
2718 * Pull the current background from the display to blend with
2719 */
2720 bgImg = XGetImage(display, drawable, drawableX, drawableY,
2721 (unsigned int)width, (unsigned int)height, AllPlanes, ZPixmap);
2722 if (bgImg == NULL) {
2723 Tk_DeleteErrorHandler(handler);
2724 return;
2725 }
2726
2727 ImgPhotoBlendComplexAlpha(bgImg, instancePtr,
2728 imageX, imageY, width, height);
2729
2730 /*
2731 * Color info is unimportant as we only do this operation for
2732 * depth >= 15.
2733 */
2734 TkPutImage(NULL, 0, display, drawable, instancePtr->gc,
2735 bgImg, 0, 0, drawableX, drawableY,
2736 (unsigned int) width, (unsigned int) height);
2737 XDestroyImage(bgImg);
2738 Tk_DeleteErrorHandler(handler);
2739 } else {
2740 /*
2741 * masterPtr->region describes which parts of the image contain
2742 * valid data. We set this region as the clip mask for the gc,
2743 * setting its origin appropriately, and use it when drawing the
2744 * image.
2745 */
2746 TkSetRegion(display, instancePtr->gc, instancePtr->masterPtr->validRegion);
2747 XSetClipOrigin(display, instancePtr->gc, drawableX - imageX,
2748 drawableY - imageY);
2749 XCopyArea(display, instancePtr->pixels, drawable, instancePtr->gc,
2750 imageX, imageY, (unsigned) width, (unsigned) height,
2751 drawableX, drawableY);
2752 XSetClipMask(display, instancePtr->gc, None);
2753 XSetClipOrigin(display, instancePtr->gc, 0, 0);
2754 }
2755 XFlush (display);
2756 }
2757
2758 /*
2759 *----------------------------------------------------------------------
2760 *
2761 * ImgPhotoFree --
2762 *
2763 * This procedure is called when a widget ceases to use a
2764 * particular instance of an image. We don't actually get
2765 * rid of the instance until later because we may be about
2766 * to get this instance again.
2767 *
2768 * Results:
2769 * None.
2770 *
2771 * Side effects:
2772 * Internal data structures get cleaned up, later.
2773 *
2774 *----------------------------------------------------------------------
2775 */
2776
2777 static void
2778 ImgPhotoFree(clientData, display)
2779 ClientData clientData; /* Pointer to PhotoInstance structure for
2780 * for instance to be displayed. */
2781 Display *display; /* Display containing window that used image. */
2782 {
2783 PhotoInstance *instancePtr = (PhotoInstance *) clientData;
2784 ColorTable *colorPtr;
2785
2786 instancePtr->refCount -= 1;
2787 if (instancePtr->refCount > 0) {
2788 return;
2789 }
2790
2791 /*
2792 * There are no more uses of the image within this widget.
2793 * Decrement the count of live uses of its color table, so
2794 * that its colors can be reclaimed if necessary, and
2795 * set up an idle call to free the instance structure.
2796 */
2797
2798 colorPtr = instancePtr->colorTablePtr;
2799 if (colorPtr != NULL) {
2800 colorPtr->liveRefCount -= 1;
2801 }
2802
2803 Tcl_DoWhenIdle(DisposeInstance, (ClientData) instancePtr);
2804 }
2805
2806 /*
2807 *----------------------------------------------------------------------
2808 *
2809 * ImgPhotoDelete --
2810 *
2811 * This procedure is called by the image code to delete the
2812 * master structure for an image.
2813 *
2814 * Results:
2815 * None.
2816 *
2817 * Side effects:
2818 * Resources associated with the image get freed.
2819 *
2820 *----------------------------------------------------------------------
2821 */
2822
2823 static void
2824 ImgPhotoDelete(masterData)
2825 ClientData masterData; /* Pointer to PhotoMaster structure for
2826 * image. Must not have any more instances. */
2827 {
2828 PhotoMaster *masterPtr = (PhotoMaster *) masterData;
2829 PhotoInstance *instancePtr;
2830
2831 while ((instancePtr = masterPtr->instancePtr) != NULL) {
2832 if (instancePtr->refCount > 0) {
2833 panic("tried to delete photo image when instances still exist");
2834 }
2835 Tcl_CancelIdleCall(DisposeInstance, (ClientData) instancePtr);
2836 DisposeInstance((ClientData) instancePtr);
2837 }
2838 masterPtr->tkMaster = NULL;
2839 if (masterPtr->imageCmd != NULL) {
2840 Tcl_DeleteCommandFromToken(masterPtr->interp, masterPtr->imageCmd);
2841 }
2842 if (masterPtr->pix32 != NULL) {
2843 ckfree((char *) masterPtr->pix32);
2844 }
2845 if (masterPtr->validRegion != NULL) {
2846 TkDestroyRegion(masterPtr->validRegion);
2847 }
2848 #ifndef _LANG
2849 if (masterPtr->dataString != NULL) {
2850 Tcl_DecrRefCount(masterPtr->dataString);
2851 }
2852 if (masterPtr->format != NULL) {
2853 Tcl_DecrRefCount(masterPtr->format);
2854 }
2855 #endif
2856 Tk_FreeOptions(configSpecs, (char *) masterPtr, (Display *) NULL, 0);
2857 ckfree((char *) masterPtr);
2858 }
2859
2860 /*
2861 *----------------------------------------------------------------------
2862 *
2863 * ImgPhotoCmdDeletedProc --
2864 *
2865 * This procedure is invoked when the image command for an image
2866 * is deleted. It deletes the image.
2867 *
2868 * Results:
2869 * None.
2870 *
2871 * Side effects:
2872 * The image is deleted.
2873 *
2874 *----------------------------------------------------------------------
2875 */
2876
2877 static void
2878 ImgPhotoCmdDeletedProc(clientData)
2879 ClientData clientData; /* Pointer to PhotoMaster structure for
2880 * image. */
2881 {
2882 PhotoMaster *masterPtr = (PhotoMaster *) clientData;
2883
2884 masterPtr->imageCmd = NULL;
2885 if (masterPtr->tkMaster != NULL) {
2886 Tk_DeleteImage(masterPtr->interp, Tk_NameOfImage(masterPtr->tkMaster));
2887 }
2888 }
2889
2890 /*
2891 *----------------------------------------------------------------------
2892 *
2893 * ImgPhotoSetSize --
2894 *
2895 * This procedure reallocates the image storage and instance
2896 * pixmaps for a photo image, as necessary, to change the
2897 * image's size to `width' x `height' pixels.
2898 *
2899 * Results:
2900 * TCL_OK if successful, TCL_ERROR if failure occurred (currently
2901 * just with memory allocation.)
2902 *
2903 * Side effects:
2904 * Storage gets reallocated, for the master and all its instances.
2905 *
2906 *----------------------------------------------------------------------
2907 */
2908
2909 static int
2910 ImgPhotoSetSize(masterPtr, width, height)
2911 PhotoMaster *masterPtr;
2912 int width, height;
2913 {
2914 unsigned char *newPix32 = NULL;
2915 int h, offset, pitch;
2916 unsigned char *srcPtr, *destPtr;
2917 XRectangle validBox, clipBox;
2918 TkRegion clipRegion;
2919 PhotoInstance *instancePtr;
2920
2921 if (masterPtr->userWidth > 0) {
2922 width = masterPtr->userWidth;
2923 }
2924 if (masterPtr->userHeight > 0) {
2925 height = masterPtr->userHeight;
2926 }
2927
2928 pitch = width * 4;
2929
2930 /*
2931 * Test if we're going to (re)allocate the main buffer now, so
2932 * that any failures will leave the photo unchanged.
2933 */
2934 if ((width != masterPtr->width) || (height != masterPtr->height)
2935 || (masterPtr->pix32 == NULL)) {
2936 /*
2937 * Not a u-long, but should be one.
2938 */
2939 unsigned /*long*/ newPixSize = (unsigned /*long*/) (height * pitch);
2940
2941 /*
2942 * Some mallocs() really hate allocating zero bytes. [Bug 619544]
2943 */
2944 if (newPixSize == 0) {
2945 newPix32 = NULL;
2946 } else {
2947 newPix32 = (unsigned char *) attemptckalloc(newPixSize);
2948 if (newPix32 == NULL) {
2949 return TCL_ERROR;
2950 }
2951 }
2952 }
2953
2954 /*
2955 * We have to trim the valid region if it is currently
2956 * larger than the new image size.
2957 */
2958
2959 TkClipBox(masterPtr->validRegion, &validBox);
2960 if ((validBox.x + validBox.width > width)
2961 || (validBox.y + validBox.height > height)) {
2962 clipBox.x = 0;
2963 clipBox.y = 0;
2964 clipBox.width = width;
2965 clipBox.height = height;
2966 clipRegion = TkCreateRegion();
2967 TkUnionRectWithRegion(&clipBox, clipRegion, clipRegion);
2968 TkIntersectRegion(masterPtr->validRegion, clipRegion,
2969 masterPtr->validRegion);
2970 TkDestroyRegion(clipRegion);
2971 TkClipBox(masterPtr->validRegion, &validBox);
2972 }
2973
2974 /*
2975 * Use the reallocated storage (allocation above) for the 32-bit
2976 * image and copy over valid regions. Note that this test is true
2977 * precisely when the allocation has already been done.
2978 */
2979 if (newPix32 != NULL) {
2980 /*
2981 * Zero the new array. The dithering code shouldn't read the
2982 * areas outside validBox, but they might be copied to another
2983 * photo image or written to a file.
2984 */
2985
2986 if ((masterPtr->pix32 != NULL)
2987 && ((width == masterPtr->width) || (width == validBox.width))) {
2988 if (validBox.y > 0) {
2989 memset((VOID *) newPix32, 0, (size_t) (validBox.y * pitch));
2990 }
2991 h = validBox.y + validBox.height;
2992 if (h < height) {
2993 memset((VOID *) (newPix32 + h * pitch), 0,
2994 (size_t) ((height - h) * pitch));
2995 }
2996 } else {
2997 memset((VOID *) newPix32, 0, (size_t) (height * pitch));
2998 }
2999
3000 if (masterPtr->pix32 != NULL) {
3001
3002 /*
3003 * Copy the common area over to the new array array and
3004 * free the old array.
3005 */
3006
3007 if (newPix32 == NULL) {
3008
3009 /*
3010 * Nowhere to copy to ...
3011 */
3012
3013 } else if (width == masterPtr->width) {
3014
3015 /*
3016 * The region to be copied is contiguous.
3017 */
3018
3019 offset = validBox.y * pitch;
3020 memcpy((VOID *) (newPix32 + offset),
3021 (VOID *) (masterPtr->pix32 + offset),
3022 (size_t) (validBox.height * pitch));
3023
3024 } else if ((validBox.width > 0) && (validBox.height > 0)) {
3025
3026 /*
3027 * Area to be copied is not contiguous - copy line by line.
3028 */
3029
3030 destPtr = newPix32 + (validBox.y * width + validBox.x) * 4;
3031 srcPtr = masterPtr->pix32 + (validBox.y * masterPtr->width
3032 + validBox.x) * 4;
3033 for (h = validBox.height; h > 0; h--) {
3034 memcpy((VOID *) destPtr, (VOID *) srcPtr,
3035 (size_t) (validBox.width * 4));
3036 destPtr += width * 4;
3037 srcPtr += masterPtr->width * 4;
3038 }
3039 }
3040
3041 ckfree((char *) masterPtr->pix32);
3042 }
3043
3044 masterPtr->pix32 = newPix32;
3045 masterPtr->width = width;
3046 masterPtr->height = height;
3047
3048 /*
3049 * Dithering will be correct up to the end of the last
3050 * pre-existing complete scanline.
3051 */
3052
3053 if ((validBox.x > 0) || (validBox.y > 0)) {
3054 masterPtr->ditherX = 0;
3055 masterPtr->ditherY = 0;
3056 } else if (validBox.width == width) {
3057 if ((int) validBox.height < masterPtr->ditherY) {
3058 masterPtr->ditherX = 0;
3059 masterPtr->ditherY = validBox.height;
3060 }
3061 } else if ((masterPtr->ditherY > 0)
3062 || ((int) validBox.width < masterPtr->ditherX)) {
3063 masterPtr->ditherX = validBox.width;
3064 masterPtr->ditherY = 0;
3065 }
3066 }
3067
3068 ToggleComplexAlphaIfNeeded(masterPtr);
3069
3070 /*
3071 * Now adjust the sizes of the pixmaps for all of the instances.
3072 */
3073
3074 for (instancePtr = masterPtr->instancePtr; instancePtr != NULL;
3075 instancePtr = instancePtr->nextPtr) {
3076 ImgPhotoInstanceSetSize(instancePtr);
3077 }
3078
3079 return TCL_OK;
3080 }
3081
3082 /*
3083 *----------------------------------------------------------------------
3084 *
3085 * ImgPhotoInstanceSetSize --
3086 *
3087 * This procedure reallocates the instance pixmap and dithering
3088 * error array for a photo instance, as necessary, to change the
3089 * image's size to `width' x `height' pixels.
3090 *
3091 * Results:
3092 * None.
3093 *
3094 * Side effects:
3095 * Storage gets reallocated, here and in the X server.
3096 *
3097 *----------------------------------------------------------------------
3098 */
3099
3100 static void
3101 ImgPhotoInstanceSetSize(instancePtr)
3102 PhotoInstance *instancePtr; /* Instance whose size is to be
3103 * changed. */
3104 {
3105 PhotoMaster *masterPtr;
3106 schar *newError;
3107 schar *errSrcPtr, *errDestPtr;
3108 int h, offset;
3109 XRectangle validBox;
3110 Pixmap newPixmap;
3111
3112 masterPtr = instancePtr->masterPtr;
3113 TkClipBox(masterPtr->validRegion, &validBox);
3114
3115 if ((instancePtr->width != masterPtr->width)
3116 || (instancePtr->height != masterPtr->height)
3117 || (instancePtr->pixels == None)) {
3118 newPixmap = Tk_GetPixmap(instancePtr->display,
3119 RootWindow(instancePtr->display,
3120 instancePtr->visualInfo.screen),
3121 (masterPtr->width > 0) ? masterPtr->width: 1,
3122 (masterPtr->height > 0) ? masterPtr->height: 1,
3123 instancePtr->visualInfo.depth);
3124 if (!newPixmap) {
3125 panic("Fail to create pixmap with Tk_GetPixmap in ImgPhotoInstanceSetSize.\n");
3126 return;
3127 }
3128
3129 /*
3130 * The following is a gross hack needed to properly support colormaps
3131 * under Windows. Before the pixels can be copied to the pixmap,
3132 * the relevent colormap must be associated with the drawable.
3133 * Normally we can infer this association from the window that
3134 * was used to create the pixmap. However, in this case we're
3135 * using the root window, so we have to be more explicit.
3136 */
3137
3138 TkSetPixmapColormap(newPixmap, instancePtr->colormap);
3139
3140 if (instancePtr->pixels != None) {
3141 /*
3142 * Copy any common pixels from the old pixmap and free it.
3143 */
3144 XCopyArea(instancePtr->display, instancePtr->pixels, newPixmap,
3145 instancePtr->gc, validBox.x, validBox.y,
3146 validBox.width, validBox.height, validBox.x, validBox.y);
3147 Tk_FreePixmap(instancePtr->display, instancePtr->pixels);
3148 }
3149 instancePtr->pixels = newPixmap;
3150 }
3151
3152 if ((instancePtr->width != masterPtr->width)
3153 || (instancePtr->height != masterPtr->height)
3154 || (instancePtr->error == NULL)) {
3155
3156 if (masterPtr->height > 0 && masterPtr->width > 0) {
3157 newError = (schar *) ckalloc((unsigned)
3158 masterPtr->height * masterPtr->width * 3 * sizeof(schar));
3159
3160 /*
3161 * Zero the new array so that we don't get bogus error
3162 * values propagating into areas we dither later.
3163 */
3164
3165 if ((instancePtr->error != NULL)
3166 && ((instancePtr->width == masterPtr->width)
3167 || (validBox.width == masterPtr->width))) {
3168 if (validBox.y > 0) {
3169 memset((VOID *) newError, 0, (size_t)
3170 validBox.y * masterPtr->width * 3 * sizeof(schar));
3171 }
3172 h = validBox.y + validBox.height;
3173 if (h < masterPtr->height) {
3174 memset((VOID *) (newError + h * masterPtr->width * 3), 0,
3175 (size_t) (masterPtr->height - h)
3176 * masterPtr->width * 3 * sizeof(schar));
3177 }
3178 } else {
3179 memset((VOID *) newError, 0, (size_t)
3180 masterPtr->height * masterPtr->width * 3 * sizeof(schar));
3181 }
3182 } else {
3183 newError = NULL;
3184 }
3185
3186 if (instancePtr->error != NULL) {
3187
3188 /*
3189 * Copy the common area over to the new array
3190 * and free the old array.
3191 */
3192
3193 if (masterPtr->width == instancePtr->width) {
3194
3195 offset = validBox.y * masterPtr->width * 3;
3196 memcpy((VOID *) (newError + offset),
3197 (VOID *) (instancePtr->error + offset),
3198 (size_t) (validBox.height
3199 * masterPtr->width * 3 * sizeof(schar)));
3200
3201 } else if (validBox.width > 0 && validBox.height > 0) {
3202
3203 errDestPtr = newError
3204 + (validBox.y * masterPtr->width + validBox.x) * 3;
3205 errSrcPtr = instancePtr->error
3206 + (validBox.y * instancePtr->width + validBox.x) * 3;
3207 for (h = validBox.height; h > 0; --h) {
3208 memcpy((VOID *) errDestPtr, (VOID *) errSrcPtr,
3209 validBox.width * 3 * sizeof(schar));
3210 errDestPtr += masterPtr->width * 3;
3211 errSrcPtr += instancePtr->width * 3;
3212 }
3213 }
3214 ckfree((char *) instancePtr->error);
3215 }
3216
3217 instancePtr->error = newError;
3218 }
3219
3220 instancePtr->width = masterPtr->width;
3221 instancePtr->height = masterPtr->height;
3222 }
3223
3224 /*
3225 *----------------------------------------------------------------------
3226 *
3227 * IsValidPalette --
3228 *
3229 * This procedure is called to check whether a value given for
3230 * the -palette option is valid for a particular instance
3231 * of a photo image.
3232 *
3233 * Results:
3234 * A boolean value: 1 if the palette is acceptable, 0 otherwise.
3235 *
3236 * Side effects:
3237 * None.
3238 *
3239 *----------------------------------------------------------------------
3240 */
3241
3242 static int
3243 IsValidPalette(instancePtr, palette)
3244 PhotoInstance *instancePtr; /* Instance to which the palette
3245 * specification is to be applied. */
3246 CONST char *palette; /* Palette specification string. */
3247 {
3248 int nRed, nGreen, nBlue, mono, numColors;
3249 char *endp;
3250
3251 /*
3252 * First parse the specification: it must be of the form
3253 * %d or %d/%d/%d.
3254 */
3255
3256 nRed = strtol(palette, &endp, 10);
3257 if ((endp == palette) || ((*endp != 0) && (*endp != '/'))
3258 || (nRed < 2) || (nRed > 256)) {
3259 return 0;
3260 }
3261
3262 if (*endp == 0) {
3263 mono = 1;
3264 nGreen = nBlue = nRed;
3265 } else {
3266 palette = endp + 1;
3267 nGreen = strtol(palette, &endp, 10);
3268 if ((endp == palette) || (*endp != '/') || (nGreen < 2)
3269 || (nGreen > 256)) {
3270 return 0;
3271 }
3272 palette = endp + 1;
3273 nBlue = strtol(palette, &endp, 10);
3274 if ((endp == palette) || (*endp != 0) || (nBlue < 2)
3275 || (nBlue > 256)) {
3276 return 0;
3277 }
3278 mono = 0;
3279 }
3280
3281 switch (instancePtr->visualInfo.class) {
3282 case DirectColor:
3283 case TrueColor:
3284 if ((nRed > (1 << CountBits(instancePtr->visualInfo.red_mask)))
3285 || (nGreen > (1
3286 << CountBits(instancePtr->visualInfo.green_mask)))
3287 || (nBlue > (1
3288 << CountBits(instancePtr->visualInfo.blue_mask)))) {
3289 return 0;
3290 }
3291 break;
3292 case PseudoColor:
3293 case StaticColor:
3294 numColors = nRed;
3295 if (!mono) {
3296 numColors *= nGreen*nBlue;
3297 }
3298 if (numColors > (1 << instancePtr->visualInfo.depth)) {
3299 return 0;
3300 }
3301 break;
3302 case GrayScale:
3303 case StaticGray:
3304 if (!mono || (nRed > (1 << instancePtr->visualInfo.depth))) {
3305 return 0;
3306 }
3307 break;
3308 }
3309
3310 return 1;
3311 }
3312
3313 /*
3314 *----------------------------------------------------------------------
3315 *
3316 * CountBits --
3317 *
3318 * This procedure counts how many bits are set to 1 in `mask'.
3319 *
3320 * Results:
3321 * The integer number of bits.
3322 *
3323 * Side effects:
3324 * None.
3325 *
3326 *----------------------------------------------------------------------
3327 */
3328
3329 static int
3330 CountBits(mask)
3331 pixel mask; /* Value to count the 1 bits in. */
3332 {
3333 int n;
3334
3335 for( n = 0; mask != 0; mask &= mask - 1 )
3336 n++;
3337 return n;
3338 }
3339
3340 /*
3341 *----------------------------------------------------------------------
3342 *
3343 * GetColorTable --
3344 *
3345 * This procedure is called to allocate a table of colormap
3346 * information for an instance of a photo image. Only one such
3347 * table is allocated for all photo instances using the same
3348 * display, colormap, palette and gamma values, so that the
3349 * application need only request a set of colors from the X
3350 * server once for all such photo widgets. This procedure
3351 * maintains a hash table to find previously-allocated
3352 * ColorTables.
3353 *
3354 * Results:
3355 * None.
3356 *
3357 * Side effects:
3358 * A new ColorTable may be allocated and placed in the hash
3359 * table, and have colors allocated for it.
3360 *
3361 *----------------------------------------------------------------------
3362 */
3363
3364 static void
3365 GetColorTable(instancePtr)
3366 PhotoInstance *instancePtr; /* Instance needing a color table. */
3367 {
3368 ColorTable *colorPtr;
3369 Tcl_HashEntry *entry;
3370 ColorTableId id;
3371 int isNew;
3372
3373 /*
3374 * Look for an existing ColorTable in the hash table.
3375 */
3376
3377 memset((VOID *) &id, 0, sizeof(id));
3378 id.display = instancePtr->display;
3379 id.colormap = instancePtr->colormap;
3380 id.palette = instancePtr->palette;
3381 id.gamma = instancePtr->gamma;
3382 if (!imgPhotoColorHashInitialized) {
3383 Tcl_InitHashTable(&imgPhotoColorHash, N_COLOR_HASH);
3384 imgPhotoColorHashInitialized = 1;
3385 }
3386 entry = Tcl_CreateHashEntry(&imgPhotoColorHash, (char *) &id, &isNew);
3387
3388 if (!isNew) {
3389 /*
3390 * Re-use the existing entry.
3391 */
3392
3393 colorPtr = (ColorTable *) Tcl_GetHashValue(entry);
3394
3395 } else {
3396 /*
3397 * No color table currently available; need to make one.
3398 */
3399
3400 colorPtr = (ColorTable *) ckalloc(sizeof(ColorTable));
3401
3402 /*
3403 * The following line of code should not normally be needed due
3404 * to the assignment in the following line. However, it compensates
3405 * for bugs in some compilers (HP, for example) where
3406 * sizeof(ColorTable) is 24 but the assignment only copies 20 bytes,
3407 * leaving 4 bytes uninitialized; these cause problems when using
3408 * the id for lookups in imgPhotoColorHash, and can result in
3409 * core dumps.
3410 */
3411
3412 memset((VOID *) &colorPtr->id, 0, sizeof(ColorTableId));
3413 colorPtr->id = id;
3414 Tk_PreserveColormap(colorPtr->id.display, colorPtr->id.colormap);
3415 colorPtr->flags = 0;
3416 colorPtr->refCount = 0;
3417 colorPtr->liveRefCount = 0;
3418 colorPtr->numColors = 0;
3419 colorPtr->visualInfo = instancePtr->visualInfo;
3420 colorPtr->pixelMap = NULL;
3421 Tcl_SetHashValue(entry, colorPtr);
3422 }
3423
3424 colorPtr->refCount++;
3425 colorPtr->liveRefCount++;
3426 instancePtr->colorTablePtr = colorPtr;
3427 if (colorPtr->flags & DISPOSE_PENDING) {
3428 Tcl_CancelIdleCall(DisposeColorTable, (ClientData) colorPtr);
3429 colorPtr->flags &= ~DISPOSE_PENDING;
3430 }
3431
3432 /*
3433 * Allocate colors for this color table if necessary.
3434 */
3435
3436 if ((colorPtr->numColors == 0)
3437 && ((colorPtr->flags & BLACK_AND_WHITE) == 0)) {
3438 AllocateColors(colorPtr);
3439 }
3440 }
3441
3442 /*
3443 *----------------------------------------------------------------------
3444 *
3445 * FreeColorTable --
3446 *
3447 * This procedure is called when an instance ceases using a
3448 * color table.
3449 *
3450 * Results:
3451 * None.
3452 *
3453 * Side effects:
3454 * If no other instances are using this color table, a when-idle
3455 * handler is registered to free up the color table and the colors
3456 * allocated for it.
3457 *
3458 *----------------------------------------------------------------------
3459 */
3460
3461 static void
3462 FreeColorTable(colorPtr, force)
3463 ColorTable *colorPtr; /* Pointer to the color table which is
3464 * no longer required by an instance. */
3465 int force; /* Force free to happen immediately. */
3466 {
3467 colorPtr->refCount--;
3468 if (colorPtr->refCount > 0) {
3469 return;
3470 }
3471 if (force) {
3472 if ((colorPtr->flags & DISPOSE_PENDING) != 0) {
3473 Tcl_CancelIdleCall(DisposeColorTable, (ClientData) colorPtr);
3474 colorPtr->flags &= ~DISPOSE_PENDING;
3475 }
3476 DisposeColorTable((ClientData) colorPtr);
3477 } else if ((colorPtr->flags & DISPOSE_PENDING) == 0) {
3478 Tcl_DoWhenIdle(DisposeColorTable, (ClientData) colorPtr);
3479 colorPtr->flags |= DISPOSE_PENDING;
3480 }
3481 }
3482
3483 /*
3484 *----------------------------------------------------------------------
3485 *
3486 * AllocateColors --
3487 *
3488 * This procedure allocates the colors required by a color table,
3489 * and sets up the fields in the color table data structure which
3490 * are used in dithering.
3491 *
3492 * Results:
3493 * None.
3494 *
3495 * Side effects:
3496 * Colors are allocated from the X server. Fields in the
3497 * color table data structure are updated.
3498 *
3499 *----------------------------------------------------------------------
3500 */
3501
3502 static void
3503 AllocateColors(colorPtr)
3504 ColorTable *colorPtr; /* Pointer to the color table requiring
3505 * colors to be allocated. */
3506 {
3507 int i, r, g, b, rMult, mono;
3508 int numColors, nRed, nGreen, nBlue;
3509 double fr, fg, fb, igam;
3510 XColor *colors;
3511 unsigned long *pixels;
3512
3513 /* 16-bit intensity value for i/n of full intensity. */
3514 # define CFRAC(i, n) ((i) * 65535 / (n))
3515
3516 /* As for CFRAC, but apply exponent of g. */
3517 # define CGFRAC(i, n, g) ((int)(65535 * pow((double)(i) / (n), (g))))
3518
3519 /*
3520 * First parse the palette specification to get the required number of
3521 * shades of each primary.
3522 */
3523
3524 mono = sscanf(colorPtr->id.palette, "%d/%d/%d", &nRed, &nGreen, &nBlue)
3525 <= 1;
3526 igam = 1.0 / colorPtr->id.gamma;
3527
3528 /*
3529 * Each time around this loop, we reduce the number of colors we're
3530 * trying to allocate until we succeed in allocating all of the colors
3531 * we need.
3532 */
3533
3534 for (;;) {
3535 /*
3536 * If we are using 1 bit/pixel, we don't need to allocate
3537 * any colors (we just use the foreground and background
3538 * colors in the GC).
3539 */
3540
3541 if (mono && (nRed <= 2)) {
3542 colorPtr->flags |= BLACK_AND_WHITE;
3543 return;
3544 }
3545
3546 /*
3547 * Calculate the RGB coordinates of the colors we want to
3548 * allocate and store them in *colors.
3549 */
3550
3551 if ((colorPtr->visualInfo.class == DirectColor)
3552 || (colorPtr->visualInfo.class == TrueColor)) {
3553
3554 /*
3555 * Direct/True Color: allocate shades of red, green, blue
3556 * independently.
3557 */
3558
3559 if (mono) {
3560 numColors = nGreen = nBlue = nRed;
3561 } else {
3562 numColors = MAX(MAX(nRed, nGreen), nBlue);
3563 }
3564 colors = (XColor *) ckalloc(numColors * sizeof(XColor));
3565
3566 for (i = 0; i < numColors; ++i) {
3567 if (igam == 1.0) {
3568 colors[i].red = CFRAC(i, nRed - 1);
3569 colors[i].green = CFRAC(i, nGreen - 1);
3570 colors[i].blue = CFRAC(i, nBlue - 1);
3571 } else {
3572 colors[i].red = CGFRAC(i, nRed - 1, igam);
3573 colors[i].green = CGFRAC(i, nGreen - 1, igam);
3574 colors[i].blue = CGFRAC(i, nBlue - 1, igam);
3575 }
3576 }
3577 } else {
3578 /*
3579 * PseudoColor, StaticColor, GrayScale or StaticGray visual:
3580 * we have to allocate each color in the color cube separately.
3581 */
3582
3583 numColors = (mono) ? nRed: (nRed * nGreen * nBlue);
3584 colors = (XColor *) ckalloc(numColors * sizeof(XColor));
3585
3586 if (!mono) {
3587 /*
3588 * Color display using a PseudoColor or StaticColor visual.
3589 */
3590
3591 i = 0;
3592 for (r = 0; r < nRed; ++r) {
3593 for (g = 0; g < nGreen; ++g) {
3594 for (b = 0; b < nBlue; ++b) {
3595 if (igam == 1.0) {
3596 colors[i].red = CFRAC(r, nRed - 1);
3597 colors[i].green = CFRAC(g, nGreen - 1);
3598 colors[i].blue = CFRAC(b, nBlue - 1);
3599 } else {
3600 colors[i].red = CGFRAC(r, nRed - 1, igam);
3601 colors[i].green = CGFRAC(g, nGreen - 1, igam);
3602 colors[i].blue = CGFRAC(b, nBlue - 1, igam);
3603 }
3604 i++;
3605 }
3606 }
3607 }
3608 } else {
3609 /*
3610 * Monochrome display - allocate the shades of grey we want.
3611 */
3612
3613 for (i = 0; i < numColors; ++i) {
3614 if (igam == 1.0) {
3615 r = CFRAC(i, numColors - 1);
3616 } else {
3617 r = CGFRAC(i, numColors - 1, igam);
3618 }
3619 colors[i].red = colors[i].green = colors[i].blue = r;
3620 }
3621 }
3622 }
3623
3624 /*
3625 * Now try to allocate the colors we've calculated.
3626 */
3627
3628 pixels = (unsigned long *) ckalloc(numColors * sizeof(unsigned long));
3629 for (i = 0; i < numColors; ++i) {
3630 if (!XAllocColor(colorPtr->id.display, colorPtr->id.colormap,
3631 &colors[i])) {
3632
3633 /*
3634 * Can't get all the colors we want in the default colormap;
3635 * first try freeing colors from other unused color tables.
3636 */
3637
3638 if (!ReclaimColors(&colorPtr->id, numColors - i)
3639 || !XAllocColor(colorPtr->id.display,
3640 colorPtr->id.colormap, &colors[i])) {
3641 /*
3642 * Still can't allocate the color.
3643 */
3644 break;
3645 }
3646 }
3647 pixels[i] = colors[i].pixel;
3648 }
3649
3650 /*
3651 * If we didn't get all of the colors, reduce the
3652 * resolution of the color cube, free the ones we got,
3653 * and try again.
3654 */
3655
3656 if (i >= numColors) {
3657 break;
3658 }
3659 XFreeColors(colorPtr->id.display, colorPtr->id.colormap, pixels, i, 0);
3660 ckfree((char *) colors);
3661 ckfree((char *) pixels);
3662
3663 if (!mono) {
3664 if ((nRed == 2) && (nGreen == 2) && (nBlue == 2)) {
3665 /*
3666 * Fall back to 1-bit monochrome display.
3667 */
3668
3669 mono = 1;
3670 } else {
3671 /*
3672 * Reduce the number of shades of each primary to about
3673 * 3/4 of the previous value. This should reduce the
3674 * total number of colors required to about half the
3675 * previous value for PseudoColor displays.
3676 */
3677
3678 nRed = (nRed * 3 + 2) / 4;
3679 nGreen = (nGreen * 3 + 2) / 4;
3680 nBlue = (nBlue * 3 + 2) / 4;
3681 }
3682 } else {
3683 /*
3684 * Reduce the number of shades of gray to about 1/2.
3685 */
3686
3687 nRed = nRed / 2;
3688 }
3689 }
3690
3691 /*
3692 * We have allocated all of the necessary colors:
3693 * fill in various fields of the ColorTable record.
3694 */
3695
3696 if (!mono) {
3697 colorPtr->flags |= COLOR_WINDOW;
3698
3699 /*
3700 * The following is a hairy hack. We only want to index into
3701 * the pixelMap on colormap displays. However, if the display
3702 * is on Windows, then we actually want to store the index not
3703 * the value since we will be passing the color table into the
3704 * TkPutImage call.
3705 */
3706
3707 #ifndef __WIN32__
3708 if ((colorPtr->visualInfo.class != DirectColor)
3709 && (colorPtr->visualInfo.class != TrueColor)) {
3710 colorPtr->flags |= MAP_COLORS;
3711 }
3712 #endif /* __WIN32__ */
3713 }
3714
3715 colorPtr->numColors = numColors;
3716 colorPtr->pixelMap = pixels;
3717
3718 /*
3719 * Set up quantization tables for dithering.
3720 */
3721 rMult = nGreen * nBlue;
3722 for (i = 0; i < 256; ++i) {
3723 r = (i * (nRed - 1) + 127) / 255;
3724 if (mono) {
3725 fr = (double) colors[r].red / 65535.0;
3726 if (colorPtr->id.gamma != 1.0 ) {
3727 fr = pow(fr, colorPtr->id.gamma);
3728 }
3729 colorPtr->colorQuant[0][i] = (int)(fr * 255.99);
3730 colorPtr->redValues[i] = colors[r].pixel;
3731 } else {
3732 g = (i * (nGreen - 1) + 127) / 255;
3733 b = (i * (nBlue - 1) + 127) / 255;
3734 if ((colorPtr->visualInfo.class == DirectColor)
3735 || (colorPtr->visualInfo.class == TrueColor)) {
3736 colorPtr->redValues[i] = colors[r].pixel
3737 & colorPtr->visualInfo.red_mask;
3738 colorPtr->greenValues[i] = colors[g].pixel
3739 & colorPtr->visualInfo.green_mask;
3740 colorPtr->blueValues[i] = colors[b].pixel
3741 & colorPtr->visualInfo.blue_mask;
3742 } else {
3743 r *= rMult;
3744 g *= nBlue;
3745 colorPtr->redValues[i] = r;
3746 colorPtr->greenValues[i] = g;
3747 colorPtr->blueValues[i] = b;
3748 }
3749 fr = (double) colors[r].red / 65535.0;
3750 fg = (double) colors[g].green / 65535.0;
3751 fb = (double) colors[b].blue / 65535.0;
3752 if (colorPtr->id.gamma != 1.0) {
3753 fr = pow(fr, colorPtr->id.gamma);
3754 fg = pow(fg, colorPtr->id.gamma);
3755 fb = pow(fb, colorPtr->id.gamma);
3756 }
3757 colorPtr->colorQuant[0][i] = (int)(fr * 255.99);
3758 colorPtr->colorQuant[1][i] = (int)(fg * 255.99);
3759 colorPtr->colorQuant[2][i] = (int)(fb * 255.99);
3760 }
3761 }
3762
3763 ckfree((char *) colors);
3764 }
3765
3766 /*
3767 *----------------------------------------------------------------------
3768 *
3769 * DisposeColorTable --
3770 *
3771 *
3772 * Results:
3773 * None.
3774 *
3775 * Side effects:
3776 * The colors in the argument color table are freed, as is the
3777 * color table structure itself. The color table is removed
3778 * from the hash table which is used to locate color tables.
3779 *
3780 *----------------------------------------------------------------------
3781 */
3782
3783 static void
3784 DisposeColorTable(clientData)
3785 ClientData clientData; /* Pointer to the ColorTable whose
3786 * colors are to be released. */
3787 {
3788 ColorTable *colorPtr;
3789 Tcl_HashEntry *entry;
3790
3791 colorPtr = (ColorTable *) clientData;
3792 if (colorPtr->pixelMap != NULL) {
3793 if (colorPtr->numColors > 0) {
3794 XFreeColors(colorPtr->id.display, colorPtr->id.colormap,
3795 colorPtr->pixelMap, colorPtr->numColors, 0);
3796 Tk_FreeColormap(colorPtr->id.display, colorPtr->id.colormap);
3797 }
3798 ckfree((char *) colorPtr->pixelMap);
3799 }
3800
3801 entry = Tcl_FindHashEntry(&imgPhotoColorHash, (char *) &colorPtr->id);
3802 if (entry == NULL) {
3803 panic("DisposeColorTable couldn't find hash entry");
3804 }
3805 Tcl_DeleteHashEntry(entry);
3806
3807 ckfree((char *) colorPtr);
3808 }
3809
3810 /*
3811 *----------------------------------------------------------------------
3812 *
3813 * ReclaimColors --
3814 *
3815 * This procedure is called to try to free up colors in the
3816 * colormap used by a color table. It looks for other color
3817 * tables with the same colormap and with a zero live reference
3818 * count, and frees their colors. It only does so if there is
3819 * the possibility of freeing up at least `numColors' colors.
3820 *
3821 * Results:
3822 * The return value is TRUE if any colors were freed, FALSE
3823 * otherwise.
3824 *
3825 * Side effects:
3826 * ColorTables which are not currently in use may lose their
3827 * color allocations.
3828 *
3829 *---------------------------------------------------------------------- */
3830
3831 static int
3832 ReclaimColors(id, numColors)
3833 ColorTableId *id; /* Pointer to information identifying
3834 * the color table which needs more colors. */
3835 int numColors; /* Number of colors required. */
3836 {
3837 Tcl_HashSearch srch;
3838 Tcl_HashEntry *entry;
3839 ColorTable *colorPtr;
3840 int nAvail;
3841
3842 /*
3843 * First scan through the color hash table to get an
3844 * upper bound on how many colors we might be able to free.
3845 */
3846
3847 nAvail = 0;
3848 entry = Tcl_FirstHashEntry(&imgPhotoColorHash, &srch);
3849 while (entry != NULL) {
3850 colorPtr = (ColorTable *) Tcl_GetHashValue(entry);
3851 if ((colorPtr->id.display == id->display)
3852 && (colorPtr->id.colormap == id->colormap)
3853 && (colorPtr->liveRefCount == 0 )&& (colorPtr->numColors != 0)
3854 && ((colorPtr->id.palette != id->palette)
3855 || (colorPtr->id.gamma != id->gamma))) {
3856
3857 /*
3858 * We could take this guy's colors off him.
3859 */
3860
3861 nAvail += colorPtr->numColors;
3862 }
3863 entry = Tcl_NextHashEntry(&srch);
3864 }
3865
3866 /*
3867 * nAvail is an (over)estimate of the number of colors we could free.
3868 */
3869
3870 if (nAvail < numColors) {
3871 return 0;
3872 }
3873
3874 /*
3875 * Scan through a second time freeing colors.
3876 */
3877
3878 entry = Tcl_FirstHashEntry(&imgPhotoColorHash, &srch);
3879 while ((entry != NULL) && (numColors > 0)) {
3880 colorPtr = (ColorTable *) Tcl_GetHashValue(entry);
3881 if ((colorPtr->id.display == id->display)
3882 && (colorPtr->id.colormap == id->colormap)
3883 && (colorPtr->liveRefCount == 0) && (colorPtr->numColors != 0)
3884 && ((colorPtr->id.palette != id->palette)
3885 || (colorPtr->id.gamma != id->gamma))) {
3886
3887 /*
3888 * Free the colors that this ColorTable has.
3889 */
3890
3891 XFreeColors(colorPtr->id.display, colorPtr->id.colormap,
3892 colorPtr->pixelMap, colorPtr->numColors, 0);
3893 numColors -= colorPtr->numColors;
3894 colorPtr->numColors = 0;
3895 ckfree((char *) colorPtr->pixelMap);
3896 colorPtr->pixelMap = NULL;
3897 }
3898
3899 entry = Tcl_NextHashEntry(&srch);
3900 }
3901 return 1; /* we freed some colors */
3902 }
3903
3904 /*
3905 *----------------------------------------------------------------------
3906 *
3907 * DisposeInstance --
3908 *
3909 * This procedure is called to finally free up an instance
3910 * of a photo image which is no longer required.
3911 *
3912 * Results:
3913 * None.
3914 *
3915 * Side effects:
3916 * The instance data structure and the resources it references
3917 * are freed.
3918 *
3919 *----------------------------------------------------------------------
3920 */
3921
3922 static void
3923 DisposeInstance(clientData)
3924 ClientData clientData; /* Pointer to the instance whose resources
3925 * are to be released. */
3926 {
3927 PhotoInstance *instancePtr = (PhotoInstance *) clientData;
3928 PhotoInstance *prevPtr;
3929
3930 if (instancePtr->pixels != None) {
3931 Tk_FreePixmap(instancePtr->display, instancePtr->pixels);
3932 }
3933 if (instancePtr->gc != None) {
3934 Tk_FreeGC(instancePtr->display, instancePtr->gc);
3935 }
3936 if (instancePtr->imagePtr != NULL) {
3937 XFree((char *) instancePtr->imagePtr);
3938 }
3939 if (instancePtr->error != NULL) {
3940 ckfree((char *) instancePtr->error);
3941 }
3942 if (instancePtr->colorTablePtr != NULL) {
3943 FreeColorTable(instancePtr->colorTablePtr, 1);
3944 }
3945
3946 if (instancePtr->masterPtr->instancePtr == instancePtr) {
3947 instancePtr->masterPtr->instancePtr = instancePtr->nextPtr;
3948 } else {
3949 for (prevPtr = instancePtr->masterPtr->instancePtr;
3950 prevPtr->nextPtr != instancePtr; prevPtr = prevPtr->nextPtr) {
3951 /* Empty loop body */
3952 }
3953 prevPtr->nextPtr = instancePtr->nextPtr;
3954 }
3955 Tk_FreeColormap(instancePtr->display, instancePtr->colormap);
3956 ckfree((char *) instancePtr);
3957 }
3958
3959 /*
3960 *----------------------------------------------------------------------
3961 *
3962 * MatchFileFormat --
3963 *
3964 * This procedure is called to find a photo image file format
3965 * handler which can parse the image data in the given file.
3966 * If a user-specified format string is provided, only handlers
3967 * whose names match a prefix of the format string are tried.
3968 *
3969 * Results:
3970 * A standard TCL return value. If the return value is TCL_OK, a
3971 * pointer to the image format record is returned in
3972 * *imageFormatPtr, and the width and height of the image are
3973 * returned in *widthPtr and *heightPtr.
3974 *
3975 * Side effects:
3976 * None.
3977 *
3978 *----------------------------------------------------------------------
3979 */
3980
3981 char *
3982 Tk_PhotoFormatName(interp, formatString)
3983 Tcl_Interp *interp; /* Interpreter to use for reporting errors. */
3984 Tcl_Obj * formatString; /* User-specified format string, or NULL. */
3985 {
3986 int objc = 0;
3987 Tcl_Obj **objv;
3988 if (formatString != NULL &&
3989 Tcl_ListObjGetElements(interp, formatString, &objc, &objv) == TCL_OK &&
3990 objc != 0) {
3991 return Tcl_GetString(objv[0]);
3992 }
3993 return NULL;
3994 }
3995
3996 static int
3997 MatchFileFormat(interp, chan, fileName, formatObj, imageFormatPtr,
3998 widthPtr, heightPtr, oldformat)
3999 Tcl_Interp *interp; /* Interpreter to use for reporting errors. */
4000 Tcl_Channel chan; /* The image file, open for reading. */
4001 Tcl_Obj *fileName; /* The name of the image file. */
4002 Tcl_Obj *formatObj; /* User-specified format string, or NULL. */
4003 Tk_PhotoImageFormat **imageFormatPtr;
4004 /* A pointer to the photo image format
4005 * record is returned here. */
4006 int *widthPtr, *heightPtr; /* The dimensions of the image are
4007 * returned here. */
4008 int *oldformat;
4009 {
4010 int matched;
4011 int useoldformat = 0;
4012 Tk_PhotoImageFormat *formatPtr;
4013 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
4014 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
4015 char *formatString = NULL;
4016
4017 if (formatObj) {
4018 formatString = Tk_PhotoFormatName(interp, formatObj);
4019 }
4020
4021 /*
4022 * Scan through the table of file format handlers to find
4023 * one which can handle the image.
4024 */
4025
4026 matched = 0;
4027 for (formatPtr = tsdPtr->formatList; formatPtr != NULL;
4028 formatPtr = formatPtr->nextPtr) {
4029 if (formatObj != NULL) {
4030 if (strncasecmp(formatString,
4031 formatPtr->name, strlen(formatPtr->name)) != 0) {
4032 continue;
4033 }
4034 matched = 1;
4035 if (formatPtr->fileMatchProc == NULL) {
4036 Tcl_AppendResult(interp, "-file option isn't supported for ",
4037 formatPtr->name, " images", (char *) NULL);
4038 return TCL_ERROR;
4039 }
4040 }
4041 if (formatPtr->fileMatchProc != NULL) {
4042 (void) Tcl_Seek(chan, Tcl_LongAsWide(0L), SEEK_SET);
4043 if ((*formatPtr->fileMatchProc)(chan, fileName, formatObj,
4044 widthPtr, heightPtr, interp)) {
4045 if (*widthPtr < 1) {
4046 *widthPtr = 1;
4047 }
4048 if (*heightPtr < 1) {
4049 *heightPtr = 1;
4050 }
4051 break;
4052 }
4053 }
4054 }
4055 if (formatPtr == NULL) {
4056 useoldformat = 1;
4057 for (formatPtr = tsdPtr->oldFormatList; formatPtr != NULL;
4058 formatPtr = formatPtr->nextPtr) {
4059 if (formatString != NULL) {
4060 if (strncasecmp(formatString,
4061 formatPtr->name, strlen(formatPtr->name)) != 0) {
4062 continue;
4063 }
4064 matched = 1;
4065 if (formatPtr->fileMatchProc == NULL) {
4066 Tcl_AppendResult(interp, "-file option isn't supported",
4067 " for ", formatString, " images", (char *) NULL);
4068 return TCL_ERROR;
4069 }
4070 }
4071 if (formatPtr->fileMatchProc != NULL) {
4072 (void) Tcl_Seek(chan, Tcl_LongAsWide(0L), SEEK_SET);
4073 if ((*formatPtr->fileMatchProc)(chan, fileName, (Tcl_Obj *)
4074 formatString, widthPtr, heightPtr, interp)) {
4075 if (*widthPtr < 1) {
4076 *widthPtr = 1;
4077 }
4078 if (*heightPtr < 1) {
4079 *heightPtr = 1;
4080 }
4081 break;
4082 }
4083 }
4084 }
4085 }
4086
4087 if (formatPtr == NULL) {
4088 if ((formatObj != NULL) && !matched) {
4089 Tcl_AppendResult(interp, "image file format \"",
4090 formatString,
4091 "\" is not supported", (char *) NULL);
4092 } else {
4093 Tcl_AppendResult(interp,
4094 "couldn't recognize data in image file \"",
4095 Tcl_GetString(fileName), "\"", (char *) NULL);
4096 }
4097 return TCL_ERROR;
4098 }
4099
4100 *imageFormatPtr = formatPtr;
4101 *oldformat = useoldformat;
4102 (void) Tcl_Seek(chan, Tcl_LongAsWide(0L), SEEK_SET);
4103 return TCL_OK;
4104 }
4105
4106 /*
4107 *----------------------------------------------------------------------
4108 *
4109 * MatchStringFormat --
4110 *
4111 * This procedure is called to find a photo image file format
4112 * handler which can parse the image data in the given string.
4113 * If a user-specified format string is provided, only handlers
4114 * whose names match a prefix of the format string are tried.
4115 *
4116 * Results:
4117 * A standard TCL return value. If the return value is TCL_OK, a
4118 * pointer to the image format record is returned in
4119 * *imageFormatPtr, and the width and height of the image are
4120 * returned in *widthPtr and *heightPtr.
4121 *
4122 * Side effects:
4123 * None.
4124 *
4125 *----------------------------------------------------------------------
4126 */
4127
4128 static int
4129 MatchStringFormat(interp, data, formatObj, imageFormatPtr,
4130 widthPtr, heightPtr, oldformat)
4131 Tcl_Interp *interp; /* Interpreter to use for reporting errors. */
4132 Tcl_Obj *data; /* Object containing the image data. */
4133 Tcl_Obj *formatObj; /* User-specified format string, or NULL. */
4134 Tk_PhotoImageFormat **imageFormatPtr;
4135 /* A pointer to the photo image format
4136 * record is returned here. */
4137 int *widthPtr, *heightPtr; /* The dimensions of the image are
4138 * returned here. */
4139 int *oldformat; /* returns 1 if the old image API is used */
4140 {
4141 int matched;
4142 int useoldformat = 0;
4143 Tk_PhotoImageFormat *formatPtr;
4144 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
4145 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
4146 char *formatString = NULL;
4147
4148 if (formatObj) {
4149 formatString = Tcl_GetString(formatObj);
4150 }
4151
4152 /*
4153 * Scan through the table of file format handlers to find
4154 * one which can handle the image.
4155 */
4156
4157 matched = 0;
4158 for (formatPtr = tsdPtr->formatList; formatPtr != NULL;
4159 formatPtr = formatPtr->nextPtr) {
4160 if (formatObj != NULL) {
4161 if (strncasecmp(formatString,
4162 formatPtr->name, strlen(formatPtr->name)) != 0) {
4163 continue;
4164 }
4165 matched = 1;
4166 if (formatPtr->stringMatchProc == NULL) {
4167 Tcl_AppendResult(interp, "-data option isn't supported for ",
4168 formatPtr->name, " images", (char *) NULL);
4169 return TCL_ERROR;
4170 }
4171 }
4172 if ((formatPtr->stringMatchProc != NULL)
4173 && (formatPtr->stringReadProc != NULL)
4174 && (*formatPtr->stringMatchProc)(data, formatObj,
4175 widthPtr, heightPtr, interp)) {
4176 break;
4177 }
4178 }
4179
4180 if (formatPtr == NULL) {
4181 useoldformat = 1;
4182 for (formatPtr = tsdPtr->oldFormatList; formatPtr != NULL;
4183 formatPtr = formatPtr->nextPtr) {
4184 if (formatObj != NULL) {
4185 if (strncasecmp(formatString,
4186 formatPtr->name, strlen(formatPtr->name)) != 0) {
4187 continue;
4188 }
4189 matched = 1;
4190 if (formatPtr->stringMatchProc == NULL) {
4191 Tcl_AppendResult(interp, "-data option isn't supported",
4192 " for ", formatString, " images", (char *) NULL);
4193 return TCL_ERROR;
4194 }
4195 }
4196 if ((formatPtr->stringMatchProc != NULL)
4197 && (formatPtr->stringReadProc != NULL)
4198 && (*formatPtr->stringMatchProc)(
4199 (Tcl_Obj *) Tcl_GetString(data),
4200 (Tcl_Obj *) formatString,
4201 widthPtr, heightPtr, interp)) {
4202 break;
4203 }
4204 }
4205 }
4206 if (formatPtr == NULL) {
4207 if ((formatObj != NULL) && !matched) {
4208 Tcl_AppendResult(interp, "image format \"", formatString,
4209 "\" is not supported", (char *) NULL);
4210 } else {
4211 Tcl_AppendResult(interp, "couldn't recognize image data",
4212 (char *) NULL);
4213 }
4214 return TCL_ERROR;
4215 }
4216
4217 *imageFormatPtr = formatPtr;
4218 *oldformat = useoldformat;
4219 return TCL_OK;
4220 }
4221
4222 /*
4223 *----------------------------------------------------------------------
4224 *
4225 * Tk_FindPhoto --
4226 *
4227 * This procedure is called to get an opaque handle (actually a
4228 * PhotoMaster *) for a given image, which can be used in
4229 * subsequent calls to Tk_PhotoPutBlock, etc. The `name'
4230 * parameter is the name of the image.
4231 *
4232 * Results:
4233 * The handle for the photo image, or NULL if there is no
4234 * photo image with the name given.
4235 *
4236 * Side effects:
4237 * None.
4238 *
4239 *----------------------------------------------------------------------
4240 */
4241
4242 Tk_PhotoHandle
4243 Tk_FindPhoto(interp, imageName)
4244 Tcl_Interp *interp; /* Interpreter (application) in which image
4245 * exists. */
4246 CONST char *imageName; /* Name of the desired photo image. */
4247 {
4248 ClientData clientData;
4249 Tk_ImageType *typePtr;
4250
4251 clientData = Tk_GetImageMasterData(interp, imageName, &typePtr);
4252 if (typePtr != &tkPhotoImageType) {
4253 return NULL;
4254 }
4255 return (Tk_PhotoHandle) clientData;
4256 }
4257
4258 /*
4259 *----------------------------------------------------------------------
4260 *
4261 * Tk_PhotoPutBlock --
4262 *
4263 * This procedure is called to put image data into a photo image.
4264 *
4265 * Results:
4266 * None.
4267 *
4268 * Side effects:
4269 * The image data is stored. The image may be expanded.
4270 * The Tk image code is informed that the image has changed.
4271 *
4272 *---------------------------------------------------------------------- */
4273
4274 void
4275 Tk_PhotoPutBlock(handle, blockPtr, x, y, width, height, compRule)
4276 Tk_PhotoHandle handle; /* Opaque handle for the photo image
4277 * to be updated. */
4278 register Tk_PhotoImageBlock *blockPtr;
4279 /* Pointer to a structure describing the
4280 * pixel data to be copied into the image. */
4281 int x, y; /* Coordinates of the top-left pixel to
4282 * be updated in the image. */
4283 int width, height; /* Dimensions of the area of the image
4284 * to be updated. */
4285 int compRule; /* Compositing rule to use when processing
4286 * transparent pixels. */
4287 {
4288 register PhotoMaster *masterPtr;
4289 int xEnd, yEnd;
4290 int greenOffset, blueOffset, alphaOffset;
4291 int wLeft, hLeft;
4292 int wCopy, hCopy;
4293 unsigned char *srcPtr, *srcLinePtr;
4294 unsigned char *destPtr, *destLinePtr;
4295 int pitch;
4296 XRectangle rect;
4297
4298 masterPtr = (PhotoMaster *) handle;
4299
4300 if ((masterPtr->userWidth != 0) && ((x + width) > masterPtr->userWidth)) {
4301 width = masterPtr->userWidth - x;
4302 }
4303 if ((masterPtr->userHeight != 0)
4304 && ((y + height) > masterPtr->userHeight)) {
4305 height = masterPtr->userHeight - y;
4306 }
4307 if ((width <= 0) || (height <= 0)) {
4308 return;
4309 }
4310
4311 xEnd = x + width;
4312 yEnd = y + height;
4313 if ((xEnd > masterPtr->width) || (yEnd > masterPtr->height)) {
4314 if (ImgPhotoSetSize(masterPtr, MAX(xEnd, masterPtr->width),
4315 MAX(yEnd, masterPtr->height)) == TCL_ERROR) {
4316 panic(TK_PHOTO_ALLOC_FAILURE_MESSAGE);
4317 }
4318 }
4319
4320 if ((y < masterPtr->ditherY) || ((y == masterPtr->ditherY)
4321 && (x < masterPtr->ditherX))) {
4322 /*
4323 * The dithering isn't correct past the start of this block.
4324 */
4325 masterPtr->ditherX = x;
4326 masterPtr->ditherY = y;
4327 }
4328
4329 /*
4330 * If this image block could have different red, green and blue
4331 * components, mark it as a color image.
4332 */
4333
4334 greenOffset = blockPtr->offset[1] - blockPtr->offset[0];
4335 blueOffset = blockPtr->offset[2] - blockPtr->offset[0];
4336 alphaOffset = blockPtr->offset[3];
4337 if ((alphaOffset >= blockPtr->pixelSize) || (alphaOffset < 0)) {
4338 alphaOffset = 0;
4339 } else {
4340 alphaOffset -= blockPtr->offset[0];
4341 }
4342 if ((greenOffset != 0) || (blueOffset != 0)) {
4343 masterPtr->flags |= COLOR_IMAGE;
4344 }
4345
4346 /*
4347 * Copy the data into our local 32-bit/pixel array.
4348 * If we can do it with a single memcpy, we do.
4349 */
4350
4351 destLinePtr = masterPtr->pix32 + (y * masterPtr->width + x) * 4;
4352 pitch = masterPtr->width * 4;
4353
4354 /*
4355 * This test is probably too restrictive. We should also be able to
4356 * do a memcpy if pixelSize == 3 and alphaOffset == 0. Maybe other cases
4357 * too.
4358 */
4359 if ((blockPtr->pixelSize == 4)
4360 && (greenOffset == 1) && (blueOffset == 2) && (alphaOffset == 3)
4361 && (width <= blockPtr->width) && (height <= blockPtr->height)
4362 && ((height == 1) || ((x == 0) && (width == masterPtr->width)
4363 && (blockPtr->pitch == pitch)))
4364 && (compRule == TK_PHOTO_COMPOSITE_SET)) {
4365 memcpy((VOID *) destLinePtr,
4366 (VOID *) (blockPtr->pixelPtr + blockPtr->offset[0]),
4367 (size_t) (height * width * 4));
4368 } else {
4369 int alpha;
4370 for (hLeft = height; hLeft > 0;) {
4371 srcLinePtr = blockPtr->pixelPtr + blockPtr->offset[0];
4372 hCopy = MIN(hLeft, blockPtr->height);
4373 hLeft -= hCopy;
4374 for (; hCopy > 0; --hCopy) {
4375 if ((blockPtr->pixelSize == 4) && (greenOffset == 1)
4376 && (blueOffset == 2) && (alphaOffset == 3)
4377 && (width <= blockPtr->width)
4378 && (compRule == TK_PHOTO_COMPOSITE_SET)) {
4379 memcpy((VOID *) destLinePtr, (VOID *) srcLinePtr,
4380 (size_t) (width * 4));
4381 } else {
4382 destPtr = destLinePtr;
4383 for (wLeft = width; wLeft > 0;) {
4384 wCopy = MIN(wLeft, blockPtr->width);
4385 wLeft -= wCopy;
4386 srcPtr = srcLinePtr;
4387 for (; wCopy > 0; --wCopy) {
4388 alpha = srcPtr[alphaOffset];
4389 /*
4390 * In the easy case, we can just copy.
4391 */
4392 if (!alphaOffset || (alpha == 255)) {
4393 /* new solid part of the image */
4394 *destPtr++ = srcPtr[0];
4395 *destPtr++ = srcPtr[greenOffset];
4396 *destPtr++ = srcPtr[blueOffset];
4397 *destPtr++ = 255;
4398 srcPtr += blockPtr->pixelSize;
4399 continue;
4400 }
4401
4402 /*
4403 * Combine according to the compositing rule.
4404 */
4405 switch (compRule) {
4406 case TK_PHOTO_COMPOSITE_SET:
4407 *destPtr++ = srcPtr[0];
4408 *destPtr++ = srcPtr[greenOffset];
4409 *destPtr++ = srcPtr[blueOffset];
4410 *destPtr++ = alpha;
4411 break;
4412
4413 case TK_PHOTO_COMPOSITE_OVERLAY:
4414 if (!destPtr[3]) {
4415 /*
4416 * There must be a better way to select a
4417 * background colour!
4418 */
4419 destPtr[0] = destPtr[1] = destPtr[2] = 0xd9;
4420 }
4421
4422 if (alpha) {
4423 destPtr[0] += (srcPtr[0] - destPtr[0]) * alpha / 255;
4424 destPtr[1] += (srcPtr[greenOffset] - destPtr[1]) * alpha / 255;
4425 destPtr[2] += (srcPtr[blueOffset] - destPtr[2]) * alpha / 255;
4426 destPtr[3] += (255 - destPtr[3]) * alpha / 255;
4427 }
4428 /*
4429 * else should be empty space
4430 */
4431 destPtr += 4;
4432 break;
4433
4434 default:
4435 panic("unknown compositing rule: %d", compRule);
4436 }
4437 srcPtr += blockPtr->pixelSize;
4438 }
4439 }
4440 }
4441 srcLinePtr += blockPtr->pitch;
4442 destLinePtr += pitch;
4443 }
4444 }
4445 }
4446
4447 /*
4448 * Add this new block to the region which specifies which data is valid.
4449 */
4450
4451 if (alphaOffset) {
4452 int x1, y1, end;
4453
4454 /*
4455 * This block is grossly inefficient. For each row in the image, it
4456 * finds each continguous string of nontransparent pixels, then marks
4457 * those areas as valid in the validRegion mask. This makes drawing
4458 * very efficient, because of the way we use X: we just say, here's
4459 * your mask, and here's your data. We need not worry about the
4460 * current background color, etc. But this costs us a lot on the
4461 * image setup. Still, image setup only happens once, whereas the
4462 * drawing happens many times, so this might be the best way to go.
4463 *
4464 * An alternative might be to not set up this mask, and instead, at
4465 * drawing time, for each transparent pixel, set its color to the
4466 * color of the background behind that pixel. This is what I suspect
4467 * most of programs do. However, they don't have to deal with the
4468 * canvas, which could have many different background colors.
4469 * Determining the correct bg color for a given pixel might be
4470 * expensive.
4471 */
4472
4473 if (compRule != TK_PHOTO_COMPOSITE_OVERLAY) {
4474 /*
4475 * Don't need this when using the OVERLAY compositing rule,
4476 * which always strictly increases the valid region.
4477 */
4478 TkRegion workRgn = TkCreateRegion();
4479
4480 rect.x = x;
4481 rect.y = y;
4482 rect.width = width;
4483 rect.height = height;
4484 TkUnionRectWithRegion(&rect, workRgn, workRgn);
4485 TkSubtractRegion(masterPtr->validRegion, workRgn,
4486 masterPtr->validRegion);
4487 TkDestroyRegion(workRgn);
4488 }
4489
4490 destLinePtr = masterPtr->pix32 + (y * masterPtr->width + x) * 4 + 3;
4491 for (y1 = 0; y1 < height; y1++) {
4492 x1 = 0;
4493 destPtr = destLinePtr;
4494 while (x1 < width) {
4495 /* search for first non-transparent pixel */
4496 while ((x1 < width) && !*destPtr) {
4497 x1++;
4498 destPtr += 4;
4499 }
4500 end = x1;
4501 /* search for first transparent pixel */
4502 while ((end < width) && *destPtr) {
4503 end++;
4504 destPtr += 4;
4505 }
4506 if (end > x1) {
4507 rect.x = x + x1;
4508 rect.y = y + y1;
4509 rect.width = end - x1;
4510 rect.height = 1;
4511 TkUnionRectWithRegion(&rect, masterPtr->validRegion,
4512 masterPtr->validRegion);
4513 }
4514 x1 = end;
4515 }
4516 destLinePtr += masterPtr->width * 4;
4517 }
4518 } else {
4519 rect.x = x;
4520 rect.y = y;
4521 rect.width = width;
4522 rect.height = height;
4523 TkUnionRectWithRegion(&rect, masterPtr->validRegion,
4524 masterPtr->validRegion);
4525 }
4526
4527 /*
4528 * Update each instance.
4529 */
4530
4531 Tk_DitherPhoto((Tk_PhotoHandle)masterPtr, x, y, width, height);
4532
4533 /*
4534 * Tell the core image code that this image has changed.
4535 */
4536
4537 Tk_ImageChanged(masterPtr->tkMaster, x, y, width, height, masterPtr->width,
4538 masterPtr->height);
4539 }
4540
4541 /*
4542 *----------------------------------------------------------------------
4543 *
4544 * Tk_PhotoPutZoomedBlock --
4545 *
4546 * This procedure is called to put image data into a photo image,
4547 * with possible subsampling and/or zooming of the pixels.
4548 *
4549 * Results:
4550 * None.
4551 *
4552 * Side effects:
4553 * The image data is stored. The image may be expanded.
4554 * The Tk image code is informed that the image has changed.
4555 *
4556 *----------------------------------------------------------------------
4557 */
4558
4559 void
4560 Tk_PhotoPutZoomedBlock(handle, blockPtr, x, y, width, height, zoomX, zoomY,
4561 subsampleX, subsampleY, compRule)
4562 Tk_PhotoHandle handle; /* Opaque handle for the photo image
4563 * to be updated. */
4564 register Tk_PhotoImageBlock *blockPtr;
4565 /* Pointer to a structure describing the
4566 * pixel data to be copied into the image. */
4567 int x, y; /* Coordinates of the top-left pixel to
4568 * be updated in the image. */
4569 int width, height; /* Dimensions of the area of the image
4570 * to be updated. */
4571 int zoomX, zoomY; /* Zoom factors for the X and Y axes. */
4572 int subsampleX, subsampleY; /* Subsampling factors for the X and Y axes. */
4573 int compRule; /* Compositing rule to use when processing
4574 * transparent pixels. */
4575 {
4576 register PhotoMaster *masterPtr;
4577 int xEnd, yEnd;
4578 int greenOffset, blueOffset, alphaOffset;
4579 int wLeft, hLeft;
4580 int wCopy, hCopy;
4581 int blockWid, blockHt;
4582 unsigned char *srcPtr, *srcLinePtr, *srcOrigPtr;
4583 unsigned char *destPtr, *destLinePtr;
4584 int pitch;
4585 int xRepeat, yRepeat;
4586 int blockXSkip, blockYSkip;
4587 XRectangle rect;
4588
4589 if (zoomX==1 && zoomY==1 && subsampleX==1 && subsampleY==1) {
4590 Tk_PhotoPutBlock(handle, blockPtr, x, y, width, height, compRule);
4591 return;
4592 }
4593
4594 masterPtr = (PhotoMaster *) handle;
4595
4596 if (zoomX <= 0 || zoomY <= 0) {
4597 return;
4598 }
4599 if ((masterPtr->userWidth != 0) && ((x + width) > masterPtr->userWidth)) {
4600 width = masterPtr->userWidth - x;
4601 }
4602 if ((masterPtr->userHeight != 0)
4603 && ((y + height) > masterPtr->userHeight)) {
4604 height = masterPtr->userHeight - y;
4605 }
4606 if (width <= 0 || height <= 0) {
4607 return;
4608 }
4609
4610 xEnd = x + width;
4611 yEnd = y + height;
4612 if ((xEnd > masterPtr->width) || (yEnd > masterPtr->height)) {
4613 int sameSrc = (blockPtr->pixelPtr == masterPtr->pix32);
4614 if (ImgPhotoSetSize(masterPtr, MAX(xEnd, masterPtr->width),
4615 MAX(yEnd, masterPtr->height)) == TCL_ERROR) {
4616 panic(TK_PHOTO_ALLOC_FAILURE_MESSAGE);
4617 }
4618 if (sameSrc) {
4619 blockPtr->pixelPtr = masterPtr->pix32;
4620 }
4621 }
4622
4623 if ((y < masterPtr->ditherY) || ((y == masterPtr->ditherY)
4624 && (x < masterPtr->ditherX))) {
4625 /*
4626 * The dithering isn't correct past the start of this block.
4627 */
4628
4629 masterPtr->ditherX = x;
4630 masterPtr->ditherY = y;
4631 }
4632
4633 /*
4634 * If this image block could have different red, green and blue
4635 * components, mark it as a color image.
4636 */
4637
4638 greenOffset = blockPtr->offset[1] - blockPtr->offset[0];
4639 blueOffset = blockPtr->offset[2] - blockPtr->offset[0];
4640 alphaOffset = blockPtr->offset[3];
4641 if ((alphaOffset >= blockPtr->pixelSize) || (alphaOffset < 0)) {
4642 alphaOffset = 0;
4643 } else {
4644 alphaOffset -= blockPtr->offset[0];
4645 }
4646 if ((greenOffset != 0) || (blueOffset != 0)) {
4647 masterPtr->flags |= COLOR_IMAGE;
4648 }
4649
4650 /*
4651 * Work out what area the pixel data in the block expands to after
4652 * subsampling and zooming.
4653 */
4654
4655 blockXSkip = subsampleX * blockPtr->pixelSize;
4656 blockYSkip = subsampleY * blockPtr->pitch;
4657 if (subsampleX > 0) {
4658 blockWid = ((blockPtr->width + subsampleX - 1) / subsampleX) * zoomX;
4659 } else if (subsampleX == 0) {
4660 blockWid = width;
4661 } else {
4662 blockWid = ((blockPtr->width - subsampleX - 1) / -subsampleX) * zoomX;
4663 }
4664 if (subsampleY > 0) {
4665 blockHt = ((blockPtr->height + subsampleY - 1) / subsampleY) * zoomY;
4666 } else if (subsampleY == 0) {
4667 blockHt = height;
4668 } else {
4669 blockHt = ((blockPtr->height - subsampleY - 1) / -subsampleY) * zoomY;
4670 }
4671
4672 /*
4673 * Copy the data into our local 32-bit/pixel array.
4674 */
4675
4676 destLinePtr = masterPtr->pix32 + (y * masterPtr->width + x) * 4;
4677 srcOrigPtr = blockPtr->pixelPtr + blockPtr->offset[0];
4678 if (subsampleX < 0) {
4679 srcOrigPtr += (blockPtr->width - 1) * blockPtr->pixelSize;
4680 }
4681 if (subsampleY < 0) {
4682 srcOrigPtr += (blockPtr->height - 1) * blockPtr->pitch;
4683 }
4684
4685 pitch = masterPtr->width * 4;
4686 for (hLeft = height; hLeft > 0; ) {
4687 hCopy = MIN(hLeft, blockHt);
4688 hLeft -= hCopy;
4689 yRepeat = zoomY;
4690 srcLinePtr = srcOrigPtr;
4691 for (; hCopy > 0; --hCopy) {
4692 destPtr = destLinePtr;
4693 for (wLeft = width; wLeft > 0;) {
4694 wCopy = MIN(wLeft, blockWid);
4695 wLeft -= wCopy;
4696 srcPtr = srcLinePtr;
4697 for (; wCopy > 0; wCopy -= zoomX) {
4698 for (xRepeat = MIN(wCopy, zoomX); xRepeat > 0; xRepeat--) {
4699 /*
4700 * Common case (solid pixels) first
4701 */
4702 if (!alphaOffset || (srcPtr[alphaOffset] == 255)) {
4703 *destPtr++ = srcPtr[0];
4704 *destPtr++ = srcPtr[greenOffset];
4705 *destPtr++ = srcPtr[blueOffset];
4706 *destPtr++ = 255;
4707 continue;
4708 }
4709
4710 switch (compRule) {
4711 case TK_PHOTO_COMPOSITE_SET:
4712 *destPtr++ = srcPtr[0];
4713 *destPtr++ = srcPtr[greenOffset];
4714 *destPtr++ = srcPtr[blueOffset];
4715 *destPtr++ = srcPtr[alphaOffset];
4716 break;
4717 case TK_PHOTO_COMPOSITE_OVERLAY:
4718 if (!destPtr[3]) {
4719 /*
4720 * There must be a better way to select a
4721 * background colour!
4722 */
4723 destPtr[0] = destPtr[1] = destPtr[2] = 0xd9;
4724 }
4725 if (srcPtr[alphaOffset]) {
4726 destPtr[0] += (srcPtr[0] - destPtr[0]) * srcPtr[alphaOffset] / 255;
4727 destPtr[1] += (srcPtr[greenOffset] - destPtr[1]) * srcPtr[alphaOffset] / 255;
4728 destPtr[2] += (srcPtr[blueOffset] - destPtr[2]) * srcPtr[alphaOffset] / 255;
4729 destPtr[3] += (255 - destPtr[3]) * srcPtr[alphaOffset] / 255;
4730 }
4731 destPtr += 4;
4732 break;
4733 default:
4734 panic("unknown compositing rule: %d", compRule);
4735 }
4736 }
4737 srcPtr += blockXSkip;
4738 }
4739 }
4740 destLinePtr += pitch;
4741 yRepeat--;
4742 if (yRepeat <= 0) {
4743 srcLinePtr += blockYSkip;
4744 yRepeat = zoomY;
4745 }
4746 }
4747 }
4748
4749 /*
4750 * Recompute the region of data for which we have valid pixels to plot.
4751 */
4752
4753 if (alphaOffset) {
4754 int x1, y1, end;
4755
4756 if (compRule != TK_PHOTO_COMPOSITE_OVERLAY) {
4757 /*
4758 * Don't need this when using the OVERLAY compositing rule, which
4759 * always strictly increases the valid region.
4760 */
4761 TkRegion workRgn = TkCreateRegion();
4762
4763 rect.x = x;
4764 rect.y = y;
4765 rect.width = width;
4766 rect.height = 1;
4767 TkUnionRectWithRegion(&rect, workRgn, workRgn);
4768 TkSubtractRegion(masterPtr->validRegion, workRgn,
4769 masterPtr->validRegion);
4770 TkDestroyRegion(workRgn);
4771 }
4772
4773 destLinePtr = masterPtr->pix32 + (y * masterPtr->width + x) * 4 + 3;
4774 for (y1 = 0; y1 < height; y1++) {
4775 x1 = 0;
4776 destPtr = destLinePtr;
4777 while (x1 < width) {
4778 /* search for first non-transparent pixel */
4779 while ((x1 < width) && !*destPtr) {
4780 x1++;
4781 destPtr += 4;
4782 }
4783 end = x1;
4784 /* search for first transparent pixel */
4785 while ((end < width) && *destPtr) {
4786 end++;
4787 destPtr += 4;
4788 }
4789 if (end > x1) {
4790 rect.x = x + x1;
4791 rect.y = y + y1;
4792 rect.width = end - x1;
4793 rect.height = 1;
4794 TkUnionRectWithRegion(&rect, masterPtr->validRegion,
4795 masterPtr->validRegion);
4796 }
4797 x1 = end;
4798 }
4799 destLinePtr += masterPtr->width * 4;
4800 }
4801 } else {
4802 rect.x = x;
4803 rect.y = y;
4804 rect.width = width;
4805 rect.height = height;
4806 TkUnionRectWithRegion(&rect, masterPtr->validRegion,
4807 masterPtr->validRegion);
4808 }
4809
4810 /*
4811 * Update each instance.
4812 */
4813
4814 Tk_DitherPhoto((Tk_PhotoHandle)masterPtr, x, y, width, height);
4815
4816 /*
4817 * Tell the core image code that this image has changed.
4818 */
4819
4820 Tk_ImageChanged(masterPtr->tkMaster, x, y, width, height, masterPtr->width,
4821 masterPtr->height);
4822 }
4823
4824 /*
4825 *----------------------------------------------------------------------
4826 *
4827 * Tk_DitherPhoto --
4828 *
4829 * This procedure is called to update an area of each instance's
4830 * pixmap by dithering the corresponding area of the image master.
4831 *
4832 * Results:
4833 * None.
4834 *
4835 * Side effects:
4836 * The pixmap of each instance of this image gets updated.
4837 * The fields in *masterPtr indicating which area of the image
4838 * is correctly dithered get updated.
4839 *
4840 *----------------------------------------------------------------------
4841 */
4842
4843 void
4844 Tk_DitherPhoto(photo, x, y, width, height)
4845 Tk_PhotoHandle photo; /* Image master whose instances are
4846 * to be updated. */
4847 int x, y; /* Coordinates of the top-left pixel
4848 * in the area to be dithered. */
4849 int width, height; /* Dimensions of the area to be dithered. */
4850 {
4851 PhotoMaster *masterPtr = (PhotoMaster *) photo;
4852 PhotoInstance *instancePtr;
4853
4854 if ((width <= 0) || (height <= 0)) {
4855 return;
4856 }
4857
4858 for (instancePtr = masterPtr->instancePtr; instancePtr != NULL;
4859 instancePtr = instancePtr->nextPtr) {
4860 DitherInstance(instancePtr, x, y, width, height);
4861 }
4862
4863 /*
4864 * Work out whether this block will be correctly dithered
4865 * and whether it will extend the correctly dithered region.
4866 */
4867
4868 if (((y < masterPtr->ditherY)
4869 || ((y == masterPtr->ditherY) && (x <= masterPtr->ditherX)))
4870 && ((y + height) > (masterPtr->ditherY))) {
4871
4872 /*
4873 * This block starts inside (or immediately after) the correctly
4874 * dithered region, so the first scan line at least will be right.
4875 * Furthermore this block extends into scanline masterPtr->ditherY.
4876 */
4877
4878 if ((x == 0) && (width == masterPtr->width)) {
4879 /*
4880 * We are doing the full width, therefore the dithering
4881 * will be correct to the end.
4882 */
4883
4884 masterPtr->ditherX = 0;
4885 masterPtr->ditherY = y + height;
4886 } else {
4887 /*
4888 * We are doing partial scanlines, therefore the
4889 * correctly-dithered region will be extended by
4890 * at most one scan line.
4891 */
4892
4893 if (x <= masterPtr->ditherX) {
4894 masterPtr->ditherX = x + width;
4895 if (masterPtr->ditherX >= masterPtr->width) {
4896 masterPtr->ditherX = 0;
4897 masterPtr->ditherY++;
4898 }
4899 }
4900 }
4901 }
4902
4903 }
4904
4905 /*
4906 *----------------------------------------------------------------------
4907 *
4908 * DitherInstance --
4909 *
4910 * This procedure is called to update an area of an instance's
4911 * pixmap by dithering the corresponding area of the master.
4912 *
4913 * Results:
4914 * None.
4915 *
4916 * Side effects:
4917 * The instance's pixmap gets updated.
4918 *
4919 *----------------------------------------------------------------------
4920 */
4921
4922 static void
4923 DitherInstance(instancePtr, xStart, yStart, width, height)
4924 PhotoInstance *instancePtr; /* The instance to be updated. */
4925 int xStart, yStart; /* Coordinates of the top-left pixel in the
4926 * block to be dithered. */
4927 int width, height; /* Dimensions of the block to be dithered. */
4928 {
4929 PhotoMaster *masterPtr;
4930 ColorTable *colorPtr;
4931 XImage *imagePtr;
4932 int nLines, bigEndian;
4933 int i, c, x, y;
4934 int xEnd, yEnd;
4935 int bitsPerPixel, bytesPerLine, lineLength;
4936 unsigned char *srcLinePtr, *srcPtr;
4937 schar *errLinePtr, *errPtr;
4938 unsigned char *destBytePtr, *dstLinePtr;
4939 pixel *destLongPtr;
4940 pixel firstBit, word, mask;
4941 int col[3];
4942 int doDithering = 1;
4943
4944 colorPtr = instancePtr->colorTablePtr;
4945 masterPtr = instancePtr->masterPtr;
4946
4947 /*
4948 * Turn dithering off in certain cases where it is not
4949 * needed (TrueColor, DirectColor with many colors).
4950 */
4951
4952 if ((colorPtr->visualInfo.class == DirectColor)
4953 || (colorPtr->visualInfo.class == TrueColor)) {
4954 int nRed, nGreen, nBlue, result;
4955
4956 result = sscanf(colorPtr->id.palette, "%d/%d/%d", &nRed,
4957 &nGreen, &nBlue);
4958 if ((nRed >= 256)
4959 && ((result == 1) || ((nGreen >= 256) && (nBlue >= 256)))) {
4960 doDithering = 0;
4961 }
4962 }
4963
4964 /*
4965 * First work out how many lines to do at a time,
4966 * then how many bytes we'll need for pixel storage,
4967 * and allocate it.
4968 */
4969
4970 nLines = (MAX_PIXELS + width - 1) / width;
4971 if (nLines < 1) {
4972 nLines = 1;
4973 }
4974 if (nLines > height ) {
4975 nLines = height;
4976 }
4977
4978 imagePtr = instancePtr->imagePtr;
4979 if (imagePtr == NULL) {
4980 return; /* we must be really tight on memory */
4981 }
4982 bitsPerPixel = imagePtr->bits_per_pixel;
4983 bytesPerLine = ((bitsPerPixel * width + 31) >> 3) & ~3;
4984 imagePtr->width = width;
4985 imagePtr->height = nLines;
4986 imagePtr->bytes_per_line = bytesPerLine;
4987 imagePtr->data = (char *) ckalloc((unsigned) (imagePtr->bytes_per_line * nLines));
4988 bigEndian = imagePtr->bitmap_bit_order == MSBFirst;
4989 firstBit = bigEndian? (1 << (imagePtr->bitmap_unit - 1)): 1;
4990
4991 lineLength = masterPtr->width * 3;
4992 srcLinePtr = masterPtr->pix32 + (yStart * masterPtr->width + xStart) * 4;
4993 errLinePtr = instancePtr->error + yStart * lineLength + xStart * 3;
4994 xEnd = xStart + width;
4995
4996 /*
4997 * Loop over the image, doing at most nLines lines before
4998 * updating the screen image.
4999 */
5000
5001 for (; height > 0; height -= nLines) {
5002 if (nLines > height) {
5003 nLines = height;
5004 }
5005 dstLinePtr = (unsigned char *) imagePtr->data;
5006 yEnd = yStart + nLines;
5007 for (y = yStart; y < yEnd; ++y) {
5008 srcPtr = srcLinePtr;
5009 errPtr = errLinePtr;
5010 destBytePtr = dstLinePtr;
5011 destLongPtr = (pixel *) dstLinePtr;
5012 if (colorPtr->flags & COLOR_WINDOW) {
5013 /*
5014 * Color window. We dither the three components
5015 * independently, using Floyd-Steinberg dithering,
5016 * which propagates errors from the quantization of
5017 * pixels to the pixels below and to the right.
5018 */
5019
5020 for (x = xStart; x < xEnd; ++x) {
5021 if (doDithering) {
5022 for (i = 0; i < 3; ++i) {
5023 /*
5024 * Compute the error propagated into this pixel
5025 * for this component.
5026 * If e[x,y] is the array of quantization error
5027 * values, we compute
5028 * 7/16 * e[x-1,y] + 1/16 * e[x-1,y-1]
5029 * + 5/16 * e[x,y-1] + 3/16 * e[x+1,y-1]
5030 * and round it to an integer.
5031 *
5032 * The expression ((c + 2056) >> 4) - 128
5033 * computes round(c / 16), and works correctly on
5034 * machines without a sign-extending right shift.
5035 */
5036
5037 c = (x > 0) ? errPtr[-3] * 7: 0;
5038 if (y > 0) {
5039 if (x > 0) {
5040 c += errPtr[-lineLength-3];
5041 }
5042 c += errPtr[-lineLength] * 5;
5043 if ((x + 1) < masterPtr->width) {
5044 c += errPtr[-lineLength+3] * 3;
5045 }
5046 }
5047
5048 /*
5049 * Add the propagated error to the value of this
5050 * component, quantize it, and store the
5051 * quantization error.
5052 */
5053
5054 c = ((c + 2056) >> 4) - 128 + *srcPtr++;
5055 if (c < 0) {
5056 c = 0;
5057 } else if (c > 255) {
5058 c = 255;
5059 }
5060 col[i] = colorPtr->colorQuant[i][c];
5061 *errPtr++ = c - col[i];
5062 }
5063 } else {
5064 /*
5065 * Output is virtually continuous in this case,
5066 * so don't bother dithering.
5067 */
5068
5069 col[0] = *srcPtr++;
5070 col[1] = *srcPtr++;
5071 col[2] = *srcPtr++;
5072 }
5073 srcPtr++;
5074
5075 /*
5076 * Translate the quantized component values into
5077 * an X pixel value, and store it in the image.
5078 */
5079
5080 i = colorPtr->redValues[col[0]]
5081 + colorPtr->greenValues[col[1]]
5082 + colorPtr->blueValues[col[2]];
5083 if (colorPtr->flags & MAP_COLORS) {
5084 i = colorPtr->pixelMap[i];
5085 }
5086 switch (bitsPerPixel) {
5087 case NBBY:
5088 *destBytePtr++ = i;
5089 break;
5090 #ifndef __WIN32__
5091 /*
5092 * This case is not valid for Windows because the image format is different
5093 * from the pixel format in Win32. Eventually we need to fix the image
5094 * code in Tk to use the Windows native image ordering. This would speed
5095 * up the image code for all of the common sizes.
5096 */
5097
5098 case NBBY * sizeof(pixel):
5099 *destLongPtr++ = i;
5100 break;
5101 #endif
5102 default:
5103 XPutPixel(imagePtr, x - xStart, y - yStart,
5104 (unsigned) i);
5105 }
5106 }
5107
5108 } else if (bitsPerPixel > 1) {
5109 /*
5110 * Multibit monochrome window. The operation here is similar
5111 * to the color window case above, except that there is only
5112 * one component. If the master image is in color, use the
5113 * luminance computed as
5114 * 0.344 * red + 0.5 * green + 0.156 * blue.
5115 */
5116
5117 for (x = xStart; x < xEnd; ++x) {
5118 c = (x > 0) ? errPtr[-1] * 7: 0;
5119 if (y > 0) {
5120 if (x > 0) {
5121 c += errPtr[-lineLength-1];
5122 }
5123 c += errPtr[-lineLength] * 5;
5124 if (x + 1 < masterPtr->width) {
5125 c += errPtr[-lineLength+1] * 3;
5126 }
5127 }
5128 c = ((c + 2056) >> 4) - 128;
5129
5130 if ((masterPtr->flags & COLOR_IMAGE) == 0) {
5131 c += srcPtr[0];
5132 } else {
5133 c += (unsigned)(srcPtr[0] * 11 + srcPtr[1] * 16
5134 + srcPtr[2] * 5 + 16) >> 5;
5135 }
5136 srcPtr += 4;
5137
5138 if (c < 0) {
5139 c = 0;
5140 } else if (c > 255) {
5141 c = 255;
5142 }
5143 i = colorPtr->colorQuant[0][c];
5144 *errPtr++ = c - i;
5145 i = colorPtr->redValues[i];
5146 switch (bitsPerPixel) {
5147 case NBBY:
5148 *destBytePtr++ = i;
5149 break;
5150 #ifndef __WIN32__
5151 /*
5152 * This case is not valid for Windows because the image format is different
5153 * from the pixel format in Win32. Eventually we need to fix the image
5154 * code in Tk to use the Windows native image ordering. This would speed
5155 * up the image code for all of the common sizes.
5156 */
5157
5158 case NBBY * sizeof(pixel):
5159 *destLongPtr++ = i;
5160 break;
5161 #endif
5162 default:
5163 XPutPixel(imagePtr, x - xStart, y - yStart,
5164 (unsigned) i);
5165 }
5166 }
5167 } else {
5168 /*
5169 * 1-bit monochrome window. This is similar to the
5170 * multibit monochrome case above, except that the
5171 * quantization is simpler (we only have black = 0
5172 * and white = 255), and we produce an XY-Bitmap.
5173 */
5174
5175 word = 0;
5176 mask = firstBit;
5177 for (x = xStart; x < xEnd; ++x) {
5178 /*
5179 * If we have accumulated a whole word, store it
5180 * in the image and start a new word.
5181 */
5182
5183 if (mask == 0) {
5184 *destLongPtr++ = word;
5185 mask = firstBit;
5186 word = 0;
5187 }
5188
5189 c = (x > 0) ? errPtr[-1] * 7: 0;
5190 if (y > 0) {
5191 if (x > 0) {
5192 c += errPtr[-lineLength-1];
5193 }
5194 c += errPtr[-lineLength] * 5;
5195 if (x + 1 < masterPtr->width) {
5196 c += errPtr[-lineLength+1] * 3;
5197 }
5198 }
5199 c = ((c + 2056) >> 4) - 128;
5200
5201 if ((masterPtr->flags & COLOR_IMAGE) == 0) {
5202 c += srcPtr[0];
5203 } else {
5204 c += (unsigned)(srcPtr[0] * 11 + srcPtr[1] * 16
5205 + srcPtr[2] * 5 + 16) >> 5;
5206 }
5207 srcPtr += 4;
5208
5209 if (c < 0) {
5210 c = 0;
5211 } else if (c > 255) {
5212 c = 255;
5213 }
5214 if (c >= 128) {
5215 word |= mask;
5216 *errPtr++ = c - 255;
5217 } else {
5218 *errPtr++ = c;
5219 }
5220 mask = bigEndian? (mask >> 1): (mask << 1);
5221 }
5222 *destLongPtr = word;
5223 }
5224 srcLinePtr += masterPtr->width * 4;
5225 errLinePtr += lineLength;
5226 dstLinePtr += bytesPerLine;
5227 }
5228
5229 /*
5230 * Update the pixmap for this instance with the block of
5231 * pixels that we have just computed.
5232 */
5233
5234 TkPutImage(colorPtr->pixelMap, colorPtr->numColors,
5235 instancePtr->display, instancePtr->pixels,
5236 instancePtr->gc, imagePtr, 0, 0, xStart, yStart,
5237 (unsigned) width, (unsigned) nLines);
5238 yStart = yEnd;
5239
5240 }
5241
5242 ckfree(imagePtr->data);
5243 imagePtr->data = NULL;
5244 }
5245
5246 /*
5247 *----------------------------------------------------------------------
5248 *
5249 * Tk_PhotoBlank --
5250 *
5251 * This procedure is called to clear an entire photo image.
5252 *
5253 * Results:
5254 * None.
5255 *
5256 * Side effects:
5257 * The valid region for the image is set to the null region.
5258 * The generic image code is notified that the image has changed.
5259 *
5260 *----------------------------------------------------------------------
5261 */
5262
5263 void
5264 Tk_PhotoBlank(handle)
5265 Tk_PhotoHandle handle; /* Handle for the image to be blanked. */
5266 {
5267 PhotoMaster *masterPtr;
5268 PhotoInstance *instancePtr;
5269
5270 masterPtr = (PhotoMaster *) handle;
5271 masterPtr->ditherX = masterPtr->ditherY = 0;
5272 masterPtr->flags = 0;
5273
5274 /*
5275 * The image has valid data nowhere.
5276 */
5277
5278 if (masterPtr->validRegion != NULL) {
5279 TkDestroyRegion(masterPtr->validRegion);
5280 }
5281 masterPtr->validRegion = TkCreateRegion();
5282
5283 /*
5284 * Clear out the 32-bit pixel storage array.
5285 * Clear out the dithering error arrays for each instance.
5286 */
5287
5288 memset((VOID *) masterPtr->pix32, 0,
5289 (size_t) (masterPtr->width * masterPtr->height * 4));
5290 for (instancePtr = masterPtr->instancePtr; instancePtr != NULL;
5291 instancePtr = instancePtr->nextPtr) {
5292 if (instancePtr->error) {
5293 memset((VOID *) instancePtr->error, 0,
5294 (size_t) (masterPtr->width * masterPtr->height
5295 * 3 * sizeof(schar)));
5296 }
5297 }
5298
5299 /*
5300 * Tell the core image code that this image has changed.
5301 */
5302
5303 Tk_ImageChanged(masterPtr->tkMaster, 0, 0, masterPtr->width,
5304 masterPtr->height, masterPtr->width, masterPtr->height);
5305 }
5306
5307 /*
5308 *----------------------------------------------------------------------
5309 *
5310 * Tk_PhotoExpand --
5311 *
5312 * This procedure is called to request that a photo image be
5313 * expanded if necessary to be at least `width' pixels wide and
5314 * `height' pixels high. If the user has declared a definite
5315 * image size (using the -width and -height configuration
5316 * options) then this call has no effect.
5317 *
5318 * Results:
5319 * None.
5320 *
5321 * Side effects:
5322 * The size of the photo image may change; if so the generic
5323 * image code is informed.
5324 *
5325 *----------------------------------------------------------------------
5326 */
5327
5328 void
5329 Tk_PhotoExpand(handle, width, height)
5330 Tk_PhotoHandle handle; /* Handle for the image to be expanded. */
5331 int width, height; /* Desired minimum dimensions of the image. */
5332 {
5333 PhotoMaster *masterPtr;
5334
5335 masterPtr = (PhotoMaster *) handle;
5336
5337 if (width <= masterPtr->width) {
5338 width = masterPtr->width;
5339 }
5340 if (height <= masterPtr->height) {
5341 height = masterPtr->height;
5342 }
5343 if ((width != masterPtr->width) || (height != masterPtr->height)) {
5344 if (ImgPhotoSetSize(masterPtr, MAX(width, masterPtr->width),
5345 MAX(height, masterPtr->height)) == TCL_ERROR) {
5346 panic(TK_PHOTO_ALLOC_FAILURE_MESSAGE);
5347 }
5348 Tk_ImageChanged(masterPtr->tkMaster, 0, 0, 0, 0, masterPtr->width,
5349 masterPtr->height);
5350 }
5351 }
5352
5353 /*
5354 *----------------------------------------------------------------------
5355 *
5356 * Tk_PhotoGetSize --
5357 *
5358 * This procedure is called to obtain the current size of a photo
5359 * image.
5360 *
5361 * Results:
5362 * The image's width and height are returned in *widthp
5363 * and *heightp.
5364 *
5365 * Side effects:
5366 * None.
5367 *
5368 *----------------------------------------------------------------------
5369 */
5370
5371 void
5372 Tk_PhotoGetSize(handle, widthPtr, heightPtr)
5373 Tk_PhotoHandle handle; /* Handle for the image whose dimensions
5374 * are requested. */
5375 int *widthPtr, *heightPtr; /* The dimensions of the image are returned
5376 * here. */
5377 {
5378 PhotoMaster *masterPtr;
5379
5380 masterPtr = (PhotoMaster *) handle;
5381 *widthPtr = masterPtr->width;
5382 *heightPtr = masterPtr->height;
5383 }
5384
5385 /*
5386 *----------------------------------------------------------------------
5387 *
5388 * Tk_PhotoSetSize --
5389 *
5390 * This procedure is called to set size of a photo image.
5391 * This call is equivalent to using the -width and -height
5392 * configuration options.
5393 *
5394 * Results:
5395 * None.
5396 *
5397 * Side effects:
5398 * The size of the image may change; if so the generic
5399 * image code is informed.
5400 *
5401 *----------------------------------------------------------------------
5402 */
5403
5404 void
5405 Tk_PhotoSetSize(handle, width, height)
5406 Tk_PhotoHandle handle; /* Handle for the image whose size is to
5407 * be set. */
5408 int width, height; /* New dimensions for the image. */
5409 {
5410 PhotoMaster *masterPtr;
5411
5412 masterPtr = (PhotoMaster *) handle;
5413
5414 masterPtr->userWidth = width;
5415 masterPtr->userHeight = height;
5416 if (ImgPhotoSetSize(masterPtr, ((width > 0) ? width: masterPtr->width),
5417 ((height > 0) ? height: masterPtr->height)) == TCL_ERROR) {
5418 panic(TK_PHOTO_ALLOC_FAILURE_MESSAGE);
5419 }
5420 Tk_ImageChanged(masterPtr->tkMaster, 0, 0, 0, 0,
5421 masterPtr->width, masterPtr->height);
5422 }
5423
5424 /*
5425 *----------------------------------------------------------------------
5426 *
5427 * TkGetPhotoValidRegion --
5428 *
5429 * This procedure is called to get the part of the photo where
5430 * there is valid data. Or, conversely, the part of the photo
5431 * which is transparent.
5432 *
5433 * Results:
5434 * A TkRegion value that indicates the current area of the photo
5435 * that is valid. This value should not be used after any
5436 * modification to the photo image.
5437 *
5438 * Side Effects:
5439 * None.
5440 *
5441 *----------------------------------------------------------------------
5442 */
5443
5444 TkRegion
5445 TkPhotoGetValidRegion(handle)
5446 Tk_PhotoHandle handle; /* Handle for the image whose valid region
5447 * is to obtained. */
5448 {
5449 PhotoMaster *masterPtr;
5450
5451 masterPtr = (PhotoMaster *) handle;
5452 return masterPtr->validRegion;
5453 }
5454
5455 /*
5456 *----------------------------------------------------------------------
5457 *
5458 * ImgGetPhoto --
5459 *
5460 * This procedure is called to obtain image data from a photo
5461 * image. This procedure fills in the Tk_PhotoImageBlock structure
5462 * pointed to by `blockPtr' with details of the address and
5463 * layout of the image data in memory.
5464 *
5465 * Results:
5466 * A pointer to the allocated data which should be freed later.
5467 * NULL if there is no need to free data because
5468 * blockPtr->pixelPtr points directly to the image data.
5469 *
5470 * Side effects:
5471 * None.
5472 *
5473 *----------------------------------------------------------------------
5474 */
5475
5476 static char *
5477 ImgGetPhoto(masterPtr, blockPtr, optPtr)
5478 PhotoMaster *masterPtr; /* Handle for the photo image from which
5479 * image data is desired. */
5480 Tk_PhotoImageBlock *blockPtr;
5481 /* Information about the address and layout
5482 * of the image data is returned here. */
5483 struct SubcommandOptions *optPtr;
5484 {
5485 unsigned char *pixelPtr;
5486 int x, y, greenOffset, blueOffset, alphaOffset;
5487
5488 Tk_PhotoGetImage((Tk_PhotoHandle) masterPtr, blockPtr);
5489 blockPtr->pixelPtr += optPtr->fromY * blockPtr->pitch
5490 + optPtr->fromX * blockPtr->pixelSize;
5491 blockPtr->width = optPtr->fromX2 - optPtr->fromX;
5492 blockPtr->height = optPtr->fromY2 - optPtr->fromY;
5493
5494 if (!(masterPtr->flags & COLOR_IMAGE) &&
5495 (!(optPtr->options & OPT_BACKGROUND)
5496 || ((optPtr->background->red == optPtr->background->green)
5497 && (optPtr->background->red == optPtr->background->blue)))) {
5498 blockPtr->offset[0] = blockPtr->offset[1] =
5499 blockPtr->offset[2];
5500 }
5501 alphaOffset = 0;
5502 for (y = 0; y < blockPtr->height; y++) {
5503 pixelPtr = blockPtr->pixelPtr + (y * blockPtr->pitch)
5504 + blockPtr->pixelSize - 1;
5505 for (x = 0; x < blockPtr->width; x++) {
5506 if (*pixelPtr != 255) {
5507 alphaOffset = 3;
5508 break;
5509 }
5510 pixelPtr += blockPtr->pixelSize;
5511 }
5512 if (alphaOffset) {
5513 break;
5514 }
5515 }
5516 if (!alphaOffset) {
5517 blockPtr->pixelPtr--;
5518 blockPtr->offset[0]++;
5519 blockPtr->offset[1]++;
5520 blockPtr->offset[2]++;
5521 }
5522 greenOffset = blockPtr->offset[1] - blockPtr->offset[0];
5523 blueOffset = blockPtr->offset[2] - blockPtr->offset[0];
5524 if (((optPtr->options & OPT_BACKGROUND) && alphaOffset) ||
5525 ((optPtr->options & OPT_GRAYSCALE) && (greenOffset || blueOffset))) {
5526 int newPixelSize,x,y;
5527 unsigned char *srcPtr, *destPtr;
5528 char *data;
5529
5530 newPixelSize = (!(optPtr->options & OPT_BACKGROUND) && alphaOffset) ? 2 : 1;
5531 if ((greenOffset || blueOffset) && !(optPtr->options & OPT_GRAYSCALE)) {
5532 newPixelSize += 2;
5533 }
5534 data = ckalloc((unsigned int) (newPixelSize *
5535 blockPtr->width * blockPtr->height));
5536 srcPtr = blockPtr->pixelPtr + blockPtr->offset[0];
5537 destPtr = (unsigned char *) data;
5538 if (!greenOffset && !blueOffset) {
5539 for (y = blockPtr->height; y > 0; y--) {
5540 for (x = blockPtr->width; x > 0; x--) {
5541 *destPtr = *srcPtr;
5542 srcPtr += blockPtr->pixelSize;
5543 destPtr += newPixelSize;
5544 }
5545 srcPtr += blockPtr->pitch - (blockPtr->width * blockPtr->pixelSize);
5546 }
5547 } else if (optPtr->options & OPT_GRAYSCALE) {
5548 for (y = blockPtr->height; y > 0; y--) {
5549 for (x = blockPtr->width; x > 0; x--) {
5550 *destPtr = (unsigned char) ((srcPtr[0] * 11 + srcPtr[1] * 16
5551 + srcPtr[2] * 5 + 16) >> 5);
5552 srcPtr += blockPtr->pixelSize;
5553 destPtr += newPixelSize;
5554 }
5555 srcPtr += blockPtr->pitch - (blockPtr->width * blockPtr->pixelSize);
5556 }
5557 } else {
5558 for (y = blockPtr->height; y > 0; y--) {
5559 for (x = blockPtr->width; x > 0; x--) {
5560 destPtr[0] = srcPtr[0];
5561 destPtr[1] = srcPtr[1];
5562 destPtr[2] = srcPtr[2];
5563 srcPtr += blockPtr->pixelSize;
5564 destPtr += newPixelSize;
5565 }
5566 srcPtr += blockPtr->pitch - (blockPtr->width * blockPtr->pixelSize);
5567 }
5568 }
5569 srcPtr = blockPtr->pixelPtr + alphaOffset;
5570 destPtr = (unsigned char *) data;
5571 if (!alphaOffset) {
5572 /* nothing to be done */
5573 } else if (optPtr->options & OPT_BACKGROUND) {
5574 if (newPixelSize > 2) {
5575 int red = optPtr->background->red>>8;
5576 int green = optPtr->background->green>>8;
5577 int blue = optPtr->background->blue>>8;
5578 for (y = blockPtr->height; y > 0; y--) {
5579 for (x = blockPtr->width; x > 0; x--) {
5580 destPtr[0] += (unsigned char) (((255 - *srcPtr) *
5581 (red-destPtr[0])) / 255);
5582 destPtr[1] += (unsigned char) (((255 - *srcPtr) *
5583 (green-destPtr[1])) / 255);
5584 destPtr[2] += (unsigned char) (((255 - *srcPtr) *
5585 (blue-destPtr[2])) / 255);
5586 srcPtr += blockPtr->pixelSize;
5587 destPtr += newPixelSize;
5588 }
5589 srcPtr += blockPtr->pitch - (blockPtr->width * blockPtr->pixelSize);
5590 }
5591 } else {
5592 int gray = (unsigned char) (((optPtr->background->red>>8) * 11
5593 + (optPtr->background->green>>8) * 16
5594 + (optPtr->background->blue>>8) * 5 + 16) >> 5);
5595 for (y = blockPtr->height; y > 0; y--) {
5596 for (x = blockPtr->width; x > 0; x--) {
5597 destPtr[0] += ((255 - *srcPtr) *
5598 (gray-destPtr[0])) / 255;
5599 srcPtr += blockPtr->pixelSize;
5600 destPtr += newPixelSize;
5601 }
5602 srcPtr += blockPtr->pitch - (blockPtr->width * blockPtr->pixelSize);
5603 }
5604 }
5605 } else {
5606 destPtr += newPixelSize-1;
5607 for (y = blockPtr->height; y > 0; y--) {
5608 for (x = blockPtr->width; x > 0; x--) {
5609 *destPtr = *srcPtr;
5610 srcPtr += blockPtr->pixelSize;
5611 destPtr += newPixelSize;
5612 }
5613 srcPtr += blockPtr->pitch - (blockPtr->width * blockPtr->pixelSize);
5614 }
5615 }
5616 blockPtr->pixelPtr = (unsigned char *) data;
5617 blockPtr->pixelSize = newPixelSize;
5618 blockPtr->pitch = newPixelSize * blockPtr->width;
5619 blockPtr->offset[0] = 0;
5620 if (newPixelSize>2) {
5621 blockPtr->offset[1]= 1;
5622 blockPtr->offset[2]= 2;
5623 } else {
5624 blockPtr->offset[1]= 0;
5625 blockPtr->offset[2]= 0;
5626 }
5627 return data;
5628 }
5629 return NULL;
5630 }
5631
5632 /*
5633 *----------------------------------------------------------------------
5634 *
5635 * ImgStringWrite --
5636 *
5637 * Default string write function. The data is formatted in
5638 * the default format as accepted by the "<img> put" command.
5639 *
5640 * Results:
5641 * A standard Tcl result.
5642 *
5643 * Side effects:
5644 * See the user documentation.
5645 *
5646 *----------------------------------------------------------------------
5647 */
5648
5649 static int
5650 ImgStringWrite(interp, formatString, blockPtr)
5651 Tcl_Interp *interp;
5652 Tcl_Obj *formatString;
5653 Tk_PhotoImageBlock *blockPtr;
5654 {
5655 int row,col;
5656 char *line, *linePtr;
5657 unsigned char *pixelPtr;
5658 int greenOffset, blueOffset;
5659 Tcl_DString data;
5660
5661 greenOffset = blockPtr->offset[1] - blockPtr->offset[0];
5662 blueOffset = blockPtr->offset[2] - blockPtr->offset[0];
5663
5664 Tcl_DStringInit(&data);
5665 if ((blockPtr->width > 0) && (blockPtr->height > 0)) {
5666 line = (char *) ckalloc((unsigned int) ((8 * blockPtr->width) + 2));
5667 for (row=0; row<blockPtr->height; row++) {
5668 pixelPtr = blockPtr->pixelPtr + blockPtr->offset[0] +
5669 row * blockPtr->pitch;
5670 linePtr = line;
5671 for (col=0; col<blockPtr->width; col++) {
5672 sprintf(linePtr, " #%02x%02x%02x", *pixelPtr,
5673 pixelPtr[greenOffset], pixelPtr[blueOffset]);
5674 pixelPtr += blockPtr->pixelSize;
5675 linePtr += 8;
5676 }
5677 Tcl_DStringAppendElement(&data, line+1);
5678 }
5679 ckfree (line);
5680 }
5681 Tcl_DStringResult(interp, &data);
5682 return TCL_OK;
5683 }
5684
5685 /*
5686 *----------------------------------------------------------------------
5687 *
5688 * Tk_PhotoGetImage --
5689 *
5690 * This procedure is called to obtain image data from a photo
5691 * image. This procedure fills in the Tk_PhotoImageBlock structure
5692 * pointed to by `blockPtr' with details of the address and
5693 * layout of the image data in memory.
5694 *
5695 * Results:
5696 * TRUE (1) indicating that image data is available,
5697 * for backwards compatibility with the old photo widget.
5698 *
5699 * Side effects:
5700 * None.
5701 *
5702 *----------------------------------------------------------------------
5703 */
5704
5705 int
5706 Tk_PhotoGetImage(handle, blockPtr)
5707 Tk_PhotoHandle handle; /* Handle for the photo image from which
5708 * image data is desired. */
5709 Tk_PhotoImageBlock *blockPtr;
5710 /* Information about the address and layout
5711 * of the image data is returned here. */
5712 {
5713 PhotoMaster *masterPtr;
5714
5715 masterPtr = (PhotoMaster *) handle;
5716 blockPtr->pixelPtr = masterPtr->pix32;
5717 blockPtr->width = masterPtr->width;
5718 blockPtr->height = masterPtr->height;
5719 blockPtr->pitch = masterPtr->width * 4;
5720 blockPtr->pixelSize = 4;
5721 blockPtr->offset[0] = 0;
5722 blockPtr->offset[1] = 1;
5723 blockPtr->offset[2] = 2;
5724 blockPtr->offset[3] = 3;
5725 return 1;
5726 }
5727
5728 /*
5729 *----------------------------------------------------------------------
5730 *
5731 * PhotoOptionFind --
5732 *
5733 * Finds a specific Photo option.
5734 *
5735 * Results:
5736 * None.
5737 *
5738 * Side effects:
5739 * After commands are removed.
5740 *
5741 *----------------------------------------------------------------------
5742 */
5743
5744 typedef struct OptionAssocData {
5745 struct OptionAssocData *nextPtr; /* pointer to next OptionAssocData */
5746 Tcl_ObjCmdProc *command; /* command associated with this
5747 * option */
5748 char name[1]; /* name of option (remaining chars) */
5749 } OptionAssocData;
5750
5751 static Tcl_ObjCmdProc *
5752 PhotoOptionFind(interp, obj)
5753 Tcl_Interp *interp; /* Interpreter that is being deleted. */
5754 Tcl_Obj *obj; /* Name of option to be found. */
5755 {
5756 size_t length;
5757 char *name = Tcl_GetStringFromObj(obj, (int *) &length);
5758 OptionAssocData *list;
5759 char *prevname = NULL;
5760 Tcl_ObjCmdProc *proc = (Tcl_ObjCmdProc *) NULL;
5761 list = (OptionAssocData *) Tcl_GetAssocData(interp, "photoOption",
5762 (Tcl_InterpDeleteProc **) NULL);
5763 while (list != (OptionAssocData *) NULL) {
5764 if (strncmp(name, list->name, length) == 0) {
5765 if (proc != (Tcl_ObjCmdProc *) NULL) {
5766 Tcl_ResetResult(interp);
5767 Tcl_AppendResult(interp, "ambiguous option \"", name,
5768 "\": must be ", prevname, (char *) NULL);
5769 while (list->nextPtr != (OptionAssocData *) NULL) {
5770 Tcl_AppendResult(interp, prevname, ", ",(char *) NULL);
5771 list = list->nextPtr;
5772 prevname = list->name;
5773 }
5774 Tcl_AppendResult(interp, ", or", prevname, (char *) NULL);
5775 return (Tcl_ObjCmdProc *) NULL;
5776 }
5777 proc = list->command;
5778 prevname = list->name;
5779 }
5780 list = list->nextPtr;
5781 }
5782 if (proc != (Tcl_ObjCmdProc *) NULL) {
5783 Tcl_ResetResult(interp);
5784 }
5785 return proc;
5786 }
5787
5788 /*
5789 *----------------------------------------------------------------------
5790 *
5791 * PhotoOptionCleanupProc --
5792 *
5793 * This procedure is invoked whenever an interpreter is deleted
5794 * to cleanup the AssocData for "photoVisitor".
5795 *
5796 * Results:
5797 * None.
5798 *
5799 * Side effects:
5800 * Photo Visitor options are removed.
5801 *
5802 *----------------------------------------------------------------------
5803 */
5804
5805 static void
5806 PhotoOptionCleanupProc(clientData, interp)
5807 ClientData clientData; /* Points to "photoVisitor" AssocData
5808 * for the interpreter. */
5809 Tcl_Interp *interp; /* Interpreter that is being deleted. */
5810 {
5811 OptionAssocData *list = (OptionAssocData *) clientData;
5812 OptionAssocData *ptr;
5813
5814 while (list != NULL) {
5815 list = (ptr = list)->nextPtr;
5816 ckfree((char *) ptr);
5817 }
5818 }
5819
5820 /*
5821 *--------------------------------------------------------------
5822 *
5823 * Tk_CreatePhotoOption --
5824 *
5825 * This procedure may be invoked to add a new kind of photo
5826 * option to the core photo command supported by Tk.
5827 *
5828 * Results:
5829 * None.
5830 *
5831 * Side effects:
5832 * From now on, the new option will be useable by the
5833 * photo command.
5834 *
5835 *--------------------------------------------------------------
5836 */
5837
5838 void
5839 Tk_CreatePhotoOption(interp, name, proc)
5840 Tcl_Interp *interp; /* interpreter */
5841 CONST char *name; /* option name */
5842 Tcl_ObjCmdProc *proc; /* proc to execute command */
5843 {
5844 OptionAssocData *typePtr2, *prevPtr, *ptr;
5845 OptionAssocData *list;
5846
5847 list = (OptionAssocData *) Tcl_GetAssocData(interp, "photoOption",
5848 (Tcl_InterpDeleteProc **) NULL);
5849
5850 /*
5851 * If there's already a photo option with the given name, remove it.
5852 */
5853
5854 for (typePtr2 = list, prevPtr = NULL; typePtr2 != NULL;
5855 prevPtr = typePtr2, typePtr2 = typePtr2->nextPtr) {
5856 if (strcmp(typePtr2->name, name) == 0) {
5857 if (prevPtr == NULL) {
5858 list = typePtr2->nextPtr;
5859 } else {
5860 prevPtr->nextPtr = typePtr2->nextPtr;
5861 }
5862 ckfree((char *) typePtr2);
5863 break;
5864 }
5865 }
5866 ptr = (OptionAssocData *) ckalloc(sizeof(OptionAssocData) + strlen(name));
5867 strcpy(&(ptr->name[0]), name);
5868 ptr->command = proc;
5869 ptr->nextPtr = list;
5870 Tcl_SetAssocData(interp, "photoOption", PhotoOptionCleanupProc,
5871 (ClientData) ptr);
5872 }
5873
5874 /*
5875 *--------------------------------------------------------------
5876 *
5877 * TkPostscriptPhoto --
5878 *
5879 * This procedure is called to output the contents of a
5880 * photo image in Postscript by calling the Tk_PostscriptPhoto
5881 * function.
5882 *
5883 * Results:
5884 * Returns a standard Tcl return value.
5885 *
5886 * Side effects:
5887 * None.
5888 *
5889 *--------------------------------------------------------------
5890 */
5891 static int
5892 ImgPhotoPostscript(clientData, interp, tkwin, psInfo,
5893 x, y, width, height, prepass)
5894 ClientData clientData; /* Handle for the photo image */
5895 Tcl_Interp *interp; /* Interpreter */
5896 Tk_Window tkwin; /* (unused) */
5897 Tk_PostscriptInfo psInfo; /* postscript info */
5898 int x, y; /* First pixel to output */
5899 int width, height; /* Width and height of area */
5900 int prepass; /* (unused) */
5901 {
5902 Tk_PhotoImageBlock block;
5903
5904 Tk_PhotoGetImage((Tk_PhotoHandle) clientData, &block);
5905 block.pixelPtr += y * block.pitch + x * block.pixelSize;
5906
5907 return Tk_PostscriptPhoto(interp, &block, psInfo, width, height);
5908 }
5909
5910 /*
5911 *----------------------------------------------------------------------
5912 *
5913 * Tk_PhotoPutBlock_NoComposite, Tk_PhotoPutZoomedBlock_NoComposite --
5914 *
5915 * These backward-compatability functions just exist to fill slots in
5916 * stubs table. For the behaviour of *_NoComposite, refer to the
5917 * corresponding function without the extra suffix.
5918 *
5919 *----------------------------------------------------------------------
5920 */
5921 void
5922 Tk_PhotoPutBlock_NoComposite(handle, blockPtr, x, y, width, height)
5923 Tk_PhotoHandle handle;
5924 Tk_PhotoImageBlock *blockPtr;
5925 int x, y, width, height;
5926 {
5927 Tk_PhotoPutBlock(handle, blockPtr, x, y, width, height,
5928 TK_PHOTO_COMPOSITE_OVERLAY);
5929 }
5930
5931 void
5932 Tk_PhotoPutZoomedBlock_NoComposite(handle, blockPtr, x, y, width, height,
5933 zoomX, zoomY, subsampleX, subsampleY)
5934 Tk_PhotoHandle handle;
5935 Tk_PhotoImageBlock *blockPtr;
5936 int x, y, width, height, zoomX, zoomY, subsampleX, subsampleY;
5937 {
5938 Tk_PhotoPutZoomedBlock(handle, blockPtr, x, y, width, height,
5939 zoomX, zoomY, subsampleX, subsampleY, TK_PHOTO_COMPOSITE_OVERLAY);
5940 }
5941
5942
5943
5944