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