home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / tkisrc04.zip / tk / os2 / tkImgPhoto.c < prev    next >
C/C++ Source or Header  |  1998-08-07  |  118KB  |  4,120 lines

  1. /*
  2.  * tkImgPhoto.c --
  3.  *
  4.  *    Implements images of type "photo" for Tk.  Photo images are
  5.  *    stored in full color (24 bits per pixel) and displayed using
  6.  *    dithering if necessary.
  7.  *
  8.  * Copyright (c) 1994 The Australian National University.
  9.  * Copyright (c) 1994-1996 Sun Microsystems, Inc.
  10.  *
  11.  * See the file "license.terms" for information on usage and redistribution
  12.  * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
  13.  *
  14.  * Author: Paul Mackerras (paulus@cs.anu.edu.au),
  15.  *       Department of Computer Science,
  16.  *       Australian National University.
  17.  *
  18.  * SCCS: @(#) tkImgPhoto.c 1.44 96/03/01 17:35:11
  19.  */
  20.  
  21. #include "tkInt.h"
  22. #include "tkPort.h"
  23. #include <math.h>
  24. #include <ctype.h>
  25.  
  26. /*
  27.  * Declaration for internal Xlib function used here:
  28.  */
  29.  
  30. extern _XInitImageFuncPtrs _ANSI_ARGS_((XImage *image));
  31.  
  32. /*
  33.  * A signed 8-bit integral type.  If chars are unsigned and the compiler
  34.  * isn't an ANSI one, then we have to use short instead (which wastes
  35.  * space) to get signed behavior.
  36.  */
  37.  
  38. #if defined(__STDC__) || defined(_AIX)
  39.     typedef signed char schar;
  40. #else
  41. #   ifndef __CHAR_UNSIGNED__
  42.     typedef char schar;
  43. #   else
  44.     typedef short schar;
  45. #   endif
  46. #endif
  47.  
  48. /*
  49.  * An unsigned 32-bit integral type, used for pixel values.
  50.  * We use int rather than long here to accommodate those systems
  51.  * where longs are 64 bits.
  52.  */
  53.  
  54. typedef unsigned int pixel;
  55.  
  56. /*
  57.  * The maximum number of pixels to transmit to the server in a
  58.  * single XPutImage call.
  59.  */
  60.  
  61. #define MAX_PIXELS 65536
  62.  
  63. /*
  64.  * The set of colors required to display a photo image in a window depends on:
  65.  *    - the visual used by the window
  66.  *    - the palette, which specifies how many levels of each primary
  67.  *      color to use, and
  68.  *    - the gamma value for the image.
  69.  *
  70.  * Pixel values allocated for specific colors are valid only for the
  71.  * colormap in which they were allocated.  Sets of pixel values
  72.  * allocated for displaying photos are re-used in other windows if
  73.  * possible, that is, if the display, colormap, palette and gamma
  74.  * values match.  A hash table is used to locate these sets of pixel
  75.  * values, using the following data structure as key:
  76.  */
  77.  
  78. typedef struct {
  79.     Display *display;        /* Qualifies the colormap resource ID */
  80.     Colormap colormap;        /* Colormap that the windows are using. */
  81.     double gamma;        /* Gamma exponent value for images. */
  82.     Tk_Uid palette;        /* Specifies how many shades of each primary
  83.                  * we want to allocate. */
  84. } ColorTableId;
  85.  
  86. /*
  87.  * For a particular (display, colormap, palette, gamma) combination,
  88.  * a data structure of the following type is used to store the allocated
  89.  * pixel values and other information:
  90.  */
  91.  
  92. typedef struct ColorTable {
  93.     ColorTableId id;        /* Information used in selecting this
  94.                  * color table. */
  95.     int    flags;            /* See below. */
  96.     int    refCount;        /* Number of instances using this map. */
  97.     int liveRefCount;        /* Number of instances which are actually
  98.                  * in use, using this map. */
  99.     int    numColors;        /* Number of colors allocated for this map. */
  100.  
  101.     XVisualInfo    visualInfo;    /* Information about the visual for windows
  102.                  * using this color table. */
  103.  
  104.     pixel redValues[256];    /* Maps 8-bit values of red intensity
  105.                  * to a pixel value or index in pixelMap. */
  106.     pixel greenValues[256];    /* Ditto for green intensity */
  107.     pixel blueValues[256];    /* Ditto for blue intensity */
  108.     unsigned long *pixelMap;    /* Actual pixel values allocated. */
  109.  
  110.     unsigned char colorQuant[3][256];
  111.                 /* Maps 8-bit intensities to quantized
  112.                  * intensities.  The first index is 0 for
  113.                  * red, 1 for green, 2 for blue. */
  114. } ColorTable;
  115.  
  116. /*
  117.  * Bit definitions for the flags field of a ColorTable.
  118.  * BLACK_AND_WHITE:        1 means only black and white colors are
  119.  *                available.
  120.  * COLOR_WINDOW:        1 means a full 3-D color cube has been
  121.  *                allocated.
  122.  * DISPOSE_PENDING:        1 means a call to DisposeColorTable has
  123.  *                been scheduled as an idle handler, but it
  124.  *                hasn't been invoked yet.
  125.  * MAP_COLORS:            1 means pixel values should be mapped
  126.  *                through pixelMap.
  127.  */
  128.  
  129. #define BLACK_AND_WHITE        1
  130. #define COLOR_WINDOW        2
  131. #define DISPOSE_PENDING        4
  132. #define MAP_COLORS        8
  133.  
  134. /*
  135.  * Definition of the data associated with each photo image master.
  136.  */
  137.  
  138. typedef struct PhotoMaster {
  139.     Tk_ImageMaster tkMaster;    /* Tk's token for image master.  NULL means
  140.                  * the image is being deleted. */
  141.     Tcl_Interp *interp;        /* Interpreter associated with the
  142.                  * application using this image. */
  143.     Tcl_Command imageCmd;    /* Token for image command (used to delete
  144.                  * it when the image goes away).  NULL means
  145.                  * the image command has already been
  146.                  * deleted. */
  147.     int    flags;            /* Sundry flags, defined below. */
  148.     int    width, height;        /* Dimensions of image. */
  149.     int userWidth, userHeight;    /* User-declared image dimensions. */
  150.     Tk_Uid palette;        /* User-specified default palette for
  151.                  * instances of this image. */
  152.     double gamma;        /* Display gamma value to correct for. */
  153.     char *fileString;        /* Name of file to read into image. */
  154.     char *dataString;        /* String value to use as contents of image. */
  155.     char *format;        /* User-specified format of data in image
  156.                  * file or string value. */
  157.     unsigned char *pix24;    /* Local storage for 24-bit image. */
  158.     int ditherX, ditherY;    /* Location of first incorrectly
  159.                  * dithered pixel in image. */
  160.     TkRegion validRegion;    /* Tk region indicating which parts of
  161.                  * the image have valid image data. */
  162.     struct PhotoInstance *instancePtr;
  163.                 /* First in the list of instances
  164.                  * associated with this master. */
  165. } PhotoMaster;
  166.  
  167. /*
  168.  * Bit definitions for the flags field of a PhotoMaster.
  169.  * COLOR_IMAGE:            1 means that the image has different color
  170.  *                components.
  171.  * IMAGE_CHANGED:        1 means that the instances of this image
  172.  *                need to be redithered.
  173.  */
  174.  
  175. #define COLOR_IMAGE        1
  176. #define IMAGE_CHANGED        2
  177.  
  178. /*
  179.  * The following data structure represents all of the instances of
  180.  * a photo image in windows on a given screen that are using the
  181.  * same colormap.
  182.  */
  183.  
  184. typedef struct PhotoInstance {
  185.     PhotoMaster *masterPtr;    /* Pointer to master for image. */
  186.     Display *display;        /* Display for windows using this instance. */
  187.     Colormap colormap;        /* The image may only be used in windows with
  188.                  * this particular colormap. */
  189.     struct PhotoInstance *nextPtr;
  190.                 /* Pointer to the next instance in the list
  191.                  * of instances associated with this master. */
  192.     int refCount;        /* Number of instances using this structure. */
  193.     Tk_Uid palette;        /* Palette for these particular instances. */
  194.     double gamma;        /* Gamma value for these instances. */
  195.     Tk_Uid defaultPalette;    /* Default palette to use if a palette
  196.                  * is not specified for the master. */
  197.     ColorTable *colorTablePtr;    /* Pointer to information about colors
  198.                  * allocated for image display in windows
  199.                  * like this one. */
  200.     Pixmap pixels;        /* X pixmap containing dithered image. */
  201.     int width, height;        /* Dimensions of the pixmap. */
  202.     schar *error;        /* Error image, used in dithering. */
  203.     XImage *imagePtr;        /* Image structure for converted pixels. */
  204.     XVisualInfo visualInfo;    /* Information about the visual that these
  205.                  * windows are using. */
  206.     GC gc;            /* Graphics context for writing images
  207.                  * to the pixmap. */
  208. } PhotoInstance;
  209.  
  210. /*
  211.  * The following data structure is used to return information
  212.  * from ParseSubcommandOptions:
  213.  */
  214.  
  215. struct SubcommandOptions {
  216.     int options;        /* Individual bits indicate which
  217.                  * options were specified - see below. */
  218.     char *name;            /* Name specified without an option. */
  219.     int fromX, fromY;        /* Values specified for -from option. */
  220.     int fromX2, fromY2;        /* Second coordinate pair for -from option. */
  221.     int toX, toY;        /* Values specified for -to option. */
  222.     int toX2, toY2;        /* Second coordinate pair for -to option. */
  223.     int zoomX, zoomY;        /* Values specified for -zoom option. */
  224.     int subsampleX, subsampleY;    /* Values specified for -subsample option. */
  225.     char *format;        /* Value specified for -format option. */
  226. };
  227.  
  228. /*
  229.  * Bit definitions for use with ParseSubcommandOptions:
  230.  * Each bit is set in the allowedOptions parameter on a call to
  231.  * ParseSubcommandOptions if that option is allowed for the current
  232.  * photo image subcommand.  On return, the bit is set in the options
  233.  * field of the SubcommandOptions structure if that option was specified.
  234.  *
  235.  * OPT_FORMAT:            Set if -format option allowed/specified.
  236.  * OPT_FROM:            Set if -from option allowed/specified.
  237.  * OPT_SHRINK:            Set if -shrink option allowed/specified.
  238.  * OPT_SUBSAMPLE:        Set if -subsample option allowed/spec'd.
  239.  * OPT_TO:            Set if -to option allowed/specified.
  240.  * OPT_ZOOM:            Set if -zoom option allowed/specified.
  241.  */
  242.  
  243. #define OPT_FORMAT    1
  244. #define OPT_FROM    2
  245. #define OPT_SHRINK    4
  246. #define OPT_SUBSAMPLE    8
  247. #define OPT_TO        0x10
  248. #define OPT_ZOOM    0x20
  249.  
  250. /*
  251.  * List of option names.  The order here must match the order of
  252.  * declarations of the OPT_* constants above.
  253.  */
  254.  
  255. static char *optionNames[] = {
  256.     "-format",
  257.     "-from",
  258.     "-shrink",
  259.     "-subsample",
  260.     "-to",
  261.     "-zoom",
  262.     (char *) NULL
  263. };
  264.  
  265. /*
  266.  * The type record for photo images:
  267.  */
  268.  
  269. static int        ImgPhotoCreate _ANSI_ARGS_((Tcl_Interp *interp,
  270.                 char *name, int argc, char **argv,
  271.                 Tk_ImageType *typePtr, Tk_ImageMaster master,
  272.                 ClientData *clientDataPtr));
  273. static ClientData    ImgPhotoGet _ANSI_ARGS_((Tk_Window tkwin,
  274.                 ClientData clientData));
  275. static void        ImgPhotoDisplay _ANSI_ARGS_((ClientData clientData,
  276.                 Display *display, Drawable drawable,
  277.                 int imageX, int imageY, int width, int height,
  278.                 int drawableX, int drawableY));
  279. static void        ImgPhotoFree _ANSI_ARGS_((ClientData clientData,
  280.                 Display *display));
  281. static void        ImgPhotoDelete _ANSI_ARGS_((ClientData clientData));
  282.  
  283. Tk_ImageType tkPhotoImageType = {
  284.     "photo",            /* name */
  285.     ImgPhotoCreate,        /* createProc */
  286.     ImgPhotoGet,        /* getProc */
  287.     ImgPhotoDisplay,        /* displayProc */
  288.     ImgPhotoFree,        /* freeProc */
  289.     ImgPhotoDelete,        /* deleteProc */
  290.     (Tk_ImageType *) NULL    /* nextPtr */
  291. };
  292.  
  293. /*
  294.  * Default configuration
  295.  */
  296.  
  297. #define DEF_PHOTO_GAMMA        "1"
  298. #define DEF_PHOTO_HEIGHT    "0"
  299. #define DEF_PHOTO_PALETTE    ""
  300. #define DEF_PHOTO_WIDTH        "0"
  301.  
  302. /*
  303.  * Information used for parsing configuration specifications:
  304.  */
  305. static Tk_ConfigSpec configSpecs[] = {
  306.     {TK_CONFIG_STRING, "-data", (char *) NULL, (char *) NULL,
  307.      (char *) NULL, Tk_Offset(PhotoMaster, dataString), TK_CONFIG_NULL_OK},
  308.     {TK_CONFIG_STRING, "-format", (char *) NULL, (char *) NULL,
  309.      (char *) NULL, Tk_Offset(PhotoMaster, format), TK_CONFIG_NULL_OK},
  310.     {TK_CONFIG_STRING, "-file", (char *) NULL, (char *) NULL,
  311.      (char *) NULL, Tk_Offset(PhotoMaster, fileString), TK_CONFIG_NULL_OK},
  312.     {TK_CONFIG_DOUBLE, "-gamma", (char *) NULL, (char *) NULL,
  313.      DEF_PHOTO_GAMMA, Tk_Offset(PhotoMaster, gamma), 0},
  314.     {TK_CONFIG_INT, "-height", (char *) NULL, (char *) NULL,
  315.      DEF_PHOTO_HEIGHT, Tk_Offset(PhotoMaster, userHeight), 0},
  316.     {TK_CONFIG_UID, "-palette", (char *) NULL, (char *) NULL,
  317.      DEF_PHOTO_PALETTE, Tk_Offset(PhotoMaster, palette), 0},
  318.     {TK_CONFIG_INT, "-width", (char *) NULL, (char *) NULL,
  319.      DEF_PHOTO_WIDTH, Tk_Offset(PhotoMaster, userWidth), 0},
  320.     {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL,
  321.      (char *) NULL, 0, 0}
  322. };
  323.  
  324. /*
  325.  * Hash table used to provide access to photo images from C code.
  326.  */
  327.  
  328. static Tcl_HashTable imgPhotoHash;
  329. static int imgPhotoHashInitialized;    /* set when Tcl_InitHashTable done */
  330.  
  331. /*
  332.  * Hash table used to hash from (display, colormap, palette, gamma)
  333.  * to ColorTable address.
  334.  */
  335.  
  336. static Tcl_HashTable imgPhotoColorHash;
  337. static int imgPhotoColorHashInitialized;
  338. #define N_COLOR_HASH    (sizeof(ColorTableId) / sizeof(int))
  339.  
  340. /*
  341.  * Pointer to the first in the list of known photo image formats.
  342.  */
  343.  
  344. static Tk_PhotoImageFormat *formatList = NULL;
  345.  
  346. /*
  347.  * Forward declarations
  348.  */
  349.  
  350. static int        ImgPhotoCmd _ANSI_ARGS_((ClientData clientData,
  351.                 Tcl_Interp *interp, int argc, char **argv));
  352. static int        ParseSubcommandOptions _ANSI_ARGS_((
  353.                 struct SubcommandOptions *optPtr,
  354.                 Tcl_Interp *interp, int allowedOptions,
  355.                 int *indexPtr, int argc, char **argv));
  356. static void        ImgPhotoCmdDeletedProc _ANSI_ARGS_((
  357.                 ClientData clientData));
  358. static int        ImgPhotoConfigureMaster _ANSI_ARGS_((
  359.                 Tcl_Interp *interp, PhotoMaster *masterPtr,
  360.                 int argc, char **argv, int flags));
  361. static void        ImgPhotoConfigureInstance _ANSI_ARGS_((
  362.                 PhotoInstance *instancePtr));
  363. static void        ImgPhotoSetSize _ANSI_ARGS_((PhotoMaster *masterPtr,
  364.                 int width, int height));
  365. static void        ImgPhotoInstanceSetSize _ANSI_ARGS_((
  366.                 PhotoInstance *instancePtr));
  367. static int        IsValidPalette _ANSI_ARGS_((PhotoInstance *instancePtr,
  368.                 char *palette));
  369. static int        CountBits _ANSI_ARGS_((pixel mask));
  370. static void        GetColorTable _ANSI_ARGS_((PhotoInstance *instancePtr));
  371. static void        FreeColorTable _ANSI_ARGS_((ColorTable *colorPtr));
  372. static void        AllocateColors _ANSI_ARGS_((ColorTable *colorPtr));
  373. static void        DisposeColorTable _ANSI_ARGS_((ClientData clientData));
  374. static void        DisposeInstance _ANSI_ARGS_((ClientData clientData));
  375. static int        ReclaimColors _ANSI_ARGS_((ColorTableId *id,
  376.                 int numColors));
  377. static int        MatchFileFormat _ANSI_ARGS_((Tcl_Interp *interp,
  378.                 FILE *f, char *fileName, char *formatString,
  379.                 Tk_PhotoImageFormat **imageFormatPtr,
  380.                 int *widthPtr, int *heightPtr));
  381. static int        MatchStringFormat _ANSI_ARGS_((Tcl_Interp *interp,
  382.                 char *string, char *formatString,
  383.                 Tk_PhotoImageFormat **imageFormatPtr,
  384.                 int *widthPtr, int *heightPtr));
  385. static void        Dither _ANSI_ARGS_((PhotoMaster *masterPtr,
  386.                 int x, int y, int width, int height));
  387. static void        DitherInstance _ANSI_ARGS_((PhotoInstance *instancePtr,
  388.                 int x, int y, int width, int height));
  389.  
  390. #undef MIN
  391. #define MIN(a, b)    ((a) < (b)? (a): (b))
  392. #undef MAX
  393. #define MAX(a, b)    ((a) > (b)? (a): (b))
  394.  
  395. /*
  396.  *----------------------------------------------------------------------
  397.  *
  398.  * Tk_CreatePhotoImageFormat --
  399.  *
  400.  *    This procedure is invoked by an image file handler to register
  401.  *    a new photo image format and the procedures that handle the
  402.  *    new format.  The procedure is typically invoked during
  403.  *    Tcl_AppInit.
  404.  *
  405.  * Results:
  406.  *    None.
  407.  *
  408.  * Side effects:
  409.  *    The new image file format is entered into a table used in the
  410.  *    photo image "read" and "write" subcommands.
  411.  *
  412.  *----------------------------------------------------------------------
  413.  */
  414.  
  415. void
  416. Tk_CreatePhotoImageFormat(formatPtr)
  417.     Tk_PhotoImageFormat *formatPtr;
  418.                 /* Structure describing the format.  All of
  419.                  * the fields except "nextPtr" must be filled
  420.                  * in by caller.  Must not have been passed
  421.                  * to Tk_CreatePhotoImageFormat previously. */
  422. {
  423.     Tk_PhotoImageFormat *copyPtr;
  424.  
  425.     copyPtr = (Tk_PhotoImageFormat *) ckalloc(sizeof(Tk_PhotoImageFormat));
  426.     *copyPtr = *formatPtr;
  427.     copyPtr->name = (char *) ckalloc((unsigned) (strlen(formatPtr->name) + 1));
  428.     strcpy(copyPtr->name, formatPtr->name);
  429.     copyPtr->nextPtr = formatList;
  430.     formatList = copyPtr;
  431. }
  432.  
  433. /*
  434.  *----------------------------------------------------------------------
  435.  *
  436.  * ImgPhotoCreate --
  437.  *
  438.  *    This procedure is called by the Tk image code to create
  439.  *    a new photo image.
  440.  *
  441.  * Results:
  442.  *    A standard Tcl result.
  443.  *
  444.  * Side effects:
  445.  *    The data structure for a new photo image is allocated and
  446.  *    initialized.
  447.  *
  448.  *----------------------------------------------------------------------
  449.  */
  450.  
  451. static int
  452. ImgPhotoCreate(interp, name, argc, argv, typePtr, master, clientDataPtr)
  453.     Tcl_Interp *interp;        /* Interpreter for application containing
  454.                  * image. */
  455.     char *name;            /* Name to use for image. */
  456.     int argc;            /* Number of arguments. */
  457.     char **argv;        /* Argument strings for options (doesn't
  458.                  * include image name or type). */
  459.     Tk_ImageType *typePtr;    /* Pointer to our type record (not used). */
  460.     Tk_ImageMaster master;    /* Token for image, to be used by us in
  461.                  * later callbacks. */
  462.     ClientData *clientDataPtr;    /* Store manager's token for image here;
  463.                  * it will be returned in later callbacks. */
  464. {
  465.     PhotoMaster *masterPtr;
  466.     Tcl_HashEntry *entry;
  467.     int isNew;
  468.  
  469.     /*
  470.      * Allocate and initialize the photo image master record.
  471.      */
  472.  
  473.     masterPtr = (PhotoMaster *) ckalloc(sizeof(PhotoMaster));
  474.     memset((void *) masterPtr, 0, sizeof(PhotoMaster));
  475.     masterPtr->tkMaster = master;
  476.     masterPtr->interp = interp;
  477.     masterPtr->imageCmd = Tcl_CreateCommand(interp, name, ImgPhotoCmd,
  478.         (ClientData) masterPtr, ImgPhotoCmdDeletedProc);
  479.     masterPtr->palette = NULL;
  480.     masterPtr->pix24 = NULL;
  481.     masterPtr->instancePtr = NULL;
  482.     masterPtr->validRegion = TkCreateRegion();
  483.  
  484.     /*
  485.      * Process configuration options given in the image create command.
  486.      */
  487.  
  488.     if (ImgPhotoConfigureMaster(interp, masterPtr, argc, argv, 0) != TCL_OK) {
  489.     ImgPhotoDelete((ClientData) masterPtr);
  490.     return TCL_ERROR;
  491.     }
  492.  
  493.     /*
  494.      * Enter this photo image in the hash table.
  495.      */
  496.  
  497.     if (!imgPhotoHashInitialized) {
  498.     Tcl_InitHashTable(&imgPhotoHash, TCL_STRING_KEYS);
  499.     imgPhotoHashInitialized = 1;
  500.     }
  501.     entry = Tcl_CreateHashEntry(&imgPhotoHash, name, &isNew);
  502.     Tcl_SetHashValue(entry, masterPtr);
  503.  
  504.     *clientDataPtr = (ClientData) masterPtr;
  505.     return TCL_OK;
  506. }
  507.  
  508. /*
  509.  *----------------------------------------------------------------------
  510.  *
  511.  * ImgPhotoCmd --
  512.  *
  513.  *    This procedure is invoked to process the Tcl command that
  514.  *    corresponds to a photo image.  See the user documentation
  515.  *    for details on what it does.
  516.  *
  517.  * Results:
  518.  *    A standard Tcl result.
  519.  *
  520.  * Side effects:
  521.  *    See the user documentation.
  522.  *
  523.  *----------------------------------------------------------------------
  524.  */
  525.  
  526. static int
  527. ImgPhotoCmd(clientData, interp, argc, argv)
  528.     ClientData clientData;    /* Information about photo master. */
  529.     Tcl_Interp *interp;        /* Current interpreter. */
  530.     int argc;            /* Number of arguments. */
  531.     char **argv;        /* Argument strings. */
  532. {
  533.     PhotoMaster *masterPtr = (PhotoMaster *) clientData;
  534.     int c, result, index;
  535.     int x, y, width, height;
  536.     int dataWidth, dataHeight;
  537.     struct SubcommandOptions options;
  538.     int listArgc;
  539.     char **listArgv;
  540.     char **srcArgv;
  541.     unsigned char *pixelPtr;
  542.     Tk_PhotoImageBlock block;
  543.     Tk_Window tkwin;
  544.     char string[16];
  545.     XColor color;
  546.     Tk_PhotoImageFormat *imageFormat;
  547.     int imageWidth, imageHeight;
  548.     int matched;
  549.     FILE *f;
  550.     Tk_PhotoHandle srcHandle;
  551.     size_t length;
  552.     Tcl_DString buffer;
  553.     char *realFileName;
  554.  
  555.     if (argc < 2) {
  556.     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
  557.         " option ?arg arg ...?\"", (char *) NULL);
  558.     return TCL_ERROR;
  559.     }
  560.     c = argv[1][0];
  561.     length = strlen(argv[1]);
  562.  
  563.     if ((c == 'b') && (strncmp(argv[1], "blank", length) == 0)) {
  564.     /*
  565.      * photo blank command - just call Tk_PhotoBlank.
  566.      */
  567.  
  568.     if (argc == 2) {
  569.         Tk_PhotoBlank(masterPtr);
  570.     } else {
  571.         Tcl_AppendResult(interp, "wrong # args: should be \"",
  572.             argv[0], " blank\"", (char *) NULL);
  573.         return TCL_ERROR;
  574.     }
  575.     } else if ((c == 'c') && (length >= 2)
  576.         && (strncmp(argv[1], "cget", length) == 0)) {
  577.     if (argc != 3) {
  578.         Tcl_AppendResult(interp, "wrong # args: should be \"",
  579.             argv[0], " cget option\"",
  580.             (char *) NULL);
  581.         return TCL_ERROR;
  582.     }
  583.     result = Tk_ConfigureValue(interp, Tk_MainWindow(interp), configSpecs,
  584.         (char *) masterPtr, argv[2], 0);
  585.     } else if ((c == 'c') && (length >= 3)
  586.         && (strncmp(argv[1], "configure", length) == 0)) {
  587.     /*
  588.      * photo configure command - handle this in the standard way.
  589.      */
  590.  
  591.     if (argc == 2) {
  592.         return Tk_ConfigureInfo(interp, Tk_MainWindow(interp),
  593.             configSpecs, (char *) masterPtr, (char *) NULL, 0);
  594.     }
  595.     if (argc == 3) {
  596.         return Tk_ConfigureInfo(interp, Tk_MainWindow(interp),
  597.             configSpecs, (char *) masterPtr, argv[2], 0);
  598.     }
  599.     return ImgPhotoConfigureMaster(interp, masterPtr, argc-2, argv+2,
  600.         TK_CONFIG_ARGV_ONLY);
  601.     } else if ((c == 'c') && (length >= 3)
  602.         && (strncmp(argv[1], "copy", length) == 0)) {
  603.     /*
  604.      * photo copy command - first parse options.
  605.      */
  606.  
  607.     index = 2;
  608.     memset((VOID *) &options, 0, sizeof(options));
  609.     options.zoomX = options.zoomY = 1;
  610.     options.subsampleX = options.subsampleY = 1;
  611.     options.name = NULL;
  612.     if (ParseSubcommandOptions(&options, interp,
  613.         OPT_FROM | OPT_TO | OPT_ZOOM | OPT_SUBSAMPLE | OPT_SHRINK,
  614.         &index, argc, argv) != TCL_OK) {
  615.         return TCL_ERROR;
  616.     }
  617.     if (options.name == NULL || index < argc) {
  618.         Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
  619.             " copy source-image ?-from x1 y1 x2 y2?",
  620.             " ?-to x1 y1 x2 y2? ?-zoom x y? ?-subsample x y?",
  621.             "\"", (char *) NULL);
  622.         return TCL_ERROR;
  623.     }
  624.  
  625.     /*
  626.      * Look for the source image and get a pointer to its image data.
  627.      * Check the values given for the -from option.
  628.      */
  629.  
  630.     if ((srcHandle = Tk_FindPhoto(options.name)) == NULL) {
  631.         Tcl_AppendResult(interp, "image \"", argv[2], "\" doesn't",
  632.             " exist or is not a photo image", (char *) NULL);
  633.         return TCL_ERROR;
  634.     }
  635.     Tk_PhotoGetImage(srcHandle, &block);
  636.     if ((options.fromX2 > block.width) || (options.fromY2 > block.height)
  637.         || (options.fromX2 > block.width)
  638.         || (options.fromY2 > block.height)) {
  639.         Tcl_AppendResult(interp, "coordinates for -from option extend ",
  640.             "outside source image", (char *) NULL);
  641.         return TCL_ERROR;
  642.     }
  643.  
  644.     /*
  645.      * Fill in default values for unspecified parameters.
  646.      */
  647.  
  648.     if (((options.options & OPT_FROM) == 0) || (options.fromX2 < 0)) {
  649.         options.fromX2 = block.width;
  650.         options.fromY2 = block.height;
  651.     }
  652.     if (((options.options & OPT_TO) == 0) || (options.toX2 < 0)) {
  653.         width = options.fromX2 - options.fromX;
  654.         if (options.subsampleX > 0) {
  655.         width = (width + options.subsampleX - 1) / options.subsampleX;
  656.         } else if (options.subsampleX == 0) {
  657.         width = 0;
  658.         } else {
  659.         width = (width - options.subsampleX - 1) / -options.subsampleX;
  660.         }
  661.         options.toX2 = options.toX + width * options.zoomX;
  662.  
  663.         height = options.fromY2 - options.fromY;
  664.         if (options.subsampleY > 0) {
  665.         height = (height + options.subsampleY - 1)
  666.             / options.subsampleY;
  667.         } else if (options.subsampleY == 0) {
  668.         height = 0;
  669.         } else {
  670.         height = (height - options.subsampleY - 1)
  671.             / -options.subsampleY;
  672.         }
  673.         options.toY2 = options.toY + height * options.zoomY;
  674.     }
  675.  
  676.     /*
  677.      * Set the destination image size if the -shrink option was specified.
  678.      */
  679.  
  680.     if (options.options & OPT_SHRINK) {
  681.         ImgPhotoSetSize(masterPtr, options.toX2, options.toY2);
  682.     }
  683.  
  684.     /*
  685.      * Copy the image data over using Tk_PhotoPutZoomedBlock.
  686.      */
  687.  
  688.     block.pixelPtr += options.fromX * block.pixelSize
  689.         + options.fromY * block.pitch;
  690.     block.width = options.fromX2 - options.fromX;
  691.     block.height = options.fromY2 - options.fromY;
  692.     Tk_PhotoPutZoomedBlock((Tk_PhotoHandle) masterPtr, &block,
  693.         options.toX, options.toY, options.toX2 - options.toX,
  694.         options.toY2 - options.toY, options.zoomX, options.zoomY,
  695.         options.subsampleX, options.subsampleY);
  696.  
  697.     } else if ((c == 'g') && (strncmp(argv[1], "get", length) == 0)) {
  698.     /*
  699.      * photo get command - first parse and check parameters.
  700.      */
  701.  
  702.     if (argc != 4) {
  703.         Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
  704.             " get x y\"", (char *) NULL);
  705.         return TCL_ERROR;
  706.     }
  707.     if ((Tcl_GetInt(interp, argv[2], &x) != TCL_OK)
  708.         || (Tcl_GetInt(interp, argv[3], &y) != TCL_OK)) {
  709.         return TCL_ERROR;
  710.     }
  711.     if ((x < 0) || (x >= masterPtr->width)
  712.         || (y < 0) || (y >= masterPtr->height)) {
  713.         Tcl_AppendResult(interp, argv[0], " get: ",
  714.             "coordinates out of range", (char *) NULL);
  715.         return TCL_ERROR;
  716.     }
  717.  
  718.     /*
  719.      * Extract the value of the desired pixel and format it as a string.
  720.      */
  721.  
  722.     pixelPtr = masterPtr->pix24 + (y * masterPtr->width + x) * 3;
  723.     sprintf(string, "%d %d %d", pixelPtr[0], pixelPtr[1],
  724.         pixelPtr[2]);
  725.     Tcl_AppendResult(interp, string, (char *) NULL);
  726.     } else if ((c == 'p') && (strncmp(argv[1], "put", length) == 0)) {
  727.     /*
  728.      * photo put command - first parse the options and colors specified.
  729.      */
  730.  
  731.     index = 2;
  732.     memset((VOID *) &options, 0, sizeof(options));
  733.     options.name = NULL;
  734.     if (ParseSubcommandOptions(&options, interp, OPT_TO,
  735.            &index, argc, argv) != TCL_OK) {
  736.         return TCL_ERROR;
  737.     }
  738.     if ((options.name == NULL) || (index < argc)) {
  739.         Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
  740.              " put {{colors...}...} ?-to x1 y1 x2 y2?\"",
  741.              (char *) NULL);
  742.         return TCL_ERROR;
  743.     }
  744.     if (Tcl_SplitList(interp, options.name, &dataHeight, &srcArgv)
  745.         != TCL_OK) {
  746.         return TCL_ERROR;
  747.     }
  748.     tkwin = Tk_MainWindow(interp);
  749.     block.pixelPtr = NULL;
  750.     dataWidth = 0;
  751.     pixelPtr = NULL;
  752.     for (y = 0; y < dataHeight; ++y) {
  753.         if (Tcl_SplitList(interp, srcArgv[y], &listArgc, &listArgv)
  754.             != TCL_OK) {
  755.         break;
  756.         }
  757.         if (y == 0) {
  758.         dataWidth = listArgc;
  759.         pixelPtr = (unsigned char *) ckalloc((unsigned)
  760.             dataWidth * dataHeight * 3);
  761.         block.pixelPtr = pixelPtr;
  762.         } else {
  763.         if (listArgc != dataWidth) {
  764.             Tcl_AppendResult(interp, "all elements of color list must",
  765.                  " have the same number of elements",
  766.                 (char *) NULL);
  767.             ckfree((char *) listArgv);
  768.             break;
  769.         }
  770.         }
  771.         for (x = 0; x < dataWidth; ++x) {
  772.         if (!XParseColor(Tk_Display(tkwin), Tk_Colormap(tkwin),
  773.             listArgv[x], &color)) {
  774.             Tcl_AppendResult(interp, "can't parse color \"",
  775.                 listArgv[x], "\"", (char *) NULL);
  776.             break;
  777.         }
  778.         *pixelPtr++ = color.red >> 8;
  779.         *pixelPtr++ = color.green >> 8;
  780.         *pixelPtr++ = color.blue >> 8;
  781.         }
  782.         ckfree((char *) listArgv);
  783.         if (x < dataWidth)
  784.         break;
  785.     }
  786.     ckfree((char *) srcArgv);
  787.     if (y < dataHeight || dataHeight == 0 || dataWidth == 0) {
  788.         if (block.pixelPtr != NULL) {
  789.         ckfree((char *) block.pixelPtr);
  790.         }
  791.         if (y < dataHeight) {
  792.         return TCL_ERROR;
  793.         }
  794.         return TCL_OK;
  795.     }
  796.  
  797.     /*
  798.      * Fill in default values for the -to option, then
  799.      * copy the block in using Tk_PhotoPutBlock.
  800.      */
  801.  
  802.     if (((options.options & OPT_TO) == 0) || (options.toX2 < 0)) {
  803.         options.toX2 = options.toX + dataWidth;
  804.         options.toY2 = options.toY + dataHeight;
  805.     }
  806.     block.width = dataWidth;
  807.     block.height = dataHeight;
  808.     block.pitch = dataWidth * 3;
  809.     block.pixelSize = 3;
  810.     block.offset[0] = 0;
  811.     block.offset[1] = 1;
  812.     block.offset[2] = 2;
  813.     Tk_PhotoPutBlock((ClientData)masterPtr, &block,
  814.         options.toX, options.toY, options.toX2 - options.toX,
  815.         options.toY2 - options.toY);
  816.     ckfree((char *) block.pixelPtr);
  817.     } else if ((c == 'r') && (length >= 3)
  818.            && (strncmp(argv[1], "read", length) == 0)) {
  819.     /*
  820.      * photo read command - first parse the options specified.
  821.      */
  822.  
  823.     index = 2;
  824.     memset((VOID *) &options, 0, sizeof(options));
  825.     options.name = NULL;
  826.     options.format = NULL;
  827.     if (ParseSubcommandOptions(&options, interp,
  828.         OPT_FORMAT | OPT_FROM | OPT_TO | OPT_SHRINK,
  829.         &index, argc, argv) != TCL_OK) {
  830.         return TCL_ERROR;
  831.     }
  832.     if ((options.name == NULL) || (index < argc)) {
  833.         Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
  834.             " read fileName ?-format format-name?",
  835.             " ?-from x1 y1 x2 y2? ?-to x y? ?-shrink?\"",
  836.             (char *) NULL);
  837.         return TCL_ERROR;
  838.     }
  839.  
  840.     /*
  841.      * Open the image file and look for a handler for it.
  842.      */
  843.  
  844.     realFileName = Tcl_TranslateFileName(interp, options.name, &buffer);
  845.     if (realFileName == NULL) {
  846.         return TCL_ERROR;
  847.     }
  848.     f = fopen(realFileName, "rb");
  849.     Tcl_DStringFree(&buffer);
  850.     if (f == NULL) {
  851.         Tcl_AppendResult(interp, "couldn't read image file \"",
  852.             options.name, "\": ", Tcl_PosixError(interp),
  853.             (char *) NULL);
  854.         return TCL_ERROR;
  855.     }
  856.     if (MatchFileFormat(interp, f, options.name, options.format,
  857.         &imageFormat, &imageWidth, &imageHeight) != TCL_OK) {
  858.         fclose(f);
  859.         return TCL_ERROR;
  860.     }
  861.  
  862.     /*
  863.      * Check the values given for the -from option.
  864.      */
  865.  
  866.     if ((options.fromX > imageWidth) || (options.fromY > imageHeight)
  867.         || (options.fromX2 > imageWidth)
  868.         || (options.fromY2 > imageHeight)) {
  869.         Tcl_AppendResult(interp, "coordinates for -from option extend ",
  870.             "outside source image", (char *) NULL);
  871.         fclose(f);
  872.         return TCL_ERROR;
  873.     }
  874.     if (((options.options & OPT_FROM) == 0) || (options.fromX2 < 0)) {
  875.         width = imageWidth - options.fromX;
  876.         height = imageHeight - options.fromY;
  877.     } else {
  878.         width = options.fromX2 - options.fromX;
  879.         height = options.fromY2 - options.fromY;
  880.     }
  881.  
  882.     /*
  883.      * If the -shrink option was specified, set the size of the image.
  884.      */
  885.  
  886.     if (options.options & OPT_SHRINK) {
  887.         ImgPhotoSetSize(masterPtr, options.toX + width,
  888.             options.toY + height);
  889.     }
  890.  
  891.     /*
  892.      * Call the handler's file read procedure to read the data
  893.      * into the image.
  894.      */
  895.  
  896.     result = (*imageFormat->fileReadProc)(interp, f, options.name,
  897.         options.format, (Tk_PhotoHandle) masterPtr, options.toX,
  898.         options.toY, width, height, options.fromX, options.fromY);
  899.     if (f != NULL) {
  900.         fclose(f);
  901.     }
  902.     return result;
  903.     } else if ((c == 'r') && (length >= 3)
  904.            && (strncmp(argv[1], "redither", length) == 0)) {
  905.  
  906.     if (argc == 2) {
  907.         /*
  908.          * Call Dither if any part of the image is not correctly
  909.          * dithered at present.
  910.          */
  911.  
  912.         x = masterPtr->ditherX;
  913.         y = masterPtr->ditherY;
  914.         if (masterPtr->ditherX != 0) {
  915.         Dither(masterPtr, x, y, masterPtr->width - x, 1);
  916.         }
  917.         if (masterPtr->ditherY < masterPtr->height) {
  918.         x = 0;
  919.         Dither(masterPtr, 0, masterPtr->ditherY, masterPtr->width,
  920.             masterPtr->height - masterPtr->ditherY);
  921.         }
  922.  
  923.         if (y < masterPtr->height) {
  924.         /*
  925.          * Tell the core image code that part of the image has changed.
  926.          */
  927.  
  928.         Tk_ImageChanged(masterPtr->tkMaster, x, y,
  929.             (masterPtr->width - x), (masterPtr->height - y),
  930.             masterPtr->width, masterPtr->height);
  931.         }
  932.  
  933.     } else {
  934.         Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
  935.             " redither\"", (char *) NULL);
  936.         return TCL_ERROR;
  937.     }
  938.     } else if ((c == 'w') && (strncmp(argv[1], "write", length) == 0)) {
  939.     /*
  940.      * photo write command - first parse and check any options given.
  941.      */
  942.  
  943.     index = 2;
  944.     memset((VOID *) &options, 0, sizeof(options));
  945.     options.name = NULL;
  946.     options.format = NULL;
  947.     if (ParseSubcommandOptions(&options, interp, OPT_FORMAT | OPT_FROM,
  948.         &index, argc, argv) != TCL_OK) {
  949.         return TCL_ERROR;
  950.     }
  951.     if ((options.name == NULL) || (index < argc)) {
  952.         Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
  953.             " write fileName ?-format format-name?",
  954.             "?-from x1 y1 x2 y2?\"", (char *) NULL);
  955.         return TCL_ERROR;
  956.     }
  957.     if ((options.fromX > masterPtr->width)
  958.         || (options.fromY > masterPtr->height)
  959.         || (options.fromX2 > masterPtr->width)
  960.         || (options.fromY2 > masterPtr->height)) {
  961.         Tcl_AppendResult(interp, "coordinates for -from option extend ",
  962.             "outside image", (char *) NULL);
  963.         return TCL_ERROR;
  964.     }
  965.  
  966.     /*
  967.      * Fill in default values for unspecified parameters.
  968.      */
  969.  
  970.     if (((options.options & OPT_FROM) == 0) || (options.fromX2 < 0)) {
  971.         options.fromX2 = masterPtr->width;
  972.         options.fromY2 = masterPtr->height;
  973.     }
  974.  
  975.     /*
  976.      * Search for an appropriate image file format handler,
  977.      * and give an error if none is found.
  978.      */
  979.  
  980.     matched = 0;
  981.     for (imageFormat = formatList; imageFormat != NULL;
  982.          imageFormat = imageFormat->nextPtr) {
  983.         if ((options.format == NULL)
  984.             || (strncasecmp(options.format, imageFormat->name,
  985.             strlen(imageFormat->name)) == 0)) {
  986.         matched = 1;
  987.         if (imageFormat->fileWriteProc != NULL) {
  988.             break;
  989.         }
  990.         }
  991.     }
  992.     if (imageFormat == NULL) {
  993.         if (options.format == NULL) {
  994.         Tcl_AppendResult(interp, "no available image file format ",
  995.             "has file writing capability", (char *) NULL);
  996.         } else if (!matched) {
  997.         Tcl_AppendResult(interp, "image file format \"",
  998.             options.format, "\" is unknown", (char *) NULL);
  999.         } else {
  1000.         Tcl_AppendResult(interp, "image file format \"",
  1001.             options.format, "\" has no file writing capability",
  1002.             (char *) NULL);
  1003.         }
  1004.         return TCL_ERROR;
  1005.     }
  1006.  
  1007.     /*
  1008.      * Call the handler's file write procedure to write out
  1009.      * the image.
  1010.      */
  1011.  
  1012.     Tk_PhotoGetImage((Tk_PhotoHandle) masterPtr, &block);
  1013.     block.pixelPtr += options.fromY * block.pitch + options.fromX * 3;
  1014.     block.width = options.fromX2 - options.fromX;
  1015.     block.height = options.fromY2 - options.fromY;
  1016.     return (*imageFormat->fileWriteProc)(interp, options.name,
  1017.         options.format, &block);
  1018.     } else {
  1019.     Tcl_AppendResult(interp, "bad option \"", argv[1],
  1020.         "\": must be blank, cget, configure, copy, get, put,",
  1021.         " read, redither, or write", (char *) NULL);
  1022.     return TCL_ERROR;
  1023.     }
  1024.  
  1025.     return TCL_OK;
  1026. }
  1027.  
  1028. /*
  1029.  *----------------------------------------------------------------------
  1030.  *
  1031.  * ParseSubcommandOptions --
  1032.  *
  1033.  *    This procedure is invoked to process one of the options
  1034.  *    which may be specified for the photo image subcommands,
  1035.  *    namely, -from, -to, -zoom, -subsample, -format, and -shrink.
  1036.  *
  1037.  * Results:
  1038.  *    A standard Tcl result.
  1039.  *
  1040.  * Side effects:
  1041.  *    Fields in *optPtr get filled in.
  1042.  *
  1043.  *----------------------------------------------------------------------
  1044.  */
  1045.  
  1046. static int
  1047. ParseSubcommandOptions(optPtr, interp, allowedOptions, optIndexPtr, argc, argv)
  1048.     struct SubcommandOptions *optPtr;
  1049.                 /* Information about the options specified
  1050.                  * and the values given is returned here. */
  1051.     Tcl_Interp *interp;        /* Interpreter to use for reporting errors. */
  1052.     int allowedOptions;        /* Indicates which options are valid for
  1053.                  * the current command. */
  1054.     int *optIndexPtr;        /* Points to a variable containing the
  1055.                  * current index in argv; this variable is
  1056.                  * updated by this procedure. */
  1057.     int argc;            /* Number of arguments in argv[]. */
  1058.     char **argv;        /* Arguments to be parsed. */
  1059. {
  1060.     int index, c, bit, currentBit;
  1061.     size_t length;
  1062.     char *option, **listPtr;
  1063.     int values[4];
  1064.     int numValues, maxValues, argIndex;
  1065.  
  1066.     for (index = *optIndexPtr; index < argc; *optIndexPtr = ++index) {
  1067.     /*
  1068.      * We can have one value specified without an option;
  1069.      * it goes into optPtr->name.
  1070.      */
  1071.  
  1072.     option = argv[index];
  1073.     if (option[0] != '-') {
  1074.         if (optPtr->name == NULL) {
  1075.         optPtr->name = option;
  1076.         continue;
  1077.         }
  1078.         break;
  1079.     }
  1080.  
  1081.     /*
  1082.      * Work out which option this is.
  1083.      */
  1084.  
  1085.     length = strlen(option);
  1086.     c = option[0];
  1087.     bit = 0;
  1088.     currentBit = 1;
  1089.     for (listPtr = optionNames; *listPtr != NULL; ++listPtr) {
  1090.         if ((c == *listPtr[0])
  1091.             && (strncmp(option, *listPtr, length) == 0)) {
  1092.         if (bit != 0) {
  1093.             bit = 0;    /* An ambiguous option. */
  1094.             break;
  1095.         }
  1096.         bit = currentBit;
  1097.         }
  1098.         currentBit <<= 1;
  1099.     }
  1100.  
  1101.     /*
  1102.      * If this option is not recognized and allowed, put
  1103.      * an error message in the interpreter and return.
  1104.      */
  1105.  
  1106.     if ((allowedOptions & bit) == 0) {
  1107.         Tcl_AppendResult(interp, "unrecognized option \"", argv[index],
  1108.             "\": must be ", (char *)NULL);
  1109.         bit = 1;
  1110.         for (listPtr = optionNames; *listPtr != NULL; ++listPtr) {
  1111.         if ((allowedOptions & bit) != 0) {
  1112.             if ((allowedOptions & (bit - 1)) != 0) {
  1113.             Tcl_AppendResult(interp, ", ", (char *) NULL);
  1114.             if ((allowedOptions & ~((bit << 1) - 1)) == 0) {
  1115.                 Tcl_AppendResult(interp, "or ", (char *) NULL);
  1116.             }
  1117.             }
  1118.             Tcl_AppendResult(interp, *listPtr, (char *) NULL);
  1119.         }
  1120.         bit <<= 1;
  1121.         }
  1122.         return TCL_ERROR;
  1123.     }
  1124.  
  1125.     /*
  1126.      * For the -from, -to, -zoom and -subsample options,
  1127.      * parse the values given.  Report an error if too few
  1128.      * or too many values are given.
  1129.      */
  1130.  
  1131.     if ((bit != OPT_SHRINK) && (bit != OPT_FORMAT)) {
  1132.         maxValues = ((bit == OPT_FROM) || (bit == OPT_TO))? 4: 2;
  1133.         argIndex = index + 1;
  1134.         for (numValues = 0; numValues < maxValues; ++numValues) {
  1135.         if ((argIndex < argc) && (isdigit(UCHAR(argv[argIndex][0]))
  1136.             || ((argv[argIndex][0] == '-')
  1137.             && (isdigit(UCHAR(argv[argIndex][1])))))) {
  1138.             if (Tcl_GetInt(interp, argv[argIndex], &values[numValues])
  1139.                 != TCL_OK) {
  1140.             return TCL_ERROR;
  1141.             }
  1142.         } else {
  1143.             break;
  1144.         }
  1145.         ++argIndex;
  1146.         }
  1147.  
  1148.         if (numValues == 0) {
  1149.         Tcl_AppendResult(interp, "the \"", argv[index], "\" option ",
  1150.              "requires one ", maxValues == 2? "or two": "to four",
  1151.              " integer values", (char *) NULL);
  1152.         return TCL_ERROR;
  1153.         }
  1154.         *optIndexPtr = (index += numValues);
  1155.  
  1156.         /*
  1157.          * Y values default to the corresponding X value if not specified.
  1158.          */
  1159.  
  1160.         if (numValues == 1) {
  1161.         values[1] = values[0];
  1162.         }
  1163.         if (numValues == 3) {
  1164.         values[3] = values[2];
  1165.         }
  1166.  
  1167.         /*
  1168.          * Check the values given and put them in the appropriate
  1169.          * field of the SubcommandOptions structure.
  1170.          */
  1171.  
  1172.         switch (bit) {
  1173.         case OPT_FROM:
  1174.             if ((values[0] < 0) || (values[1] < 0) || ((numValues > 2)
  1175.                 && ((values[2] < 0) || (values[3] < 0)))) {
  1176.             Tcl_AppendResult(interp, "value(s) for the -from",
  1177.                 " option must be non-negative", (char *) NULL);
  1178.             return TCL_ERROR;
  1179.             }
  1180.             if (numValues <= 2) {
  1181.             optPtr->fromX = values[0];
  1182.             optPtr->fromY = values[1];
  1183.             optPtr->fromX2 = -1;
  1184.             optPtr->fromY2 = -1;
  1185.             } else {
  1186.             optPtr->fromX = MIN(values[0], values[2]);
  1187.             optPtr->fromY = MIN(values[1], values[3]);
  1188.             optPtr->fromX2 = MAX(values[0], values[2]);
  1189.             optPtr->fromY2 = MAX(values[1], values[3]);
  1190.             }
  1191.             break;
  1192.         case OPT_SUBSAMPLE:
  1193.             optPtr->subsampleX = values[0];
  1194.             optPtr->subsampleY = values[1];
  1195.             break;
  1196.         case OPT_TO:
  1197.             if ((values[0] < 0) || (values[1] < 0) || ((numValues > 2)
  1198.                 && ((values[2] < 0) || (values[3] < 0)))) {
  1199.             Tcl_AppendResult(interp, "value(s) for the -to",
  1200.                 " option must be non-negative", (char *) NULL);
  1201.             return TCL_ERROR;
  1202.             }
  1203.             if (numValues <= 2) {
  1204.             optPtr->toX = values[0];
  1205.             optPtr->toY = values[1];
  1206.             optPtr->toX2 = -1;
  1207.             optPtr->toY2 = -1;
  1208.             } else {
  1209.             optPtr->toX = MIN(values[0], values[2]);
  1210.             optPtr->toY = MIN(values[1], values[3]);
  1211.             optPtr->toX2 = MAX(values[0], values[2]);
  1212.             optPtr->toY2 = MAX(values[1], values[3]);
  1213.             }
  1214.             break;
  1215.         case OPT_ZOOM:
  1216.             if ((values[0] <= 0) || (values[1] <= 0)) {
  1217.             Tcl_AppendResult(interp, "value(s) for the -zoom",
  1218.                 " option must be positive", (char *) NULL);
  1219.             return TCL_ERROR;
  1220.             }
  1221.             optPtr->zoomX = values[0];
  1222.             optPtr->zoomY = values[1];
  1223.             break;
  1224.         }
  1225.     } else if (bit == OPT_FORMAT) {
  1226.         /*
  1227.          * The -format option takes a single string value.
  1228.          */
  1229.  
  1230.         if (index + 1 < argc) {
  1231.         *optIndexPtr = ++index;
  1232.         optPtr->format = argv[index];
  1233.         } else {
  1234.         Tcl_AppendResult(interp, "the \"-format\" option ",
  1235.             "requires a value", (char *) NULL);
  1236.         return TCL_ERROR;
  1237.         }
  1238.     }
  1239.  
  1240.     /*
  1241.      * Remember that we saw this option.
  1242.      */
  1243.  
  1244.     optPtr->options |= bit;
  1245.     }
  1246.  
  1247.     return TCL_OK;
  1248. }
  1249.  
  1250. /*
  1251.  *----------------------------------------------------------------------
  1252.  *
  1253.  * ImgPhotoConfigureMaster --
  1254.  *
  1255.  *    This procedure is called when a photo image is created or
  1256.  *    reconfigured.  It processes configuration options and resets
  1257.  *    any instances of the image.
  1258.  *
  1259.  * Results:
  1260.  *    A standard Tcl return value.  If TCL_ERROR is returned then
  1261.  *    an error message is left in masterPtr->interp->result.
  1262.  *
  1263.  * Side effects:
  1264.  *    Existing instances of the image will be redisplayed to match
  1265.  *    the new configuration options.
  1266.  *
  1267.  *----------------------------------------------------------------------
  1268.  */
  1269.  
  1270. static int
  1271. ImgPhotoConfigureMaster(interp, masterPtr, argc, argv, flags)
  1272.     Tcl_Interp *interp;        /* Interpreter to use for reporting errors. */
  1273.     PhotoMaster *masterPtr;    /* Pointer to data structure describing
  1274.                  * overall photo image to (re)configure. */
  1275.     int argc;            /* Number of entries in argv. */
  1276.     char **argv;        /* Pairs of configuration options for image. */
  1277.     int flags;            /* Flags to pass to Tk_ConfigureWidget,
  1278.                  * such as TK_CONFIG_ARGV_ONLY. */
  1279. {
  1280.     PhotoInstance *instancePtr;
  1281.     char *oldFileString, *oldDataString, *realFileName, *oldPaletteString;
  1282.     double oldGamma;
  1283.     int result;
  1284.     FILE *f;
  1285.     Tk_PhotoImageFormat *imageFormat;
  1286.     int imageWidth, imageHeight;
  1287.     Tcl_DString buffer;
  1288.  
  1289.     /*
  1290.      * Save the current values for fileString and dataString, so we
  1291.      * can tell if the user specifies them anew.
  1292.      */
  1293.  
  1294.     oldFileString = masterPtr->fileString;
  1295.     oldDataString = (oldFileString == NULL)? masterPtr->dataString: NULL;
  1296.     oldPaletteString = masterPtr->palette;
  1297.     oldGamma = masterPtr->gamma;
  1298.  
  1299.     /*
  1300.      * Process the configuration options specified.
  1301.      */
  1302.  
  1303.     if (Tk_ConfigureWidget(interp, Tk_MainWindow(interp), configSpecs,
  1304.         argc, argv, (char *) masterPtr, flags) != TCL_OK) {
  1305.     return TCL_ERROR;
  1306.     }
  1307.  
  1308.     /*
  1309.      * Regard the empty string for -file, -data or -format as the null
  1310.      * value.
  1311.      */
  1312.  
  1313.     if ((masterPtr->fileString != NULL) && (masterPtr->fileString[0] == 0)) {
  1314.     ckfree(masterPtr->fileString);
  1315.     masterPtr->fileString = NULL;
  1316.     }
  1317.     if ((masterPtr->dataString != NULL) && (masterPtr->dataString[0] == 0)) {
  1318.     ckfree(masterPtr->dataString);
  1319.     masterPtr->dataString = NULL;
  1320.     }
  1321.     if ((masterPtr->format != NULL) && (masterPtr->format[0] == 0)) {
  1322.     ckfree(masterPtr->format);
  1323.     masterPtr->format = NULL;
  1324.     }
  1325.  
  1326.     /*
  1327.      * Set the image to the user-requested size, if any,
  1328.      * and make sure storage is correctly allocated for this image.
  1329.      */
  1330.  
  1331.     ImgPhotoSetSize(masterPtr, masterPtr->width, masterPtr->height);
  1332.  
  1333.     /*
  1334.      * Read in the image from the file or string if the user has
  1335.      * specified the -file or -data option.
  1336.      */
  1337.  
  1338.     if ((masterPtr->fileString != NULL)
  1339.         && (masterPtr->fileString != oldFileString)) {
  1340.  
  1341.     realFileName = Tcl_TranslateFileName(interp, masterPtr->fileString,
  1342.         &buffer);
  1343.     if (realFileName == NULL) {
  1344.         return TCL_ERROR;
  1345.     }
  1346.     f = fopen(realFileName, "rb");
  1347.     Tcl_DStringFree(&buffer);
  1348.     if (f == NULL) {
  1349.         Tcl_AppendResult(interp, "couldn't read image file \"",
  1350.             masterPtr->fileString, "\": ", Tcl_PosixError(interp),
  1351.             (char *) NULL);
  1352.         return TCL_ERROR;
  1353.     }
  1354.     if (MatchFileFormat(interp, f, masterPtr->fileString,
  1355.         masterPtr->format, &imageFormat, &imageWidth,
  1356.         &imageHeight) != TCL_OK) {
  1357.         fclose(f);
  1358.         return TCL_ERROR;
  1359.     }
  1360.     ImgPhotoSetSize(masterPtr, imageWidth, imageHeight);
  1361.     result = (*imageFormat->fileReadProc)(interp, f, masterPtr->fileString,
  1362.         masterPtr->format, (Tk_PhotoHandle) masterPtr, 0, 0,
  1363.         imageWidth, imageHeight, 0, 0);
  1364.     fclose(f);
  1365.     if (result != TCL_OK) {
  1366.         return TCL_ERROR;
  1367.     }
  1368.  
  1369.     masterPtr->flags |= IMAGE_CHANGED;
  1370.     }
  1371.  
  1372.     if ((masterPtr->fileString == NULL) && (masterPtr->dataString != NULL)
  1373.         && (masterPtr->dataString != oldDataString)) {
  1374.  
  1375.     if (MatchStringFormat(interp, masterPtr->dataString, 
  1376.         masterPtr->format, &imageFormat, &imageWidth,
  1377.         &imageHeight) != TCL_OK) {
  1378.         return TCL_ERROR;
  1379.     }
  1380.     ImgPhotoSetSize(masterPtr, imageWidth, imageHeight);
  1381.     if ((*imageFormat->stringReadProc)(interp, masterPtr->dataString,
  1382.         masterPtr->format, (Tk_PhotoHandle) masterPtr,
  1383.         0, 0, imageWidth, imageHeight, 0, 0) != TCL_OK) {
  1384.         return TCL_ERROR;
  1385.     }
  1386.  
  1387.     masterPtr->flags |= IMAGE_CHANGED;
  1388.     }
  1389.  
  1390.     /*
  1391.      * Enforce a reasonable value for gamma.
  1392.      */
  1393.  
  1394.     if (masterPtr->gamma <= 0) {
  1395.     masterPtr->gamma = 1.0;
  1396.     }
  1397.  
  1398.     if ((masterPtr->gamma != oldGamma)
  1399.         || (masterPtr->palette != oldPaletteString)) {
  1400.     masterPtr->flags |= IMAGE_CHANGED;
  1401.     }
  1402.  
  1403.     /*
  1404.      * Cycle through all of the instances of this image, regenerating
  1405.      * the information for each instance.  Then force the image to be
  1406.      * redisplayed everywhere that it is used.
  1407.      */
  1408.  
  1409.     for (instancePtr = masterPtr->instancePtr; instancePtr != NULL;
  1410.         instancePtr = instancePtr->nextPtr) {
  1411.     ImgPhotoConfigureInstance(instancePtr);
  1412.     }
  1413.  
  1414.     /*
  1415.      * Inform the generic image code that the image
  1416.      * has (potentially) changed.
  1417.      */
  1418.  
  1419.     Tk_ImageChanged(masterPtr->tkMaster, 0, 0, masterPtr->width,
  1420.         masterPtr->height, masterPtr->width, masterPtr->height);
  1421.     masterPtr->flags &= ~IMAGE_CHANGED;
  1422.  
  1423.     return TCL_OK;
  1424. }
  1425.  
  1426. /*
  1427.  *----------------------------------------------------------------------
  1428.  *
  1429.  * ImgPhotoConfigureInstance --
  1430.  *
  1431.  *    This procedure is called to create displaying information for
  1432.  *    a photo image instance based on the configuration information
  1433.  *    in the master.  It is invoked both when new instances are
  1434.  *    created and when the master is reconfigured.
  1435.  *
  1436.  * Results:
  1437.  *    None.
  1438.  *
  1439.  * Side effects:
  1440.  *    Generates errors via Tcl_BackgroundError if there are problems
  1441.  *    in setting up the instance.
  1442.  *
  1443.  *----------------------------------------------------------------------
  1444.  */
  1445.  
  1446. static void
  1447. ImgPhotoConfigureInstance(instancePtr)
  1448.     PhotoInstance *instancePtr;    /* Instance to reconfigure. */
  1449. {
  1450.     PhotoMaster *masterPtr = instancePtr->masterPtr;
  1451.     XImage *imagePtr;
  1452.     int bitsPerPixel;
  1453.     ColorTable *colorTablePtr;
  1454.     XRectangle validBox;
  1455.  
  1456.     /*
  1457.      * If the -palette configuration option has been set for the master,
  1458.      * use the value specified for our palette, but only if it is
  1459.      * a valid palette for our windows.  Use the gamma value specified
  1460.      * the master.
  1461.      */
  1462.  
  1463.     if ((masterPtr->palette && masterPtr->palette[0])
  1464.         && IsValidPalette(instancePtr, masterPtr->palette)) {
  1465.     instancePtr->palette = masterPtr->palette;
  1466.     } else {
  1467.     instancePtr->palette = instancePtr->defaultPalette;
  1468.     }
  1469.     instancePtr->gamma = masterPtr->gamma;
  1470.  
  1471.     /*
  1472.      * If we don't currently have a color table, or if the one we
  1473.      * have no longer applies (e.g. because our palette or gamma
  1474.      * has changed), get a new one.
  1475.      */
  1476.  
  1477.     colorTablePtr = instancePtr->colorTablePtr;
  1478.     if ((colorTablePtr == NULL)
  1479.         || (instancePtr->colormap != colorTablePtr->id.colormap)
  1480.         || (instancePtr->palette != colorTablePtr->id.palette)
  1481.         || (instancePtr->gamma != colorTablePtr->id.gamma)) {
  1482.     /*
  1483.      * Free up our old color table, and get a new one.
  1484.      */
  1485.  
  1486.     if (colorTablePtr != NULL) {
  1487.         colorTablePtr->liveRefCount -= 1;
  1488.         FreeColorTable(colorTablePtr);
  1489.     }
  1490.     GetColorTable(instancePtr);
  1491.  
  1492.     /*
  1493.      * Create a new XImage structure for sending data to
  1494.      * the X server, if necessary.
  1495.      */
  1496.  
  1497.     if (instancePtr->colorTablePtr->flags & BLACK_AND_WHITE) {
  1498.         bitsPerPixel = 1;
  1499.     } else {
  1500.         bitsPerPixel = instancePtr->visualInfo.depth;
  1501.     }
  1502.  
  1503.     if ((instancePtr->imagePtr == NULL)
  1504.         || (instancePtr->imagePtr->bits_per_pixel != bitsPerPixel)) {
  1505.         if (instancePtr->imagePtr != NULL) {
  1506.         XFree((char *) instancePtr->imagePtr);
  1507.         }
  1508.         imagePtr = XCreateImage(instancePtr->display,
  1509.             instancePtr->visualInfo.visual, (unsigned) bitsPerPixel,
  1510.             (bitsPerPixel > 1? ZPixmap: XYBitmap), 0, (char *) NULL,
  1511.             1, 1, 32, 0);
  1512.         instancePtr->imagePtr = imagePtr;
  1513.  
  1514.         /*
  1515.          * Determine the endianness of this machine.
  1516.          * We create images using the local host's endianness, rather
  1517.          * than the endianness of the server; otherwise we would have
  1518.          * to byte-swap any 16 or 32 bit values that we store in the
  1519.          * image in those situations where the server's endianness
  1520.          * is different from ours.
  1521.          */
  1522.  
  1523.         if (imagePtr != NULL) {
  1524.         union {
  1525.             int i;
  1526.             char c[sizeof(int)];
  1527.         } kludge;
  1528.  
  1529.         imagePtr->bitmap_unit = sizeof(pixel) * NBBY;
  1530.         kludge.i = 0;
  1531.         kludge.c[0] = 1;
  1532.         imagePtr->byte_order = (kludge.i == 1) ? LSBFirst : MSBFirst;
  1533.         _XInitImageFuncPtrs(imagePtr);
  1534.         }
  1535.     }
  1536.     }
  1537.  
  1538.     /*
  1539.      * If the user has specified a width and/or height for the master
  1540.      * which is different from our current width/height, set the size
  1541.      * to the values specified by the user.  If we have no pixmap, we
  1542.      * do this also, since it has the side effect of allocating a
  1543.      * pixmap for us.
  1544.      */
  1545.  
  1546.     if ((instancePtr->pixels == None) || (instancePtr->error == NULL)
  1547.         || (instancePtr->width != masterPtr->width)
  1548.         || (instancePtr->height != masterPtr->height)) {
  1549.     ImgPhotoInstanceSetSize(instancePtr);
  1550.     }
  1551.  
  1552.     /*
  1553.      * Redither this instance if necessary.
  1554.      */
  1555.  
  1556.     if ((masterPtr->flags & IMAGE_CHANGED)
  1557.         || (instancePtr->colorTablePtr != colorTablePtr)) {
  1558.     TkClipBox(masterPtr->validRegion, &validBox);
  1559.     if ((validBox.width > 0) && (validBox.height > 0)) {
  1560.         DitherInstance(instancePtr, validBox.x, validBox.y,
  1561.             validBox.width, validBox.height);
  1562.     }
  1563.     }
  1564.  
  1565. }
  1566.  
  1567. /*
  1568.  *----------------------------------------------------------------------
  1569.  *
  1570.  * ImgPhotoGet --
  1571.  *
  1572.  *    This procedure is called for each use of a photo image in a
  1573.  *    widget.
  1574.  *
  1575.  * Results:
  1576.  *    The return value is a token for the instance, which is passed
  1577.  *    back to us in calls to ImgPhotoDisplay and ImgPhotoFree.
  1578.  *
  1579.  * Side effects:
  1580.  *    A data structure is set up for the instance (or, an existing
  1581.  *    instance is re-used for the new one).
  1582.  *
  1583.  *----------------------------------------------------------------------
  1584.  */
  1585.  
  1586. static ClientData
  1587. ImgPhotoGet(tkwin, masterData)
  1588.     Tk_Window tkwin;        /* Window in which the instance will be
  1589.                  * used. */
  1590.     ClientData masterData;    /* Pointer to our master structure for the
  1591.                  * image. */
  1592. {
  1593.     PhotoMaster *masterPtr = (PhotoMaster *) masterData;
  1594.     PhotoInstance *instancePtr;
  1595.     Colormap colormap;
  1596.     int mono, nRed, nGreen, nBlue;
  1597.     XVisualInfo visualInfo, *visInfoPtr;
  1598.     XRectangle validBox;
  1599.     char buf[16];
  1600.     int numVisuals;
  1601.     XColor *white, *black;
  1602.     XGCValues gcValues;
  1603.  
  1604.     /*
  1605.      * Table of "best" choices for palette for PseudoColor displays
  1606.      * with between 3 and 15 bits/pixel.
  1607.      */
  1608.  
  1609.     static int paletteChoice[13][3] = {
  1610.     /*  #red, #green, #blue */
  1611.      {2,  2,  2,            /* 3 bits, 8 colors */},
  1612.      {2,  3,  2,            /* 4 bits, 12 colors */},
  1613.      {3,  4,  2,            /* 5 bits, 24 colors */},
  1614.      {4,  5,  3,            /* 6 bits, 60 colors */},
  1615.      {5,  6,  4,            /* 7 bits, 120 colors */},
  1616.      {7,  7,  4,            /* 8 bits, 198 colors */},
  1617.      {8, 10,  6,            /* 9 bits, 480 colors */},
  1618.     {10, 12,  8,            /* 10 bits, 960 colors */},
  1619.     {14, 15,  9,            /* 11 bits, 1890 colors */},
  1620.     {16, 20, 12,            /* 12 bits, 3840 colors */},
  1621.     {20, 24, 16,            /* 13 bits, 7680 colors */},
  1622.     {26, 30, 20,            /* 14 bits, 15600 colors */},
  1623.     {32, 32, 30,            /* 15 bits, 30720 colors */}
  1624.     };
  1625.  
  1626.     /*
  1627.      * See if there is already an instance for windows using
  1628.      * the same colormap.  If so then just re-use it.
  1629.      */
  1630.  
  1631.     colormap = Tk_Colormap(tkwin);
  1632.     for (instancePtr = masterPtr->instancePtr; instancePtr != NULL;
  1633.         instancePtr = instancePtr->nextPtr) {
  1634.     if ((colormap == instancePtr->colormap)
  1635.         && (Tk_Display(tkwin) == instancePtr->display)) {
  1636.  
  1637.         /*
  1638.          * Re-use this instance.
  1639.          */
  1640.  
  1641.         if (instancePtr->refCount == 0) {
  1642.         /*
  1643.          * We are resurrecting this instance.
  1644.          */
  1645.  
  1646.         Tcl_CancelIdleCall(DisposeInstance, (ClientData) instancePtr);
  1647.         if (instancePtr->colorTablePtr != NULL) {
  1648.             FreeColorTable(instancePtr->colorTablePtr);
  1649.         }
  1650.         GetColorTable(instancePtr);
  1651.         }
  1652.         instancePtr->refCount++;
  1653.         return (ClientData) instancePtr;
  1654.     }
  1655.     }
  1656.  
  1657.     /*
  1658.      * The image isn't already in use in a window with the same colormap.
  1659.      * Make a new instance of the image.
  1660.      */
  1661.  
  1662.     instancePtr = (PhotoInstance *) ckalloc(sizeof(PhotoInstance));
  1663.     instancePtr->masterPtr = masterPtr;
  1664.     instancePtr->display = Tk_Display(tkwin);
  1665.     instancePtr->colormap = Tk_Colormap(tkwin);
  1666.     Tk_PreserveColormap(instancePtr->display, instancePtr->colormap);
  1667.     instancePtr->refCount = 1;
  1668.     instancePtr->colorTablePtr = NULL;
  1669.     instancePtr->pixels = None;
  1670.     instancePtr->error = NULL;
  1671.     instancePtr->width = 0;
  1672.     instancePtr->height = 0;
  1673.     instancePtr->imagePtr = 0;
  1674.     instancePtr->nextPtr = masterPtr->instancePtr;
  1675.     masterPtr->instancePtr = instancePtr;
  1676.  
  1677.     /*
  1678.      * Obtain information about the visual and decide on the
  1679.      * default palette.
  1680.      */
  1681.  
  1682.     visualInfo.screen = Tk_ScreenNumber(tkwin);
  1683.     visualInfo.visualid = XVisualIDFromVisual(Tk_Visual(tkwin));
  1684.     visInfoPtr = XGetVisualInfo(Tk_Display(tkwin),
  1685.         VisualScreenMask | VisualIDMask, &visualInfo, &numVisuals);
  1686.     nRed = 2;
  1687.     nGreen = nBlue = 0;
  1688.     mono = 1;
  1689.     if (visInfoPtr != NULL) {
  1690.     instancePtr->visualInfo = *visInfoPtr;
  1691.     switch (visInfoPtr->class) {
  1692.         case DirectColor:
  1693.         case TrueColor:
  1694.         nRed = 1 << CountBits(visInfoPtr->red_mask);
  1695.         nGreen = 1 << CountBits(visInfoPtr->green_mask);
  1696.         nBlue = 1 << CountBits(visInfoPtr->blue_mask);
  1697.         mono = 0;
  1698.         break;
  1699.         case PseudoColor:
  1700.         case StaticColor:
  1701.         if (visInfoPtr->depth > 15) {
  1702.             nRed = 32;
  1703.             nGreen = 32;
  1704.             nBlue = 32;
  1705.             mono = 0;
  1706.         } else if (visInfoPtr->depth >= 3) {
  1707.             int *ip = paletteChoice[visInfoPtr->depth - 3];
  1708.     
  1709.             nRed = ip[0];
  1710.             nGreen = ip[1];
  1711.             nBlue = ip[2];
  1712.             mono = 0;
  1713.         }
  1714.         break;
  1715.         case GrayScale:
  1716.         case StaticGray:
  1717.         nRed = 1 << visInfoPtr->depth;
  1718.         break;
  1719.     }
  1720.     XFree((char *) visInfoPtr);
  1721.  
  1722.     } else {
  1723.     panic("ImgPhotoGet couldn't find visual for window");
  1724.     }
  1725.  
  1726.     sprintf(buf, ((mono) ? "%d": "%d/%d/%d"), nRed, nGreen, nBlue);
  1727.     instancePtr->defaultPalette = Tk_GetUid(buf);
  1728.  
  1729.     /*
  1730.      * Make a GC with background = black and foreground = white.
  1731.      */
  1732.  
  1733.     white = Tk_GetColor(masterPtr->interp, tkwin, "white");
  1734.     black = Tk_GetColor(masterPtr->interp, tkwin, "black");
  1735.     gcValues.foreground = (white != NULL)? white->pixel:
  1736.         WhitePixelOfScreen(Tk_Screen(tkwin));
  1737.     gcValues.background = (black != NULL)? black->pixel:
  1738.         BlackPixelOfScreen(Tk_Screen(tkwin));
  1739.     gcValues.graphics_exposures = False;
  1740.     instancePtr->gc = Tk_GetGC(tkwin,
  1741.         GCForeground|GCBackground|GCGraphicsExposures, &gcValues);
  1742.  
  1743.     /*
  1744.      * Set configuration options and finish the initialization of the instance.
  1745.      */
  1746.  
  1747.     ImgPhotoConfigureInstance(instancePtr);
  1748.  
  1749.     /*
  1750.      * If this is the first instance, must set the size of the image.
  1751.      */
  1752.  
  1753.     if (instancePtr->nextPtr == NULL) {
  1754.     Tk_ImageChanged(masterPtr->tkMaster, 0, 0, 0, 0,
  1755.         masterPtr->width, masterPtr->height);
  1756.     }
  1757.  
  1758.     /*
  1759.      * Dither the image to fill in this instance's pixmap.
  1760.      */
  1761.  
  1762.     TkClipBox(masterPtr->validRegion, &validBox);
  1763.     if ((validBox.width > 0) && (validBox.height > 0)) {
  1764.     DitherInstance(instancePtr, validBox.x, validBox.y, validBox.width,
  1765.         validBox.height);
  1766.     }
  1767.  
  1768.     return (ClientData) instancePtr;
  1769. }
  1770.  
  1771. /*
  1772.  *----------------------------------------------------------------------
  1773.  *
  1774.  * ImgPhotoDisplay --
  1775.  *
  1776.  *    This procedure is invoked to draw a photo image.
  1777.  *
  1778.  * Results:
  1779.  *    None.
  1780.  *
  1781.  * Side effects:
  1782.  *    A portion of the image gets rendered in a pixmap or window.
  1783.  *
  1784.  *----------------------------------------------------------------------
  1785.  */
  1786.  
  1787. static void
  1788. ImgPhotoDisplay(clientData, display, drawable, imageX, imageY, width,
  1789.     height, drawableX, drawableY)
  1790.     ClientData clientData;    /* Pointer to PhotoInstance structure for
  1791.                  * for instance to be displayed. */
  1792.     Display *display;        /* Display on which to draw image. */
  1793.     Drawable drawable;        /* Pixmap or window in which to draw image. */
  1794.     int imageX, imageY;        /* Upper-left corner of region within image
  1795.                  * to draw. */
  1796.     int width, height;        /* Dimensions of region within image to draw. */
  1797.     int drawableX, drawableY;    /* Coordinates within drawable that
  1798.                  * correspond to imageX and imageY. */
  1799. {
  1800.     PhotoInstance *instancePtr = (PhotoInstance *) clientData;
  1801.  
  1802.     /*
  1803.      * If there's no pixmap, it means that an error occurred
  1804.      * while creating the image instance so it can't be displayed.
  1805.      */
  1806.  
  1807.     if (instancePtr->pixels == None) {
  1808.     return;
  1809.     }
  1810.  
  1811.     /*
  1812.      * masterPtr->region describes which parts of the image contain
  1813.      * valid data.  We set this region as the clip mask for the gc,
  1814.      * setting its origin appropriately, and use it when drawing the
  1815.      * image.
  1816.      */
  1817.  
  1818.     TkSetRegion(display, instancePtr->gc, instancePtr->masterPtr->validRegion);
  1819.     XSetClipOrigin(display, instancePtr->gc, drawableX - imageX,
  1820.         drawableY - imageY);
  1821.     XCopyArea(display, instancePtr->pixels, drawable, instancePtr->gc,
  1822.         imageX, imageY, (unsigned) width, (unsigned) height,
  1823.         drawableX, drawableY);
  1824.     XSetClipMask(display, instancePtr->gc, None);
  1825.     XSetClipOrigin(display, instancePtr->gc, 0, 0);
  1826. }
  1827.  
  1828. /*
  1829.  *----------------------------------------------------------------------
  1830.  *
  1831.  * ImgPhotoFree --
  1832.  *
  1833.  *    This procedure is called when a widget ceases to use a
  1834.  *    particular instance of an image.  We don't actually get
  1835.  *    rid of the instance until later because we may be about
  1836.  *    to get this instance again.
  1837.  *
  1838.  * Results:
  1839.  *    None.
  1840.  *
  1841.  * Side effects:
  1842.  *    Internal data structures get cleaned up, later.
  1843.  *
  1844.  *----------------------------------------------------------------------
  1845.  */
  1846.  
  1847. static void
  1848. ImgPhotoFree(clientData, display)
  1849.     ClientData clientData;    /* Pointer to PhotoInstance structure for
  1850.                  * for instance to be displayed. */
  1851.     Display *display;        /* Display containing window that used image. */
  1852. {
  1853.     PhotoInstance *instancePtr = (PhotoInstance *) clientData;
  1854.     ColorTable *colorPtr;
  1855.  
  1856.     instancePtr->refCount -= 1;
  1857.     if (instancePtr->refCount > 0) {
  1858.     return;
  1859.     }
  1860.  
  1861.     /*
  1862.      * There are no more uses of the image within this widget.
  1863.      * Decrement the count of live uses of its color table, so
  1864.      * that its colors can be reclaimed if necessary, and
  1865.      * set up an idle call to free the instance structure.
  1866.      */
  1867.  
  1868.     colorPtr = instancePtr->colorTablePtr;
  1869.     if (colorPtr != NULL) {
  1870.     colorPtr->liveRefCount -= 1;
  1871.     }
  1872.     
  1873.     Tcl_DoWhenIdle(DisposeInstance, (ClientData) instancePtr);
  1874. }
  1875.  
  1876. /*
  1877.  *----------------------------------------------------------------------
  1878.  *
  1879.  * ImgPhotoDelete --
  1880.  *
  1881.  *    This procedure is called by the image code to delete the
  1882.  *    master structure for an image.
  1883.  *
  1884.  * Results:
  1885.  *    None.
  1886.  *
  1887.  * Side effects:
  1888.  *    Resources associated with the image get freed.
  1889.  *
  1890.  *----------------------------------------------------------------------
  1891.  */
  1892.  
  1893. static void
  1894. ImgPhotoDelete(masterData)
  1895.     ClientData masterData;    /* Pointer to PhotoMaster structure for
  1896.                  * image.  Must not have any more instances. */
  1897. {
  1898.     PhotoMaster *masterPtr = (PhotoMaster *) masterData;
  1899.     PhotoInstance *instancePtr;
  1900.  
  1901.     while ((instancePtr = masterPtr->instancePtr) != NULL) {
  1902.     if (instancePtr->refCount > 0) {
  1903.         panic("tried to delete photo image when instances still exist");
  1904.     }
  1905.     Tcl_CancelIdleCall(DisposeInstance, (ClientData) instancePtr);
  1906.     DisposeInstance((ClientData) instancePtr);
  1907.     }
  1908.     masterPtr->tkMaster = NULL;
  1909.     if (masterPtr->imageCmd != NULL) {
  1910.     Tcl_DeleteCommand(masterPtr->interp,
  1911.         Tcl_GetCommandName(masterPtr->interp, masterPtr->imageCmd));
  1912.     }
  1913.     if (masterPtr->pix24 != NULL) {
  1914.     ckfree((char *) masterPtr->pix24);
  1915.     }
  1916.     if (masterPtr->validRegion != NULL) {
  1917.     TkDestroyRegion(masterPtr->validRegion);
  1918.     }
  1919.     Tk_FreeOptions(configSpecs, (char *) masterPtr, (Display *) NULL, 0);
  1920.     ckfree((char *) masterPtr);
  1921. }
  1922.  
  1923. /*
  1924.  *----------------------------------------------------------------------
  1925.  *
  1926.  * ImgPhotoCmdDeletedProc --
  1927.  *
  1928.  *    This procedure is invoked when the image command for an image
  1929.  *    is deleted.  It deletes the image.
  1930.  *
  1931.  * Results:
  1932.  *    None.
  1933.  *
  1934.  * Side effects:
  1935.  *    The image is deleted.
  1936.  *
  1937.  *----------------------------------------------------------------------
  1938.  */
  1939.  
  1940. static void
  1941. ImgPhotoCmdDeletedProc(clientData)
  1942.     ClientData clientData;    /* Pointer to PhotoMaster structure for
  1943.                  * image. */
  1944. {
  1945.     PhotoMaster *masterPtr = (PhotoMaster *) clientData;
  1946.  
  1947.     masterPtr->imageCmd = NULL;
  1948.     if (masterPtr->tkMaster != NULL) {
  1949.     Tk_DeleteImage(masterPtr->interp, Tk_NameOfImage(masterPtr->tkMaster));
  1950.     }
  1951. }
  1952.  
  1953. /*
  1954.  *----------------------------------------------------------------------
  1955.  *
  1956.  * ImgPhotoSetSize --
  1957.  *
  1958.  *    This procedure reallocates the image storage and instance
  1959.  *    pixmaps for a photo image, as necessary, to change the
  1960.  *    image's size to `width' x `height' pixels.
  1961.  *
  1962.  * Results:
  1963.  *    None.
  1964.  *
  1965.  * Side effects:
  1966.  *    Storage gets reallocated, for the master and all its instances.
  1967.  *
  1968.  *----------------------------------------------------------------------
  1969.  */
  1970.  
  1971. static void
  1972. ImgPhotoSetSize(masterPtr, width, height)
  1973.     PhotoMaster *masterPtr;
  1974.     int width, height;
  1975. {
  1976.     unsigned char *newPix24;
  1977.     int h, offset, pitch;
  1978.     unsigned char *srcPtr, *destPtr;
  1979.     XRectangle validBox, clipBox;
  1980.     TkRegion clipRegion;
  1981.     PhotoInstance *instancePtr;
  1982.  
  1983.     if (masterPtr->userWidth > 0) {
  1984.     width = masterPtr->userWidth;
  1985.     }
  1986.     if (masterPtr->userHeight > 0) {
  1987.     height = masterPtr->userHeight;
  1988.     }
  1989.  
  1990.     /*
  1991.      * We have to trim the valid region if it is currently
  1992.      * larger than the new image size.
  1993.      */
  1994.  
  1995.     TkClipBox(masterPtr->validRegion, &validBox);
  1996.     if ((validBox.x + validBox.width > (unsigned) width)
  1997.         || (validBox.y + validBox.height > (unsigned) height)) {
  1998.     clipBox.x = 0;
  1999.     clipBox.y = 0;
  2000.     clipBox.width = width;
  2001.     clipBox.height = height;
  2002.     clipRegion = TkCreateRegion();
  2003.     TkUnionRectWithRegion(&clipBox, clipRegion, clipRegion);
  2004.     TkIntersectRegion(masterPtr->validRegion, clipRegion,
  2005.         masterPtr->validRegion);
  2006.     TkDestroyRegion(clipRegion);
  2007.     TkClipBox(masterPtr->validRegion, &validBox);
  2008.     }
  2009.  
  2010.     if ((width != masterPtr->width) || (height != masterPtr->height)
  2011.         || (masterPtr->pix24 == NULL)) {
  2012.  
  2013.     /*
  2014.      * Reallocate storage for the 24-bit image and copy
  2015.      * over valid regions.
  2016.      */
  2017.  
  2018.     pitch = width * 3;
  2019.     newPix24 = (unsigned char *) ckalloc((unsigned) (height * pitch));
  2020.  
  2021.     /*
  2022.      * Zero the new array.  The dithering code shouldn't read the
  2023.      * areas outside validBox, but they might be copied to another
  2024.      * photo image or written to a file.
  2025.      */
  2026.  
  2027.     if ((masterPtr->pix24 != NULL)
  2028.         && ((width == masterPtr->width) || (width == validBox.width))) {
  2029.         if (validBox.y > 0) {
  2030.         memset((VOID *) newPix24, 0, (size_t) (validBox.y * pitch));
  2031.         }
  2032.         h = validBox.y + validBox.height;
  2033.         if (h < height) {
  2034.         memset((VOID *) (newPix24 + h * pitch), 0,
  2035.             (size_t) ((height - h) * pitch));
  2036.         }
  2037.     } else {
  2038.         memset((VOID *) newPix24, 0, (size_t) (height * pitch));
  2039.     }
  2040.  
  2041.     if (masterPtr->pix24 != NULL) {
  2042.  
  2043.         /*
  2044.          * Copy the common area over to the new array array and
  2045.          * free the old array.
  2046.          */
  2047.  
  2048.         if (width == masterPtr->width) {
  2049.  
  2050.         /*
  2051.          * The region to be copied is contiguous.
  2052.          */
  2053.  
  2054.         offset = validBox.y * pitch;
  2055.         memcpy((VOID *) (newPix24 + offset),
  2056.             (VOID *) (masterPtr->pix24 + offset),
  2057.             (size_t) (validBox.height * pitch));
  2058.  
  2059.         } else if ((validBox.width > 0) && (validBox.height > 0)) {
  2060.  
  2061.         /*
  2062.          * Area to be copied is not contiguous - copy line by line.
  2063.          */
  2064.  
  2065.         destPtr = newPix24 + (validBox.y * width + validBox.x) * 3;
  2066.         srcPtr = masterPtr->pix24 + (validBox.y * masterPtr->width
  2067.             + validBox.x) * 3;
  2068.         for (h = validBox.height; h > 0; h--) {
  2069.             memcpy((VOID *) destPtr, (VOID *) srcPtr,
  2070.                 (size_t) (validBox.width * 3));
  2071.             destPtr += width * 3;
  2072.             srcPtr += masterPtr->width * 3;
  2073.         }
  2074.         }
  2075.  
  2076.         ckfree((char *) masterPtr->pix24);
  2077.     }
  2078.  
  2079.     masterPtr->pix24 = newPix24;
  2080.     masterPtr->width = width;
  2081.     masterPtr->height = height;
  2082.  
  2083.     /*
  2084.      * Dithering will be correct up to the end of the last
  2085.      * pre-existing complete scanline.
  2086.      */
  2087.  
  2088.     if ((validBox.x > 0) || (validBox.y > 0)) {
  2089.         masterPtr->ditherX = 0;
  2090.         masterPtr->ditherY = 0;
  2091.     } else if (validBox.width == width) {
  2092.         if ((int) validBox.height < masterPtr->ditherY) {
  2093.         masterPtr->ditherX = 0;
  2094.         masterPtr->ditherY = validBox.height;
  2095.         }
  2096.     } else {
  2097.         if ((masterPtr->ditherY > 0)
  2098.             || ((int) validBox.width < masterPtr->ditherX)) {
  2099.         masterPtr->ditherX = validBox.width;
  2100.         masterPtr->ditherY = 0;
  2101.         }
  2102.     }
  2103.     }
  2104.  
  2105.     /*
  2106.      * Now adjust the sizes of the pixmaps for all of the instances.
  2107.      */
  2108.  
  2109.     for (instancePtr = masterPtr->instancePtr; instancePtr != NULL;
  2110.         instancePtr = instancePtr->nextPtr) {
  2111.     ImgPhotoInstanceSetSize(instancePtr);
  2112.     }
  2113. }
  2114.  
  2115. /*
  2116.  *----------------------------------------------------------------------
  2117.  *
  2118.  * ImgPhotoInstanceSetSize --
  2119.  *
  2120.  *     This procedure reallocates the instance pixmap and dithering
  2121.  *    error array for a photo instance, as necessary, to change the
  2122.  *    image's size to `width' x `height' pixels.
  2123.  *
  2124.  * Results:
  2125.  *    None.
  2126.  *
  2127.  * Side effects:
  2128.  *    Storage gets reallocated, here and in the X server.
  2129.  *
  2130.  *----------------------------------------------------------------------
  2131.  */
  2132.  
  2133. static void
  2134. ImgPhotoInstanceSetSize(instancePtr)
  2135.     PhotoInstance *instancePtr;        /* Instance whose size is to be
  2136.                      * changed. */
  2137. {
  2138.     PhotoMaster *masterPtr;
  2139.     schar *newError;
  2140.     schar *errSrcPtr, *errDestPtr;
  2141.     int h, offset;
  2142.     XRectangle validBox;
  2143.     Pixmap newPixmap;
  2144.  
  2145.     masterPtr = instancePtr->masterPtr;
  2146.     TkClipBox(masterPtr->validRegion, &validBox);
  2147.  
  2148.     if ((instancePtr->width != masterPtr->width)
  2149.         || (instancePtr->height != masterPtr->height)
  2150.         || (instancePtr->pixels == None)) {
  2151.     newPixmap = Tk_GetPixmap(instancePtr->display,
  2152.         RootWindow(instancePtr->display,
  2153.             instancePtr->visualInfo.screen),
  2154.         (masterPtr->width > 0) ? masterPtr->width: 1,
  2155.         (masterPtr->height > 0) ? masterPtr->height: 1,
  2156.         instancePtr->visualInfo.depth);
  2157.  
  2158.     /*
  2159.      * The following is a gross hack needed to properly support colormaps
  2160.      * under Windows.  Before the pixels can be copied to the pixmap,
  2161.      * the relevent colormap must be associated with the drawable.
  2162.      * Normally we can infer this association from the window that
  2163.      * was used to create the pixmap.  However, in this case we're
  2164.      * using the root window, so we have to be more explicit.
  2165.      */
  2166.  
  2167.     TkSetPixmapColormap(newPixmap, instancePtr->colormap);
  2168.  
  2169.     if (instancePtr->pixels != None) {
  2170.         /*
  2171.          * Copy any common pixels from the old pixmap and free it.
  2172.          */
  2173.         XCopyArea(instancePtr->display, instancePtr->pixels, newPixmap,
  2174.             instancePtr->gc, validBox.x, validBox.y,
  2175.             validBox.width, validBox.height, validBox.x, validBox.y);
  2176.         Tk_FreePixmap(instancePtr->display, instancePtr->pixels);
  2177.     }
  2178.     instancePtr->pixels = newPixmap;
  2179.     }
  2180.  
  2181.     if ((instancePtr->width != masterPtr->width)
  2182.         || (instancePtr->height != masterPtr->height)
  2183.         || (instancePtr->error == NULL)) {
  2184.  
  2185.     newError = (schar *) ckalloc((unsigned)
  2186.         (masterPtr->height * masterPtr->width * 3 * sizeof(schar)));
  2187.  
  2188.     /*
  2189.      * Zero the new array so that we don't get bogus error values
  2190.      * propagating into areas we dither later.
  2191.      */
  2192.  
  2193.     if ((instancePtr->error != NULL)
  2194.         && ((instancePtr->width == masterPtr->width)
  2195.         || (validBox.width == masterPtr->width))) {
  2196.         if (validBox.y > 0) {
  2197.         memset((VOID *) newError, 0, (size_t)
  2198.             (validBox.y * masterPtr->width * 3 * sizeof(schar)));
  2199.         }
  2200.         h = validBox.y + validBox.height;
  2201.         if (h < masterPtr->height) {
  2202.         memset((VOID *) (newError + h * masterPtr->width * 3), 0,
  2203.             (size_t) ((masterPtr->height - h)
  2204.                 * masterPtr->width * 3 * sizeof(schar)));
  2205.         }
  2206.     } else {
  2207.         memset((VOID *) newError, 0, (size_t)
  2208.             (masterPtr->height * masterPtr->width * 3 * sizeof(schar)));
  2209.     }
  2210.  
  2211.     if (instancePtr->error != NULL) {
  2212.  
  2213.         /*
  2214.          * Copy the common area over to the new array
  2215.          * and free the old array.
  2216.          */
  2217.  
  2218.         if (masterPtr->width == instancePtr->width) {
  2219.  
  2220.         offset = validBox.y * masterPtr->width * 3;
  2221.         memcpy((VOID *) (newError + offset),
  2222.             (VOID *) (instancePtr->error + offset),
  2223.             (size_t) (validBox.height
  2224.             * masterPtr->width * 3 * sizeof(schar)));
  2225.  
  2226.         } else if (validBox.width > 0 && validBox.height > 0) {
  2227.  
  2228.         errDestPtr = newError
  2229.             + (validBox.y * masterPtr->width + validBox.x) * 3;
  2230.         errSrcPtr = instancePtr->error
  2231.             + (validBox.y * instancePtr->width + validBox.x) * 3;
  2232.         for (h = validBox.height; h > 0; --h) {
  2233.             memcpy((VOID *) errDestPtr, (VOID *) errSrcPtr,
  2234.                 validBox.width * 3 * sizeof(schar));
  2235.             errDestPtr += masterPtr->width * 3;
  2236.             errSrcPtr += instancePtr->width * 3;
  2237.         }
  2238.         }
  2239.         ckfree((char *) instancePtr->error);
  2240.     }
  2241.  
  2242.     instancePtr->error = newError;
  2243.     }
  2244.  
  2245.     instancePtr->width = masterPtr->width;
  2246.     instancePtr->height = masterPtr->height;
  2247. }
  2248.  
  2249. /*
  2250.  *----------------------------------------------------------------------
  2251.  *
  2252.  * IsValidPalette --
  2253.  *
  2254.  *    This procedure is called to check whether a value given for
  2255.  *    the -palette option is valid for a particular instance
  2256.  *     of a photo image.
  2257.  *
  2258.  * Results:
  2259.  *    A boolean value: 1 if the palette is acceptable, 0 otherwise.
  2260.  *
  2261.  * Side effects:
  2262.  *    None.
  2263.  *
  2264.  *----------------------------------------------------------------------
  2265.  */
  2266.  
  2267. static int
  2268. IsValidPalette(instancePtr, palette)
  2269.     PhotoInstance *instancePtr;        /* Instance to which the palette
  2270.                      * specification is to be applied. */
  2271.     char *palette;            /* Palette specification string. */
  2272. {
  2273.     int nRed, nGreen, nBlue, mono, numColors;
  2274.     char *endp;
  2275.  
  2276.     /*
  2277.      * First parse the specification: it must be of the form
  2278.      * %d or %d/%d/%d.
  2279.      */
  2280.  
  2281.     nRed = strtol(palette, &endp, 10);
  2282.     if ((endp == palette) || ((*endp != 0) && (*endp != '/'))
  2283.         || (nRed < 2) || (nRed > 256)) {
  2284.     return 0;
  2285.     }
  2286.  
  2287.     if (*endp == 0) {
  2288.     mono = 1;
  2289.     nGreen = nBlue = nRed;
  2290.     } else {
  2291.     palette = endp + 1;
  2292.     nGreen = strtol(palette, &endp, 10);
  2293.     if ((endp == palette) || (*endp != '/') || (nGreen < 2)
  2294.         || (nGreen > 256)) {
  2295.         return 0;
  2296.     }
  2297.     palette = endp + 1;
  2298.     nBlue = strtol(palette, &endp, 10);
  2299.     if ((endp == palette) || (*endp != 0) || (nBlue < 2)
  2300.         || (nBlue > 256)) {
  2301.         return 0;
  2302.     }
  2303.     mono = 0;
  2304.     }
  2305.  
  2306.     switch (instancePtr->visualInfo.class) {
  2307.     case DirectColor:
  2308.     case TrueColor:
  2309.         if ((nRed > (1 << CountBits(instancePtr->visualInfo.red_mask)))
  2310.             || (nGreen > (1
  2311.             << CountBits(instancePtr->visualInfo.green_mask)))
  2312.             || (nBlue > (1
  2313.             << CountBits(instancePtr->visualInfo.blue_mask)))) {
  2314.         return 0;
  2315.         }
  2316.         break;
  2317.     case PseudoColor:
  2318.     case StaticColor:
  2319.         numColors = nRed;
  2320.         if (!mono) {
  2321.         numColors *= nGreen*nBlue;
  2322.         }
  2323.         if (numColors > (1 << instancePtr->visualInfo.depth)) {
  2324.         return 0;
  2325.         }
  2326.         break;
  2327.     case GrayScale:
  2328.     case StaticGray:
  2329.         if (!mono || (nRed > (1 << instancePtr->visualInfo.depth))) {
  2330.         return 0;
  2331.         }
  2332.         break;
  2333.     }
  2334.  
  2335.     return 1;
  2336. }
  2337.  
  2338. /*
  2339.  *----------------------------------------------------------------------
  2340.  *
  2341.  * CountBits --
  2342.  *
  2343.  *    This procedure counts how many bits are set to 1 in `mask'.
  2344.  *
  2345.  * Results:
  2346.  *    The integer number of bits.
  2347.  *
  2348.  * Side effects:
  2349.  *    None.
  2350.  *
  2351.  *----------------------------------------------------------------------
  2352.  */
  2353.  
  2354. static int
  2355. CountBits(mask)
  2356.     pixel mask;            /* Value to count the 1 bits in. */
  2357. {
  2358.     int n;
  2359.  
  2360.     for( n = 0; mask != 0; mask &= mask - 1 )
  2361.     n++;
  2362.     return n;
  2363. }
  2364.  
  2365. /*
  2366.  *----------------------------------------------------------------------
  2367.  *
  2368.  * GetColorTable --
  2369.  *
  2370.  *    This procedure is called to allocate a table of colormap
  2371.  *    information for an instance of a photo image.  Only one such
  2372.  *    table is allocated for all photo instances using the same
  2373.  *    display, colormap, palette and gamma values, so that the
  2374.  *    application need only request a set of colors from the X
  2375.  *    server once for all such photo widgets.  This procedure
  2376.  *    maintains a hash table to find previously-allocated
  2377.  *    ColorTables.
  2378.  *
  2379.  * Results:
  2380.  *    None.
  2381.  *
  2382.  * Side effects:
  2383.  *    A new ColorTable may be allocated and placed in the hash
  2384.  *    table, and have colors allocated for it.
  2385.  *
  2386.  *----------------------------------------------------------------------
  2387.  */
  2388.  
  2389. static void
  2390. GetColorTable(instancePtr)
  2391.     PhotoInstance *instancePtr;        /* Instance needing a color table. */
  2392. {
  2393.     ColorTable *colorPtr;
  2394.     Tcl_HashEntry *entry;
  2395.     ColorTableId id;
  2396.     int isNew;
  2397.  
  2398.     /*
  2399.      * Look for an existing ColorTable in the hash table.
  2400.      */
  2401.  
  2402.     memset((VOID *) &id, 0, sizeof(id));
  2403.     id.display = instancePtr->display;
  2404.     id.colormap = instancePtr->colormap;
  2405.     id.palette = instancePtr->palette;
  2406.     id.gamma = instancePtr->gamma;
  2407.     if (!imgPhotoColorHashInitialized) {
  2408.     Tcl_InitHashTable(&imgPhotoColorHash, N_COLOR_HASH);
  2409.     imgPhotoColorHashInitialized = 1;
  2410.     }
  2411.     entry = Tcl_CreateHashEntry(&imgPhotoColorHash, (char *) &id, &isNew);
  2412.  
  2413.     if (!isNew) {
  2414.     /*
  2415.      * Re-use the existing entry.
  2416.      */
  2417.  
  2418.     colorPtr = (ColorTable *) Tcl_GetHashValue(entry);
  2419.  
  2420.     } else {
  2421.     /*
  2422.      * No color table currently available; need to make one.
  2423.      */
  2424.  
  2425.     colorPtr = (ColorTable *) ckalloc(sizeof(ColorTable));
  2426.  
  2427.     /*
  2428.      * The following line of code should not normally be needed due
  2429.      * to the assignment in the following line.  However, it compensates
  2430.      * for bugs in some compilers (HP, for example) where
  2431.      * sizeof(ColorTable) is 24 but the assignment only copies 20 bytes,
  2432.      * leaving 4 bytes uninitialized;  these cause problems when using
  2433.      * the id for lookups in imgPhotoColorHash, and can result in
  2434.      * core dumps.
  2435.      */
  2436.  
  2437.     memset((VOID *) &colorPtr->id, 0, sizeof(ColorTableId));
  2438.     colorPtr->id = id;
  2439.     Tk_PreserveColormap(colorPtr->id.display, colorPtr->id.colormap);
  2440.     colorPtr->flags = 0;
  2441.     colorPtr->refCount = 0;
  2442.     colorPtr->liveRefCount = 0;
  2443.     colorPtr->numColors = 0;
  2444.     colorPtr->visualInfo = instancePtr->visualInfo;
  2445.     colorPtr->pixelMap = NULL;
  2446.     Tcl_SetHashValue(entry, colorPtr);
  2447.     }
  2448.  
  2449.     colorPtr->refCount++;
  2450.     colorPtr->liveRefCount++;
  2451.     instancePtr->colorTablePtr = colorPtr;
  2452.     if (colorPtr->flags & DISPOSE_PENDING) {
  2453.     Tcl_CancelIdleCall(DisposeColorTable, (ClientData) colorPtr);
  2454.     colorPtr->flags &= ~DISPOSE_PENDING;
  2455.     }
  2456.  
  2457.     /*
  2458.      * Allocate colors for this color table if necessary.
  2459.      */
  2460.  
  2461.     if ((colorPtr->numColors == 0)
  2462.         && ((colorPtr->flags & BLACK_AND_WHITE) == 0)) {
  2463.     AllocateColors(colorPtr);
  2464.     }
  2465. }
  2466.  
  2467. /*
  2468.  *----------------------------------------------------------------------
  2469.  *
  2470.  * FreeColorTable --
  2471.  *
  2472.  *    This procedure is called when an instance ceases using a
  2473.  *    color table.
  2474.  *
  2475.  * Results:
  2476.  *    None.
  2477.  *
  2478.  * Side effects:
  2479.  *    If no other instances are using this color table, a when-idle
  2480.  *    handler is registered to free up the color table and the colors
  2481.  *    allocated for it.
  2482.  *
  2483.  *----------------------------------------------------------------------
  2484.  */
  2485.  
  2486. static void
  2487. FreeColorTable(colorPtr)
  2488.     ColorTable *colorPtr;    /* Pointer to the color table which is
  2489.                  * no longer required by an instance. */
  2490. {
  2491.     colorPtr->refCount--;
  2492.     if (colorPtr->refCount > 0) {
  2493.     return;
  2494.     }
  2495.     if ((colorPtr->flags & DISPOSE_PENDING) == 0) {
  2496.     Tcl_DoWhenIdle(DisposeColorTable, (ClientData) colorPtr);
  2497.     colorPtr->flags |= DISPOSE_PENDING;
  2498.     }
  2499. }
  2500.  
  2501. /*
  2502.  *----------------------------------------------------------------------
  2503.  *
  2504.  * AllocateColors --
  2505.  *
  2506.  *    This procedure allocates the colors required by a color table,
  2507.  *    and sets up the fields in the color table data structure which
  2508.  *    are used in dithering.
  2509.  *
  2510.  * Results:
  2511.  *    None.
  2512.  *
  2513.  * Side effects:
  2514.  *    Colors are allocated from the X server.  Fields in the
  2515.  *    color table data structure are updated.
  2516.  *
  2517.  *----------------------------------------------------------------------
  2518.  */
  2519.  
  2520. static void
  2521. AllocateColors(colorPtr)
  2522.     ColorTable *colorPtr;    /* Pointer to the color table requiring
  2523.                  * colors to be allocated. */
  2524. {
  2525.     int i, r, g, b, rMult, mono;
  2526.     int numColors, nRed, nGreen, nBlue;
  2527.     double fr, fg, fb, igam;
  2528.     XColor *colors;
  2529.     unsigned long *pixels;
  2530.  
  2531.     /* 16-bit intensity value for i/n of full intensity. */
  2532. #   define CFRAC(i, n)    ((i) * 65535 / (n))
  2533.  
  2534.     /* As for CFRAC, but apply exponent of g. */
  2535. #   define CGFRAC(i, n, g)    ((int)(65535 * pow((double)(i) / (n), (g))))
  2536.  
  2537.     /*
  2538.      * First parse the palette specification to get the required number of
  2539.      * shades of each primary.
  2540.      */
  2541.  
  2542.     mono = sscanf(colorPtr->id.palette, "%d/%d/%d", &nRed, &nGreen, &nBlue)
  2543.         <= 1;
  2544.     igam = 1.0 / colorPtr->id.gamma;
  2545.  
  2546.     /*
  2547.      * Each time around this loop, we reduce the number of colors we're
  2548.      * trying to allocate until we succeed in allocating all of the colors
  2549.      * we need.
  2550.      */
  2551.  
  2552.     for (;;) {
  2553.     /*
  2554.      * If we are using 1 bit/pixel, we don't need to allocate
  2555.      * any colors (we just use the foreground and background
  2556.      * colors in the GC).
  2557.      */
  2558.  
  2559.     if (mono && (nRed <= 2)) {
  2560.         colorPtr->flags |= BLACK_AND_WHITE;
  2561.         return;
  2562.     }
  2563.  
  2564.     /*
  2565.      * Calculate the RGB coordinates of the colors we want to
  2566.      * allocate and store them in *colors.
  2567.      */
  2568.  
  2569.     if ((colorPtr->visualInfo.class == DirectColor)
  2570.         || (colorPtr->visualInfo.class == TrueColor)) {
  2571.  
  2572.         /*
  2573.          * Direct/True Color: allocate shades of red, green, blue
  2574.          * independently.
  2575.          */
  2576.  
  2577.         if (mono) {
  2578.         numColors = nGreen = nBlue = nRed;
  2579.         } else {
  2580.         numColors = MAX(MAX(nRed, nGreen), nBlue);
  2581.         }
  2582.         colors = (XColor *) ckalloc(numColors * sizeof(XColor));
  2583.  
  2584.         for (i = 0; i < numColors; ++i) {
  2585.         if (igam == 1.0) {
  2586.             colors[i].red = CFRAC(i, nRed - 1);
  2587.             colors[i].green = CFRAC(i, nGreen - 1);
  2588.             colors[i].blue = CFRAC(i, nBlue - 1);
  2589.         } else {
  2590.             colors[i].red = CGFRAC(i, nRed - 1, igam);
  2591.             colors[i].green = CGFRAC(i, nGreen - 1, igam);
  2592.             colors[i].blue = CGFRAC(i, nBlue - 1, igam);
  2593.         }
  2594.         }
  2595.     } else {
  2596.         /*
  2597.          * PseudoColor, StaticColor, GrayScale or StaticGray visual:
  2598.          * we have to allocate each color in the color cube separately.
  2599.          */
  2600.  
  2601.         numColors = (mono) ? nRed: (nRed * nGreen * nBlue);
  2602.         colors = (XColor *) ckalloc(numColors * sizeof(XColor));
  2603.  
  2604.         if (!mono) {
  2605.         /*
  2606.          * Color display using a PseudoColor or StaticColor visual.
  2607.          */
  2608.  
  2609.         i = 0;
  2610.         for (r = 0; r < nRed; ++r) {
  2611.             for (g = 0; g < nGreen; ++g) {
  2612.             for (b = 0; b < nBlue; ++b) {
  2613.                 if (igam == 1.0) {
  2614.                 colors[i].red = CFRAC(r, nRed - 1);
  2615.                 colors[i].green = CFRAC(g, nGreen - 1);
  2616.                 colors[i].blue = CFRAC(b, nBlue - 1);
  2617.                 } else {
  2618.                 colors[i].red = CGFRAC(r, nRed - 1, igam);
  2619.                 colors[i].green = CGFRAC(g, nGreen - 1, igam);
  2620.                 colors[i].blue = CGFRAC(b, nBlue - 1, igam);
  2621.                 }
  2622.                 i++;
  2623.             }
  2624.             }
  2625.         }
  2626.         } else {
  2627.         /*
  2628.          * Monochrome display - allocate the shades of grey we want.
  2629.          */
  2630.  
  2631.         for (i = 0; i < numColors; ++i) {
  2632.             if (igam == 1.0) {
  2633.             r = CFRAC(i, numColors - 1);
  2634.             } else {
  2635.             r = CGFRAC(i, numColors - 1, igam);
  2636.             }
  2637.             colors[i].red = colors[i].green = colors[i].blue = r;
  2638.         }
  2639.         }
  2640.     }
  2641.  
  2642.     /*
  2643.      * Now try to allocate the colors we've calculated.
  2644.      */
  2645.  
  2646.     pixels = (unsigned long *) ckalloc(numColors * sizeof(unsigned long));
  2647.     for (i = 0; i < numColors; ++i) {
  2648.         if (!XAllocColor(colorPtr->id.display, colorPtr->id.colormap,
  2649.             &colors[i])) {
  2650.  
  2651.         /*
  2652.          * Can't get all the colors we want in the default colormap;
  2653.          * first try freeing colors from other unused color tables.
  2654.          */
  2655.  
  2656.         if (!ReclaimColors(&colorPtr->id, numColors - i)
  2657.             || !XAllocColor(colorPtr->id.display,
  2658.             colorPtr->id.colormap, &colors[i])) {
  2659.             /*
  2660.              * Still can't allocate the color.
  2661.              */
  2662.             break;
  2663.         }
  2664.         }
  2665.         pixels[i] = colors[i].pixel;
  2666.     }
  2667.  
  2668.     /*
  2669.      * If we didn't get all of the colors, reduce the
  2670.      * resolution of the color cube, free the ones we got,
  2671.      * and try again.
  2672.      */
  2673.  
  2674.     if (i >= numColors) {
  2675.         break;
  2676.     }
  2677.     XFreeColors(colorPtr->id.display, colorPtr->id.colormap, pixels, i, 0);
  2678.     ckfree((char *) colors);
  2679.     ckfree((char *) pixels);
  2680.  
  2681.     if (!mono) {
  2682.         if ((nRed == 2) && (nGreen == 2) && (nBlue == 2)) {
  2683.         /*
  2684.          * Fall back to 1-bit monochrome display.
  2685.          */
  2686.  
  2687.         mono = 1;
  2688.         } else {
  2689.         /*
  2690.          * Reduce the number of shades of each primary to about
  2691.          * 3/4 of the previous value.  This should reduce the
  2692.          * total number of colors required to about half the
  2693.          * previous value for PseudoColor displays.
  2694.          */
  2695.  
  2696.         nRed = (nRed * 3 + 2) / 4;
  2697.         nGreen = (nGreen * 3 + 2) / 4;
  2698.         nBlue = (nBlue * 3 + 2) / 4;
  2699.         }
  2700.     } else {
  2701.         /*
  2702.          * Reduce the number of shades of gray to about 1/2.
  2703.          */
  2704.  
  2705.         nRed = nRed / 2;
  2706.     }
  2707.     }
  2708.     
  2709.     /*
  2710.      * We have allocated all of the necessary colors:
  2711.      * fill in various fields of the ColorTable record.
  2712.      */
  2713.  
  2714.     if (!mono) {
  2715.     colorPtr->flags |= COLOR_WINDOW;
  2716.  
  2717.     /*
  2718.      * The following is a hairy hack.  We only want to index into
  2719.      * the pixelMap on colormap displays.  However, if the display
  2720.      * is on Windows, then we actually want to store the index not
  2721.      * the value since we will be passing the color table into the
  2722.      * TkPutImage call.
  2723.      */
  2724.     
  2725. #ifndef __WIN32__
  2726.     if ((colorPtr->visualInfo.class != DirectColor)
  2727.         && (colorPtr->visualInfo.class != TrueColor)) {
  2728.         colorPtr->flags |= MAP_COLORS;
  2729.     }
  2730. #endif /* __WIN32__ */
  2731.     }
  2732.  
  2733.     colorPtr->numColors = numColors;
  2734.     colorPtr->pixelMap = pixels;
  2735.  
  2736.     /*
  2737.      * Set up quantization tables for dithering.
  2738.      */
  2739.     rMult = nGreen * nBlue;
  2740.     for (i = 0; i < 256; ++i) {
  2741.     r = (i * (nRed - 1) + 127) / 255;
  2742.     if (mono) {
  2743.         fr = (double) colors[r].red / 65535.0;
  2744.         if (colorPtr->id.gamma != 1.0 ) {
  2745.         fr = pow(fr, colorPtr->id.gamma);
  2746.         }
  2747.         colorPtr->colorQuant[0][i] = (int)(fr * 255.99);
  2748.         colorPtr->redValues[i] = colors[r].pixel;
  2749.     } else {
  2750.         g = (i * (nGreen - 1) + 127) / 255;
  2751.         b = (i * (nBlue - 1) + 127) / 255;
  2752.         if ((colorPtr->visualInfo.class == DirectColor)
  2753.             || (colorPtr->visualInfo.class == TrueColor)) {
  2754.         colorPtr->redValues[i] = colors[r].pixel
  2755.             & colorPtr->visualInfo.red_mask;
  2756.         colorPtr->greenValues[i] = colors[g].pixel
  2757.             & colorPtr->visualInfo.green_mask;
  2758.         colorPtr->blueValues[i] = colors[b].pixel
  2759.             & colorPtr->visualInfo.blue_mask;
  2760.         } else {
  2761.         r *= rMult;
  2762.         g *= nBlue;
  2763.         colorPtr->redValues[i] = r;
  2764.         colorPtr->greenValues[i] = g;
  2765.         colorPtr->blueValues[i] = b;
  2766.         }
  2767.         fr = (double) colors[r].red / 65535.0;
  2768.         fg = (double) colors[g].green / 65535.0;
  2769.         fb = (double) colors[b].blue / 65535.0;
  2770.         if (colorPtr->id.gamma != 1.0) {
  2771.         fr = pow(fr, colorPtr->id.gamma);
  2772.         fg = pow(fg, colorPtr->id.gamma);
  2773.         fb = pow(fb, colorPtr->id.gamma);
  2774.         }
  2775.         colorPtr->colorQuant[0][i] = (int)(fr * 255.99);
  2776.         colorPtr->colorQuant[1][i] = (int)(fg * 255.99);
  2777.         colorPtr->colorQuant[2][i] = (int)(fb * 255.99);
  2778.     }
  2779.     }
  2780.  
  2781.     ckfree((char *) colors);
  2782. }
  2783.  
  2784. /*
  2785.  *----------------------------------------------------------------------
  2786.  *
  2787.  * DisposeColorTable --
  2788.  *
  2789.  *
  2790.  * Results:
  2791.  *    None.
  2792.  *
  2793.  * Side effects:
  2794.  *    The colors in the argument color table are freed, as is the
  2795.  *    color table structure itself.  The color table is removed
  2796.  *    from the hash table which is used to locate color tables.
  2797.  *
  2798.  *----------------------------------------------------------------------
  2799.  */
  2800.  
  2801. static void
  2802. DisposeColorTable(clientData)
  2803.     ClientData clientData;    /* Pointer to the ColorTable whose
  2804.                  * colors are to be released. */
  2805. {
  2806.     ColorTable *colorPtr;
  2807.     Tcl_HashEntry *entry;
  2808.  
  2809.     colorPtr = (ColorTable *) clientData;
  2810.     if (colorPtr->pixelMap != NULL) {
  2811.     if (colorPtr->numColors > 0) {
  2812.         XFreeColors(colorPtr->id.display, colorPtr->id.colormap,
  2813.             colorPtr->pixelMap, colorPtr->numColors, 0);
  2814.         Tk_FreeColormap(colorPtr->id.display, colorPtr->id.colormap);
  2815.     }
  2816.     ckfree((char *) colorPtr->pixelMap);
  2817.     }
  2818.  
  2819.     entry = Tcl_FindHashEntry(&imgPhotoColorHash, (char *) &colorPtr->id);
  2820.     if (entry == NULL) {
  2821.     panic("DisposeColorTable couldn't find hash entry");
  2822.     }
  2823.     Tcl_DeleteHashEntry(entry);
  2824.  
  2825.     ckfree((char *) colorPtr);
  2826. }
  2827.  
  2828. /*
  2829.  *----------------------------------------------------------------------
  2830.  *
  2831.  * ReclaimColors --
  2832.  *
  2833.  *    This procedure is called to try to free up colors in the
  2834.  *    colormap used by a color table.  It looks for other color
  2835.  *    tables with the same colormap and with a zero live reference
  2836.  *    count, and frees their colors.  It only does so if there is
  2837.  *    the possibility of freeing up at least `numColors' colors.
  2838.  *
  2839.  * Results:
  2840.  *    The return value is TRUE if any colors were freed, FALSE
  2841.  *    otherwise.
  2842.  *
  2843.  * Side effects:
  2844.  *    ColorTables which are not currently in use may lose their
  2845.  *    color allocations.
  2846.  *
  2847.  *---------------------------------------------------------------------- */
  2848.  
  2849. static int
  2850. ReclaimColors(id, numColors)
  2851.     ColorTableId *id;        /* Pointer to information identifying
  2852.                  * the color table which needs more colors. */
  2853.     int numColors;        /* Number of colors required. */
  2854. {
  2855.     Tcl_HashSearch srch;
  2856.     Tcl_HashEntry *entry;
  2857.     ColorTable *colorPtr;
  2858.     int nAvail;
  2859.  
  2860.     /*
  2861.      * First scan through the color hash table to get an
  2862.      * upper bound on how many colors we might be able to free.
  2863.      */
  2864.  
  2865.     nAvail = 0;
  2866.     entry = Tcl_FirstHashEntry(&imgPhotoColorHash, &srch);
  2867.     while (entry != NULL) {
  2868.     colorPtr = (ColorTable *) Tcl_GetHashValue(entry);
  2869.     if ((colorPtr->id.display == id->display)
  2870.         && (colorPtr->id.colormap == id->colormap)
  2871.         && (colorPtr->liveRefCount == 0 )&& (colorPtr->numColors != 0)
  2872.         && ((colorPtr->id.palette != id->palette)
  2873.         || (colorPtr->id.gamma != id->gamma))) {
  2874.  
  2875.         /*
  2876.          * We could take this guy's colors off him.
  2877.          */
  2878.  
  2879.         nAvail += colorPtr->numColors;
  2880.     }
  2881.     entry = Tcl_NextHashEntry(&srch);
  2882.     }
  2883.  
  2884.     /*
  2885.      * nAvail is an (over)estimate of the number of colors we could free.
  2886.      */
  2887.  
  2888.     if (nAvail < numColors) {
  2889.     return 0;
  2890.     }
  2891.  
  2892.     /*
  2893.      * Scan through a second time freeing colors.
  2894.      */
  2895.  
  2896.     entry = Tcl_FirstHashEntry(&imgPhotoColorHash, &srch);
  2897.     while ((entry != NULL) && (numColors > 0)) {
  2898.     colorPtr = (ColorTable *) Tcl_GetHashValue(entry);
  2899.     if ((colorPtr->id.display == id->display)
  2900.         && (colorPtr->id.colormap == id->colormap)
  2901.         && (colorPtr->liveRefCount == 0) && (colorPtr->numColors != 0)
  2902.         && ((colorPtr->id.palette != id->palette)
  2903.             || (colorPtr->id.gamma != id->gamma))) {
  2904.  
  2905.         /*
  2906.          * Free the colors that this ColorTable has.
  2907.          */
  2908.  
  2909.         XFreeColors(colorPtr->id.display, colorPtr->id.colormap,
  2910.             colorPtr->pixelMap, colorPtr->numColors, 0);
  2911.         numColors -= colorPtr->numColors;
  2912.         colorPtr->numColors = 0;
  2913.         ckfree((char *) colorPtr->pixelMap);
  2914.         colorPtr->pixelMap = NULL;
  2915.     }
  2916.  
  2917.     entry = Tcl_NextHashEntry(&srch);
  2918.     }
  2919.     return 1;            /* we freed some colors */
  2920. }
  2921.  
  2922. /*
  2923.  *----------------------------------------------------------------------
  2924.  *
  2925.  * DisposeInstance --
  2926.  *
  2927.  *    This procedure is called to finally free up an instance
  2928.  *    of a photo image which is no longer required.
  2929.  *
  2930.  * Results:
  2931.  *    None.
  2932.  *
  2933.  * Side effects:
  2934.  *    The instance data structure and the resources it references
  2935.  *    are freed.
  2936.  *
  2937.  *----------------------------------------------------------------------
  2938.  */
  2939.  
  2940. static void
  2941. DisposeInstance(clientData)
  2942.     ClientData clientData;    /* Pointer to the instance whose resources
  2943.                  * are to be released. */
  2944. {
  2945.     PhotoInstance *instancePtr = (PhotoInstance *) clientData;
  2946.     PhotoInstance *prevPtr;
  2947.  
  2948.     if (instancePtr->pixels != None) {
  2949.     Tk_FreePixmap(instancePtr->display, instancePtr->pixels);
  2950.     }
  2951.     if (instancePtr->gc != None) {
  2952.     Tk_FreeGC(instancePtr->display, instancePtr->gc);
  2953.     }
  2954.     if (instancePtr->imagePtr != NULL) {
  2955.     XFree((char *) instancePtr->imagePtr);
  2956.     }
  2957.     if (instancePtr->error != NULL) {
  2958.     ckfree((char *) instancePtr->error);
  2959.     }
  2960.     if (instancePtr->colorTablePtr != NULL) {
  2961.     FreeColorTable(instancePtr->colorTablePtr);
  2962.     }
  2963.  
  2964.     if (instancePtr->masterPtr->instancePtr == instancePtr) {
  2965.     instancePtr->masterPtr->instancePtr = instancePtr->nextPtr;
  2966.     } else {
  2967.     for (prevPtr = instancePtr->masterPtr->instancePtr;
  2968.         prevPtr->nextPtr != instancePtr; prevPtr = prevPtr->nextPtr) {
  2969.         /* Empty loop body */
  2970.     }
  2971.     prevPtr->nextPtr = instancePtr->nextPtr;
  2972.     }
  2973.     Tk_FreeColormap(instancePtr->display, instancePtr->colormap);
  2974.     ckfree((char *) instancePtr);
  2975. }
  2976.  
  2977. /*
  2978.  *----------------------------------------------------------------------
  2979.  *
  2980.  * MatchFileFormat --
  2981.  *
  2982.  *    This procedure is called to find a photo image file format
  2983.  *    handler which can parse the image data in the given file.
  2984.  *    If a user-specified format string is provided, only handlers
  2985.  *    whose names match a prefix of the format string are tried.
  2986.  *
  2987.  * Results:
  2988.  *    A standard TCL return value.  If the return value is TCL_OK, a
  2989.  *    pointer to the image format record is returned in
  2990.  *    *imageFormatPtr, and the width and height of the image are
  2991.  *    returned in *widthPtr and *heightPtr.
  2992.  *
  2993.  * Side effects:
  2994.  *    None.
  2995.  *
  2996.  *----------------------------------------------------------------------
  2997.  */
  2998.  
  2999. static int
  3000. MatchFileFormat(interp, f, fileName, formatString, imageFormatPtr,
  3001.     widthPtr, heightPtr)
  3002.     Tcl_Interp *interp;        /* Interpreter to use for reporting errors. */
  3003.     FILE *f;            /* The image file, open for reading. */
  3004.     char *fileName;        /* The name of the image file. */
  3005.     char *formatString;        /* User-specified format string, or NULL. */
  3006.     Tk_PhotoImageFormat **imageFormatPtr;
  3007.                 /* A pointer to the photo image format
  3008.                  * record is returned here. */
  3009.     int *widthPtr, *heightPtr;    /* The dimensions of the image are
  3010.                  * returned here. */
  3011. {
  3012.     int matched;
  3013.     Tk_PhotoImageFormat *formatPtr;
  3014.  
  3015.     /*
  3016.      * Scan through the table of file format handlers to find
  3017.      * one which can handle the image.
  3018.      */
  3019.  
  3020.     matched = 0;
  3021.     for (formatPtr = formatList; formatPtr != NULL;
  3022.      formatPtr = formatPtr->nextPtr) {
  3023.     if (formatString != NULL) {
  3024.         if (strncasecmp(formatString, formatPtr->name,
  3025.             strlen(formatPtr->name)) != 0) {
  3026.         continue;
  3027.         }
  3028.         matched = 1;
  3029.         if (formatPtr->fileMatchProc == NULL) {
  3030.         Tcl_AppendResult(interp, "-file option isn't supported for ",
  3031.             formatString, " images", (char *) NULL);
  3032.         return TCL_ERROR;
  3033.         }
  3034.     }
  3035.     if (formatPtr->fileMatchProc != NULL) {
  3036.         fseek(f, 0L, SEEK_SET);
  3037.         if ((*formatPtr->fileMatchProc)(f, fileName, formatString,
  3038.             widthPtr, heightPtr)) {
  3039.         if (*widthPtr < 1) {
  3040.             *widthPtr = 1;
  3041.         }
  3042.         if (*heightPtr < 1) {
  3043.             *heightPtr = 1;
  3044.         }
  3045.         break;
  3046.         }
  3047.     }
  3048.     }
  3049.  
  3050.     if (formatPtr == NULL) {
  3051.     if ((formatString != NULL) && !matched) {
  3052.         Tcl_AppendResult(interp, "image file format \"", formatString,
  3053.             "\" is not supported", (char *) NULL);
  3054.     } else {
  3055.         Tcl_AppendResult(interp,
  3056.             "couldn't recognize data in image file \"",
  3057.             fileName, "\"", (char *) NULL);
  3058.     }
  3059.     return TCL_ERROR;
  3060.     }
  3061.  
  3062.     *imageFormatPtr = formatPtr;
  3063.     fseek(f, 0L, SEEK_SET);
  3064.     return TCL_OK;
  3065. }
  3066.  
  3067. /*
  3068.  *----------------------------------------------------------------------
  3069.  *
  3070.  * MatchStringFormat --
  3071.  *
  3072.  *    This procedure is called to find a photo image file format
  3073.  *    handler which can parse the image data in the given string.
  3074.  *    If a user-specified format string is provided, only handlers
  3075.  *    whose names match a prefix of the format string are tried.
  3076.  *
  3077.  * Results:
  3078.  *    A standard TCL return value.  If the return value is TCL_OK, a
  3079.  *    pointer to the image format record is returned in
  3080.  *    *imageFormatPtr, and the width and height of the image are
  3081.  *    returned in *widthPtr and *heightPtr.
  3082.  *
  3083.  * Side effects:
  3084.  *    None.
  3085.  *
  3086.  *----------------------------------------------------------------------
  3087.  */
  3088.  
  3089. static int
  3090. MatchStringFormat(interp, string, formatString, imageFormatPtr,
  3091.     widthPtr, heightPtr)
  3092.     Tcl_Interp *interp;        /* Interpreter to use for reporting errors. */
  3093.     char *string;        /* String containing the image data. */
  3094.     char *formatString;        /* User-specified format string, or NULL. */
  3095.     Tk_PhotoImageFormat **imageFormatPtr;
  3096.                 /* A pointer to the photo image format
  3097.                  * record is returned here. */
  3098.     int *widthPtr, *heightPtr;    /* The dimensions of the image are
  3099.                  * returned here. */
  3100. {
  3101.     int matched;
  3102.     Tk_PhotoImageFormat *formatPtr;
  3103.  
  3104.     /*
  3105.      * Scan through the table of file format handlers to find
  3106.      * one which can handle the image.
  3107.      */
  3108.  
  3109.     matched = 0;
  3110.     for (formatPtr = formatList; formatPtr != NULL;
  3111.         formatPtr = formatPtr->nextPtr) {
  3112.     if (formatString != NULL) {
  3113.         if (strncasecmp(formatString, formatPtr->name,
  3114.             strlen(formatPtr->name)) != 0) {
  3115.         continue;
  3116.         }
  3117.         matched = 1;
  3118.         if (formatPtr->stringMatchProc == NULL) {
  3119.         Tcl_AppendResult(interp, "-data option isn't supported for ",
  3120.             formatString, " images", (char *) NULL);
  3121.         return TCL_ERROR;
  3122.         }
  3123.     }
  3124.     if ((formatPtr->stringMatchProc != NULL)
  3125.         && (*formatPtr->stringMatchProc)(string, formatString,
  3126.         widthPtr, heightPtr)) {
  3127.         break;
  3128.     }
  3129.     }
  3130.  
  3131.     if (formatPtr == NULL) {
  3132.     if ((formatString != NULL) && !matched) {
  3133.         Tcl_AppendResult(interp, "image format \"", formatString,
  3134.             "\" is not supported", (char *) NULL);
  3135.     } else {
  3136.         Tcl_AppendResult(interp, "couldn't recognize image data",
  3137.             (char *) NULL);
  3138.     }
  3139.     return TCL_ERROR;
  3140.     }
  3141.  
  3142.     *imageFormatPtr = formatPtr;
  3143.     return TCL_OK;
  3144. }
  3145.  
  3146. /*
  3147.  *----------------------------------------------------------------------
  3148.  *
  3149.  * Tk_FindPhoto --
  3150.  *
  3151.  *    This procedure is called to get an opaque handle (actually a
  3152.  *    PhotoMaster *) for a given image, which can be used in
  3153.  *    subsequent calls to Tk_PhotoPutBlock, etc.  The `name'
  3154.  *    parameter is the name of the image.
  3155.  *
  3156.  * Results:
  3157.  *    The handle for the photo image, or NULL if there is no
  3158.  *    photo image with the name given.
  3159.  *
  3160.  * Side effects:
  3161.  *    None.
  3162.  *
  3163.  *----------------------------------------------------------------------
  3164.  */
  3165.  
  3166. Tk_PhotoHandle
  3167. Tk_FindPhoto(imageName)
  3168.     char *imageName;        /* Name of the desired photo image. */
  3169. {
  3170.     Tcl_HashEntry *entry;
  3171.  
  3172.     if (!imgPhotoHashInitialized) {
  3173.     return NULL;
  3174.     }
  3175.     entry = Tcl_FindHashEntry(&imgPhotoHash, imageName);
  3176.     if (entry == NULL) {
  3177.     return NULL;
  3178.     }
  3179.     return (Tk_PhotoHandle) Tcl_GetHashValue(entry);
  3180. }
  3181.  
  3182. /*
  3183.  *----------------------------------------------------------------------
  3184.  *
  3185.  * Tk_PhotoPutBlock --
  3186.  *
  3187.  *    This procedure is called to put image data into a photo image.
  3188.  *
  3189.  * Results:
  3190.  *    None.
  3191.  *
  3192.  * Side effects:
  3193.  *    The image data is stored.  The image may be expanded.
  3194.  *    The Tk image code is informed that the image has changed.
  3195.  *
  3196.  *---------------------------------------------------------------------- */
  3197.  
  3198. void
  3199. Tk_PhotoPutBlock(handle, blockPtr, x, y, width, height)
  3200.     Tk_PhotoHandle handle;    /* Opaque handle for the photo image
  3201.                  * to be updated. */
  3202.     register Tk_PhotoImageBlock *blockPtr;
  3203.                 /* Pointer to a structure describing the
  3204.                  * pixel data to be copied into the image. */
  3205.     int x, y;            /* Coordinates of the top-left pixel to
  3206.                  * be updated in the image. */
  3207.     int width, height;        /* Dimensions of the area of the image
  3208.                  * to be updated. */
  3209. {
  3210.     register PhotoMaster *masterPtr;
  3211.     int xEnd, yEnd;
  3212.     int greenOffset, blueOffset;
  3213.     int wLeft, hLeft;
  3214.     int wCopy, hCopy;
  3215.     unsigned char *srcPtr, *srcLinePtr;
  3216.     unsigned char *destPtr, *destLinePtr;
  3217.     int pitch;
  3218.     XRectangle rect;
  3219.  
  3220.     masterPtr = (PhotoMaster *) handle;
  3221.  
  3222.     if ((masterPtr->userWidth != 0) && ((x + width) > masterPtr->userWidth)) {
  3223.     width = masterPtr->userWidth - x;
  3224.     }
  3225.     if ((masterPtr->userHeight != 0)
  3226.         && ((y + height) > masterPtr->userHeight)) {
  3227.     height = masterPtr->userHeight - y;
  3228.     }
  3229.     if ((width <= 0) || (height <= 0))
  3230.     return;
  3231.  
  3232.     xEnd = x + width;
  3233.     yEnd = y + height;
  3234.     if ((xEnd > masterPtr->width) || (yEnd > masterPtr->height)) {
  3235.     ImgPhotoSetSize(masterPtr, MAX(xEnd, masterPtr->width),
  3236.         MAX(yEnd, masterPtr->height));
  3237.     }
  3238.  
  3239.     if ((y < masterPtr->ditherY) || ((y == masterPtr->ditherY)
  3240.         && (x < masterPtr->ditherX))) {
  3241.     /*
  3242.      * The dithering isn't correct past the start of this block.
  3243.      */
  3244.     masterPtr->ditherX = x;
  3245.     masterPtr->ditherY = y;
  3246.     }
  3247.  
  3248.     /*
  3249.      * If this image block could have different red, green and blue
  3250.      * components, mark it as a color image.
  3251.      */
  3252.  
  3253.     greenOffset = blockPtr->offset[1] - blockPtr->offset[0];
  3254.     blueOffset = blockPtr->offset[2] - blockPtr->offset[0];
  3255.     if ((greenOffset != 0) || (blueOffset != 0)) {
  3256.     masterPtr->flags |= COLOR_IMAGE;
  3257.     }
  3258.  
  3259.     /*
  3260.      * Copy the data into our local 24-bit/pixel array.
  3261.      * If we can do it with a single memcpy, we do.
  3262.      */
  3263.  
  3264.     destLinePtr = masterPtr->pix24 + (y * masterPtr->width + x) * 3;
  3265.     pitch = masterPtr->width * 3;
  3266.  
  3267.     if ((blockPtr->pixelSize == 3) && (greenOffset == 1) && (blueOffset == 2)
  3268.         && (width <= blockPtr->width) && (height <= blockPtr->height)
  3269.         && ((height == 1) || ((x == 0) && (width == masterPtr->width)
  3270.         && (blockPtr->pitch == pitch)))) {
  3271.     memcpy((VOID *) destLinePtr,
  3272.         (VOID *) (blockPtr->pixelPtr + blockPtr->offset[0]),
  3273.         (size_t) (height * width * 3));
  3274.     } else {
  3275.     for (hLeft = height; hLeft > 0;) {
  3276.         srcLinePtr = blockPtr->pixelPtr + blockPtr->offset[0];
  3277.         hCopy = MIN(hLeft, blockPtr->height);
  3278.         hLeft -= hCopy;
  3279.         for (; hCopy > 0; --hCopy) {
  3280.         destPtr = destLinePtr;
  3281.         for (wLeft = width; wLeft > 0;) {
  3282.             wCopy = MIN(wLeft, blockPtr->width);
  3283.             wLeft -= wCopy;
  3284.             srcPtr = srcLinePtr;
  3285.             for (; wCopy > 0; --wCopy) {
  3286.             *destPtr++ = srcPtr[0];
  3287.             *destPtr++ = srcPtr[greenOffset];
  3288.             *destPtr++ = srcPtr[blueOffset];
  3289.             srcPtr += blockPtr->pixelSize;
  3290.             }
  3291.         }
  3292.         srcLinePtr += blockPtr->pitch;
  3293.         destLinePtr += pitch;
  3294.         }
  3295.     }
  3296.     }
  3297.  
  3298.     /*
  3299.      * Add this new block to the region which specifies which data is valid.
  3300.      */
  3301.  
  3302.     rect.x = x;
  3303.     rect.y = y;
  3304.     rect.width = width;
  3305.     rect.height = height;
  3306.     TkUnionRectWithRegion(&rect, masterPtr->validRegion,
  3307.         masterPtr->validRegion);
  3308.  
  3309.     /*
  3310.      * Update each instance.
  3311.      */
  3312.  
  3313.     Dither(masterPtr, x, y, width, height);
  3314.  
  3315.     /*
  3316.      * Tell the core image code that this image has changed.
  3317.      */
  3318.  
  3319.     Tk_ImageChanged(masterPtr->tkMaster, x, y, width, height, masterPtr->width,
  3320.         masterPtr->height);
  3321. }
  3322.  
  3323. /*
  3324.  *----------------------------------------------------------------------
  3325.  *
  3326.  * Tk_PhotoPutZoomedBlock --
  3327.  *
  3328.  *    This procedure is called to put image data into a photo image,
  3329.  *    with possible subsampling and/or zooming of the pixels.
  3330.  *
  3331.  * Results:
  3332.  *    None.
  3333.  *
  3334.  * Side effects:
  3335.  *    The image data is stored.  The image may be expanded.
  3336.  *    The Tk image code is informed that the image has changed.
  3337.  *
  3338.  *----------------------------------------------------------------------
  3339.  */
  3340.  
  3341. void
  3342. Tk_PhotoPutZoomedBlock(handle, blockPtr, x, y, width, height, zoomX, zoomY,
  3343.     subsampleX, subsampleY)
  3344.     Tk_PhotoHandle handle;    /* Opaque handle for the photo image
  3345.                  * to be updated. */
  3346.     register Tk_PhotoImageBlock *blockPtr;
  3347.                 /* Pointer to a structure describing the
  3348.                  * pixel data to be copied into the image. */
  3349.     int x, y;            /* Coordinates of the top-left pixel to
  3350.                  * be updated in the image. */
  3351.     int width, height;        /* Dimensions of the area of the image
  3352.                  * to be updated. */
  3353.     int zoomX, zoomY;        /* Zoom factors for the X and Y axes. */
  3354.     int subsampleX, subsampleY;    /* Subsampling factors for the X and Y axes. */
  3355. {
  3356.     register PhotoMaster *masterPtr;
  3357.     int xEnd, yEnd;
  3358.     int greenOffset, blueOffset;
  3359.     int wLeft, hLeft;
  3360.     int wCopy, hCopy;
  3361.     int blockWid, blockHt;
  3362.     unsigned char *srcPtr, *srcLinePtr, *srcOrigPtr;
  3363.     unsigned char *destPtr, *destLinePtr;
  3364.     int pitch;
  3365.     int xRepeat, yRepeat;
  3366.     int blockXSkip, blockYSkip;
  3367.     XRectangle rect;
  3368.  
  3369.     if ((zoomX == 1) && (zoomY == 1) && (subsampleX == 1)
  3370.         && (subsampleY == 1)) {
  3371.     Tk_PhotoPutBlock(handle, blockPtr, x, y, width, height);
  3372.     return;
  3373.     }
  3374.  
  3375.     masterPtr = (PhotoMaster *) handle;
  3376.  
  3377.     if ((zoomX <= 0) || (zoomY <= 0))
  3378.     return;
  3379.     if ((masterPtr->userWidth != 0) && ((x + width) > masterPtr->userWidth)) {
  3380.     width = masterPtr->userWidth - x;
  3381.     }
  3382.     if ((masterPtr->userHeight != 0)
  3383.         && ((y + height) > masterPtr->userHeight)) {
  3384.     height = masterPtr->userHeight - y;
  3385.     }
  3386.     if ((width <= 0) || (height <= 0))
  3387.     return;
  3388.  
  3389.     xEnd = x + width;
  3390.     yEnd = y + height;
  3391.     if ((xEnd > masterPtr->width) || (yEnd > masterPtr->height)) {
  3392.     ImgPhotoSetSize(masterPtr, MAX(xEnd, masterPtr->width),
  3393.         MAX(yEnd, masterPtr->height));
  3394.     }
  3395.  
  3396.     if ((y < masterPtr->ditherY) || ((y == masterPtr->ditherY)
  3397.        && (x < masterPtr->ditherX))) {
  3398.     /*
  3399.      * The dithering isn't correct past the start of this block.
  3400.      */
  3401.  
  3402.     masterPtr->ditherX = x;
  3403.     masterPtr->ditherY = y;
  3404.     }
  3405.  
  3406.     /*
  3407.      * If this image block could have different red, green and blue
  3408.      * components, mark it as a color image.
  3409.      */
  3410.  
  3411.     greenOffset = blockPtr->offset[1] - blockPtr->offset[0];
  3412.     blueOffset = blockPtr->offset[2] - blockPtr->offset[0];
  3413.     if ((greenOffset != 0) || (blueOffset != 0)) {
  3414.     masterPtr->flags |= COLOR_IMAGE;
  3415.     }
  3416.  
  3417.     /*
  3418.      * Work out what area the pixel data in the block expands to after
  3419.      * subsampling and zooming.
  3420.      */
  3421.  
  3422.     blockXSkip = subsampleX * blockPtr->pixelSize;
  3423.     blockYSkip = subsampleY * blockPtr->pitch;
  3424.     if (subsampleX > 0)
  3425.     blockWid = ((blockPtr->width + subsampleX - 1) / subsampleX) * zoomX;
  3426.     else if (subsampleX == 0)
  3427.     blockWid = width;
  3428.     else
  3429.     blockWid = ((blockPtr->width - subsampleX - 1) / -subsampleX) * zoomX;
  3430.     if (subsampleY > 0)
  3431.     blockHt = ((blockPtr->height + subsampleY - 1) / subsampleY) * zoomY;
  3432.     else if (subsampleY == 0)
  3433.     blockHt = height;
  3434.     else
  3435.     blockHt = ((blockPtr->height - subsampleY - 1) / -subsampleY) * zoomY;
  3436.  
  3437.     /*
  3438.      * Copy the data into our local 24-bit/pixel array.
  3439.      */
  3440.  
  3441.     destLinePtr = masterPtr->pix24 + (y * masterPtr->width + x) * 3;
  3442.     srcOrigPtr = blockPtr->pixelPtr + blockPtr->offset[0];
  3443.     if (subsampleX < 0) {
  3444.     srcOrigPtr += (blockPtr->width - 1) * blockPtr->pixelSize;
  3445.     }
  3446.     if (subsampleY < 0) {
  3447.     srcOrigPtr += (blockPtr->height - 1) * blockPtr->pitch;
  3448.     }
  3449.  
  3450.     pitch = masterPtr->width * 3;
  3451.     for (hLeft = height; hLeft > 0; ) {
  3452.     hCopy = MIN(hLeft, blockHt);
  3453.     hLeft -= hCopy;
  3454.     yRepeat = zoomY;
  3455.     srcLinePtr = srcOrigPtr;
  3456.     for (; hCopy > 0; --hCopy) {
  3457.         destPtr = destLinePtr;
  3458.         for (wLeft = width; wLeft > 0;) {
  3459.         wCopy = MIN(wLeft, blockWid);
  3460.         wLeft -= wCopy;
  3461.         srcPtr = srcLinePtr;
  3462.         for (; wCopy > 0; wCopy -= zoomX) {
  3463.             for (xRepeat = MIN(wCopy, zoomX); xRepeat > 0; xRepeat--) {
  3464.             *destPtr++ = srcPtr[0];
  3465.             *destPtr++ = srcPtr[greenOffset];
  3466.             *destPtr++ = srcPtr[blueOffset];
  3467.             }
  3468.             srcPtr += blockXSkip;
  3469.         }
  3470.         }
  3471.         destLinePtr += pitch;
  3472.         yRepeat--;
  3473.         if (yRepeat <= 0) {
  3474.         srcLinePtr += blockYSkip;
  3475.         yRepeat = zoomY;
  3476.         }
  3477.     }
  3478.     }
  3479.  
  3480.     /*
  3481.      * Add this new block to the region that specifies which data is valid.
  3482.      */
  3483.  
  3484.     rect.x = x;
  3485.     rect.y = y;
  3486.     rect.width = width;
  3487.     rect.height = height;
  3488.     TkUnionRectWithRegion(&rect, masterPtr->validRegion,
  3489.         masterPtr->validRegion);
  3490.  
  3491.     /*
  3492.      * Update each instance.
  3493.      */
  3494.  
  3495.     Dither(masterPtr, x, y, width, height);
  3496.  
  3497.     /*
  3498.      * Tell the core image code that this image has changed.
  3499.      */
  3500.  
  3501.     Tk_ImageChanged(masterPtr->tkMaster, x, y, width, height, masterPtr->width,
  3502.         masterPtr->height);
  3503. }
  3504.  
  3505. /*
  3506.  *----------------------------------------------------------------------
  3507.  *
  3508.  * Dither --
  3509.  *
  3510.  *    This procedure is called to update an area of each instance's
  3511.  *    pixmap by dithering the corresponding area of the image master.
  3512.  *
  3513.  * Results:
  3514.  *    None.
  3515.  *
  3516.  * Side effects:
  3517.  *    The pixmap of each instance of this image gets updated.
  3518.  *    The fields in *masterPtr indicating which area of the image
  3519.  *    is correctly dithered get updated.
  3520.  *
  3521.  *----------------------------------------------------------------------
  3522.  */
  3523.  
  3524. static void
  3525. Dither(masterPtr, x, y, width, height)
  3526.     PhotoMaster *masterPtr;    /* Image master whose instances are
  3527.                  * to be updated. */
  3528.     int x, y;            /* Coordinates of the top-left pixel
  3529.                  * in the area to be dithered. */
  3530.     int width, height;        /* Dimensions of the area to be dithered. */
  3531. {
  3532.     PhotoInstance *instancePtr;
  3533.  
  3534.     if ((width <= 0) || (height <= 0)) {
  3535.     return;
  3536.     }
  3537.  
  3538.     for (instancePtr = masterPtr->instancePtr; instancePtr != NULL;
  3539.         instancePtr = instancePtr->nextPtr) {
  3540.     DitherInstance(instancePtr, x, y, width, height);
  3541.     }
  3542.  
  3543.     /*
  3544.      * Work out whether this block will be correctly dithered
  3545.      * and whether it will extend the correctly dithered region.
  3546.      */
  3547.  
  3548.     if (((y < masterPtr->ditherY)
  3549.         || ((y == masterPtr->ditherY) && (x <= masterPtr->ditherX)))
  3550.         && ((y + height) > (masterPtr->ditherY))) {
  3551.  
  3552.     /*
  3553.      * This block starts inside (or immediately after) the correctly
  3554.      * dithered region, so the first scan line at least will be right.
  3555.      * Furthermore this block extends into scanline masterPtr->ditherY.
  3556.      */
  3557.  
  3558.     if ((x == 0) && (width == masterPtr->width)) {
  3559.         /*
  3560.          * We are doing the full width, therefore the dithering
  3561.          * will be correct to the end.
  3562.          */
  3563.  
  3564.         masterPtr->ditherX = 0;
  3565.         masterPtr->ditherY = y + height;
  3566.     } else {
  3567.         /*
  3568.          * We are doing partial scanlines, therefore the
  3569.          * correctly-dithered region will be extended by
  3570.          * at most one scan line.
  3571.          */
  3572.  
  3573.         if (x <= masterPtr->ditherX) {
  3574.         masterPtr->ditherX = x + width;
  3575.         if (masterPtr->ditherX >= masterPtr->width) {
  3576.             masterPtr->ditherX = 0;
  3577.             masterPtr->ditherY++;
  3578.         }
  3579.         }
  3580.     }
  3581.     }
  3582.  
  3583. }    
  3584.  
  3585. /*
  3586.  *----------------------------------------------------------------------
  3587.  *
  3588.  * DitherInstance --
  3589.  *
  3590.  *    This procedure is called to update an area of an instance's
  3591.  *    pixmap by dithering the corresponding area of the master.
  3592.  *
  3593.  * Results:
  3594.  *    None.
  3595.  *
  3596.  * Side effects:
  3597.  *    The instance's pixmap gets updated.
  3598.  *
  3599.  *----------------------------------------------------------------------
  3600.  */
  3601.  
  3602. static void
  3603. DitherInstance(instancePtr, xStart, yStart, width, height)
  3604.     PhotoInstance *instancePtr;    /* The instance to be updated. */
  3605.     int xStart, yStart;        /* Coordinates of the top-left pixel in the
  3606.                  * block to be dithered. */
  3607.     int width, height;        /* Dimensions of the block to be dithered. */
  3608. {
  3609.     PhotoMaster *masterPtr;
  3610.     ColorTable *colorPtr;
  3611.     XImage *imagePtr;
  3612.     int nLines, bigEndian;
  3613.     int i, c, x, y;
  3614.     int xEnd, yEnd;
  3615.     int bitsPerPixel, bytesPerLine, lineLength;
  3616.     unsigned char *srcLinePtr, *srcPtr;
  3617.     schar *errLinePtr, *errPtr;
  3618.     unsigned char *destBytePtr, *dstLinePtr;
  3619.     pixel *destLongPtr;
  3620.     pixel firstBit, word, mask;
  3621.     int col[3];
  3622.     int doDithering = 1;
  3623.  
  3624.     colorPtr = instancePtr->colorTablePtr;
  3625.     masterPtr = instancePtr->masterPtr;
  3626.  
  3627.     /*
  3628.      * Turn dithering off in certain cases where it is not
  3629.      * needed (TrueColor, DirectColor with many colors).
  3630.      */
  3631.  
  3632.     if ((colorPtr->visualInfo.class == DirectColor)
  3633.         || (colorPtr->visualInfo.class == TrueColor)) {
  3634.     int nRed, nGreen, nBlue, result;
  3635.  
  3636.     result = sscanf(colorPtr->id.palette, "%d/%d/%d", &nRed,
  3637.         &nGreen, &nBlue);
  3638.     if ((nRed >= 256)
  3639.         && ((result == 1) || ((nGreen >= 256) && (nBlue >= 256)))) {
  3640.         doDithering = 0;
  3641.     }
  3642.     }
  3643.  
  3644.     /*
  3645.      * First work out how many lines to do at a time,
  3646.      * then how many bytes we'll need for pixel storage,
  3647.      * and allocate it.
  3648.      */
  3649.  
  3650.     nLines = (MAX_PIXELS + width - 1) / width;
  3651.     if (nLines < 1) {
  3652.     nLines = 1;
  3653.     }
  3654.     if (nLines > height ) {
  3655.     nLines = height;
  3656.     }
  3657.  
  3658.     imagePtr = instancePtr->imagePtr;
  3659.     if (imagePtr == NULL) {
  3660.     return;            /* we must be really tight on memory */
  3661.     }
  3662.     bitsPerPixel = imagePtr->bits_per_pixel;
  3663.     bytesPerLine = ((bitsPerPixel * width + 31) >> 3) & ~3;
  3664.     imagePtr->width = width;
  3665.     imagePtr->height = nLines;
  3666.     imagePtr->bytes_per_line = bytesPerLine;
  3667.     imagePtr->data = (char *) ckalloc((unsigned) (imagePtr->bytes_per_line * nLines));
  3668.     bigEndian = imagePtr->bitmap_bit_order == MSBFirst;
  3669.     firstBit = bigEndian? (1 << (imagePtr->bitmap_unit - 1)): 1;
  3670.  
  3671.     lineLength = masterPtr->width * 3;
  3672.     srcLinePtr = masterPtr->pix24 + yStart * lineLength + xStart * 3;
  3673.     errLinePtr = instancePtr->error + yStart * lineLength + xStart * 3;
  3674.     xEnd = xStart + width;
  3675.  
  3676.     /*
  3677.      * Loop over the image, doing at most nLines lines before
  3678.      * updating the screen image.
  3679.      */
  3680.  
  3681.     for (; height > 0; height -= nLines) {
  3682.     if (nLines > height) {
  3683.         nLines = height;
  3684.     }
  3685.     dstLinePtr = (unsigned char *) imagePtr->data;
  3686.     yEnd = yStart + nLines;
  3687.     for (y = yStart; y < yEnd; ++y) {
  3688.         srcPtr = srcLinePtr;
  3689.         errPtr = errLinePtr;
  3690.         destBytePtr = dstLinePtr;
  3691.         destLongPtr = (pixel *) dstLinePtr;
  3692.         if (colorPtr->flags & COLOR_WINDOW) {
  3693.         /*
  3694.          * Color window.  We dither the three components
  3695.          * independently, using Floyd-Steinberg dithering,
  3696.          * which propagates errors from the quantization of
  3697.          * pixels to the pixels below and to the right.
  3698.          */
  3699.  
  3700.         for (x = xStart; x < xEnd; ++x) {
  3701.             if (doDithering) {
  3702.             for (i = 0; i < 3; ++i) {
  3703.                 /*
  3704.                  * Compute the error propagated into this pixel
  3705.                  * for this component.
  3706.                  * If e[x,y] is the array of quantization error
  3707.                  * values, we compute
  3708.                  *     7/16 * e[x-1,y] + 1/16 * e[x-1,y-1]
  3709.                  *   + 5/16 * e[x,y-1] + 3/16 * e[x+1,y-1]
  3710.                  * and round it to an integer.
  3711.                  *
  3712.                  * The expression ((c + 2056) >> 4) - 128
  3713.                  * computes round(c / 16), and works correctly on
  3714.                  * machines without a sign-extending right shift.
  3715.                  */
  3716.                 
  3717.                 c = (x > 0) ? errPtr[-3] * 7: 0;
  3718.                 if (y > 0) {
  3719.                 if (x > 0) {
  3720.                     c += errPtr[-lineLength-3];
  3721.                 }
  3722.                 c += errPtr[-lineLength] * 5;
  3723.                 if ((x + 1) < masterPtr->width) {
  3724.                     c += errPtr[-lineLength+3] * 3;
  3725.                 }
  3726.                 }
  3727.                 
  3728.                 /*
  3729.                  * Add the propagated error to the value of this
  3730.                  * component, quantize it, and store the
  3731.                  * quantization error.
  3732.                  */
  3733.                 
  3734.                 c = ((c + 2056) >> 4) - 128 + *srcPtr++;
  3735.                 if (c < 0) {
  3736.                 c = 0;
  3737.                 } else if (c > 255) {
  3738.                 c = 255;
  3739.                 }
  3740.                 col[i] = colorPtr->colorQuant[i][c];
  3741.                 *errPtr++ = c - col[i];
  3742.             }
  3743.             } else {
  3744.             /* 
  3745.              * Output is virtually continuous in this case,
  3746.              * so don't bother dithering.
  3747.              */
  3748.  
  3749.             col[0] = *srcPtr++;
  3750.             col[1] = *srcPtr++;
  3751.             col[2] = *srcPtr++;
  3752.             }
  3753.  
  3754.             /*
  3755.              * Translate the quantized component values into
  3756.              * an X pixel value, and store it in the image.
  3757.              */
  3758.  
  3759.             i = colorPtr->redValues[col[0]]
  3760.                 + colorPtr->greenValues[col[1]]
  3761.                 + colorPtr->blueValues[col[2]];
  3762.             if (colorPtr->flags & MAP_COLORS) {
  3763.             i = colorPtr->pixelMap[i];
  3764.             }
  3765.             switch (bitsPerPixel) {
  3766.             case NBBY:
  3767.                 *destBytePtr++ = i;
  3768.                 break;
  3769.             case NBBY * sizeof(pixel):
  3770.                 *destLongPtr++ = i;
  3771.                 break;
  3772.             default:
  3773.                 XPutPixel(imagePtr, x - xStart, y - yStart,
  3774.                     (unsigned) i);
  3775.             }
  3776.         }
  3777.  
  3778.         } else if (bitsPerPixel > 1) {
  3779.         /*
  3780.          * Multibit monochrome window.  The operation here is similar
  3781.          * to the color window case above, except that there is only
  3782.          * one component.  If the master image is in color, use the
  3783.          * luminance computed as
  3784.          *    0.344 * red + 0.5 * green + 0.156 * blue.
  3785.          */
  3786.  
  3787.         for (x = xStart; x < xEnd; ++x) {
  3788.             c = (x > 0) ? errPtr[-1] * 7: 0;
  3789.             if (y > 0) {
  3790.             if (x > 0)  {
  3791.                 c += errPtr[-lineLength-1];
  3792.             }
  3793.             c += errPtr[-lineLength] * 5;
  3794.             if (x + 1 < masterPtr->width) {
  3795.                 c += errPtr[-lineLength+1] * 3;
  3796.             }
  3797.             }
  3798.             c = ((c + 2056) >> 4) - 128;
  3799.  
  3800.             if ((masterPtr->flags & COLOR_IMAGE) == 0) {
  3801.             c += srcPtr[0];
  3802.             } else {
  3803.             c += (unsigned)(srcPtr[0] * 11 + srcPtr[1] * 16
  3804.                     + srcPtr[2] * 5 + 16) >> 5;
  3805.             }
  3806.             srcPtr += 3;
  3807.  
  3808.             if (c < 0) {
  3809.             c = 0;
  3810.             } else if (c > 255) {
  3811.             c = 255;
  3812.             }
  3813.             i = colorPtr->colorQuant[0][c];
  3814.             *errPtr++ = c - i;
  3815.             i = colorPtr->redValues[i];
  3816.             switch (bitsPerPixel) {
  3817.             case NBBY:
  3818.                 *destBytePtr++ = i;
  3819.                 break;
  3820.             case NBBY * sizeof(pixel):
  3821.                 *destLongPtr++ = i;
  3822.                 break;
  3823.             default:
  3824.                 XPutPixel(imagePtr, x - xStart, y - yStart,
  3825.                     (unsigned) i);
  3826.             }
  3827.         }
  3828.         } else {
  3829.         /*
  3830.          * 1-bit monochrome window.  This is similar to the
  3831.          * multibit monochrome case above, except that the
  3832.          * quantization is simpler (we only have black = 0
  3833.          * and white = 255), and we produce an XY-Bitmap.
  3834.          */
  3835.  
  3836.         word = 0;
  3837.         mask = firstBit;
  3838.         for (x = xStart; x < xEnd; ++x) {
  3839.             /*
  3840.              * If we have accumulated a whole word, store it
  3841.              * in the image and start a new word.
  3842.              */
  3843.  
  3844.             if (mask == 0) {
  3845.             *destLongPtr++ = word;
  3846.             mask = firstBit;
  3847.             word = 0;
  3848.             }
  3849.  
  3850.             c = (x > 0) ? errPtr[-1] * 7: 0;
  3851.             if (y > 0) {
  3852.             if (x > 0) {
  3853.                 c += errPtr[-lineLength-1];
  3854.             }
  3855.             c += errPtr[-lineLength] * 5;
  3856.             if (x + 1 < masterPtr->width) {
  3857.                 c += errPtr[-lineLength+1] * 3;
  3858.             }
  3859.             }
  3860.             c = ((c + 2056) >> 4) - 128;
  3861.  
  3862.             if ((masterPtr->flags & COLOR_IMAGE) == 0) {
  3863.             c += srcPtr[0];
  3864.             } else {
  3865.             c += (unsigned)(srcPtr[0] * 11 + srcPtr[1] * 16
  3866.                     + srcPtr[2] * 5 + 16) >> 5;
  3867.             }
  3868.             srcPtr += 3;
  3869.  
  3870.             if (c < 0) {
  3871.             c = 0;
  3872.             } else if (c > 255) {
  3873.             c = 255;
  3874.             }
  3875.             if (c >= 128) {
  3876.             word |= mask;
  3877.             *errPtr++ = c - 255;
  3878.             } else {
  3879.             *errPtr++ = c;
  3880.             }
  3881.             mask = bigEndian? (mask >> 1): (mask << 1);
  3882.         }
  3883.         *destLongPtr = word;
  3884.         }
  3885.         srcLinePtr += lineLength;
  3886.         errLinePtr += lineLength;
  3887.         dstLinePtr += bytesPerLine;
  3888.     }
  3889.  
  3890.     /*
  3891.      * Update the pixmap for this instance with the block of
  3892.      * pixels that we have just computed.
  3893.      */
  3894.  
  3895.     TkPutImage(colorPtr->pixelMap, colorPtr->numColors,
  3896.         instancePtr->display, instancePtr->pixels,
  3897.         instancePtr->gc, imagePtr, 0, 0, xStart, yStart,
  3898.         (unsigned) width, (unsigned) nLines);
  3899.     yStart = yEnd;
  3900.     
  3901.     }
  3902.  
  3903.     ckfree(imagePtr->data);
  3904.     imagePtr->data = NULL;
  3905. }
  3906.  
  3907. /*
  3908.  *----------------------------------------------------------------------
  3909.  *
  3910.  * Tk_PhotoBlank --
  3911.  *
  3912.  *    This procedure is called to clear an entire photo image.
  3913.  *
  3914.  * Results:
  3915.  *    None.
  3916.  *
  3917.  * Side effects:
  3918.  *    The valid region for the image is set to the null region.
  3919.  *    The generic image code is notified that the image has changed.
  3920.  *
  3921.  *----------------------------------------------------------------------
  3922.  */
  3923.  
  3924. void
  3925. Tk_PhotoBlank(handle)
  3926.     Tk_PhotoHandle handle;    /* Handle for the image to be blanked. */
  3927. {
  3928.     PhotoMaster *masterPtr;
  3929.     PhotoInstance *instancePtr;
  3930.  
  3931.     masterPtr = (PhotoMaster *) handle;
  3932.     masterPtr->ditherX = masterPtr->ditherY = 0;
  3933.     masterPtr->flags = 0;
  3934.  
  3935.     /*
  3936.      * The image has valid data nowhere.
  3937.      */
  3938.  
  3939.     if (masterPtr->validRegion != NULL) {
  3940.     TkDestroyRegion(masterPtr->validRegion);
  3941.     }
  3942.     masterPtr->validRegion = TkCreateRegion();
  3943.  
  3944.     /*
  3945.      * Clear out the 24-bit pixel storage array.
  3946.      * Clear out the dithering error arrays for each instance.
  3947.      */
  3948.  
  3949.     memset((VOID *) masterPtr->pix24, 0,
  3950.         (size_t) (masterPtr->width * masterPtr->height));
  3951.     for (instancePtr = masterPtr->instancePtr; instancePtr != NULL;
  3952.         instancePtr = instancePtr->nextPtr) {
  3953.     memset((VOID *) instancePtr->error, 0,
  3954.         (size_t) (masterPtr->width * masterPtr->height
  3955.             * sizeof(schar)));
  3956.     }
  3957.  
  3958.     /*
  3959.      * Tell the core image code that this image has changed.
  3960.      */
  3961.  
  3962.     Tk_ImageChanged(masterPtr->tkMaster, 0, 0, masterPtr->width,
  3963.         masterPtr->height, masterPtr->width, masterPtr->height);
  3964. }
  3965.  
  3966. /*
  3967.  *----------------------------------------------------------------------
  3968.  *
  3969.  * Tk_PhotoExpand --
  3970.  *
  3971.  *    This procedure is called to request that a photo image be
  3972.  *    expanded if necessary to be at least `width' pixels wide and
  3973.  *    `height' pixels high.  If the user has declared a definite
  3974.  *    image size (using the -width and -height configuration
  3975.  *    options) then this call has no effect.
  3976.  *
  3977.  * Results:
  3978.  *    None.
  3979.  *
  3980.  * Side effects:
  3981.  *    The size of the photo image may change; if so the generic
  3982.  *    image code is informed.
  3983.  *
  3984.  *----------------------------------------------------------------------
  3985.  */
  3986.  
  3987. void
  3988. Tk_PhotoExpand(handle, width, height)
  3989.     Tk_PhotoHandle handle;    /* Handle for the image to be expanded. */
  3990.     int width, height;        /* Desired minimum dimensions of the image. */
  3991. {
  3992.     PhotoMaster *masterPtr;
  3993.  
  3994.     masterPtr = (PhotoMaster *) handle;
  3995.  
  3996.     if (width <= masterPtr->width) {
  3997.     width = masterPtr->width;
  3998.     }
  3999.     if (height <= masterPtr->height) {
  4000.     height = masterPtr->height;
  4001.     }
  4002.     if ((width != masterPtr->width) || (height != masterPtr->height)) {
  4003.     ImgPhotoSetSize(masterPtr, MAX(width, masterPtr->width),
  4004.         MAX(height, masterPtr->height));
  4005.     Tk_ImageChanged(masterPtr->tkMaster, 0, 0, 0, 0, masterPtr->width,
  4006.         masterPtr->height);
  4007.     }
  4008. }
  4009.  
  4010. /*
  4011.  *----------------------------------------------------------------------
  4012.  *
  4013.  * Tk_PhotoGetSize --
  4014.  *
  4015.  *    This procedure is called to obtain the current size of a photo
  4016.  *    image.
  4017.  *
  4018.  * Results:
  4019.  *    The image's width and height are returned in *widthp
  4020.  *    and *heightp.
  4021.  *
  4022.  * Side effects:
  4023.  *    None.
  4024.  *
  4025.  *----------------------------------------------------------------------
  4026.  */
  4027.  
  4028. void
  4029. Tk_PhotoGetSize(handle, widthPtr, heightPtr)
  4030.     Tk_PhotoHandle handle;    /* Handle for the image whose dimensions
  4031.                  * are requested. */
  4032.     int *widthPtr, *heightPtr;    /* The dimensions of the image are returned
  4033.                  * here. */
  4034. {
  4035.     PhotoMaster *masterPtr;
  4036.  
  4037.     masterPtr = (PhotoMaster *) handle;
  4038.     *widthPtr = masterPtr->width;
  4039.     *heightPtr = masterPtr->height;
  4040. }
  4041.  
  4042. /*
  4043.  *----------------------------------------------------------------------
  4044.  *
  4045.  * Tk_PhotoSetSize --
  4046.  *
  4047.  *    This procedure is called to set size of a photo image.
  4048.  *    This call is equivalent to using the -width and -height
  4049.  *    configuration options.
  4050.  *
  4051.  * Results:
  4052.  *    None.
  4053.  *
  4054.  * Side effects:
  4055.  *    The size of the image may change; if so the generic
  4056.  *    image code is informed.
  4057.  *
  4058.  *----------------------------------------------------------------------
  4059.  */
  4060.  
  4061. void
  4062. Tk_PhotoSetSize(handle, width, height)
  4063.     Tk_PhotoHandle handle;    /* Handle for the image whose size is to
  4064.                  * be set. */
  4065.     int width, height;        /* New dimensions for the image. */
  4066. {
  4067.     PhotoMaster *masterPtr;
  4068.  
  4069.     masterPtr = (PhotoMaster *) handle;
  4070.  
  4071.     masterPtr->userWidth = width;
  4072.     masterPtr->userHeight = height;
  4073.     ImgPhotoSetSize(masterPtr, ((width > 0) ? width: masterPtr->width),
  4074.         ((height > 0) ? height: masterPtr->height));
  4075.     Tk_ImageChanged(masterPtr->tkMaster, 0, 0, 0, 0,
  4076.         masterPtr->width, masterPtr->height);
  4077. }
  4078.  
  4079. /*
  4080.  *----------------------------------------------------------------------
  4081.  *
  4082.  * Tk_PhotoGetImage --
  4083.  *
  4084.  *    This procedure is called to obtain image data from a photo
  4085.  *    image.  This procedure fills in the Tk_PhotoImageBlock structure
  4086.  *    pointed to by `blockPtr' with details of the address and
  4087.  *    layout of the image data in memory.
  4088.  *
  4089.  * Results:
  4090.  *    TRUE (1) indicating that image data is available,
  4091.  *    for backwards compatibility with the old photo widget.
  4092.  *
  4093.  * Side effects:
  4094.  *    None.
  4095.  *
  4096.  *----------------------------------------------------------------------
  4097.  */
  4098.  
  4099. int
  4100. Tk_PhotoGetImage(handle, blockPtr)
  4101.     Tk_PhotoHandle handle;    /* Handle for the photo image from which
  4102.                  * image data is desired. */
  4103.     Tk_PhotoImageBlock *blockPtr;
  4104.                 /* Information about the address and layout
  4105.                  * of the image data is returned here. */
  4106. {
  4107.     PhotoMaster *masterPtr;
  4108.  
  4109.     masterPtr = (PhotoMaster *) handle;
  4110.     blockPtr->pixelPtr = masterPtr->pix24;
  4111.     blockPtr->width = masterPtr->width;
  4112.     blockPtr->height = masterPtr->height;
  4113.     blockPtr->pitch = masterPtr->width * 3;
  4114.     blockPtr->pixelSize = 3;
  4115.     blockPtr->offset[0] = 0;
  4116.     blockPtr->offset[1] = 1;
  4117.     blockPtr->offset[2] = 2;
  4118.     return 1;
  4119. }
  4120.