home *** CD-ROM | disk | FTP | other *** search
/ PC Pro 2002 April / pcpro0402.iso / essentials / graphics / Gimp / gimp-src-20001226.exe / src / gimp / plug-ins / common / psd.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-08-24  |  68.7 KB  |  2,822 lines

  1. /*
  2.  * PSD Plugin version 2.0.6
  3.  * This GIMP plug-in is designed to load Adobe Photoshop(tm) files (.PSD)
  4.  *
  5.  * Adam D. Moss <adam@gimp.org> <adam@foxbox.org>
  6.  *
  7.  *     If this plug-in fails to load a file which you think it should,
  8.  *     please tell me what seemed to go wrong, and anything you know
  9.  *     about the image you tried to load.  Please don't send big PSD
  10.  *     files to me without asking first.
  11.  *
  12.  *          Copyright (C) 1997-2000 Adam D. Moss
  13.  *          Copyright (C) 1996      Torsten Martinsen
  14.  *
  15.  * This program is free software; you can redistribute it and/or modify
  16.  * it under the terms of the GNU General Public License as published by
  17.  * the Free Software Foundation; either version 2 of the License, or
  18.  * (at your option) any later version.
  19.  *
  20.  * This program is distributed in the hope that it will be useful,
  21.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  23.  * GNU General Public License for more details.
  24.  *
  25.  * You should have received a copy of the GNU General Public License
  26.  * along with this program; if not, write to the Free Software
  27.  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  28.  */
  29.  
  30. /*
  31.  * Adobe and Adobe Photoshop are trademarks of Adobe Systems
  32.  * Incorporated that may be registered in certain jurisdictions.
  33.  */
  34.  
  35. /*
  36.  * Revision history:
  37.  *
  38.  *  2000.08.23 / v2.0.6 / Adam D. Moss
  39.  *       Eliminate more debugging output (don't people have more
  40.  *       substantial problems to report?  I'm poised at my keyboard).
  41.  *
  42.  *  1999.11.14 / v2.0.5 / Adam D. Moss
  43.  *       Applied patch by Andy Hefner to load 1-bit images.
  44.  *
  45.  *  1999.08.13 / v2.0.4 / Adam D. Moss
  46.  *       Allowed NULL layer names again, whee.  (Also fixed the time machine.)
  47.  *
  48.  *  1999.08.20 / v2.0.3 / Adam D. Moss
  49.  *       Ensure that NULL name does not get passed to gimp_layer_new(),
  50.  *       or it will fail to create the layer and cause problems down
  51.  *       the line (only since April 1999).
  52.  *
  53.  *  1999.01.18 / v2.0.2 / Adam D. Moss
  54.  *       Better guess at how PSD files store Guide position precision.
  55.  *
  56.  *  1999.01.10 / v2.0.1 / Adam D. Moss
  57.  *       Greatly reduced memory requirements for layered image loading -
  58.  *       we now do just-in-time channel unpacking.  Some little
  59.  *       cleanups too.
  60.  *
  61.  *  1998.09.04 / v2.0.0 / Adam D. Moss
  62.  *       Now recognises and loads the new Guides extensions written
  63.  *       by Photoshop 4 and 5.
  64.  *
  65.  *  1998.07.31 / v1.9.9.9f / Adam D. Moss
  66.  *       Use GIMP_OVERLAY_MODE if available.
  67.  *
  68.  *  1998.07.31 / v1.9.9.9e / Adam D. Moss
  69.  *       Worked around some buggy PSD savers (suspect PS4 on Mac) - ugh.
  70.  *       Fixed a bug when loading layer masks of certain dimensions.
  71.  *
  72.  *  1998.05.04 / v1.9.9.9b / Adam D. Moss
  73.  *       Changed the Pascal-style string-reading stuff.  That fixed
  74.  *       some file-padding problems.  Made all debugging output
  75.  *       compile-time optional (please leave it enabled for now).
  76.  *       Reduced memory requirements; still much room for improvement.
  77.  *
  78.  *  1998.04.28 / v1.9.9.9 / Adam D. Moss
  79.  *       Fixed the correct channel interlacing of 'raw' flat images.
  80.  *       Thanks to Christian Kirsch and Jay Cox for spotting this.
  81.  *       Changed some of the I/O routines.
  82.  *
  83.  *  1998.04.26 / v1.9.9.8 / Adam D. Moss
  84.  *       Implemented Aux-channels for layered files.  Got rid
  85.  *       of <endian.h> nonsense.  Improved Layer Mask padding.
  86.  *       Enforced num_layers/num_channels limit checks.
  87.  *
  88.  *  1998.04.23 / v1.9.9.5 / Adam D. Moss
  89.  *       Got Layer Masks working, got Aux-channels working
  90.  *       for unlayered files, fixed 'raw' channel loading, fixed
  91.  *       some other mini-bugs, slightly better progress meters.
  92.  *       Thanks to everyone who is helping with the testing!
  93.  *
  94.  *  1998.04.21 / v1.9.9.1 / Adam D. Moss
  95.  *       A little cleanup.  Implemented Layer Masks but disabled
  96.  *       them again - PS masks can be a different size to their
  97.  *       owning layer, unlike those in GIMP.
  98.  *
  99.  *  1998.04.19 / v1.9.9.0 / Adam D. Moss
  100.  *       Much happier now.
  101.  *
  102.  *  1997.03.13 / v1.9.0 / Adam D. Moss
  103.  *       Layers, channels and masks, oh my.
  104.  *       + Bugfixes & rearchitecturing.
  105.  *
  106.  *  1997.01.30 / v1.0.12 / Torsten Martinsen
  107.  *       Flat PSD image loading.
  108.  */
  109.  
  110. /*
  111.  * TODO:
  112.  *
  113.  *      Crush 16bpp channels *
  114.  *    CMYK -> RGB *
  115.  *      * I don't think these should be done lossily -- wait for
  116.  *        GIMP to be able to support them natively.
  117.  *
  118.  *      Read in the paths.
  119.  *
  120.  *      File saving (someone has an alpha plugin for this)
  121.  */
  122.  
  123. /*
  124.  * BUGS:
  125.  *
  126.  *      Sometimes creates a superfluous aux channel?  Harmless.
  127.  */
  128.  
  129.  
  130.  
  131. /* *** USER DEFINES *** */
  132.  
  133. /* set to TRUE if you want debugging, FALSE otherwise */
  134. #define PSD_DEBUG FALSE
  135.  
  136. /* the max number of layers that this plugin should try to load */
  137. #define MAX_LAYERS 100
  138.  
  139. /* the max number of channels that this plugin should let a layer have */
  140. #define MAX_CHANNELS 30
  141.  
  142. /* the max number of guides that this plugin should let an image have */
  143. #define MAX_GUIDES 200
  144.  
  145. /* *** END OF USER DEFINES *** */
  146.  
  147.  
  148.  
  149. #define IFDBG if (PSD_DEBUG)
  150.  
  151. #include "config.h"
  152.  
  153. #include <stdio.h>
  154. #include <stdlib.h>
  155. #ifdef HAVE_UNISTD_H
  156. #include <unistd.h>
  157. #endif
  158. #include <string.h>
  159.  
  160. #include <glib.h>
  161.  
  162. #include <libgimp/gimp.h>
  163.  
  164. #include "libgimp/stdplugins-intl.h"
  165.  
  166.  
  167. /* Local types etc
  168.  */
  169. typedef enum
  170. {
  171.   PSD_UNKNOWN_IMAGE,
  172.   PSD_RGB_IMAGE,
  173.   PSD_RGBA_IMAGE,
  174.   PSD_GRAY_IMAGE,
  175.   PSD_GRAYA_IMAGE,
  176.   PSD_INDEXED_IMAGE,
  177.   PSD_INDEXEDA_IMAGE,
  178.   PSD_BITMAP_IMAGE
  179. } psd_imagetype;
  180.  
  181.  
  182. typedef struct PsdChannel
  183. {
  184.   gchar *name;
  185.   guchar *data;
  186.   gint type;
  187.  
  188.   guint32 compressedsize;
  189.  
  190.   fpos_t fpos; /* Remember where the data is in the file, so we can
  191.           come back to it! */
  192.  
  193.  /* We can't just assume that the channel's width and height are the
  194.   * same as those of the layer that owns the channel, since this
  195.   * channel may be a layer mask, which Photoshop allows to have a
  196.   * different size from the layer which it applies to.
  197.   */
  198.   guint32 width;
  199.   guint32 height;
  200.   
  201. } PSDchannel;
  202.  
  203.  
  204. typedef struct PsdGuide
  205. {
  206.   gboolean horizontal; /* else vertical */
  207.   gint position;
  208. } PSDguide;
  209.  
  210.  
  211. typedef struct PsdLayer
  212. {
  213.   gint num_channels;
  214.   PSDchannel channel[MAX_CHANNELS];
  215.   
  216.   gint32 x;
  217.   gint32 y;
  218.   guint32 width;
  219.   guint32 height;
  220.   
  221.   gchar blendkey[4];
  222.   guchar opacity;
  223.   gchar clipping;
  224.  
  225.   gboolean protecttrans;
  226.   gboolean visible;
  227.  
  228.   gchar* name;
  229.  
  230.   gint32 lm_x;
  231.   gint32 lm_y;
  232.   gint32 lm_width;
  233.   gint32 lm_height;
  234.  
  235. } PSDlayer;
  236.  
  237.  
  238. typedef gint32 Fixed;
  239.  
  240. typedef struct
  241. {
  242.   Fixed hRes;
  243.   gint16 hRes_unit;
  244.   gint16 widthUnit;
  245.  
  246.   Fixed vRes;
  247.   gint16 vRes_unit;
  248.   gint16 heightUnit;
  249.  
  250. /* Res_unit : 
  251.     1 == Pixels per inch
  252.         2 == Pixels per cm
  253. */
  254.  
  255. } PSDresolution;
  256.  
  257. typedef struct PsdImage
  258. {
  259.   gint num_layers;
  260.   PSDlayer layer[MAX_LAYERS];
  261.  
  262.   gboolean absolute_alpha;
  263.  
  264.   gint type;
  265.   
  266.   gulong colmaplen;
  267.   guchar *colmapdata;
  268.  
  269.   guint num_aux_channels;
  270.   PSDchannel aux_channel[MAX_CHANNELS];
  271.  
  272.   guint num_guides;
  273.   PSDguide guides[MAX_GUIDES];
  274.  
  275.   gchar *caption;
  276.  
  277.   guint active_layer_num;
  278.  
  279.   guint resolution_is_set;
  280.   PSDresolution resolution;
  281. } PSDimage;
  282.  
  283.  
  284.  
  285. /* Declare some local functions.
  286.  */
  287. static void   query      (void);
  288. static void   run        (gchar   *name,
  289.                           gint     nparams,
  290.                           GimpParam  *param,
  291.                           gint    *nreturn_vals,
  292.                           GimpParam **return_vals);
  293.  
  294. static GimpImageType  psd_type_to_gimp_type      (psd_imagetype  psdtype);
  295. static GimpImageBaseType     psd_type_to_gimp_base_type (psd_imagetype  psdtype);
  296. static GimpLayerModeEffects     psd_lmode_to_gimp_lmode    (gchar          modekey[4]);
  297. static GimpUnit       psd_unit_to_gimp_unit      (gint           psdunit);
  298.  
  299. static gint32         load_image                 (gchar         *filename);
  300.  
  301.  
  302.  
  303. /* Various local variables...
  304.  */
  305. GimpPlugInInfo PLUG_IN_INFO =
  306. {
  307.   NULL,  /* init_proc  */
  308.   NULL,  /* quit_proc  */
  309.   query, /* query_proc */
  310.   run,   /* run_proc   */
  311. };
  312.  
  313.  
  314. static PSDimage psd_image;
  315.  
  316.  
  317. static struct
  318. {
  319.   gchar    signature[4];
  320.   gushort  version;
  321.   guchar   reserved[6];
  322.   gushort  channels;
  323.   gulong   rows;
  324.   gulong   columns;
  325.   gushort  bpp;
  326.   gushort  mode;
  327.   gulong   imgreslen;
  328.   gulong   miscsizelen;
  329.   gushort  compression;
  330.   gushort *rowlength;
  331.   long     imgdatalen;
  332. } PSDheader;
  333.  
  334.  
  335. static gchar * modename[] =
  336. {
  337.   "Bitmap", 
  338.   "Grayscale", 
  339.   "Indexed Colour", 
  340.   "RGB Colour", 
  341.   "CMYK Colour", 
  342.   "<invalid>", 
  343.   "<invalid>", 
  344.   "Multichannel", 
  345.   "Duotone", 
  346.   "Lab Colour", 
  347.   "<invalid>"
  348. };
  349.  
  350.  
  351. static const gchar *prog_name = "PSD";
  352.  
  353.  
  354. static void unpack_pb_channel(FILE *fd, guchar *dst, gint32 unpackedlen,
  355.                   guint32 *offset);
  356. static void decode(long clen, long uclen, gchar *src, gchar *dst, int step);
  357. static void packbitsdecode(long *clenp, long uclen,
  358.                gchar *src, gchar *dst, int step);
  359. static void cmyk2rgb(guchar *src, guchar *destp,
  360.              long width, long height, int alpha);
  361. static void cmykp2rgb(guchar *src, guchar *destp,
  362.               long width, long height, int alpha);
  363. static void cmyk_to_rgb(int *c, int *m, int *y, int *k);
  364. static void bitmap2gray(guchar *src,guchar *dest,long w,long h);
  365. static guchar getguchar(FILE *fd, gchar *why);
  366. static gshort getgshort(FILE *fd, gchar *why);
  367. static glong getglong(FILE *fd, gchar *why);
  368. static void xfread(FILE *fd, void *buf, long len, gchar *why);
  369. static void xfread_interlaced(FILE *fd, guchar *buf, long len, gchar *why,
  370.                   gint step);
  371. static void* xmalloc(size_t n);
  372. static void read_whole_file(FILE *fd);
  373. static void reshuffle_cmap(guchar *map256);
  374. static guchar* getpascalstring(FILE *fd, gchar *why);
  375. static gchar* getstring(size_t n, FILE * fd, gchar *why);
  376. static void throwchunk(size_t n, FILE * fd, gchar *why);
  377. static void dumpchunk(size_t n, FILE * fd, gchar *why);
  378. static void seek_to_and_unpack_pixeldata(FILE* fd, gint layeri, gint channeli);
  379.  
  380.  
  381. MAIN ()
  382.  
  383.  
  384. static void
  385. query (void)
  386. {
  387.   static GimpParamDef load_args[] =
  388.   {
  389.     { GIMP_PDB_INT32, "run_mode", "Interactive, non-interactive" },
  390.     { GIMP_PDB_STRING, "filename", "The name of the file to load" },
  391.     { GIMP_PDB_STRING, "raw_filename", "The name of the file to load" }
  392.   };
  393.   static GimpParamDef load_return_vals[] =
  394.   {
  395.     { GIMP_PDB_IMAGE, "image", "Output image" }
  396.   };
  397.   static gint nload_args = sizeof (load_args) / sizeof (load_args[0]);
  398.   static gint nload_return_vals = (sizeof (load_return_vals) /
  399.                    sizeof (load_return_vals[0]));
  400.  
  401.   gimp_install_procedure ("file_psd_load",
  402.                           "loads files of the Photoshop(tm) PSD file format",
  403.                           "This filter loads files of Adobe Photoshop(tm) native PSD format.  These files may be of any image type supported by GIMP, with or without layers, layer masks, aux channels and guides.",
  404.                           "Adam D. Moss & Torsten Martinsen",
  405.                           "Adam D. Moss & Torsten Martinsen",
  406.                           "1996-1998",
  407.                           "<Load>/PSD",
  408.               NULL,
  409.                           GIMP_PLUGIN,
  410.                           nload_args, nload_return_vals,
  411.                           load_args, load_return_vals);
  412.  
  413.   gimp_register_magic_load_handler ("file_psd_load",
  414.                     "psd",
  415.                     "",
  416.                     "0,string,8BPS");
  417. }
  418.  
  419.  
  420. static void
  421. run (char    *name,
  422.      int      nparams,
  423.      GimpParam  *param,
  424.      int     *nreturn_vals,
  425.      GimpParam **return_vals)
  426. {
  427.   static GimpParam values[2];
  428.   GimpRunModeType run_mode;
  429.   /*  GimpPDBStatusType status = GIMP_PDB_SUCCESS;*/
  430.   gint32 image_ID;
  431.  
  432.   run_mode = param[0].data.d_int32;
  433.  
  434.   *nreturn_vals = 1;
  435.   *return_vals = values;
  436.   values[0].type = GIMP_PDB_STATUS;
  437.   values[0].data.d_status = GIMP_PDB_CALLING_ERROR;
  438.  
  439.   if (strcmp (name, "file_psd_load") == 0)
  440.     {
  441.       image_ID = load_image (param[1].data.d_string);
  442.  
  443.       if (image_ID != -1)
  444.     {
  445.       *nreturn_vals = 2;
  446.       values[0].data.d_status = GIMP_PDB_SUCCESS;
  447.       values[1].type = GIMP_PDB_IMAGE;
  448.       values[1].data.d_image = image_ID;
  449.     }
  450.       else
  451.     {
  452.       values[0].data.d_status = GIMP_PDB_EXECUTION_ERROR;
  453.     }
  454.     }
  455. }
  456.  
  457.  
  458. static GimpImageType
  459. psd_type_to_gimp_type (psd_imagetype psdtype)
  460. {
  461.   switch(psdtype)
  462.     {
  463.     case PSD_RGBA_IMAGE: return(GIMP_RGBA_IMAGE);
  464.     case PSD_RGB_IMAGE: return(GIMP_RGB_IMAGE);
  465.     case PSD_GRAYA_IMAGE: return(GIMP_GRAYA_IMAGE);
  466.     case PSD_GRAY_IMAGE: return(GIMP_GRAY_IMAGE);
  467.     case PSD_INDEXEDA_IMAGE: return(GIMP_INDEXEDA_IMAGE);
  468.     case PSD_INDEXED_IMAGE: return(GIMP_INDEXED_IMAGE);
  469.     case PSD_BITMAP_IMAGE: return(GIMP_GRAY_IMAGE);
  470.     default: return(GIMP_RGB_IMAGE);
  471.     }
  472. }
  473.  
  474.  
  475.  
  476. static GimpLayerModeEffects
  477. psd_lmode_to_gimp_lmode (gchar modekey[4])
  478. {
  479.   if (strncmp(modekey, "norm", 4)==0) return(GIMP_NORMAL_MODE);
  480.   if (strncmp(modekey, "dark", 4)==0) return(GIMP_DARKEN_ONLY_MODE);
  481.   if (strncmp(modekey, "lite", 4)==0) return(GIMP_LIGHTEN_ONLY_MODE);
  482.   if (strncmp(modekey, "hue ", 4)==0) return(GIMP_HUE_MODE);
  483.   if (strncmp(modekey, "sat ", 4)==0) return(GIMP_SATURATION_MODE);
  484.   if (strncmp(modekey, "colr", 4)==0) return(GIMP_COLOR_MODE);
  485.   if (strncmp(modekey, "mul ", 4)==0) return(GIMP_MULTIPLY_MODE);
  486.   if (strncmp(modekey, "scrn", 4)==0) return(GIMP_SCREEN_MODE);
  487.   if (strncmp(modekey, "diss", 4)==0) return(GIMP_DISSOLVE_MODE);
  488.   if (strncmp(modekey, "diff", 4)==0) return(GIMP_DIFFERENCE_MODE);
  489.   if (strncmp(modekey, "lum ", 4)==0) return(GIMP_VALUE_MODE);
  490.  
  491. #if (GIMP_MAJOR_VERSION > 0) && (GIMP_MINOR_VERSION > 0)
  492.   if (strncmp(modekey, "over", 4)==0) return(GIMP_OVERLAY_MODE);
  493.  
  494.   printf("PSD: Warning - unsupported layer-blend mode '%c%c%c%c', using "
  495.      "'overlay' mode\n", modekey[0], modekey[1], modekey[2], modekey[3]);
  496.   if (strncmp(modekey, "hLit", 4)==0) return(/**/GIMP_OVERLAY_MODE);
  497.   if (strncmp(modekey, "sLit", 4)==0) return(/**/GIMP_OVERLAY_MODE);
  498. #else
  499.   printf("PSD: Warning - unsupported layer-blend mode '%c%c%c%c', using "
  500.      "'addition' mode\n", modekey[0], modekey[1], modekey[2], modekey[3]);
  501.   if (strncmp(modekey, "over", 4)==0) return(GIMP_ADDITION_MODE); /* ? */
  502.   if (strncmp(modekey, "hLit", 4)==0) return(/**/GIMP_ADDITION_MODE);
  503.   if (strncmp(modekey, "sLit", 4)==0) return(/**/GIMP_ADDITION_MODE);
  504. #endif
  505.  
  506.   printf("PSD: Warning - UNKNOWN layer-blend mode, reverting to 'normal'\n");
  507.  
  508.   return(GIMP_NORMAL_MODE);
  509. }
  510.  
  511.  
  512.  
  513. static GimpImageBaseType
  514. psd_type_to_gimp_base_type (psd_imagetype psdtype)
  515. {
  516.   switch(psdtype)
  517.     {
  518.     case PSD_RGBA_IMAGE:
  519.     case PSD_RGB_IMAGE: return(GIMP_RGB);
  520.     case PSD_BITMAP_IMAGE:
  521.     case PSD_GRAYA_IMAGE:
  522.     case PSD_GRAY_IMAGE: return(GIMP_GRAY);
  523.     case PSD_INDEXEDA_IMAGE:
  524.     case PSD_INDEXED_IMAGE: return(GIMP_INDEXED);
  525.     default:
  526.       g_message ("PSD: Error: Can't convert PSD imagetype to GIMP imagetype\n");
  527.       gimp_quit();
  528.       return(GIMP_RGB);
  529.     }
  530. }
  531.  
  532.  
  533. static GimpUnit
  534. psd_unit_to_gimp_unit (int psdunit)
  535. {
  536.   switch (psdunit)
  537.     {
  538.     case 1:
  539.       return GIMP_UNIT_INCH;
  540.     case 2: /* this means cm to PS, but MM is as close as we have */
  541.       return GIMP_UNIT_MM;
  542.     case 3:
  543.       return GIMP_UNIT_POINT;
  544.     case 4:
  545.       return GIMP_UNIT_PICA;
  546.     case 5: /* 5 == Columns, but what the heck is a column? */
  547.     default:
  548.       IFDBG printf("Warning: unable to convert psd unit %d to gimp unit\n", psdunit);
  549.       return GIMP_UNIT_PIXEL;
  550.     }
  551. }
  552.  
  553.  
  554.  
  555. GimpImageBaseType
  556. psd_mode_to_gimp_base_type (gushort psdtype)
  557. {
  558.   switch(psdtype)
  559.     {
  560.     case 1: return(GIMP_GRAY);
  561.     case 2: return(GIMP_INDEXED);
  562.     case 3: return(GIMP_RGB);
  563.     default:
  564.       g_message ("PSD: Error: Can't convert PSD mode to GIMP base imagetype\n");
  565.       gimp_quit();
  566.       return(GIMP_RGB);
  567.     }
  568. }
  569.  
  570.  
  571.  
  572. static void
  573. reshuffle_cmap (guchar *map256)
  574. {
  575.   guchar *tmpmap;
  576.   int i;
  577.  
  578.   tmpmap = xmalloc(768);
  579.  
  580.   for (i=0;i<256;i++)
  581.     {
  582.       tmpmap[i*3  ] = map256[i];
  583.       tmpmap[i*3+1] = map256[i+256];
  584.       tmpmap[i*3+2] = map256[i+512];
  585.     }
  586.  
  587.   for (i=0;i<768;i++)
  588.     {
  589.       map256[i] = tmpmap[i];
  590.     }
  591.  
  592.   g_free(tmpmap);
  593. }
  594.  
  595.  
  596.  
  597. static void
  598. dispatch_resID(guint ID, FILE *fd, guint32 *offset, guint32 Size)
  599. {
  600.   if ( (ID < 0x0bb6) && (ID >0x07d0) )
  601.     {
  602.       IFDBG printf ("\t\tPath data is irrelevant to GIMP at this time.\n");
  603.       throwchunk(Size, fd, "dispatch_res path throw");
  604.       (*offset) += Size;
  605.     }
  606.   else
  607.     switch (ID)
  608.       {
  609.       case 0x03ee:
  610.     {
  611.       gint32 remaining = Size;
  612.       
  613.       IFDBG printf ("\t\tALPHA CHANNEL NAMES:\n");
  614.       if (Size > 0)
  615.         {
  616.           do
  617.         {
  618.           guchar slen;
  619.           gchar* sname;
  620.  
  621.           slen = getguchar (fd, "alpha channel name length");
  622.           (*offset)++;
  623.           remaining--;
  624.  
  625.           /* Check for (Mac?) Photoshop (4?) file-writing bug */
  626.           if (slen > remaining)
  627.             {
  628.               IFDBG {printf("\nYay, a file bug.  "
  629.                     "Yuck.  Photoshop 4/Mac?  "
  630.                     "I'll work around you.\n");fflush(stdout);}
  631.               break;
  632.             }
  633.  
  634.           if (slen)
  635.             {
  636.               sname = getstring(slen, fd, "alpha channel name");
  637.  
  638.               psd_image.aux_channel[psd_image.num_aux_channels].name =
  639.             sname;
  640.             }
  641.           else
  642.             {
  643.               psd_image.aux_channel[psd_image.num_aux_channels].name =
  644.             NULL;
  645.             }
  646.  
  647.           if (psd_image.aux_channel[psd_image.num_aux_channels].name
  648.               == NULL)
  649.             {
  650.               IFDBG
  651.             {printf("\t\t\tNull channel name %d.\n",
  652.                 psd_image.num_aux_channels);fflush(stdout);}
  653.             }
  654.  
  655.           if (psd_image.aux_channel[psd_image.num_aux_channels].name)
  656.             {
  657.               guint32 alpha_name_len;
  658.           
  659.               alpha_name_len =
  660.             strlen(psd_image.aux_channel[psd_image.num_aux_channels].name);
  661.               
  662.               IFDBG printf("\t\t\tname: \"%s\"\n",
  663.                    psd_image.aux_channel[psd_image.num_aux_channels].name);
  664.           
  665.               (*offset) += alpha_name_len;
  666.               remaining -= alpha_name_len;
  667.             }
  668.  
  669.           psd_image.num_aux_channels++;
  670.  
  671.           if (psd_image.num_aux_channels > MAX_CHANNELS)
  672.             {
  673.               printf("\nPSD: Sorry - this image has too many "
  674.                  "aux channels.  Tell Adam!\n");
  675.               gimp_quit();
  676.             }
  677.         }
  678.           while (remaining > 0);
  679.         }
  680.  
  681.       if (remaining)
  682.         {
  683.           IFDBG
  684.         dumpchunk(remaining, fd, "alphaname padding 0 throw");
  685.               else
  686.         throwchunk(remaining, fd, "alphaname padding 0 throw");
  687.           (*offset) += remaining;
  688.           remaining = 0;
  689.         }
  690.     }
  691.     break;
  692.       case 0x03ef:
  693.     IFDBG printf("\t\tDISPLAYINFO STRUCTURE: unhandled\n");
  694.     throwchunk(Size, fd, "dispatch_res");
  695.     (*offset) += Size;
  696.     break;
  697.       case 0x03f0: /* FIXME: untested */
  698.     {
  699.       psd_image.caption = getpascalstring(fd, "caption string");
  700.       (*offset)++;
  701.  
  702.       if (psd_image.caption)
  703.         {
  704.           IFDBG printf("\t\t\tcontent: \"%s\"\n",psd_image.caption);
  705.           (*offset) += strlen(psd_image.caption);
  706.         }
  707.     }
  708.     break;
  709.       case 0x03f2:
  710.     IFDBG printf("\t\tBACKGROUND COLOR: unhandled\n");
  711.     throwchunk(Size, fd, "dispatch_res");
  712.     (*offset) += Size;
  713.     break;    
  714.       case 0x03f4:
  715.     IFDBG printf("\t\tGREY/MULTICHANNEL HALFTONING INFO: unhandled\n");
  716.     throwchunk(Size, fd, "dispatch_res");
  717.     (*offset) += Size;
  718.     break;
  719.       case 0x03f5:
  720.     IFDBG printf("\t\tCOLOUR HALFTONING INFO: unhandled\n");
  721.     throwchunk(Size, fd, "dispatch_res");
  722.     (*offset) += Size;
  723.     break;
  724.       case 0x03f6:
  725.     IFDBG printf("\t\tDUOTONE HALFTONING INFO: unhandled\n");
  726.     throwchunk(Size, fd, "dispatch_res");
  727.     (*offset) += Size;
  728.     break;
  729.       case 0x03f7:
  730.     IFDBG printf("\t\tGREYSCALE/MULTICHANNEL TRANSFER FUNCTION: unhandled\n");
  731.     throwchunk(Size, fd, "dispatch_res");
  732.     (*offset) += Size;
  733.     break;
  734.       case 0x03f8:
  735.     IFDBG printf("\t\tCOLOUR TRANSFER FUNCTION: unhandled\n");
  736.     throwchunk(Size, fd, "dispatch_res");
  737.     (*offset) += Size;
  738.     break;
  739.       case 0x03f9:
  740.     IFDBG printf("\t\tDUOTONE TRANSFER FUNCTION: unhandled\n");
  741.     throwchunk(Size, fd, "dispatch_res");
  742.     (*offset) += Size;
  743.     break;
  744.       case 0x03fa:
  745.     IFDBG printf("\t\tDUOTONE IMAGE INFO: unhandled\n");
  746.     throwchunk(Size, fd, "dispatch_res");
  747.     (*offset) += Size;
  748.     break;
  749.       case 0x03fb:
  750.     IFDBG printf("\t\tEFFECTIVE BLACK/WHITE VALUES: unhandled\n");
  751.     throwchunk(Size, fd, "dispatch_res");
  752.     (*offset) += Size;
  753.     break;
  754.       case 0x03fe:
  755.     IFDBG printf("\t\tQUICK MASK INFO: unhandled\n");
  756.     throwchunk(Size, fd, "dispatch_res");
  757.     (*offset) += Size;
  758.     break;
  759.       case 0x0400:
  760.     {
  761.       IFDBG printf("\t\tLAYER STATE INFO:\n");
  762.       psd_image.active_layer_num = getgshort(fd, "ID target_layer_num");
  763.  
  764.       IFDBG printf("\t\t\ttarget: %d\n",(gint)psd_image.active_layer_num);
  765.       (*offset) += 2;
  766.     }
  767.     break;
  768.       case 0x0402:
  769.     IFDBG printf("\t\tLAYER GROUP INFO: unhandled\n");
  770.     IFDBG printf("\t\t\t(Inferred number of layers: %d)\n",(gint)(Size/2));
  771.     throwchunk(Size, fd, "dispatch_res");
  772.     (*offset) += Size;
  773.     break;
  774.       case 0x0405:
  775.     IFDBG printf ("\t\tIMAGE MODE FOR RAW FORMAT: unhandled\n");
  776.     throwchunk(Size, fd, "dispatch_res");
  777.     (*offset) += Size;
  778.     break;
  779.       case 0x0408:
  780.     {
  781.       gint32 remaining = Size;
  782.       int i;
  783.       IFDBG printf ("\t\tGUIDE INFORMATION:\n");
  784.       
  785.       if (Size > 0)
  786.         {
  787.           gshort magic1, magic2, magic3, magic4, magic5, magic6;
  788.           glong num_guides;
  789.  
  790.           magic1 = getgshort(fd, "guide"); (*offset) += 2;
  791.           magic2 = getgshort(fd, "guide"); (*offset) += 2;
  792.           magic3 = getgshort(fd, "guide"); (*offset) += 2;
  793.           magic4 = getgshort(fd, "guide"); (*offset) += 2;
  794.           magic5 = getgshort(fd, "guide"); (*offset) += 2;
  795.           magic6 = getgshort(fd, "guide"); (*offset) += 2;
  796.           remaining -= 12;
  797.  
  798.           IFDBG printf("\t\t\tMagic: %d %d %d %d %d %d\n",
  799.                magic1, magic2, magic3, magic4, magic5, magic6);
  800.           IFDBG printf("\t\t\tMagic: 0x%04x 0x%04x 0x%04x 0x%04x 0x%04x 0x%04x\n",
  801.                magic1, magic2, magic3, magic4, magic5, magic6);
  802.  
  803.           num_guides = getglong(fd, "guide");
  804.           (*offset) += 4; remaining -= 4;
  805.  
  806.           if (remaining != num_guides*5)
  807.         {
  808.           IFDBG printf ("** FUNNY AMOUNT OF GUIDE DATA (%d)\n",
  809.                 remaining);
  810.           goto funny_amount_of_guide_data;
  811.         }
  812.  
  813.           IFDBG printf("\t\t\tNumber of guides is %ld\n", num_guides);
  814.           if (num_guides > MAX_GUIDES)
  815.         {
  816.           g_message ("Sorry, this image has too many Guides.  "
  817.                  "Tell Adam!\n");
  818.           gimp_quit();
  819.         }
  820.           psd_image.num_guides = num_guides;
  821.  
  822.           for (i=0; i<num_guides; i++)
  823.         {
  824.           psd_image.guides[i].position = getglong(fd, "guide");
  825.  
  826.           psd_image.guides[i].horizontal = (1==getguchar(fd, "guide"));
  827.           (*offset) += 5; remaining -= 5;
  828.  
  829.           if (psd_image.guides[i].horizontal)
  830.             {
  831.               psd_image.guides[i].position =
  832.             RINT((double)(psd_image.guides[i].position *
  833.                       (magic4>>8))
  834.                  /(double)(magic4&255));
  835.             }
  836.           else
  837.             {
  838.               psd_image.guides[i].position =
  839.             RINT((double)(psd_image.guides[i].position *
  840.                       (magic6>>8))
  841.                  /(double)(magic6&255));
  842.             }
  843.  
  844.           IFDBG printf("\t\t\tGuide %d at %d, %s\n", i+1,
  845.                    psd_image.guides[i].position,
  846.                    psd_image.guides[i].horizontal ? "horizontal" :
  847.                    "vertical");
  848.         }
  849.         }
  850.  
  851.     funny_amount_of_guide_data:
  852.       
  853.       if (remaining)
  854.         {
  855.           IFDBG
  856.         {
  857.           printf ("** GUIDE INFORMATION DROSS: ");
  858.           dumpchunk(remaining, fd, "dispatch_res");
  859.         }
  860.           else
  861.         {
  862.           throwchunk(remaining, fd, "dispatch_res");
  863.         }
  864.  
  865.           (*offset) += remaining;
  866.         }
  867.     }
  868.     break;
  869.       case 0x03ed:
  870.     {
  871.       IFDBG printf ("\t\tResolution Info:\n");
  872.       psd_image.resolution_is_set = 1;
  873.  
  874.       psd_image.resolution.hRes = getglong(fd, "hRes");
  875.       psd_image.resolution.hRes_unit = getgshort(fd, "hRes_unit");
  876.       psd_image.resolution.widthUnit = getgshort(fd, "WidthUnit");
  877.       psd_image.resolution.vRes = getglong(fd, "vRes");
  878.       psd_image.resolution.vRes_unit = getgshort(fd, "vRes_unit");
  879.       psd_image.resolution.heightUnit = getgshort(fd, "HeightUnit");
  880.       (*offset) += Size;
  881.       IFDBG  printf("\t\t\tres = %f, %f\n",
  882.             psd_image.resolution.hRes / 65536.0, 
  883.             psd_image.resolution.vRes / 65536.0);
  884.     } break;
  885.  
  886.       case 0x03e9:
  887.       case 0x03f1:
  888.       case 0x03f3:
  889.       case 0x03fd:
  890.       case 0x0401:
  891.       case 0x0404:
  892.       case 0x0406:
  893.       case 0x0bb7:
  894.       case 0x2710:
  895.     IFDBG printf ("\t\t<Field is irrelevant to GIMP at this time.>\n");
  896.     throwchunk(Size, fd, "dispatch_res");    
  897.     (*offset) += Size;
  898.     break;
  899.     
  900.       case 0x03e8:
  901.       case 0x03eb:
  902.     IFDBG printf ("\t\t<Obsolete Photoshop 2.0 field.>\n");
  903.     throwchunk(Size, fd, "dispatch_res");
  904.     (*offset) += Size;
  905.     break;
  906.     
  907.       case 0x03fc:
  908.       case 0x03ff:
  909.       case 0x0403:
  910.     IFDBG printf ("\t\t<Obsolete field.>\n");
  911.     throwchunk(Size, fd, "dispatch_res");
  912.     (*offset) += Size;
  913.     break;
  914.     
  915.       default:
  916.     IFDBG
  917.       {
  918.         printf ("\t\t<Undocumented field.>\n");
  919.         dumpchunk(Size, fd, "dispatch_res");
  920.       }
  921.     else
  922.       throwchunk(Size, fd, "dispatch_res");
  923.  
  924.     (*offset) += Size;
  925.     break;
  926.       }
  927. }
  928.  
  929.  
  930. static void
  931. do_layer_record(FILE *fd, guint32 *offset, gint layernum)
  932. {
  933.   gint32 top, left, bottom, right;
  934.   guint32 extradatasize, layermaskdatasize, layerrangesdatasize;
  935.   guint32 totaloff;
  936.   gchar sig[4];
  937.   guchar flags;
  938.   gint i;
  939.  
  940.   IFDBG printf("\t\t\tLAYER RECORD (layer %d)\n", (int)layernum);
  941.  
  942.  
  943.   /* table 11-12 */
  944.   top = getglong (fd, "layer top");
  945.   (*offset)+=4;
  946.   left = getglong (fd, "layer left");
  947.   (*offset)+=4;
  948.   bottom = getglong (fd, "layer bottom");
  949.   (*offset)+=4;
  950.   right = getglong (fd, "layer right");
  951.   (*offset)+=4;
  952.  
  953.   psd_image.layer[layernum].x = left;
  954.   psd_image.layer[layernum].y = top;
  955.   psd_image.layer[layernum].width = right-left;
  956.   psd_image.layer[layernum].height = bottom-top;
  957.   
  958.   IFDBG printf("\t\t\t\tLayer extents: (%d,%d) -> (%d,%d)\n",left,top,right,bottom);
  959.   
  960.   psd_image.layer[layernum].num_channels =
  961.     getgshort (fd, "layer num_channels");
  962.   (*offset)+=2;
  963.  
  964.   if (psd_image.layer[layernum].num_channels > MAX_CHANNELS)
  965.     {
  966.       g_message ("\nPSD: Sorry - this image has too many channels.  Tell Adam!\n");
  967.       gimp_quit();
  968.     }
  969.   
  970.   IFDBG printf("\t\t\t\tNumber of channels: %d\n",
  971.      (int)psd_image.layer[layernum].num_channels);
  972.  
  973.   for (i=0;i<psd_image.layer[layernum].num_channels;i++)
  974.     {
  975.       /* table 11-13 */
  976.       IFDBG printf("\t\t\t\tCHANNEL LENGTH INFO (%d)\n", i);
  977.  
  978.       psd_image.layer[layernum].channel[i].type    = getgshort(fd, "channel id");
  979.       (*offset)+=2;
  980.       IFDBG printf("\t\t\t\t\tChannel TYPE: %d\n",
  981.          psd_image.layer[layernum].channel[i].type);
  982.  
  983.       psd_image.layer[layernum].channel[i].compressedsize =
  984.     getglong(fd, "channeldatalength");
  985.       (*offset)+=4;
  986.       IFDBG printf("\t\t\t\t\tChannel Data Length: %d\n",
  987.          psd_image.layer[layernum].channel[i].compressedsize);
  988.     }
  989.  
  990.   xfread(fd, sig, 4, "layer blend sig");
  991.   (*offset)+=4;
  992.   
  993.   if (strncmp(sig, "8BIM", 4)!=0)
  994.     {
  995.       g_message ("PSD: Error - layer blend signature is incorrect. :-(\n");
  996.       gimp_quit();
  997.     }
  998.  
  999.   xfread(fd, psd_image.layer[layernum].blendkey, 4, "layer blend key");
  1000.   (*offset)+=4;
  1001.  
  1002.   IFDBG printf("\t\t\t\tBlend type: PSD(\"%c%c%c%c\") = GIMP(%d)\n",
  1003.      psd_image.layer[layernum].blendkey[0],
  1004.      psd_image.layer[layernum].blendkey[1],
  1005.      psd_image.layer[layernum].blendkey[2],
  1006.      psd_image.layer[layernum].blendkey[3],
  1007.      psd_lmode_to_gimp_lmode(psd_image.layer[layernum].blendkey));
  1008.  
  1009.   psd_image.layer[layernum].opacity = getguchar(fd, "layer opacity");
  1010.   (*offset)++;
  1011.  
  1012.   IFDBG printf("\t\t\t\tLayer Opacity: %d\n", psd_image.layer[layernum].opacity);
  1013.  
  1014.   psd_image.layer[layernum].clipping = getguchar(fd, "layer clipping");
  1015.   (*offset)++;
  1016.  
  1017.   IFDBG printf("\t\t\t\tLayer Clipping: %d (%s)\n",
  1018.      psd_image.layer[layernum].clipping,
  1019.      psd_image.layer[layernum].clipping==0?"base":"non-base");
  1020.  
  1021.   flags = getguchar(fd, "layer flags");
  1022.   (*offset)++;
  1023.  
  1024.   IFDBG printf("\t\t\t\tLayer Flags: %d (%s, %s)\n", flags,
  1025.      flags&1?"preserve transparency":"don't preserve transparency",
  1026.      flags&2?"visible":"not visible");
  1027.  
  1028.   psd_image.layer[layernum].protecttrans = (flags&1) ? TRUE : FALSE;
  1029.   psd_image.layer[layernum].visible = (flags&2) ? FALSE : TRUE;
  1030.  
  1031.   getguchar(fd, "layer record filler");
  1032.   (*offset)++;
  1033.  
  1034.   extradatasize = getglong(fd, "layer extra data size");
  1035.   (*offset)+=4;
  1036.   IFDBG printf("\t\t\t\tEXTRA DATA SIZE: %d\n",extradatasize);
  1037.  
  1038.   /* FIXME: should do something with this data */
  1039.   /*throwchunk(extradatasize, fd, "layer extradata throw");
  1040.   (*offset) += extradatasize;*/
  1041.  
  1042.   totaloff = (*offset) + extradatasize;
  1043.  
  1044.   /* table 11-14 */
  1045.   layermaskdatasize = getglong(fd, "layer mask data size");
  1046.   (*offset)+=4;
  1047.   IFDBG printf("\t\t\t\t\tLAYER MASK DATA SIZE: %d\n",layermaskdatasize);
  1048.   
  1049.   if (layermaskdatasize)
  1050.     {
  1051.       top    = getglong(fd, "lmask top");
  1052.       (*offset) += 4;
  1053.       left   = getglong(fd, "lmask left");
  1054.       (*offset) += 4;
  1055.       bottom = getglong(fd, "lmask bottom");
  1056.       (*offset) += 4;
  1057.       right  = getglong(fd, "lmask right");
  1058.       (*offset) += 4;
  1059.  
  1060.       psd_image.layer[layernum].lm_x = left;
  1061.       psd_image.layer[layernum].lm_y = top;
  1062.       psd_image.layer[layernum].lm_width = right-left;
  1063.       psd_image.layer[layernum].lm_height = bottom-top;
  1064.  
  1065.       getglong(fd, "lmask data throw");
  1066.       (*offset) += 4;
  1067.  
  1068.       /*      throwchunk(layermaskdatasize, fd, "layer mask data throw");
  1069.       (*offset) += layermaskdatasize;*/
  1070.     }
  1071.  
  1072.  
  1073.   layerrangesdatasize = getglong(fd, "layer ranges data size");
  1074.   (*offset)+=4;
  1075.   IFDBG printf("\t\t\t\t\t\tLAYER RANGES DATA SIZE: %d\n",layermaskdatasize);
  1076.   
  1077.   if (layerrangesdatasize)
  1078.     {
  1079.       throwchunk(layerrangesdatasize, fd, "layer ranges data throw");
  1080.       (*offset) += layerrangesdatasize;
  1081.     }
  1082.  
  1083.   psd_image.layer[layernum].name = getpascalstring(fd, "layer name");
  1084.   (*offset)++;
  1085.  
  1086.   if (psd_image.layer[layernum].name)
  1087.     {
  1088.       (*offset) += strlen(psd_image.layer[layernum].name);
  1089.       IFDBG printf("\t\t\t\t\t\tLAYER NAME: '%s'\n",psd_image.layer[layernum].name);
  1090.     }
  1091.   else
  1092.     {
  1093.       IFDBG printf("\t\t\t\t\t\tNULL LAYER NAME\n");
  1094.     }
  1095.   
  1096.   if (totaloff-(*offset) > 0)
  1097.     {
  1098.       IFDBG 
  1099.     {
  1100.       printf("Warning: layer record dross: ");
  1101.       dumpchunk(totaloff-(*offset), fd, "layer record dross throw");
  1102.     }
  1103.     else
  1104.     {
  1105.       throwchunk(totaloff-(*offset), fd, "layer record dross throw");
  1106.     }
  1107.       (*offset) = totaloff;
  1108.     }
  1109. }
  1110.  
  1111.  
  1112. static void
  1113. do_layer_struct(FILE *fd, guint32 *offset)
  1114. {
  1115.   gint i;
  1116.  
  1117.   IFDBG printf("\t\tLAYER STRUCTURE SECTION\n");
  1118.   
  1119.   psd_image.num_layers = getgshort(fd, "layer struct numlayers");
  1120.   (*offset)+=2;
  1121.  
  1122.   IFDBG printf("\t\t\tCanonical number of layers: %d%s\n",
  1123.      psd_image.num_layers>0?
  1124.      (int)psd_image.num_layers:abs(psd_image.num_layers),
  1125.      psd_image.num_layers>0?"":" (absolute/alpha)");
  1126.  
  1127.   if (psd_image.num_layers<0)
  1128.     {
  1129.       psd_image.num_layers = -psd_image.num_layers;
  1130.       psd_image.absolute_alpha = TRUE;
  1131.     }
  1132.   else
  1133.     {
  1134.       psd_image.absolute_alpha = FALSE;
  1135.     }
  1136.  
  1137.   if (psd_image.num_layers > MAX_LAYERS)
  1138.     {
  1139.       g_message ("\nPSD: Sorry - this image has too many layers.  Tell Adam!\n");
  1140.       gimp_quit();
  1141.     }
  1142.  
  1143.   for (i=0; i<psd_image.num_layers; i++)
  1144.     {
  1145.       do_layer_record(fd, offset, i);
  1146.     }
  1147. }
  1148.  
  1149.  
  1150. static void
  1151. do_layer_pixeldata(FILE *fd, guint32 *offset)
  1152. {
  1153.   gint layeri, channeli;
  1154.  
  1155.   for (layeri=0; layeri<psd_image.num_layers; layeri++)
  1156.     {
  1157.       for (channeli=0;
  1158.        channeli<psd_image.layer[layeri].num_channels;
  1159.        channeli++)
  1160.     {
  1161.       int width, height;
  1162.  
  1163.       if (psd_image.layer[layeri].channel[channeli].type == -2)
  1164.         {
  1165.           width = psd_image.layer[layeri].lm_width;
  1166.           height = psd_image.layer[layeri].lm_height;
  1167.         }
  1168.       else
  1169.         {
  1170.           width = psd_image.layer[layeri].width;
  1171.           height = psd_image.layer[layeri].height;
  1172.         }
  1173.  
  1174.       fgetpos(fd, &psd_image.layer[layeri].channel[channeli].fpos);
  1175.       psd_image.layer[layeri].channel[channeli].width = width;
  1176.       psd_image.layer[layeri].channel[channeli].height = height;
  1177.  
  1178.       throwchunk(psd_image.layer[layeri].channel[channeli].compressedsize,
  1179.              fd, "channel data skip");
  1180.       (*offset) +=
  1181.         psd_image.layer[layeri].channel[channeli].compressedsize;
  1182.     }
  1183.     }
  1184. }
  1185.  
  1186.  
  1187. static void
  1188. seek_to_and_unpack_pixeldata(FILE* fd, gint layeri, gint channeli)
  1189. {
  1190.   int width, height;
  1191.   guchar *tmpline;
  1192.   gint compression;
  1193.   guint32 offset = 0;
  1194.  
  1195.   fsetpos(fd, &psd_image.layer[layeri].channel[channeli].fpos);
  1196.  
  1197.   compression = getgshort(fd, "layer channel compression type");
  1198.   offset+=2;
  1199.  
  1200.   width = psd_image.layer[layeri].channel[channeli].width;
  1201.   height = psd_image.layer[layeri].channel[channeli].height;
  1202.  
  1203.   IFDBG
  1204.     {
  1205.       printf("\t\t\tLayer (%d) Channel (%d:%d) Compression: %d (%s)\n",
  1206.          layeri,
  1207.          channeli,
  1208.          psd_image.layer[layeri].channel[channeli].type,
  1209.          compression,
  1210.          compression==0?"raw":(compression==1?"RLE":"*UNKNOWN!*"));
  1211.       
  1212.       fflush(stdout);
  1213.     }
  1214.  
  1215.   psd_image.layer[layeri].channel[channeli].data =
  1216.     xmalloc (width * height);
  1217.  
  1218.   tmpline = xmalloc(width + 1);
  1219.   
  1220.   switch (compression)
  1221.     {
  1222.     case 0: /* raw data */
  1223.       {
  1224.     gint linei;
  1225.     
  1226.     for (linei=0; linei < height; linei++)
  1227.       {
  1228.         xfread(fd,
  1229.            (psd_image.layer[layeri].channel[channeli].data+
  1230.             linei * width),
  1231.            width,
  1232.            "raw channel line");
  1233.         offset += width;
  1234.       }
  1235.  
  1236. #if 0
  1237.     /* Pad raw data to multiple of 2? */
  1238.     if ((height * width) & 1)
  1239.       {
  1240.         getguchar(fd, "raw channel padding");
  1241.         offset++;
  1242.       }
  1243. #endif
  1244.       }
  1245.       break;
  1246.     case 1: /* RLE, one row at a time, padded to an even width */
  1247.       {
  1248.     gint linei;
  1249.     gint blockread;
  1250.             
  1251.     /* we throw this away because in theory we can trust the
  1252.        data to unpack to the right length... hmm... */
  1253.     throwchunk(height * 2,
  1254.            fd, "widthlist");
  1255.     offset += height * 2;
  1256.  
  1257.     blockread = offset;
  1258.             
  1259.     /*IFDBG {printf("\nHere comes the guitar solo...\n");
  1260.       fflush(stdout);}*/
  1261.  
  1262.     for (linei=0;
  1263.          linei<height;
  1264.          linei++)
  1265.       {
  1266.         /*printf(" %d ", *offset);*/
  1267.         unpack_pb_channel(fd, tmpline,
  1268.                   width 
  1269.                   /*+ (width&1)*/,
  1270.                   &offset);
  1271.         memcpy((psd_image.layer[layeri].channel[channeli].data+
  1272.             linei * width),
  1273.            tmpline,
  1274.            width);
  1275.       }
  1276.             
  1277.     IFDBG {printf("\t\t\t\t\tActual compressed size was %d bytes\n"
  1278.               , offset-blockread);fflush(stdout);}
  1279.       }
  1280.       break;
  1281.     default: /* *unknown* */
  1282.       IFDBG {printf("\nEEP!\n");fflush(stdout);}
  1283.       g_message ("*** Unknown compression type in channel.\n");
  1284.       gimp_quit();
  1285.       break;
  1286.     }
  1287.       
  1288.   if (tmpline)
  1289.     g_free(tmpline);
  1290.   else
  1291.     IFDBG {printf("\nTRIED TO FREE NULL!");fflush(stdout);}
  1292. }
  1293.  
  1294.  
  1295. static void
  1296. do_layers(FILE *fd, guint32 *offset)
  1297. {
  1298.   guint32 section_length;
  1299.  
  1300.   section_length = getglong(fd, "layerinfo sectionlength");
  1301.   (*offset)+=4;
  1302.  
  1303.   IFDBG printf("\tLAYER INFO SECTION\n");
  1304.   IFDBG printf("\t\tSECTION LENGTH: %u\n",section_length);
  1305.   
  1306.   do_layer_struct(fd, offset);
  1307.  
  1308.   do_layer_pixeldata(fd, offset);
  1309. }
  1310.  
  1311.  
  1312. static void
  1313. do_layer_and_mask(FILE *fd)
  1314. {
  1315.   guint32 offset = 0;
  1316.   guint32 Size = PSDheader.miscsizelen;
  1317.  
  1318.  
  1319.   guint32 offset_now = ftell(fd);
  1320.  
  1321.  
  1322.   IFDBG printf("LAYER AND MASK INFO\n");
  1323.   IFDBG printf("\tSECTION LENGTH: %u\n",Size);
  1324.  
  1325.   if (Size == 0) return;
  1326.  
  1327.   do_layers(fd, &offset);
  1328.  
  1329.   IFDBG {printf("And...?\n");fflush(stdout);}
  1330.  
  1331.   if (offset < Size)
  1332.     {
  1333.       IFDBG
  1334.     {
  1335.       printf("PSD: Supposedly there are %d bytes of mask info left.\n",
  1336.          Size-offset);
  1337.       if ((Size-offset == 4) || (Size-offset == 24))
  1338.         printf("     That sounds good to me.\n");
  1339.       else
  1340.         printf("     That sounds strange to me.\n");
  1341.     }
  1342.  
  1343.  
  1344.       /*      if ((getguchar(fd, "mask info throw")!=0) ||
  1345.       (getguchar(fd, "mask info throw")!=0) ||
  1346.       (getguchar(fd, "mask info throw")!=0) ||
  1347.       (getguchar(fd, "mask info throw")!=0))
  1348.     {
  1349.       printf("*** This mask info block looks pretty bogus.\n");
  1350.     }*/
  1351.     }
  1352.   else
  1353.     printf("PSD: Stern warning - no mask info.\n");
  1354.  
  1355.  
  1356.   /* If 'offset' wasn't being buggily updated, we wouldn't need this. (!?) */
  1357.   fseek(fd, Size+offset_now, SEEK_SET);
  1358. }
  1359.  
  1360.  
  1361. static void
  1362. do_image_resources(FILE *fd)
  1363. {
  1364.   guint16 ID;
  1365.   gchar *Name;
  1366.   guint32 Size;
  1367.  
  1368.   guint32 offset = 0;
  1369.  
  1370.   IFDBG printf("IMAGE RESOURCE BLOCK:\n");
  1371.  
  1372.   psd_image.resolution_is_set = 0;
  1373.  
  1374.   /* FIXME: too trusting that the file isn't corrupt */
  1375.   while (offset < PSDheader.imgreslen-1)
  1376.     {
  1377.       gchar sig[4];
  1378.       
  1379.       xfread(fd, sig, 4, "imageresources signature");
  1380.  
  1381.       if (strncmp(sig, "8BIM", 4) != 0)
  1382.     {
  1383.       printf("PSD: Error - imageresources block has invalid signature.\n");
  1384.       gimp_quit();
  1385.     }
  1386.       offset += 4;
  1387.  
  1388.       /* generic information about a block ID */
  1389.  
  1390.  
  1391.       ID = getgshort(fd, "ID num");
  1392.       offset += 2;
  1393.       IFDBG printf("\tID: 0x%04x / ",ID);
  1394.  
  1395.  
  1396.       Name = getpascalstring(fd, "ID name");
  1397.       offset++;
  1398.  
  1399.       if (Name)
  1400.     {
  1401.       IFDBG printf("\"%s\" ", Name);
  1402.       offset += strlen(Name);
  1403.  
  1404.       if (!(strlen(Name)&1))
  1405.         {
  1406.           throwchunk(1, fd, "ID name throw");
  1407.           offset ++;
  1408.         }
  1409.       g_free(Name);
  1410.     }
  1411.       else
  1412.     {
  1413.       throwchunk(1, fd, "ID name throw2");
  1414.       offset++;
  1415.     }
  1416.  
  1417.       Size = getglong(fd, "ID Size");
  1418.       offset += 4;
  1419.       IFDBG printf("Size: %d\n", Size);
  1420.  
  1421.       dispatch_resID(ID, fd, &offset, Size);
  1422.  
  1423.       if (Size&1)
  1424.     {
  1425.       IFDBG printf("+1");
  1426.       throwchunk(1, fd, "ID content throw");
  1427.       offset ++;
  1428.     }
  1429.     }
  1430.  
  1431.   /*  if (offset != PSDheader.imgreslen)
  1432.     {
  1433.       printf("\tSucking imageres byte...\n");
  1434.       throwchunk(1, fd, "imageres suck");
  1435.       offset ++;
  1436.     }*/
  1437.  
  1438. }
  1439.  
  1440.  
  1441. static
  1442. guchar* chans_to_GRAYA (guchar* grey, guchar* alpha, gint numpix)
  1443. {
  1444.   guchar* rtn;
  1445.   int i; /* clearly, 'i' stands for 'Imaginative loop variable' */
  1446.  
  1447.   if ((grey==NULL)||(alpha==NULL))
  1448.     {
  1449.       printf("NULL channel - eep!");
  1450.       return NULL;
  1451.     }
  1452.  
  1453.   rtn = xmalloc(numpix * 2);
  1454.  
  1455.   for (i=0; i<numpix; i++)
  1456.     {
  1457.       rtn[i*2  ] = grey[i];
  1458.       rtn[i*2+1] = alpha[i];
  1459.     }
  1460.  
  1461.   return (rtn);
  1462. }
  1463.  
  1464.  
  1465. static
  1466. guchar* chans_to_RGB (guchar* red, guchar* green, guchar* blue, gint numpix)
  1467. {
  1468.   guchar* rtn;
  1469.   int i;
  1470.  
  1471.   if ((red==NULL)||(green==NULL)||(blue==NULL))
  1472.     {
  1473.       printf("NULL channel - eep!");
  1474.       return NULL;
  1475.     }
  1476.  
  1477.   rtn = xmalloc(numpix * 3);
  1478.  
  1479.   for (i=0; i<numpix; i++)
  1480.     {
  1481.       rtn[i*3  ] = red[i];
  1482.       rtn[i*3+1] = green[i];
  1483.       rtn[i*3+2] = blue[i];
  1484.     }
  1485.  
  1486.   return (rtn);
  1487. }
  1488.  
  1489.  
  1490.  
  1491. static
  1492. guchar* chans_to_RGBA (guchar* red, guchar* green, guchar* blue,
  1493.                guchar* alpha,
  1494.                gint numpix)
  1495. {
  1496.   guchar* rtn;
  1497.   int i;
  1498.   gboolean careful = FALSE;
  1499.  
  1500.   if ((red==NULL)||(green==NULL)||(blue==NULL)||(alpha==NULL))
  1501.     {
  1502.       printf("chans_to_RGBA : NULL channel - eep!");
  1503.       careful = TRUE;
  1504.     }
  1505.  
  1506.   rtn = xmalloc(numpix * 4);
  1507.  
  1508.   if (!careful)
  1509.     {
  1510.       for (i=0; i<numpix; i++)
  1511.     {
  1512.       rtn[i*4  ] = red[i];
  1513.       rtn[i*4+1] = green[i];
  1514.       rtn[i*4+2] = blue[i];
  1515.       rtn[i*4+3] = alpha[i];
  1516.     }
  1517.     }
  1518.   else
  1519.     {
  1520.       for (i=0; i<numpix; i++)
  1521.     {
  1522.       rtn[i*4  ] = (red==NULL) ? 0 : red[i];
  1523.       rtn[i*4+1] = (green==NULL) ? 0 : green[i];
  1524.       rtn[i*4+2] = (blue==NULL) ? 0 : blue[i];
  1525.       rtn[i*4+3] = (alpha==NULL) ? 0 : alpha[i];
  1526.     }
  1527.     }
  1528.  
  1529.   return (rtn);
  1530. }
  1531.  
  1532.  
  1533. static
  1534. gboolean psd_layer_has_alpha(PSDlayer* layer)
  1535. {
  1536.   int i;
  1537.  
  1538.   for (i=0; i<layer->num_channels; i++)
  1539.     {
  1540.       if (layer->channel[i].type == -1)
  1541.     {
  1542.       return TRUE;
  1543.     }
  1544.     }
  1545.  
  1546.   return FALSE;
  1547. }
  1548.  
  1549.  
  1550. static
  1551. void extract_data_and_channels(guchar* src, gint gimpstep, gint psstep,
  1552.                    gint32 image_ID, GimpDrawable* drawable,
  1553.                    gint width, gint height)
  1554. {
  1555.   guchar* primary_data;
  1556.   guchar* aux_data;
  1557.   GimpPixelRgn pixel_rgn;
  1558.  
  1559.   IFDBG printf("Extracting primary channel data (%d channels)\n"
  1560.      "\tand %d auxiliary channels.\n", gimpstep, psstep-gimpstep);
  1561.  
  1562.   primary_data = xmalloc(width * height * gimpstep);
  1563.   {
  1564.     int pix,chan;
  1565.  
  1566.     for (pix=0; pix<width*height; pix++)
  1567.       {
  1568.     for (chan=0; chan<gimpstep; chan++)
  1569.       {
  1570.         primary_data [pix*gimpstep + chan] =
  1571.           src [pix*psstep + chan];
  1572.       }
  1573.       }
  1574.     
  1575.     gimp_pixel_rgn_init (&pixel_rgn, drawable,
  1576.              0, 0, drawable->width, drawable->height,
  1577.              TRUE, FALSE);
  1578.     gimp_pixel_rgn_set_rect (&pixel_rgn, primary_data,
  1579.                  0, 0, drawable->width, drawable->height);    
  1580.   
  1581.     gimp_drawable_flush (drawable);
  1582.     gimp_drawable_detach (drawable);
  1583.   }
  1584.   g_free(primary_data);
  1585.  
  1586.  
  1587.   aux_data = xmalloc(width * height);
  1588.   {
  1589.     int pix, chan;
  1590.     gint32 channel_ID;
  1591.     GimpDrawable* chdrawable;
  1592.     guchar colour[3]= {0, 0, 0};
  1593.  
  1594.  
  1595.     for (chan=gimpstep; chan<psstep; chan++)
  1596.       {
  1597.     for (pix=0; pix<width*height; pix++)
  1598.       {
  1599.         aux_data [pix] =
  1600.           src [pix*psstep + chan];
  1601.       }
  1602.     
  1603.     channel_ID = gimp_channel_new(image_ID,
  1604.                       psd_image.aux_channel[chan-gimpstep].name ? psd_image.aux_channel[chan-gimpstep].name : _("Unnamed channel"),
  1605.                       width, height,
  1606.                       100.0, colour);
  1607.     gimp_image_add_channel(image_ID, channel_ID, 0);
  1608.     gimp_channel_set_visible(channel_ID, FALSE);
  1609.  
  1610.     chdrawable = gimp_drawable_get(channel_ID);
  1611.  
  1612.     gimp_pixel_rgn_init (&pixel_rgn, chdrawable,
  1613.                  0, 0, chdrawable->width, chdrawable->height,
  1614.                  TRUE, FALSE);
  1615.     gimp_pixel_rgn_set_rect (&pixel_rgn, aux_data,
  1616.                  0, 0, chdrawable->width, chdrawable->height);
  1617.     
  1618.     gimp_drawable_flush (chdrawable);
  1619.     gimp_drawable_detach (chdrawable);
  1620.       }
  1621.   }
  1622.   g_free(aux_data);
  1623.  
  1624.   IFDBG printf("Done with that.\n\n");
  1625. }
  1626.  
  1627.  
  1628. static
  1629. void extract_channels(guchar* src, gint num_wanted, gint psstep,
  1630.               gint32 image_ID,
  1631.               gint width, gint height)
  1632. {
  1633.   guchar* aux_data;
  1634.   GimpPixelRgn pixel_rgn;
  1635.  
  1636.   IFDBG printf("Extracting %d/%d auxiliary channels.\n", num_wanted, psstep);
  1637.  
  1638.   aux_data = xmalloc(width * height);
  1639.   {
  1640.     int pix, chan;
  1641.     gint32 channel_ID;
  1642.     GimpDrawable* chdrawable;
  1643.     guchar colour[3]= {0, 0, 0};
  1644.  
  1645.     for (chan=psstep-num_wanted; chan<psstep; chan++)
  1646.       {
  1647.     for (pix=0; pix<width*height; pix++)
  1648.       {
  1649.         aux_data [pix] =
  1650.           src [pix*psstep + chan];
  1651.       }
  1652.     
  1653.     channel_ID = gimp_channel_new(image_ID,
  1654.                       psd_image.aux_channel[chan-(psstep-num_wanted)].name ? psd_image.aux_channel[chan-(psstep-num_wanted)].name : "Unnamed channel",
  1655.                       width, height,
  1656.                       100.0, colour);
  1657.     gimp_image_add_channel(image_ID, channel_ID, 0);
  1658.     gimp_channel_set_visible(channel_ID, FALSE);
  1659.  
  1660.     chdrawable = gimp_drawable_get(channel_ID);
  1661.  
  1662.     gimp_pixel_rgn_init (&pixel_rgn, chdrawable,
  1663.                  0, 0, chdrawable->width, chdrawable->height,
  1664.                  TRUE, FALSE);
  1665.     gimp_pixel_rgn_set_rect (&pixel_rgn, aux_data,
  1666.                  0, 0, chdrawable->width, chdrawable->height);
  1667.     
  1668.     gimp_drawable_flush (chdrawable);
  1669.     gimp_drawable_detach (chdrawable);
  1670.       }
  1671.   }
  1672.   g_free(aux_data);
  1673.  
  1674.   IFDBG printf("Done with that.\n\n");
  1675. }
  1676.  
  1677.  
  1678. static void
  1679. resize_mask(guchar* src, guchar* dest,
  1680.         gint32 src_x, gint32 src_y,
  1681.         gint32 src_w, gint32 src_h,
  1682.         gint32 dest_w, gint32 dest_h)
  1683. {
  1684.   int x,y;
  1685.  
  1686.   IFDBG printf("--> %p %p : %d %d . %d %d . %d %d\n",
  1687.      src, dest,
  1688.      src_x, src_y,
  1689.      src_w, src_h,
  1690.      dest_w, dest_h);
  1691.  
  1692.   for (y=0; y<dest_h; y++)
  1693.     {
  1694.       for (x=0; x<dest_w; x++)
  1695.     {
  1696.       if ((x>src_x) && (x<src_x+src_w) &&
  1697.           (y>src_y) && (y<src_y+src_h))
  1698.         {
  1699.           dest[dest_w * y + x] =
  1700.         src[src_w * (y-src_y) + (x-src_x)];
  1701.         }
  1702.       else
  1703.         {
  1704.           dest[dest_w * y + x] = 255;
  1705.         }
  1706.     }
  1707.     }
  1708. }
  1709.  
  1710.  
  1711. static gint32
  1712. load_image(char *name)
  1713. {
  1714.   FILE *fd;
  1715.   gboolean want_aux;
  1716.   char *name_buf;
  1717.   guchar *cmykbuf;
  1718.   guchar *dest, *temp;
  1719.   long channels, nguchars;
  1720.   psd_imagetype imagetype;
  1721.   int cmyk = 0, step = 1;
  1722.   gint32 image_ID = -1;
  1723.   gint32 layer_ID = -1;
  1724.   GimpDrawable *drawable = NULL;
  1725.   GimpPixelRgn pixel_rgn;
  1726.   gint32 iter;
  1727.   fpos_t tmpfpos;
  1728.  
  1729.   IFDBG printf("------- %s ---------------------------------\n",name);
  1730.  
  1731.   name_buf = g_strdup_printf( _("Loading %s:"), name);
  1732.  
  1733.   gimp_progress_init(name_buf);
  1734.  
  1735.   fd = fopen(name, "rb");
  1736.   if (fd==NULL) {
  1737.     printf("%s: can't open \"%s\"\n", prog_name, name);
  1738.     return(-1);
  1739.   }
  1740.  
  1741.   read_whole_file(fd);
  1742.  
  1743.   if (psd_image.num_layers > 0) /* PS3-style */
  1744.     {
  1745.       int lnum;
  1746.       GimpImageBaseType gimagetype;
  1747.  
  1748.       gimagetype = psd_mode_to_gimp_base_type(PSDheader.mode);
  1749.       image_ID =
  1750.     gimp_image_new (PSDheader.columns, PSDheader.rows, gimagetype);
  1751.       gimp_image_set_filename (image_ID, name);
  1752.       
  1753.       if (psd_image.resolution_is_set)
  1754.     {
  1755.       gimp_image_set_resolution(image_ID,
  1756.                     psd_image.resolution.hRes / 65536.0,
  1757.                     psd_image.resolution.vRes / 65536.0);
  1758.       /* currently can only set one unit for the image so we use the
  1759.          horizontal unit from the psd image */
  1760.       gimp_image_set_unit(image_ID, psd_unit_to_gimp_unit( psd_image.resolution.widthUnit));
  1761.     }
  1762.  
  1763.  
  1764.       fgetpos (fd, &tmpfpos);
  1765.  
  1766.       for (lnum=0; lnum<psd_image.num_layers; lnum++)
  1767.     {
  1768.       gint numc;
  1769.       guchar* merged_data = NULL;
  1770.  
  1771.       numc = psd_image.layer[lnum].num_channels;
  1772.  
  1773.       IFDBG printf("Hey, it's a LAYER with %d channels!\n", numc);
  1774.       
  1775.       switch (gimagetype)
  1776.         {
  1777.         case GIMP_GRAY:
  1778.           {
  1779.         IFDBG printf("It's GRAY.\n");
  1780.         if (!psd_layer_has_alpha(&psd_image.layer[lnum]))
  1781.           {
  1782.             merged_data = xmalloc(psd_image.layer[lnum].width *
  1783.                       psd_image.layer[lnum].height);
  1784.             seek_to_and_unpack_pixeldata(fd, lnum, 0);
  1785.             memcpy(merged_data, psd_image.layer[lnum].channel[0].data,
  1786.                psd_image.layer[lnum].width *
  1787.                psd_image.layer[lnum].height);
  1788.  
  1789.             if (psd_image.layer[lnum].channel[0].data)
  1790.               g_free(psd_image.layer[lnum].channel[0].data);
  1791.           }
  1792.         else
  1793.           {
  1794.             seek_to_and_unpack_pixeldata(fd, lnum, 0);
  1795.             seek_to_and_unpack_pixeldata(fd, lnum, 1);
  1796.             merged_data =
  1797.               chans_to_GRAYA (psd_image.layer[lnum].channel[1].data,
  1798.                       psd_image.layer[lnum].channel[0].data,
  1799.                       psd_image.layer[lnum].width *
  1800.                       psd_image.layer[lnum].height);
  1801.  
  1802.             if (psd_image.layer[lnum].channel[0].data)
  1803.               g_free(psd_image.layer[lnum].channel[0].data);
  1804.             if (psd_image.layer[lnum].channel[1].data)
  1805.               g_free(psd_image.layer[lnum].channel[1].data);
  1806.           }
  1807.           
  1808.         layer_ID = gimp_layer_new (image_ID,
  1809.                        psd_image.layer[lnum].name,
  1810.                        psd_image.layer[lnum].width,
  1811.                        psd_image.layer[lnum].height,
  1812.                        (numc==1) ? GIMP_GRAY_IMAGE : GIMP_GRAYA_IMAGE,
  1813.                        (100.0*(double)psd_image.layer[lnum].opacity)/255.0,
  1814.                        psd_lmode_to_gimp_lmode(psd_image.layer[lnum].blendkey));
  1815.  
  1816.           }; break; /* case GIMP_GRAY */
  1817.  
  1818.         case GIMP_RGB:
  1819.           {
  1820.         IFDBG printf("It's RGB, %dx%d.\n",
  1821.                  psd_image.layer[lnum].width,
  1822.                  psd_image.layer[lnum].height);
  1823.         if (!psd_layer_has_alpha(&psd_image.layer[lnum]))
  1824.           {
  1825.             seek_to_and_unpack_pixeldata(fd, lnum, 0);
  1826.             seek_to_and_unpack_pixeldata(fd, lnum, 1);
  1827.             seek_to_and_unpack_pixeldata(fd, lnum, 2);
  1828.             merged_data =
  1829.               chans_to_RGB (psd_image.layer[lnum].channel[0].data,
  1830.                     psd_image.layer[lnum].channel[1].data,
  1831.                     psd_image.layer[lnum].channel[2].data,
  1832.                     psd_image.layer[lnum].width *
  1833.                     psd_image.layer[lnum].height);
  1834.  
  1835.             if (psd_image.layer[lnum].channel[0].data)
  1836.               g_free(psd_image.layer[lnum].channel[0].data);
  1837.             if (psd_image.layer[lnum].channel[1].data)
  1838.               g_free(psd_image.layer[lnum].channel[1].data);
  1839.             if (psd_image.layer[lnum].channel[2].data)
  1840.               g_free(psd_image.layer[lnum].channel[2].data);
  1841.  
  1842.             IFDBG
  1843.               fprintf(stderr, "YAH0a\n");
  1844.           }
  1845.         else
  1846.           {
  1847.             seek_to_and_unpack_pixeldata(fd, lnum, 0);
  1848.             seek_to_and_unpack_pixeldata(fd, lnum, 1);
  1849.             seek_to_and_unpack_pixeldata(fd, lnum, 2);
  1850.             seek_to_and_unpack_pixeldata(fd, lnum, 3);
  1851.             merged_data =
  1852.               chans_to_RGBA (psd_image.layer[lnum].channel[1].data,
  1853.                      psd_image.layer[lnum].channel[2].data,
  1854.                      psd_image.layer[lnum].channel[3].data,
  1855.                      psd_image.layer[lnum].channel[0].data,
  1856.                      psd_image.layer[lnum].width *
  1857.                      psd_image.layer[lnum].height);
  1858.  
  1859.             if (psd_image.layer[lnum].channel[0].data)
  1860.               g_free(psd_image.layer[lnum].channel[0].data);
  1861.             if (psd_image.layer[lnum].channel[1].data)
  1862.               g_free(psd_image.layer[lnum].channel[1].data);
  1863.             if (psd_image.layer[lnum].channel[2].data)
  1864.               g_free(psd_image.layer[lnum].channel[2].data);
  1865.             if (psd_image.layer[lnum].channel[3].data)
  1866.               g_free(psd_image.layer[lnum].channel[3].data);
  1867.  
  1868.             IFDBG
  1869.               fprintf(stderr, "YAH0b\n");
  1870.           }
  1871.           
  1872.         IFDBG
  1873.           fprintf(stderr, "YAH1\n");
  1874.  
  1875.         layer_ID = gimp_layer_new (image_ID,
  1876.                        psd_image.layer[lnum].name,
  1877.                        psd_image.layer[lnum].width,
  1878.                        psd_image.layer[lnum].height,
  1879.                        (numc==3) ? GIMP_RGB_IMAGE : GIMP_RGBA_IMAGE,
  1880.                        (100.0*(double)psd_image.layer[lnum].opacity)/255.0,
  1881.                        psd_lmode_to_gimp_lmode(psd_image.layer[lnum].blendkey));
  1882.         
  1883.         IFDBG
  1884.           fprintf(stderr, "YAH2\n");
  1885.  
  1886.           }; break; /* case GIMP_RGB */
  1887.  
  1888.         default:
  1889.           {
  1890.         printf("Error: Sorry, can't deal with a layered image of this type.\n");
  1891.         gimp_quit();
  1892.           }; break; /* default */
  1893.         }
  1894.  
  1895.       gimp_image_add_layer (image_ID, layer_ID, 0);
  1896.  
  1897.       IFDBG
  1898.         fprintf(stderr, "YAH3\n");
  1899.  
  1900.       /* Do a layer mask if it exists */
  1901.       for (iter=0; iter<psd_image.layer[lnum].num_channels; iter++)
  1902.         {
  1903.           if (psd_image.layer[lnum].channel[iter].type == -2) /* is mask */
  1904.         {
  1905.           gint32 mask_id;
  1906.           guchar* lm_data;
  1907.  
  1908.           IFDBG
  1909.             fprintf(stderr, "YAH3m\n");
  1910.  
  1911.           lm_data = xmalloc(psd_image.layer[lnum].width *
  1912.                     psd_image.layer[lnum].height);
  1913.           {
  1914.             seek_to_and_unpack_pixeldata(fd, lnum, iter);
  1915.             /* PS layer masks can be a different size to
  1916.                their owning layer, so we have to resize them. */
  1917.             resize_mask(psd_image.layer[lnum].channel[iter].data,
  1918.                 lm_data,
  1919.                 psd_image.layer[lnum].lm_x-
  1920.                 psd_image.layer[lnum].x,
  1921.                 psd_image.layer[lnum].lm_y-
  1922.                 psd_image.layer[lnum].y,
  1923.                 psd_image.layer[lnum].lm_width,
  1924.                 psd_image.layer[lnum].lm_height,
  1925.                 psd_image.layer[lnum].width,
  1926.                 psd_image.layer[lnum].height);
  1927.  
  1928.             /* won't be needing the original data any more */
  1929.             if (psd_image.layer[lnum].channel[iter].data)
  1930.               g_free(psd_image.layer[lnum].channel[iter].data);
  1931.  
  1932.             /* give it to GIMP */
  1933.             mask_id = gimp_layer_create_mask(layer_ID, 0);
  1934.             gimp_image_add_layer_mask(image_ID, layer_ID, mask_id);
  1935.             
  1936.             drawable = gimp_drawable_get (mask_id);
  1937.             
  1938.             gimp_pixel_rgn_init (&pixel_rgn, drawable,
  1939.                      0, 0, 
  1940.                      psd_image.layer[lnum].width,
  1941.                      psd_image.layer[lnum].height,
  1942.                      TRUE, FALSE);
  1943.             gimp_pixel_rgn_set_rect (&pixel_rgn,
  1944.                          lm_data,
  1945.                          0, 0, 
  1946.                          psd_image.layer[lnum].width,
  1947.                          psd_image.layer[lnum].height);
  1948.           }
  1949.           g_free(lm_data);
  1950.           
  1951.           gimp_drawable_flush (drawable);
  1952.           gimp_drawable_detach (drawable);
  1953.         }
  1954.         }
  1955.  
  1956.       IFDBG
  1957.         fprintf(stderr, "YAH4\n");
  1958.  
  1959.       gimp_layer_translate(layer_ID,
  1960.                    psd_image.layer[lnum].x,
  1961.                    psd_image.layer[lnum].y);
  1962.       
  1963.       gimp_layer_set_preserve_transparency(layer_ID, psd_image.layer[lnum].protecttrans);
  1964.       gimp_layer_set_visible(layer_ID, psd_image.layer[lnum].visible);
  1965.  
  1966.       drawable = gimp_drawable_get (layer_ID);
  1967.       
  1968.       IFDBG
  1969.         fprintf(stderr, "YAH5 - merged_data=%p, drawable=%p, drawdim=%dx%dx%d\n",
  1970.             merged_data,
  1971.             drawable,
  1972.             drawable->width,
  1973.             drawable->height,
  1974.             drawable->bpp);
  1975.  
  1976.       gimp_pixel_rgn_init (&pixel_rgn, drawable,
  1977.                    0, 0, 
  1978.                    psd_image.layer[lnum].width,
  1979.                    psd_image.layer[lnum].height,
  1980.                    TRUE, FALSE);
  1981.  
  1982.       gimp_pixel_rgn_set_rect (&pixel_rgn,
  1983.                    merged_data,
  1984.                    0, 0, 
  1985.                    psd_image.layer[lnum].width,
  1986.                    psd_image.layer[lnum].height);
  1987.       
  1988.       IFDBG
  1989.         fprintf(stderr, "YAH6\n");
  1990.  
  1991.       gimp_drawable_flush (drawable);
  1992.       gimp_drawable_detach (drawable);
  1993.       drawable = NULL;
  1994.       
  1995.       if (merged_data)
  1996.         g_free(merged_data);
  1997.  
  1998.       gimp_progress_update ((double)(lnum+1.0) /
  1999.                 (double)psd_image.num_layers);
  2000.     }
  2001.  
  2002.       fsetpos (fd, &tmpfpos);
  2003.     }
  2004.  
  2005.  
  2006.   if ((psd_image.num_aux_channels > 0) &&
  2007.       (psd_image.num_layers > 0))
  2008.     {
  2009.       want_aux = TRUE;
  2010.       IFDBG printf("::::::::::: WANT AUX :::::::::::::::::::::::::::::::::::::::\n");
  2011.     }
  2012.   else
  2013.     {
  2014.       want_aux = FALSE;
  2015.     }
  2016.  
  2017.  
  2018.   if (want_aux || (psd_image.num_layers==0)) /* Photoshop2-style: NO LAYERS. */
  2019.     {
  2020.       
  2021.       IFDBG printf("Image data %ld chars\n", PSDheader.imgdatalen);
  2022.  
  2023.       step = PSDheader.channels;
  2024.     
  2025.       imagetype = PSD_UNKNOWN_IMAGE;
  2026.      switch (PSDheader.mode)
  2027.     {
  2028.     case 0:        /* Bitmap */
  2029.       imagetype = PSD_BITMAP_IMAGE;
  2030.       break;
  2031.     case 1:        /* Grayscale */
  2032.       imagetype = PSD_GRAY_IMAGE;
  2033.       break;
  2034.     case 2:        /* Indexed Colour */
  2035.       imagetype = PSD_INDEXED_IMAGE;
  2036.       break;
  2037.     case 3:        /* RGB Colour */
  2038.       imagetype = PSD_RGB_IMAGE;
  2039.       break;
  2040.     case 4:        /* CMYK Colour */
  2041.       cmyk = 1;
  2042.       switch (PSDheader.channels)
  2043.         {
  2044.         case 4:
  2045.           imagetype = PSD_RGB_IMAGE;
  2046.           break;
  2047.         case 5:
  2048.           imagetype = PSD_RGBA_IMAGE;
  2049.           break;
  2050.         default:
  2051.           printf("%s: cannot handle CMYK with more than 5 channels\n",
  2052.              prog_name);
  2053.           return(-1);
  2054.           break;
  2055.         }
  2056.       break;
  2057.     case 7:        /* Multichannel (?) */
  2058.     case 8:        /* Duotone */
  2059.     case 9:        /* Lab Colour */
  2060.     default:
  2061.       break;
  2062.     }
  2063.  
  2064.  
  2065.       if (imagetype == PSD_UNKNOWN_IMAGE)
  2066.     {
  2067.       printf("%s: Image type %d (%s) is not supported in this data format\n",
  2068.          prog_name, PSDheader.mode,
  2069.          (PSDheader.mode > 10) ?
  2070.          "<out of range>" : modename[PSDheader.mode]);
  2071.  
  2072.       return(-1);
  2073.     }
  2074.  
  2075.       if ((PSDheader.bpp != 8) && (PSDheader.bpp != 1))
  2076.     {
  2077.       printf("%s: The GIMP only supports 8-bit or 1-bit deep PSD images "
  2078.          "at this time.\n",
  2079.          prog_name);
  2080.       return(-1);
  2081.     }
  2082.  
  2083.       IFDBG printf(
  2084.          "psd:%d gimp:%d gimpbase:%d\n",
  2085.          imagetype,
  2086.          psd_type_to_gimp_type(imagetype),
  2087.          psd_type_to_gimp_base_type(imagetype)
  2088.          );
  2089.  
  2090.  
  2091.       if (!want_aux)
  2092.     {
  2093.       image_ID = gimp_image_new (PSDheader.columns, PSDheader.rows,
  2094.                      psd_type_to_gimp_base_type(imagetype));
  2095.       gimp_image_set_filename (image_ID, name);
  2096.       if (psd_type_to_gimp_base_type(imagetype) == GIMP_INDEXED)
  2097.         {
  2098.           if ((psd_image.colmaplen%3)!=0)
  2099.         printf("PSD: Colourmap looks screwed! Aiee!\n");
  2100.           if (psd_image.colmaplen==0)
  2101.         printf("PSD: Indexed image has no colourmap!\n");
  2102.           if (psd_image.colmaplen!=768)
  2103.         printf("PSD: Warning: Indexed image is %ld!=256 colours.\n",
  2104.                psd_image.colmaplen/3);
  2105.           if (psd_image.colmaplen==768)
  2106.         {
  2107.           reshuffle_cmap(psd_image.colmapdata);
  2108.           gimp_image_set_cmap (image_ID,
  2109.                        psd_image.colmapdata,
  2110.                        256);
  2111.         }
  2112.         }
  2113.  
  2114.       layer_ID = gimp_layer_new (image_ID, _("Background"),
  2115.                      PSDheader.columns, PSDheader.rows,
  2116.                      psd_type_to_gimp_type(imagetype),
  2117.                      100, GIMP_NORMAL_MODE);
  2118.  
  2119.       g_free(name_buf);
  2120.  
  2121.       gimp_image_add_layer (image_ID, layer_ID, 0);
  2122.       drawable = gimp_drawable_get (layer_ID);
  2123.     
  2124.     }
  2125.  
  2126.     
  2127.       if (want_aux)
  2128.     {
  2129.       switch (PSDheader.mode)
  2130.         {
  2131.         case 1:        /* Grayscale */
  2132.           channels = 1;
  2133.           break;
  2134.         case 2:        /* Indexed Colour */
  2135.           channels = 1;
  2136.           break;
  2137.         case 3:        /* RGB Colour */
  2138.           channels = 3;
  2139.           break;
  2140.         default:
  2141.           printf("aux? Aieeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee!!!!!!!!!\n");
  2142.           channels = 1;
  2143.           break;
  2144.         }
  2145.       
  2146.       channels = PSDheader.channels - channels;
  2147.       
  2148.       if (psd_image.absolute_alpha)
  2149.         {
  2150.           channels--;
  2151.         }
  2152.     }
  2153.       else
  2154.     {
  2155.       channels = gimp_drawable_bpp(drawable->id);
  2156.     }
  2157.  
  2158.  
  2159.       dest = xmalloc( step * PSDheader.columns * PSDheader.rows );
  2160.  
  2161.       
  2162.       if (PSDheader.compression == 1)
  2163.     {
  2164.       nguchars = PSDheader.columns * PSDheader.rows;
  2165.       temp = xmalloc(PSDheader.imgdatalen);
  2166.       xfread(fd, temp, PSDheader.imgdatalen, "image data");
  2167.       if (!cmyk)
  2168.         {
  2169.           gimp_progress_update ((double)1.00);
  2170.           if(imagetype==PSD_BITMAP_IMAGE) /* convert bitmap to grayscale */
  2171.         {
  2172.           guchar *monobuf=(guchar *)xmalloc(PSDheader.columns*PSDheader.rows>>3);
  2173.           decode(PSDheader.imgdatalen,nguchars>>3,temp,monobuf,step);
  2174.           bitmap2gray(monobuf,dest,PSDheader.columns,PSDheader.rows);
  2175.           g_free((gpointer)monobuf);                    
  2176.         }
  2177.           else
  2178.         {
  2179.           decode(PSDheader.imgdatalen, nguchars, temp, dest, step);
  2180.         }
  2181.         }
  2182.       else
  2183.         {
  2184.           gimp_progress_update ((double)1.00);
  2185.           cmykbuf = xmalloc(step * nguchars);
  2186.           decode(PSDheader.imgdatalen, nguchars, temp, cmykbuf, step);
  2187.           
  2188.           cmyk2rgb(cmykbuf, dest, PSDheader.columns, PSDheader.rows,
  2189.                step > 4);
  2190.           g_free(cmykbuf);
  2191.         }
  2192.       g_free(temp);
  2193.     }
  2194.       else
  2195.     {
  2196.       if (!cmyk)
  2197.         {
  2198.           gimp_progress_update ((double)1.00);
  2199.           xfread_interlaced(fd, dest, PSDheader.imgdatalen,
  2200.                 "raw image data", step);
  2201.         }
  2202.       else
  2203.         {      
  2204.           gimp_progress_update ((double)1.00);
  2205.           cmykbuf = xmalloc(PSDheader.imgdatalen);
  2206.           xfread_interlaced(fd, cmykbuf, PSDheader.imgdatalen,
  2207.                 "raw cmyk image data", step);
  2208.  
  2209.           cmykp2rgb(cmykbuf, dest,
  2210.             PSDheader.columns, PSDheader.rows, step > 4);
  2211.           g_free(cmykbuf);
  2212.         }
  2213.     }
  2214.  
  2215.  
  2216.       if (want_aux) /* want_aux */
  2217.     {
  2218.       extract_channels(dest, channels, step,
  2219.                image_ID,
  2220.                PSDheader.columns, PSDheader.rows);
  2221.  
  2222.       goto finish_up; /* Haha!  Look!  A goto! */
  2223.     }
  2224.       else
  2225.     {
  2226.       gimp_progress_update ((double)1.00);
  2227.  
  2228.       if (channels == step) /* gimp bpp == psd bpp */
  2229.         {
  2230.  
  2231.           if (psd_type_to_gimp_type(imagetype)==GIMP_INDEXEDA_IMAGE)
  2232.         {
  2233.           printf("@@@@ Didn't know that this could happen...\n");
  2234.           for (iter=0; iter<drawable->width*drawable->height; iter++)
  2235.             {
  2236.               dest[iter*2+1] = 255;
  2237.             }
  2238.         }
  2239.       
  2240.           gimp_pixel_rgn_init (&pixel_rgn, drawable,
  2241.                    0, 0, drawable->width, drawable->height,
  2242.                    TRUE, FALSE);
  2243.           gimp_pixel_rgn_set_rect (&pixel_rgn, dest,
  2244.                        0, 0, drawable->width, drawable->height);
  2245.  
  2246.           gimp_drawable_flush (drawable);
  2247.           gimp_drawable_detach (drawable);
  2248.         }
  2249.       else
  2250.         {
  2251.           IFDBG printf("Uhhh... uhm... extra channels... heavy...\n");
  2252.       
  2253.           extract_data_and_channels(dest, channels, step,
  2254.                     image_ID, drawable,
  2255.                     drawable->width, drawable->height);      
  2256.         }
  2257.     }
  2258.  
  2259.  
  2260.  
  2261.     finish_up:
  2262.       
  2263.       g_free (dest);
  2264.       
  2265.       if (psd_image.colmaplen > 0)
  2266.     g_free(psd_image.colmapdata);
  2267.     }
  2268.  
  2269.   if (psd_image.num_guides > 0)
  2270.     {
  2271.       int i;
  2272.  
  2273.       IFDBG printf("--- Adding %d Guides\n", psd_image.num_guides);
  2274.  
  2275.       for (i=0; i<psd_image.num_guides; i++)
  2276.     {
  2277.       if (psd_image.guides[i].horizontal)
  2278.         gimp_image_add_hguide (image_ID, psd_image.guides[i].position);
  2279.       else
  2280.         gimp_image_add_vguide (image_ID, psd_image.guides[i].position);
  2281.     }
  2282.     }
  2283.  
  2284.   gimp_displays_flush();
  2285.  
  2286.   IFDBG printf("--- %d layers : pos %ld : a-alph %d ---\n",
  2287.      psd_image.num_layers, (long int)ftell(fd),
  2288.      psd_image.absolute_alpha);
  2289.  
  2290.   return(image_ID);
  2291. }
  2292.  
  2293.  
  2294.  
  2295. static void
  2296. decode(long clen, long uclen, char * src, char * dst, int step)
  2297. {
  2298.     gint i, j;
  2299.     gint32 l;
  2300.     gushort * w;
  2301.  
  2302.     l = clen;
  2303.     for (i = 0; i < PSDheader.rows*PSDheader.channels; ++i)
  2304.       {
  2305.     l -= PSDheader.rowlength[i];
  2306.       }
  2307.     if (l)
  2308.       {
  2309.     g_warning("decode: %ld should be zero\n", (long)l);
  2310.       }
  2311.  
  2312.     w = PSDheader.rowlength;
  2313.     
  2314.     packbitsdecode(&clen, uclen, src, dst++, step);
  2315.  
  2316.     for (j = 0; j < step-1; ++j)
  2317.       {
  2318.     for (i = 0; i < PSDheader.rows; ++i)
  2319.       {
  2320.         src += *w++;
  2321.       }
  2322.     packbitsdecode(&clen, uclen, src, dst++, step);
  2323.       }
  2324.  
  2325.     IFDBG printf("clen %ld\n", clen);
  2326. }
  2327.  
  2328.  
  2329.  
  2330. /*
  2331.  * Decode a PackBits data stream.
  2332.  */
  2333. static void
  2334. packbitsdecode(long * clenp, long uclen, char * src, char * dst, int step)
  2335. {
  2336.     gint n, b;
  2337.     gint32 clen = *clenp;
  2338.     
  2339.     while ((clen > 0) && (uclen > 0)) {
  2340.     n = (int) *src++;
  2341.     if (n >= 128)
  2342.         n -= 256;
  2343.     if (n < 0) {        /* replicate next guchar -n+1 times */
  2344.         clen -= 2;
  2345.         if (n == -128)    /* nop */
  2346.         continue;
  2347.         n = -n + 1;
  2348.         uclen -= n;
  2349.         for (b = *src++; n > 0; --n) {
  2350.         *dst = b;
  2351.         dst += step;
  2352.         }
  2353.     } else {        /* copy next n+1 guchars literally */
  2354.         for (b = ++n; b > 0; --b) {
  2355.         *dst = *src++;
  2356.         dst += step;
  2357.         }
  2358.         uclen -= n;
  2359.         clen -= n+1;
  2360.     }
  2361.     }
  2362.     if (uclen > 0) {
  2363.     printf("%s: unexpected EOF while reading image data\n", prog_name);
  2364.     gimp_quit();
  2365.     }
  2366.     *clenp = clen;
  2367. }
  2368.  
  2369.  
  2370.  
  2371. /*
  2372.  * Decode a PackBits channel from file.
  2373.  */
  2374. static void
  2375. unpack_pb_channel(FILE *fd, guchar *dst, gint32 unpackedlen, guint32 *offset)
  2376. {
  2377.     int n, b;
  2378.     gint32 upremain = unpackedlen;
  2379.  
  2380.     while (upremain > 0)
  2381.       {
  2382.     (*offset)++;
  2383.     n = (int) getguchar(fd, "packbits1");
  2384.  
  2385.     if (n >= 128)
  2386.       n -= 256;
  2387.     if (n < 0)
  2388.       {        /* replicate next guchar -n+1 times */
  2389.         if (n == -128)    /* nop */
  2390.           continue;
  2391.         n = -n + 1;
  2392.         /*        upremain -= n;*/
  2393.  
  2394.         b = getguchar(fd, "packbits2");
  2395.         (*offset)++;
  2396.         for (; n > 0; --n)
  2397.           {
  2398.         *dst = b;
  2399.         dst ++;
  2400.         upremain--;
  2401.           }
  2402.       }
  2403.     else
  2404.       {        /* copy next n+1 guchars literally */
  2405.         for (b = ++n; b > 0; --b)
  2406.           {
  2407.         *dst = getguchar(fd, "packbits3");;
  2408.         (*offset)++;
  2409.         dst ++;
  2410.         upremain--;
  2411.           }
  2412.         /*        upremain -= n;*/
  2413.       }
  2414.       }
  2415.  
  2416.     if (upremain < 0)
  2417.       {
  2418.     printf("*** Unpacking overshot destination (%d) buffer by %d bytes!\n",
  2419.            unpackedlen,
  2420.            -upremain);
  2421.       }
  2422. }
  2423.  
  2424. static void
  2425. cmyk2rgb(unsigned char * src, unsigned char * dst,
  2426.      long width, long height, int alpha)
  2427. {
  2428.     int r, g, b, k;
  2429.     int i, j;
  2430.  
  2431.  
  2432.     for (i = 0; i < height; i++) {
  2433.     for (j = 0; j < width; j++) {
  2434.         r = *src++;
  2435.         g = *src++;
  2436.         b = *src++;
  2437.         k = *src++;
  2438.  
  2439.         cmyk_to_rgb (&r, &g, &b, &k);
  2440.       
  2441.         *dst++ = r;
  2442.         *dst++ = g;
  2443.         *dst++ = b;
  2444.  
  2445.         if (alpha)
  2446.         *dst++ = *src++;
  2447.     }
  2448.     if ((i % 5) == 0)
  2449.         gimp_progress_update ((double)(2.0*(double)height)/((double)height+(double)i));
  2450.     }
  2451. }
  2452.  
  2453.  
  2454. /*
  2455.  * Decode planar CMYK(A) to RGB(A).
  2456.  */
  2457. static void
  2458. cmykp2rgb(unsigned char * src, unsigned char * dst,
  2459.       long width, long height, int alpha)
  2460. {
  2461.     int r, g, b, k;
  2462.     int i, j;
  2463.     long n;
  2464.     char *rp, *gp, *bp, *kp, *ap;
  2465.  
  2466.     n = width * height;
  2467.     rp = src;
  2468.     gp = rp + n;
  2469.     bp = gp + n;
  2470.     kp = bp + n;
  2471.     ap = kp + n;
  2472.     
  2473.     for (i = 0; i < height; i++) {
  2474.     for (j = 0; j < width; j++) {
  2475.         r = *rp++;
  2476.         g = *gp++;
  2477.         b = *bp++;
  2478.         k = *kp++;
  2479.  
  2480.         cmyk_to_rgb (&r, &g, &b, &k);
  2481.       
  2482.         *dst++ = r;
  2483.         *dst++ = g;
  2484.         *dst++ = b;
  2485.  
  2486.         if (alpha)
  2487.         *dst++ = *ap++;
  2488.     }
  2489.     if ((i % 5) == 0)
  2490.       gimp_progress_update ((double)(2.0*(double)height)/((double)height+(double)i));
  2491.     }
  2492. }
  2493.  
  2494.  
  2495. static void
  2496. cmyk_to_rgb(gint *c, gint *m, gint *y, gint *k)
  2497. {
  2498. #if 0
  2499.     gint cyan, magenta, yellow, black;
  2500.  
  2501.     cyan = *c;
  2502.     magenta = *m;
  2503.     yellow = *y;
  2504.     black = *k;
  2505.  
  2506.     if (black > 0) {
  2507.     cyan -= black;
  2508.     magenta -= black;
  2509.     yellow -= black;
  2510.     }
  2511.     *c = 255 - cyan;
  2512.     *m = 255 - magenta;
  2513.     *y = 255 - yellow;
  2514.     if (*c < 0) *c = 0; else if (*c > 255) *c = 255;
  2515.     if (*m < 0) *m = 0; else if (*m > 255) *m = 255;
  2516.     if (*y < 0) *y = 0; else if (*y > 255) *y = 255;
  2517. #endif
  2518. }
  2519.  
  2520.  
  2521. static void
  2522. bitmap2gray(guchar *src,guchar *dest,long w,long h)
  2523. {
  2524.   int i,j;
  2525.   for(i=0;i<h;i++)
  2526.     {
  2527.       int mask=0x80;
  2528.       for(j=0;j<w;j++)
  2529.     {
  2530.       *dest++=(*src&mask)?0:255;
  2531.       mask>>=1;
  2532.       if(!mask)
  2533.         {
  2534.           src++;
  2535.           mask=0x80;
  2536.         }
  2537.     }
  2538.       if(mask!=0x80) src++;
  2539.     }
  2540. }
  2541.  
  2542.  
  2543. static void
  2544. dumpchunk(size_t n, FILE * fd, gchar *why)
  2545. {
  2546.   guint32 i;
  2547.  
  2548.   printf("\n");
  2549.  
  2550.   for (i=0;i<n;i++)
  2551.     {
  2552.       printf("%02x ",(int)getguchar(fd, why));
  2553.     }
  2554.  
  2555.   printf("\n");
  2556. }
  2557.  
  2558.  
  2559. static void
  2560. throwchunk(size_t n, FILE * fd, gchar *why)
  2561. {
  2562. #if 0
  2563.   guchar *tmpchunk;
  2564.  
  2565.   if (n==0)
  2566.     {
  2567.       return;
  2568.     }
  2569.  
  2570.   tmpchunk = xmalloc(n);
  2571.   xfread(fd, tmpchunk, n, why);
  2572.   g_free(tmpchunk);
  2573. #else
  2574.   if (n==0)
  2575.     {
  2576.       return;
  2577.     }
  2578.  
  2579.   if (fseek(fd, n, SEEK_CUR) != 0)
  2580.     {
  2581.       printf("%s: unable to seek forward while reading '%s' chunk\n",
  2582.          prog_name, why);
  2583.       gimp_quit();
  2584.     }    
  2585. #endif
  2586. }
  2587.  
  2588.  
  2589. static gchar *
  2590. getstring(size_t n, FILE * fd, gchar *why)
  2591. {
  2592.   gchar *tmpchunk;
  2593.  
  2594.   tmpchunk = xmalloc(n+1);
  2595.   xfread(fd, tmpchunk, n, why);
  2596.   tmpchunk[n]=0;
  2597.  
  2598.   return(tmpchunk);  /* caller should free memory */
  2599. }
  2600.  
  2601.  
  2602. static guchar *
  2603. getpascalstring(FILE *fd, gchar *why)
  2604. {
  2605.   guchar *tmpchunk;
  2606.   guchar len;
  2607.  
  2608.   xfread(fd, &len, 1, why);
  2609.  
  2610.   if (len==0)
  2611.     {
  2612.       return (NULL);
  2613.     }
  2614.  
  2615.   tmpchunk = xmalloc(len+1);
  2616.  
  2617.   xfread(fd, tmpchunk, len, why);
  2618.   tmpchunk[len]=0;
  2619.   
  2620.   return(tmpchunk); /* caller should free memory */
  2621. }
  2622.  
  2623.  
  2624. static guchar
  2625. getguchar(FILE *fd, gchar *why)
  2626. {
  2627.   gint tmp;
  2628.  
  2629.   tmp = fgetc(fd);
  2630.  
  2631.   if (tmp == EOF)
  2632.     {
  2633.       printf("%s: unexpected EOF while reading '%s' chunk\n",
  2634.          prog_name, why);
  2635.       gimp_quit();
  2636.     }
  2637.  
  2638.   return(tmp);
  2639. }
  2640.  
  2641.  
  2642. static gshort
  2643. getgshort(FILE *fd, gchar *why)
  2644. {
  2645.   gushort w;
  2646.   guchar b1, b2;
  2647.   
  2648.   b1 = getguchar(fd, why);
  2649.   b2 = getguchar(fd, why);
  2650.   
  2651.   w = (b1*256) + b2;
  2652.   
  2653.   return ((gshort) w);
  2654. }
  2655.  
  2656.  
  2657. static glong
  2658. getglong(FILE *fd, gchar *why)
  2659. {
  2660.   unsigned char s1, s2, s3, s4;
  2661.   gulong w;
  2662.  
  2663.   s1 = getguchar(fd, why);
  2664.   s2 = getguchar(fd, why);
  2665.   s3 = getguchar(fd, why);
  2666.   s4 = getguchar(fd, why);
  2667.   
  2668.   w = (s1*256*256*256) + (s2*256*256) + (s3*256) + s4;
  2669.   
  2670.   return (glong) w;
  2671. }
  2672.  
  2673.  
  2674. static void
  2675. xfread(FILE * fd, void * buf, long len, gchar *why)
  2676. {
  2677.   if (fread(buf, len, 1, fd) == 0)
  2678.     {
  2679.       printf("%s: unexpected EOF while reading '%s' chunk\n",
  2680.          prog_name, why);
  2681.       gimp_quit();
  2682.     }
  2683. }
  2684.  
  2685.           
  2686. static void
  2687. xfread_interlaced(FILE* fd, guchar* buf, long len, gchar *why, gint step)
  2688. {
  2689.   guchar* dest;
  2690.   gint pix, pos, bpplane;
  2691.  
  2692.   bpplane = len/step;
  2693.  
  2694.   if (len%step != 0)
  2695.     {
  2696.       printf("PSD: Stern warning: data size is not a factor of step size!\n");
  2697.     }
  2698.  
  2699.   for (pix=0; pix<step; pix++)
  2700.     {
  2701.       dest = buf + pix;
  2702.  
  2703.       for (pos=0; pos<bpplane; pos++)
  2704.     {
  2705.       *dest = getguchar(fd, why);
  2706.       dest += step;
  2707.     }
  2708.     }
  2709. }
  2710.  
  2711.  
  2712. static void *
  2713. xmalloc(size_t n)
  2714. {
  2715.   void *p;
  2716.   
  2717.   if (n == 0)
  2718.     {
  2719.       IFDBG
  2720.     printf("PSD: WARNING: %s: xmalloc asked for zero-sized chunk\n",
  2721.            prog_name);
  2722.       
  2723.       return (NULL);
  2724.     }
  2725.   
  2726.   if ((p = g_malloc(n)) != NULL)
  2727.     return p;
  2728.   
  2729.   printf("%s: out of memory\n", prog_name);
  2730.   gimp_quit();
  2731.   return NULL;
  2732. }
  2733.  
  2734.  
  2735. static void
  2736. read_whole_file(FILE * fd)
  2737. {
  2738.     guint16 w;
  2739.     gint32 pos;
  2740.     gchar dummy[6];
  2741.     gint i;
  2742.     
  2743.     xfread(fd, &PSDheader.signature, 4, "signature");
  2744.     PSDheader.version = getgshort(fd, "version");
  2745.     xfread(fd, &dummy, 6, "reserved");
  2746.     PSDheader.channels = getgshort(fd, "channels");
  2747.     PSDheader.rows = getglong(fd, "rows");
  2748.     PSDheader.columns = getglong(fd, "columns");
  2749.     PSDheader.bpp = getgshort(fd, "depth");
  2750.     PSDheader.mode = getgshort(fd, "mode");
  2751.  
  2752.  
  2753.     psd_image.num_layers = 0;
  2754.     psd_image.type = PSDheader.mode;
  2755.     psd_image.colmaplen = 0;
  2756.     psd_image.num_aux_channels = 0;
  2757.     psd_image.num_guides = 0;
  2758.  
  2759.  
  2760.     psd_image.colmaplen = getglong(fd, "color data length");
  2761.  
  2762.     if (psd_image.colmaplen > 0)
  2763.       {
  2764.     psd_image.colmapdata = xmalloc(psd_image.colmaplen);
  2765.     xfread(fd, psd_image.colmapdata, psd_image.colmaplen, "colormap");
  2766.       }
  2767.  
  2768.  
  2769.     PSDheader.imgreslen = getglong(fd, "image resource length");
  2770.     if (PSDheader.imgreslen > 0)
  2771.       {
  2772.     do_image_resources(fd);
  2773.       }
  2774.  
  2775.  
  2776.     PSDheader.miscsizelen = getglong(fd, "misc size data length");
  2777.     if (PSDheader.miscsizelen > 0)
  2778.       {
  2779.     do_layer_and_mask(fd);
  2780.       }
  2781.  
  2782.  
  2783.     PSDheader.compression = getgshort(fd, "compression");
  2784.     IFDBG printf("<<compr:%d>>", (int)PSDheader.compression);
  2785.     if (PSDheader.compression == 1) /* RLE */
  2786.       {
  2787.     PSDheader.rowlength = xmalloc(PSDheader.rows *
  2788.                       PSDheader.channels * sizeof(gushort));
  2789.     for (i = 0; i < PSDheader.rows*PSDheader.channels; ++i)
  2790.       PSDheader.rowlength[i] = getgshort(fd, "x");
  2791.       }
  2792.     pos = ftell(fd);
  2793.     fseek(fd, 0, SEEK_END);
  2794.     PSDheader.imgdatalen = ftell(fd)-pos;
  2795.     fseek(fd, pos, SEEK_SET);
  2796.  
  2797.  
  2798.     if (strncmp(PSDheader.signature, "8BPS", 4) != 0)
  2799.       {
  2800.     printf("%s: not an Adobe Photoshop PSD file\n", prog_name);
  2801.     gimp_quit();
  2802.       }
  2803.     if (PSDheader.version != 1)
  2804.       {
  2805.     printf("%s: bad version number '%d', not 1\n",
  2806.            prog_name, PSDheader.version);
  2807.     gimp_quit();
  2808.       }
  2809.     w = PSDheader.mode;
  2810.     IFDBG printf("HEAD:\n"
  2811.        "\tChannels %d\n\tRows %ld\n\tColumns %ld\n\tDepth %d\n\tMode %d (%s)\n"
  2812.        "\tColour data %ld guchars\n",
  2813.        PSDheader.channels, PSDheader.rows,
  2814.        PSDheader.columns, PSDheader.bpp,
  2815.        w, modename[w < 10 ? w : 10],
  2816.        psd_image.colmaplen);
  2817.     /*    printf("\tImage resource length: %lu\n", PSDheader.imgreslen);*/
  2818.     IFDBG printf("\tLayer/Mask Data length: %lu\n", PSDheader.miscsizelen);
  2819.     w = PSDheader.compression;
  2820.     IFDBG printf("\tCompression %d (%s)\n", w, w ? "RLE" : "raw");
  2821. }
  2822.