home *** CD-ROM | disk | FTP | other *** search
/ ftp.sunet.sepub/pictures / 2014.11.ftp.sunet.se-pictures.tar / ftp.sunet.se / pub / pictures / ACiD-artpacks / programs / unix / editors / gimp-plugins-unstable-0_99_23_tar.gz / gimp-plugins-unstable-0_99_23_tar / gimp-plugins-unstable-0.99.23 / psd / psd.c < prev   
C/C++ Source or Header  |  1998-02-20  |  40KB  |  1,761 lines

  1.  
  2. /*
  3.  * NOTE: This plugin is not currently in very good working order.  There
  4.  * are big pieces of code missing.  I am aware of this.  :)  And it
  5.  * would probably take longer for you to understand the code and finish it
  6.  * than wait for me to do so.  :)  Nonetheless, if you do spot an obviously
  7.  * grubby bug before I make a 'real' release then feel free to send a patch.
  8.  *
  9.  * In the meantime, I don't think that this will crash very often, but you'll
  10.  * often get some strange results.
  11.  * 
  12.  *   -adam 97/03/16
  13.  */
  14.  
  15. /*
  16.  * This GIMP plug-in is designed to load Photoshop(tm) files (.PSD)
  17.  *
  18.  * Plug-in maintainer: Adam D. Moss <adam@foxbox.org>
  19.  *     If this plug-in fails to load a file which you think it should,
  20.  *     please tell me what seemed to go wrong, and anything you know
  21.  *     about the image you tried to load.  Please don't send big PSD
  22.  *     files to me without asking first.
  23.  *
  24.  * Copyright (C) 1997 Adam D. Moss
  25.  * Copyright (C) 1996 Torsten Martinsen
  26.  * Portions Copyright (C) 1995 Peter Mattis
  27.  *
  28.  * This program is free software; you can redistribute it and/or modify
  29.  * it under the terms of the GNU General Public License as published by
  30.  * the Free Software Foundation; either version 2 of the License, or
  31.  * (at your option) any later version.
  32.  *
  33.  * This program is distributed in the hope that it will be useful,
  34.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  35.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  36.  * GNU General Public License for more details.
  37.  *
  38.  * You should have received a copy of the GNU General Public License
  39.  * along with this program; if not, write to the Free Software
  40.  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  41.  */
  42.  
  43. /*
  44.  * Adobe and Adobe Photoshop are trademarks of Adobe Systems
  45.  * Incorporated that may be registered in certain jurisdictions.
  46.  */
  47.  
  48. /*
  49.  * TODO:
  50.  *    Make CMYK -> RGB conversion work
  51.  *    Better progress indicators
  52.  *    Load BITMAP mode
  53.  *      File saving
  54.  */
  55.  
  56. /*
  57.  * Revision history:
  58.  *
  59.  *  97.03.13 / v1.9.0 / Adam D. Moss
  60.  *       Layers, channels and masks, oh my.
  61.  *       Bugfixes, rearchitecturing(!).
  62.  *
  63.  *  97.01.30 / v1.0.12 / Torsten Martinsen
  64.  *       Flat image loading.
  65.  */
  66.  
  67.  
  68. /* *** DEFINES *** */
  69. /* the max number of layers that this plugin should try to load */
  70. #define MAX_LAYERS 180
  71.  
  72. /* the max number of channels that this plugin should let a layer have */
  73. #define MAX_CHANNELS 40
  74.  
  75. /* *** END OF DEFINES *** */
  76. /* Ideally the above defines wouldn't be necessary because the lists of
  77.  * channels and layers would be dynamic/linked, but:
  78.  *
  79.  * a) We don't necessarily know any limits that may be defined within
  80.  *      GIMP itself
  81.  *
  82.  * b) K.I.S.S.
  83.  *
  84.  */
  85.  
  86.  
  87. #include <stdio.h>
  88. #include <stdlib.h>
  89. #include <string.h>
  90. /*#include <endian.h>*/
  91. #include "gtk/gtk.h"
  92. #include "libgimp/gimp.h"
  93.  
  94.  
  95. /* Local types etc
  96.  */
  97. typedef enum
  98. {
  99.   PSD_UNKNOWN_IMAGE,
  100.   PSD_RGB_IMAGE,
  101.   PSD_RGBA_IMAGE,
  102.   PSD_GRAY_IMAGE,
  103.   PSD_GRAYA_IMAGE,
  104.   PSD_INDEXED_IMAGE,
  105.   PSD_INDEXEDA_IMAGE
  106. } psd_imagetype;
  107.  
  108.  
  109.  
  110. /* Declare some local functions.
  111.  */
  112. static void   query      (void);
  113. static void   run        (char    *name,
  114.                           int      nparams,
  115.                           GParam  *param,
  116.                           int     *nreturn_vals,
  117.                           GParam **return_vals);
  118. GDrawableType psd_type_to_gimp_type
  119.                          (psd_imagetype psdtype);
  120. GImageType psd_type_to_gimp_base_type
  121.                          (psd_imagetype psdtype);
  122. GLayerMode psd_lmode_to_gimp_lmode
  123.                          (gchar modekey[4]);
  124. static gint32 load_image (char   *filename);
  125.  
  126.  
  127.  
  128. GPlugInInfo PLUG_IN_INFO =
  129. {
  130.   NULL,    /* init_proc */
  131.   NULL,    /* quit_proc */
  132.   query,   /* query_proc */
  133.   run,     /* run_proc */
  134. };
  135.  
  136.  
  137.  
  138. typedef struct PsdChannel
  139. {
  140.   gchar *name;
  141.   guchar *data;
  142.   gint type;
  143.  
  144.   guint32 compressedsize;
  145.   
  146. } PSDchannel;
  147.  
  148.  
  149.  
  150. typedef struct PsdLayer
  151. {
  152.   gint num_channels;
  153.   PSDchannel channel[MAX_CHANNELS];
  154.   
  155.   gint32 x;
  156.   gint32 y;
  157.   guint32 width;
  158.   guint32 height;
  159.   
  160.   gchar blendkey[4];
  161.   guchar opacity;
  162.   gchar clipping;
  163.  
  164.   gboolean protecttrans;
  165.   gboolean visible;
  166.  
  167. } PSDlayer;
  168.  
  169.  
  170.  
  171. typedef struct PsdImage
  172. {
  173.   gint num_layers;
  174.   PSDlayer layer[MAX_LAYERS];
  175.  
  176.   gboolean absolute_alpha;
  177.  
  178.   gint type;
  179.   
  180.   gulong colmaplen;
  181.   guchar *colmapdata;
  182.  
  183.   guint num_aux_channels;
  184.   PSDchannel aux_channel[MAX_CHANNELS];
  185.  
  186.   gchar *caption;
  187.  
  188.   guint active_layer_num;
  189.  
  190. } PSDimage;
  191.  
  192.  
  193.  
  194. static PSDimage psd_image;
  195.  
  196.  
  197.  
  198. static struct {
  199.     guchar signature[4];
  200.     gushort version;
  201.     guchar reserved[6];
  202.     gushort channels;
  203.     gulong rows;
  204.     gulong columns;
  205.     gushort bpp;
  206.     gushort mode;
  207.     gulong imgreslen;
  208.     gulong miscsizelen;
  209.     gushort compression;
  210.     gushort * rowlength;
  211.     long  imgdatalen;
  212. } PSDheader;
  213.  
  214.  
  215. static gchar * modename[] = {
  216.     "Bitmap", 
  217.     "Grayscale", 
  218.     "Indexed Colour", 
  219.     "RGB Colour", 
  220.     "CMYK Colour", 
  221.     "<invalid>", 
  222.     "<invalid>", 
  223.     "Multichannel", 
  224.     "Duotone", 
  225.     "Lab Colour", 
  226.     "<invalid>"
  227. };
  228.  
  229.  
  230. static const gchar *prog_name = "PSD";
  231.  
  232.  
  233. static void unpack_pb_channel(FILE *fd, guchar *dst, gint32 unpackedlen,
  234.                   guint32 *offset);
  235. static void decode(long clen, long uclen, gchar *src, gchar *dst, int step);
  236. static void packbitsdecode(long *clenp, long uclen,
  237.                gchar *src, gchar *dst, int step);
  238. static void cmyk2rgb(guchar *src, guchar *destp,
  239.              long width, long height, int alpha);
  240. static void cmykp2rgb(guchar *src, guchar *destp,
  241.               long width, long height, int alpha);
  242. static void cmyk_to_rgb(int *c, int *m, int *y, int *k);
  243. static guchar getguchar(FILE *fd, gchar *why);
  244. static gshort getgshort(FILE *fd, gchar *why);
  245. static gulong getglong(FILE *fd, gchar *why);
  246. static void xfread(FILE *fd, void *buf, long len, gchar *why);
  247. static void *xmalloc(size_t n);
  248. static void read_whole_file(FILE *fd);
  249. static void reshuffle_cmap(guchar *map256);
  250. static guchar *getpascalstring(FILE *fd, guchar *why);
  251. void throwchunk(size_t n, FILE * fd, guchar *why);
  252. void dumpchunk(size_t n, FILE * fd, guchar *why);
  253.  
  254.  
  255. MAIN ()
  256.  
  257. static void
  258. query ()
  259. {
  260.   static GParamDef load_args[] =
  261.   {
  262.     { PARAM_INT32, "run_mode", "Interactive, non-interactive" },
  263.     { PARAM_STRING, "filename", "The name of the file to load" },
  264.     { PARAM_STRING, "raw_filename", "The name of the file to load" },
  265.   };
  266.   static GParamDef load_return_vals[] =
  267.   {
  268.     { PARAM_IMAGE, "image", "Output image" },
  269.   };
  270.   static int nload_args = sizeof (load_args) / sizeof (load_args[0]);
  271.   static int nload_return_vals = sizeof (load_return_vals) / sizeof (load_return_vals[0]);
  272.  
  273.   /*  static GParamDef save_args[] =
  274.   {
  275.     { PARAM_INT32, "run_mode", "Interactive, non-interactive" },
  276.     { PARAM_IMAGE, "image", "Input image" },
  277.     { PARAM_DRAWABLE, "drawable", "Drawable to save" },
  278.     { PARAM_STRING, "filename", "The name of the file to save the image in" },
  279.     { PARAM_STRING, "raw_filename", "The name of the file to save the image in" },
  280.     { PARAM_INT32, "compression", "Compression type: { NONE (0), LZW (1), PACKBITS (2)" },
  281.     { PARAM_INT32, "fillorder", "Fill Order: { MSB to LSB (0), LSB to MSB (1)" }
  282.   };
  283.   static int nsave_args = sizeof (save_args) / sizeof (save_args[0]);*/
  284.  
  285.   gimp_install_procedure ("file_psd_load",
  286.                           "loads files of the Photoshop(tm) PSD file format",
  287.                           "FIXME: write help for psd_load",
  288.                           "Adam D. Moss & Torsten Martinsen",
  289.                           "Adam D. Moss & Torsten Martinsen",
  290.                           "1996-1997",
  291.                           "<Load>/PSD",
  292.               NULL,
  293.                           PROC_PLUG_IN,
  294.                           nload_args, nload_return_vals,
  295.                           load_args, load_return_vals);
  296.  
  297.   /*  gimp_install_procedure ("file_psd_save",
  298.                           "saves files in the Photoshop(tm) PSD file format",
  299.                           "FIXME: write help for psd_save",
  300.                           "Adam D. Moss & Torsten Martinsen",
  301.                           "Adam D. Moss & Torsten Martinsen",
  302.                           "1996-1997",
  303.                           "<Save>/PSD",
  304.               "RGB, GRAY, INDEXED",
  305.                           PROC_PLUG_IN,
  306.                           nsave_args, 0,
  307.                           save_args, NULL);*/
  308.  
  309.   gimp_register_load_handler ("file_psd_load", "psd", "");
  310.   /*  gimp_register_save_handler ("file_psd_save", "psd", "");*/
  311. }
  312.  
  313.  
  314.  
  315. static void
  316. run (char    *name,
  317.      int      nparams,
  318.      GParam  *param,
  319.      int     *nreturn_vals,
  320.      GParam **return_vals)
  321. {
  322.   static GParam values[2];
  323.   GRunModeType run_mode;
  324.   /*  GStatusType status = STATUS_SUCCESS;*/
  325.   gint32 image_ID;
  326.  
  327.   run_mode = param[0].data.d_int32;
  328.  
  329.   *nreturn_vals = 1;
  330.   *return_vals = values;
  331.   values[0].type = PARAM_STATUS;
  332.   values[0].data.d_status = STATUS_CALLING_ERROR;
  333.  
  334.   if (strcmp (name, "file_psd_load") == 0)
  335.     {
  336.       image_ID = load_image (param[1].data.d_string);
  337.  
  338.       if (image_ID != -1)
  339.     {
  340.       *nreturn_vals = 2;
  341.       values[0].data.d_status = STATUS_SUCCESS;
  342.       values[1].type = PARAM_IMAGE;
  343.       values[1].data.d_image = image_ID;
  344.     }
  345.       else
  346.     {
  347.       values[0].data.d_status = STATUS_EXECUTION_ERROR;
  348.     }
  349.     }
  350. }
  351.  
  352.  
  353. GDrawableType
  354. psd_type_to_gimp_type (psd_imagetype psdtype)
  355. {
  356.   switch(psdtype)
  357.     {
  358.     case PSD_RGBA_IMAGE: return(RGBA_IMAGE);
  359.     case PSD_RGB_IMAGE: return(RGB_IMAGE);
  360.     case PSD_GRAYA_IMAGE: return(GRAYA_IMAGE);
  361.     case PSD_GRAY_IMAGE: return(GRAY_IMAGE);
  362.     case PSD_INDEXEDA_IMAGE: return(INDEXEDA_IMAGE);
  363.     case PSD_INDEXED_IMAGE: return(INDEXED_IMAGE);
  364.     default: return(RGB_IMAGE);
  365.     }
  366. }
  367.  
  368.  
  369.  
  370. GLayerMode
  371. psd_lmode_to_gimp_lmode (gchar modekey[4])
  372. {
  373.   if (strncmp(modekey, "norm", 4)==0) return(NORMAL_MODE);
  374.   if (strncmp(modekey, "dark", 4)==0) return(DARKEN_ONLY_MODE);
  375.   if (strncmp(modekey, "lite", 4)==0) return(LIGHTEN_ONLY_MODE);
  376.   if (strncmp(modekey, "hue ", 4)==0) return(HUE_MODE);
  377.   if (strncmp(modekey, "sat ", 4)==0) return(SATURATION_MODE);
  378.   if (strncmp(modekey, "colr", 4)==0) return(COLOR_MODE);
  379.   if (strncmp(modekey, "mul ", 4)==0) return(MULTIPLY_MODE);
  380.   if (strncmp(modekey, "scrn", 4)==0) return(SCREEN_MODE);
  381.   if (strncmp(modekey, "diss", 4)==0) return(DISSOLVE_MODE);
  382.   if (strncmp(modekey, "diff", 4)==0) return(DIFFERENCE_MODE);
  383.   
  384.   printf("PSD: Warning - unsupported layer-blend mode, reverting to 'normal'\n");
  385.   if (strncmp(modekey, "lum ", 4)==0) return(/**/NORMAL_MODE);
  386.   if (strncmp(modekey, "over", 4)==0) return(/****/NORMAL_MODE);
  387.   if (strncmp(modekey, "hLit", 4)==0) return(/**/NORMAL_MODE);
  388.   if (strncmp(modekey, "sLit", 4)==0) return(/**/NORMAL_MODE);
  389.   printf("PSD: Warning - UNKNOWN layer-blend mode, reverting to 'normal'\n");
  390.   return(NORMAL_MODE);
  391. }
  392.  
  393.  
  394.  
  395. GImageType
  396. psd_type_to_gimp_base_type (psd_imagetype psdtype)
  397. {
  398.   switch(psdtype)
  399.     {
  400.     case PSD_RGBA_IMAGE:
  401.     case PSD_RGB_IMAGE: return(RGB);
  402.     case PSD_GRAYA_IMAGE:
  403.     case PSD_GRAY_IMAGE: return(GRAY);
  404.     case PSD_INDEXEDA_IMAGE:
  405.     case PSD_INDEXED_IMAGE: return(INDEXED);
  406.     default:
  407.       printf("PSD: Can't convert PSD imagetype to GIMP imagetype\n");
  408.       return(RGB);
  409.     }
  410. }
  411.  
  412.  
  413.  
  414. static void
  415. reshuffle_cmap(guchar *map256)
  416. {
  417.   guchar *tmpmap;
  418.   int i;
  419.  
  420.   tmpmap = xmalloc(768);
  421.  
  422.   for (i=0;i<256;i++)
  423.     {
  424.       tmpmap[i*3  ] = map256[i];
  425.       tmpmap[i*3+1] = map256[i+256];
  426.       tmpmap[i*3+2] = map256[i+512];
  427.     }
  428.  
  429.   for (i=0;i<768;i++)
  430.     {
  431.       map256[i] = tmpmap[i];
  432.     }
  433.  
  434.   free(tmpmap);
  435. }
  436.  
  437.  
  438.  
  439. static void
  440. dispatch_resID(guint ID, FILE *fd, guint32 *offset, guint32 Size)
  441. {
  442.   if ( (ID < 0x0bb6) && (ID >0x07d0) )
  443.     {
  444.       printf ("\t\tPath data is irrelevant to GIMP at this time.\n");
  445.       throwchunk(Size, fd, "dispatch_res path throw");
  446.       *offset += Size;
  447.     }
  448.   else
  449.     switch (ID)
  450.       {
  451.       case 0x03ee:
  452.     {
  453.       gint32 remaining = Size;
  454.       
  455.       printf ("\t\tALPHA CHANNEL NAMES:\n");
  456.       while (remaining > 1)
  457.         {
  458.           guint32 alpha_name_len;
  459.           
  460.           psd_image.aux_channel[psd_image.num_aux_channels].name =
  461.         getpascalstring(fd, "alpha channel name");
  462.  
  463.           alpha_name_len =
  464.         strlen(psd_image.aux_channel[psd_image.num_aux_channels].name);
  465.           
  466.           printf("\t\t\tname: \"%s\"\n",
  467.              psd_image.aux_channel[psd_image.num_aux_channels].name);
  468.  
  469.           psd_image.num_aux_channels++;
  470.           
  471.           *offset   += alpha_name_len+1;
  472.           remaining -= alpha_name_len+1;
  473.         }
  474.       throwchunk(remaining, fd, "alphaname padding 0 throw");
  475.     }
  476.     break;
  477.       case 0x03ef:
  478.       printf("\t\tDISPLAYINFO STRUCTURE: unhandled\n");
  479.       throwchunk(Size, fd, "dispatch_res");
  480.       *offset += Size;
  481.     break;
  482.       case 0x03f0: /* FIXME: untested */
  483.     {
  484.       guint32 caption_len;
  485.       
  486.       psd_image.caption = getpascalstring(fd, "caption string");
  487.       caption_len = strlen(psd_image.caption);
  488.       
  489.       printf("\t\t\tcontent: \"%s\"\n",psd_image.caption);
  490.       *offset   += caption_len+1;
  491.     }
  492.     break;
  493.       case 0x03f2:
  494.     printf("\t\tBACKGROUND COLOR: unhandled\n");
  495.     throwchunk(Size, fd, "dispatch_res");
  496.     *offset += Size;
  497.     break;    
  498.       case 0x03f4:
  499.     printf("\t\tGREY/MULTICHANNEL HALFTONING INFO: unhandled\n");
  500.     throwchunk(Size, fd, "dispatch_res");
  501.     *offset += Size;
  502.     break;
  503.       case 0x03f5:
  504.     printf("\t\tCOLOUR HALFTONING INFO: unhandled\n");
  505.     throwchunk(Size, fd, "dispatch_res");
  506.     *offset += Size;
  507.     break;
  508.       case 0x03f6:
  509.     printf("\t\tDUOTONE HALFTONING INFO: unhandled\n");
  510.     throwchunk(Size, fd, "dispatch_res");
  511.     *offset += Size;
  512.     break;
  513.       case 0x03f7:
  514.     printf("\t\tGREYSCALE/MULTICHANNEL TRANSFER FUNCTION: unhandled\n");
  515.     throwchunk(Size, fd, "dispatch_res");
  516.     *offset += Size;
  517.     break;
  518.       case 0x03f8:
  519.     printf("\t\tCOLOUR TRANSFER FUNCTION: unhandled\n");
  520.     throwchunk(Size, fd, "dispatch_res");
  521.     *offset += Size;
  522.     break;
  523.       case 0x03f9:
  524.     printf("\t\tDUOTONE TRANSFER FUNCTION: unhandled\n");
  525.     throwchunk(Size, fd, "dispatch_res");
  526.     *offset += Size;
  527.     break;
  528.       case 0x03fa:
  529.     printf("\t\tDUOTONE IMAGE INFO: unhandled\n");
  530.     throwchunk(Size, fd, "dispatch_res");
  531.     *offset += Size;
  532.     break;
  533.       case 0x03fb:
  534.     printf("\t\tEFFECTIVE BLACK/WHITE VALUES: unhandled\n");
  535.     throwchunk(Size, fd, "dispatch_res");
  536.     *offset += Size;
  537.     break;
  538.       case 0x03fe:
  539.     printf("\t\tQUICK MASK INFO: unhandled\n");
  540.     throwchunk(Size, fd, "dispatch_res");
  541.     *offset += Size;
  542.     break;
  543.       case 0x0400:
  544.     {
  545.       printf("\t\tLAYER STATE INFO:\n");
  546.       psd_image.active_layer_num = getgshort(fd, "ID target_layer_num");
  547.  
  548.       printf("\t\t\ttarget: %d\n",(gint)psd_image.active_layer_num);
  549.       *offset += 2;
  550.     }
  551.     break;
  552.       case 0x0402:
  553.     printf("\t\tLAYER GROUP INFO: unhandled\n");
  554.     printf("\t\t\t(Inferred number of layers: %d)\n",(gint)(Size/2));
  555.     throwchunk(Size, fd, "dispatch_res");
  556.     *offset += Size;
  557.     break;
  558.       case 0x0405:
  559.     printf ("\t\tIMAGE MODE FOR RAW FORMAT: unhandled\n");
  560.     throwchunk(Size, fd, "dispatch_res");
  561.     *offset += Size;
  562.     break;
  563.  
  564.       case 0x03e9:
  565.       case 0x03ed:
  566.       case 0x03f1:
  567.       case 0x03f3:
  568.       case 0x03fd:
  569.       case 0x0401:
  570.       case 0x0404:
  571.       case 0x0406:
  572.       case 0x0bb7:
  573.       case 0x2710:
  574.     printf ("\t\t<Field is irrelevant to GIMP at this time.>\n");
  575.     throwchunk(Size, fd, "dispatch_res");    
  576.     *offset += Size;
  577.     break;
  578.     
  579.       case 0x03e8:
  580.       case 0x03eb:
  581.     printf ("\t\t<Obsolete Photoshop 2.0 field.>\n");
  582.     throwchunk(Size, fd, "dispatch_res");
  583.     *offset += Size;
  584.     break;
  585.     
  586.       case 0x03fc:
  587.       case 0x03ff:
  588.       case 0x0403:
  589.     printf ("\t\t<Obsolete field.>\n");
  590.     throwchunk(Size, fd, "dispatch_res");
  591.     *offset += Size;
  592.     break;
  593.     
  594.       default:
  595.     printf ("\t\t<Undocumented (Photoshop 4.0?) field.>\n");
  596.     throwchunk(Size, fd, "dispatch_res");
  597.     *offset += Size;
  598.     break;
  599.       }
  600. }
  601.  
  602.  
  603. static void
  604. do_layer_record(FILE *fd, guint32 *offset, gint layernum)
  605. {
  606.   gint32 top, left, bottom, right;
  607.   guint32 extradatasize;
  608.   gchar sig[4];
  609.   guchar flags;
  610.   gint i;
  611.  
  612.   printf("\t\t\tLAYER RECORD (layer %d)\n", (int)layernum);
  613.   
  614.   top = getglong (fd, "layer top");
  615.   (*offset)+=4;
  616.   left = getglong (fd, "layer left");
  617.   (*offset)+=4;
  618.   bottom = getglong (fd, "layer bottom");
  619.   (*offset)+=4;
  620.   right = getglong (fd, "layer right");
  621.   (*offset)+=4;
  622.  
  623.   psd_image.layer[layernum].x = left;
  624.   psd_image.layer[layernum].y = top;
  625.   psd_image.layer[layernum].width = right-left;
  626.   psd_image.layer[layernum].height = bottom-top;
  627.   
  628.   printf("\t\t\t\tLayer extents: (%d,%d) -> (%d,%d)\n",left,top,right,bottom);
  629.   
  630.   psd_image.layer[layernum].num_channels =
  631.     getgshort (fd, "layer num_channels");
  632.   (*offset)+=2;
  633.   
  634.   printf("\t\t\t\tNumber of channels: %d\n",
  635.      (int)psd_image.layer[layernum].num_channels);
  636.  
  637.   for (i=0;i<psd_image.layer[layernum].num_channels;i++)
  638.     {
  639.       printf("\t\t\t\tCHANNEL LENGTH INFO (%d)\n", i);
  640.  
  641.       psd_image.layer[layernum].channel[i].type    = getgshort(fd, "channel id");
  642.       offset+=2;
  643.       printf("\t\t\t\t\tChannel ID: %d\n",
  644.          psd_image.layer[layernum].channel[i].type);
  645.  
  646.       psd_image.layer[layernum].channel[i].compressedsize =
  647.     getglong(fd, "channeldatalength");
  648.       offset+=4;
  649.       printf("\t\t\t\t\tChannel Data Length: %d\n",
  650.          psd_image.layer[layernum].channel[i].compressedsize);
  651.     }
  652.  
  653.   xfread(fd, sig, 4, "layer blend sig");
  654.   offset+=4;
  655.   
  656.   if (strncmp(sig, "8BIM", 4)!=0)
  657.     {
  658.       printf("PSD: Error - layer blend signature is incorrect. :-(\n");
  659.       gimp_quit();
  660.     }
  661.  
  662.   xfread(fd, psd_image.layer[layernum].blendkey, 4, "layer blend key");
  663.   offset+=4;
  664.  
  665.   printf("\t\t\t\tBlend type: PSD(\"%c%c%c%c\") = GIMP(%d)\n",
  666.      psd_image.layer[layernum].blendkey[0],
  667.      psd_image.layer[layernum].blendkey[1],
  668.      psd_image.layer[layernum].blendkey[2],
  669.      psd_image.layer[layernum].blendkey[3],
  670.      psd_lmode_to_gimp_lmode(psd_image.layer[layernum].blendkey));
  671.  
  672.   psd_image.layer[layernum].opacity = getguchar(fd, "layer opacity");
  673.   offset++;
  674.  
  675.   printf("\t\t\t\tLayer Opacity: %d\n", psd_image.layer[layernum].opacity);
  676.  
  677.   psd_image.layer[layernum].clipping = getguchar(fd, "layer clipping");
  678.   offset++;
  679.  
  680.   printf("\t\t\t\tLayer Clipping: %d (%s)\n",
  681.      psd_image.layer[layernum].clipping,
  682.      psd_image.layer[layernum].clipping==0?"base":"non-base");
  683.  
  684.   flags = getguchar(fd, "layer flags");
  685.   offset++;
  686.  
  687.   printf("\t\t\t\tLayer Flags: %d (%s, %s)\n", flags,
  688.      flags&1?"preserve transparency":"don't preserve transparency",
  689.      flags&2?"visible":"not visible");
  690.  
  691.   psd_image.layer[layernum].protecttrans = (flags&1) ? TRUE : FALSE;
  692.   psd_image.layer[layernum].protecttrans = (flags&2) ? TRUE : FALSE;  
  693.  
  694.   getguchar(fd, "layer record filler");
  695.   offset++;
  696.  
  697.   extradatasize = getglong(fd, "layer extra data size");
  698.   offset+=4;
  699.   printf("\t\t\t\tEXTRA DATA SIZE: %d\n",extradatasize);
  700.   /* FIXME: should do something with this data */
  701.   throwchunk(extradatasize, fd, "layer extradata throw");
  702.  
  703. }
  704.  
  705.  
  706. static void
  707. do_layer_struct(FILE *fd, guint32 *offset)
  708. {
  709.   gint i;
  710.  
  711.   printf("\t\tLAYER STRUCTURE SECTION\n");
  712.   
  713.   psd_image.num_layers = getgshort(fd, "layer struct numlayers");
  714.   (*offset)+=2;
  715.  
  716.   printf("\t\t\tCanonical number of layers: %d%s\n",
  717.      psd_image.num_layers>0?
  718.      (int)psd_image.num_layers:abs(psd_image.num_layers),
  719.      psd_image.num_layers>0?"":" (absolute/alpha)");
  720.  
  721.   if (psd_image.num_layers<0)
  722.     {
  723.       psd_image.num_layers = -psd_image.num_layers;
  724.       psd_image.absolute_alpha = TRUE;
  725.     }
  726.   else
  727.     {
  728.       psd_image.absolute_alpha = FALSE;
  729.     }
  730.  
  731.   for (i=0; i<psd_image.num_layers; i++)
  732.     {
  733.       do_layer_record(fd, offset, i);
  734.     }
  735. }
  736.  
  737.  
  738. static void
  739. do_layer_pixeldata(FILE *fd, guint32 *offset)
  740. {
  741.   guint16 compression;
  742.   gint layeri, channeli;
  743.   guchar *tmpline;
  744.  
  745.   for (layeri=0; layeri<psd_image.num_layers; layeri++)
  746.     {
  747.       tmpline = xmalloc(psd_image.layer[layeri].width + 1);
  748.  
  749.       for (channeli=0;
  750.        channeli<psd_image.layer[layeri].num_channels;
  751.        channeli++)
  752.     {
  753.       if (psd_image.layer[layeri].channel[channeli].type != -2)
  754.         {          
  755.           compression = getgshort(fd, "layer channel compression type");
  756.           (*offset)+=2;
  757.           
  758.           printf("\t\t\tLayer (%d) Channel (%d:%d) Compression: %d (%s)\n",
  759.              layeri,
  760.              channeli,
  761.              psd_image.layer[layeri].channel[channeli].type,
  762.              compression,
  763.              compression==0?"raw":"RLE");
  764.           
  765.           printf("\t\t\t\tLoading channel data (%d bytes)...\n",
  766.              psd_image.layer[layeri].width *
  767.              psd_image.layer[layeri].height);
  768.           
  769.           psd_image.layer[layeri].channel[channeli].data =
  770.         xmalloc(psd_image.layer[layeri].width *
  771.             psd_image.layer[layeri].height);
  772.           
  773.           switch (compression)
  774.         {
  775.         case 0: /* raw data, padded to an even width (jeez, psd sux) */
  776.           {
  777.             /* FIXME: untested */
  778.             gint linei;
  779.             
  780.             for (linei=0;
  781.              linei<psd_image.layer[layeri].height;
  782.              linei++)
  783.               {
  784.             xfread(fd,
  785.                    (psd_image.layer[layeri].channel[channeli].data+
  786.                 linei * psd_image.layer[layeri].width),
  787.                    psd_image.layer[layeri].width,
  788.                    "raw channel line");
  789.             (*offset) += psd_image.layer[layeri].width;
  790.             if (psd_image.layer[layeri].width & 1)
  791.               {
  792.                 getguchar(fd, "raw channel line padding");
  793.                 (*offset)++;
  794.               }
  795.               }
  796.           }
  797.           break;
  798.         case 1: /* RLE, one row at a time, padded to an even width */
  799.           {
  800.             gint linei;
  801.             gint blockread;
  802.             
  803.             /* we throw this away because in theory we can trust the
  804.                data to unpack to the right length... hmm... */
  805.             throwchunk(psd_image.layer[layeri].height * 2,
  806.                    fd, "widthlist");
  807.             (*offset) += psd_image.layer[layeri].height * 2;
  808.             
  809.             blockread = *offset;
  810.             
  811.             for (linei=0;
  812.              linei<psd_image.layer[layeri].height;
  813.              linei++)
  814.               {
  815.             /*printf(" %d ", *offset);*/
  816.             unpack_pb_channel(fd, tmpline,
  817.                       psd_image.layer[layeri].width 
  818.                       /*(psd_image.layer[layeri].width&1)*/,
  819.                       offset);
  820.             memcpy((psd_image.layer[layeri].channel[channeli].data+
  821.                 linei * psd_image.layer[layeri].width),
  822.                    tmpline,
  823.                    psd_image.layer[layeri].width);
  824.               }
  825.             
  826.             printf("\t\t\t\t\tActual compressed size was %d bytes\n",
  827.                (*offset)-blockread);
  828.           }
  829.           break;
  830.         default: /* *unknown* */
  831.           printf("*** Unknown compression type in channel.\n");
  832.           gimp_quit();
  833.           break;
  834.         }
  835.         }
  836.     }
  837.       
  838.       g_free(tmpline);
  839.     }
  840. }
  841.  
  842.  
  843. static void
  844. do_layers(FILE *fd, guint32 *offset)
  845. {
  846.   guint32 section_length;
  847.  
  848.   section_length = getglong(fd, "layerinfo sectionlength");
  849.   (*offset)+=4;
  850.  
  851.   printf("\tLAYER INFO SECTION\n");
  852.   printf("\t\tSECTION LENGTH: %u\n",section_length);
  853.   
  854.   do_layer_struct(fd, offset);
  855.  
  856.   do_layer_pixeldata(fd, offset);
  857. }
  858.  
  859.  
  860. /*
  861. static void
  862. do_masks(guint32 *offset)
  863. {
  864.   
  865. }
  866. */
  867.  
  868.  
  869.  
  870. static void
  871. do_layer_and_mask(FILE *fd)
  872. {
  873.   guint32 offset = 0;
  874.   guint32 Size = PSDheader.miscsizelen;
  875.  
  876.  
  877.   printf("LAYER AND MASK INFO\n");
  878.   printf("\tSECTION LENGTH: %u\n",Size);
  879.  
  880.   if (Size == 0) return;
  881.  
  882.   do_layers(fd, &offset);
  883.  
  884.   if (offset < Size)
  885.     {
  886.       printf("PSD: Supposedly there are %d bytes of mask info left.\n",
  887.          Size-offset);
  888.       if ((Size-offset == 4) || (Size-offset == 0x14))
  889.     printf("     That sounds good to me.\n");
  890.       else
  891.     printf("     That sounds strange to me.\n");
  892.       
  893.  
  894.       /* FIXME: supposed to do something with this */
  895.       /*      dumpchunk(4, fd, "mask info throw");*/
  896.  
  897.       if ((getguchar(fd, "mask info throw")!=0) ||
  898.       (getguchar(fd, "mask info throw")!=0) ||
  899.       (getguchar(fd, "mask info throw")!=0) ||
  900.       (getguchar(fd, "mask info throw")!=0))
  901.     {
  902.       printf("*** This is bogus.  Quitting.\n");
  903.       gimp_quit();
  904.     }
  905.  
  906.     /*      do_masks(&offset);*/
  907.     }
  908.   else
  909.     printf("PSD: Stern warning - no mask info.\n");
  910. }
  911.  
  912.  
  913.  
  914. static void
  915. do_image_resources(FILE *fd)
  916. {
  917.   guint16 ID;
  918.   gchar *Name;
  919.   guint32 Size;
  920.  
  921.   guint32 offset = 0;
  922.  
  923.   printf("IMAGE RESOURCE BLOCK:\n");
  924.  
  925.   /* FIXME: too trusting that the file isn't corrupt */
  926.   while (offset < PSDheader.imgreslen-1)
  927.     {
  928.       gchar sig[4];
  929.       
  930.       xfread(fd, sig, 4, "imageresources signature");
  931.  
  932.       if (strncmp(sig, "8BIM", 4) != 0)
  933.     {
  934.       printf("PSD: Error - imageresources block has invalid signature.\n");
  935.       gimp_quit();
  936.     }
  937.       offset += 4;
  938.  
  939.       /* generic information about a block ID */
  940.  
  941.  
  942.       ID = getgshort(fd, "ID num");
  943.       offset+=2;
  944.       printf("\tID: 0x%04x / ",ID);
  945.  
  946.  
  947.       Name = getpascalstring(fd, "ID name");
  948.       offset += strlen(Name)+1;
  949.  
  950.       if (!strlen(Name)&1)
  951.     {
  952.       throwchunk(1, fd, "ID name throw");
  953.       offset ++;
  954.     }
  955.       g_free(Name);
  956.  
  957.       Size = getglong(fd, "ID Size");
  958.       offset+=4;
  959.       printf("Size: %d\n", Size);
  960.  
  961.       dispatch_resID(ID, fd, &offset, Size);
  962.  
  963.       if (Size&1)
  964.     {
  965.       throwchunk(1, fd, "ID content throw");
  966.       offset ++;
  967.     }
  968.     }
  969.  
  970.   /*  if (offset != PSDheader.imgreslen)
  971.     {
  972.       printf("\tSucking imageres byte...\n");
  973.       throwchunk(1, fd, "imageres suck");
  974.       offset ++;
  975.     }*/
  976.  
  977. }
  978.  
  979.  
  980.  
  981. static gint32
  982. load_image(char *name)
  983. {
  984.     FILE *fd;
  985.     char *name_buf, *cmykbuf;
  986.     static int number = 1;
  987.     unsigned char *dest, *temp;
  988.     long rowstride, channels, nguchars;
  989.     psd_imagetype imagetype;
  990.     int cmyk = 0, step = 1;
  991.     gint32 image_ID = -1;
  992.     gint32 layer_ID;
  993.     GDrawable *drawable;
  994.     GPixelRgn pixel_rgn;
  995.     gint32 iter;
  996.  
  997.     
  998.     printf("------- %s --------------------------------------\n",name);
  999.  
  1000.  
  1001.     name_buf = xmalloc(strlen(name) + 11);
  1002.     if (number > 1)
  1003.     sprintf (name_buf, "%s-%d", name, number);
  1004.     else
  1005.     sprintf (name_buf, "%s", name);
  1006.     sprintf(name_buf, "Loading %s:", name);
  1007.  
  1008.     gimp_progress_init(name_buf);
  1009.  
  1010.     fd = fopen(name, "rb");
  1011.     if (fd==NULL) {
  1012.     printf("%s: can't open \"%s\"\n", prog_name, name);
  1013.     return(-1);
  1014.     }
  1015.  
  1016.  
  1017.  
  1018.  
  1019.     read_whole_file(fd);
  1020.  
  1021.  
  1022.  
  1023.  
  1024.     printf("Image data %ld chars\n", PSDheader.imgdatalen);
  1025.     
  1026.     imagetype = PSD_UNKNOWN_IMAGE;
  1027.     switch (PSDheader.mode) {
  1028.     case 0:        /* Bitmap */
  1029.       break;
  1030.     case 1:        /* Grayscale */
  1031.       switch (PSDheader.channels) {
  1032.       case 1:
  1033.     step = 1;
  1034.     imagetype = PSD_GRAY_IMAGE;
  1035.     break;
  1036.       case 2:
  1037.     step = 2;
  1038.     imagetype = PSD_GRAYA_IMAGE;
  1039.     break;
  1040.       default:
  1041.     printf("Warning: base GRAY image has %d channels...\n",
  1042.            step = PSDheader.channels);
  1043.     imagetype = PSD_GRAYA_IMAGE;
  1044.     break;
  1045.       }
  1046.       break;
  1047.     case 2:        /* Indexed Colour */
  1048.       switch (PSDheader.channels) {
  1049.       case 1:
  1050.     step = 1;
  1051.     imagetype = PSD_INDEXED_IMAGE;
  1052.     break;
  1053.       case 2:
  1054.     step = 2;
  1055.     printf("Warning: base INDEXED image has 2 channels - "
  1056.            "ignoring alpha.\n");
  1057.     imagetype = PSD_INDEXEDA_IMAGE;
  1058.     break;
  1059.       default:
  1060.     printf("Warning: base INDEXED image has %d channels...\n",
  1061.            step = PSDheader.channels);
  1062.     imagetype = PSD_INDEXEDA_IMAGE;
  1063.     break;
  1064.       }
  1065.       break;
  1066.     case 3:        /* RGB Colour */
  1067.       switch (PSDheader.channels) {
  1068.       case 3:
  1069.     step = 3;
  1070.     imagetype = PSD_RGB_IMAGE;
  1071.     break;
  1072.       case 4:
  1073.     step = 4;
  1074.     imagetype = PSD_RGBA_IMAGE;
  1075.     break;
  1076.       default:
  1077.     printf("Warning: base RGB image has %d channels...\n",
  1078.            step = PSDheader.channels);
  1079.     break;
  1080.       }
  1081.       break;
  1082.     case 4:        /* CMYK Colour */
  1083.       cmyk = 1;
  1084.       switch (PSDheader.channels) {
  1085.       case 4:
  1086.     step = 4;
  1087.     imagetype = PSD_RGB_IMAGE;
  1088.     break;
  1089.       case 5:
  1090.     step = 5;
  1091.     imagetype = PSD_RGBA_IMAGE;
  1092.     break;
  1093.       default:
  1094.     printf("%s: cannot handle CMYK with more than 5 channels\n",
  1095.            prog_name);
  1096.     return(-1);
  1097.     break;
  1098.       }
  1099.       break;
  1100.     case 7:        /* Multichannel (?) */
  1101.     case 8:        /* Duotone */
  1102.     case 9:        /* Lab Colour */
  1103.     default:
  1104.       break;
  1105.     }
  1106.  
  1107.     if (imagetype == PSD_UNKNOWN_IMAGE)
  1108.       {
  1109.     printf("%s: Image type %d (%s) is not supported\n",
  1110.            prog_name, PSDheader.mode,
  1111.            (PSDheader.mode > 10) ?
  1112.            "<out of range>" : modename[PSDheader.mode]);
  1113.     return(-1);
  1114.       }
  1115.     if (PSDheader.bpp != 8)
  1116.       {
  1117.     printf("%s: The GIMP only supports 8-bit deep PSD images\n",
  1118.            prog_name);
  1119.     return(-1);
  1120.       }
  1121.  
  1122.     printf(
  1123.        "psd:%d gimp:%d gimpbase:%d\n",
  1124.        imagetype,
  1125.        psd_type_to_gimp_type(imagetype),
  1126.        psd_type_to_gimp_base_type(imagetype)
  1127.        );
  1128.  
  1129.     image_ID = gimp_image_new (PSDheader.columns, PSDheader.rows,
  1130.                    psd_type_to_gimp_base_type(imagetype));
  1131.     gimp_image_set_filename (image_ID, name);
  1132.     if (psd_type_to_gimp_base_type(imagetype) == INDEXED)
  1133.       {
  1134.     if ((psd_image.colmaplen%3)!=0)
  1135.       printf("PSD: Colourmap looks screwed! Aiee!\n");
  1136.     if (psd_image.colmaplen==0)
  1137.       printf("PSD: Indexed image has no colourmap!\n");
  1138.     if (psd_image.colmaplen!=768)
  1139.       printf("PSD: Warning: Indexed image is !=256 (%ld) colours.\n",
  1140.          psd_image.colmaplen/3);
  1141.     if (psd_image.colmaplen==768)
  1142.       {
  1143.         reshuffle_cmap(psd_image.colmapdata);
  1144.         gimp_image_set_cmap (image_ID,
  1145.                  psd_image.colmapdata,
  1146.                  256);
  1147.       }
  1148.       }
  1149.  
  1150.     layer_ID = gimp_layer_new (image_ID, "Background",
  1151.                    PSDheader.columns, PSDheader.rows,
  1152.                    psd_type_to_gimp_type(imagetype),
  1153.                    100, NORMAL_MODE);
  1154.  
  1155.     g_free(name_buf);
  1156.  
  1157.     gimp_image_add_layer (image_ID, layer_ID, 0);
  1158.     drawable = gimp_drawable_get (layer_ID);
  1159.  
  1160.  
  1161.     
  1162.  
  1163.     /*    dest = gimp_image_data (image);
  1164.     channels = gimp_image_channels (image);
  1165.     rowstride = gimp_image_width (image) * channels;*/
  1166.  
  1167.     channels = gimp_drawable_bpp(drawable->id);
  1168.     rowstride = PSDheader.columns * channels;
  1169.     dest = xmalloc( rowstride * PSDheader.rows );
  1170.  
  1171.     
  1172.  
  1173.     gimp_progress_update ((double)0.0);
  1174.  
  1175.  
  1176.     if (PSDheader.compression!=0)
  1177.       {
  1178.     nguchars = PSDheader.columns * PSDheader.rows;
  1179.     temp = xmalloc(PSDheader.imgdatalen);
  1180.     xfread(fd, temp, PSDheader.imgdatalen, "image data");
  1181.     if (!cmyk)
  1182.       {
  1183.         gimp_progress_update ((double)0.25);
  1184.         decode(PSDheader.imgdatalen, nguchars, temp, dest, step);
  1185.       }
  1186.     else
  1187.       {
  1188.         gimp_progress_update ((double)0.25);
  1189.         cmykbuf = xmalloc(step * nguchars);
  1190.         decode(PSDheader.imgdatalen, nguchars, temp, cmykbuf, step);
  1191.         gimp_progress_update ((double)0.50);
  1192.         cmyk2rgb(cmykbuf, dest, PSDheader.columns, PSDheader.rows, step > 4);
  1193.         g_free(cmykbuf);
  1194.     }
  1195.     g_free(temp);
  1196.       }
  1197.     else
  1198.       if (!cmyk)
  1199.     {
  1200.       gimp_progress_update ((double)0.50);
  1201.       xfread(fd, dest, PSDheader.imgdatalen, "image data");
  1202.     }
  1203.       else
  1204.     {      
  1205.       gimp_progress_update ((double)0.25);
  1206.       cmykbuf = xmalloc(PSDheader.imgdatalen);
  1207.       xfread(fd, cmykbuf, PSDheader.imgdatalen, "image data");
  1208.       gimp_progress_update ((double)0.50);
  1209.       cmykp2rgb(cmykbuf, dest,
  1210.             PSDheader.columns, PSDheader.rows, step > 4);
  1211.       g_free(cmykbuf);
  1212.     }
  1213.  
  1214.     gimp_progress_update ((double)1.00);
  1215.     
  1216.  
  1217.     if (psd_type_to_gimp_type(imagetype)==INDEXEDA_IMAGE)
  1218.       for (iter=0;iter<drawable->width*drawable->height;iter++)
  1219.     {
  1220.       dest[iter*2+1] = 255;
  1221.     }
  1222.  
  1223.  
  1224.     gimp_pixel_rgn_init (&pixel_rgn, drawable,
  1225.              0, 0, drawable->width, drawable->height,
  1226.              TRUE, FALSE);
  1227.     gimp_pixel_rgn_set_rect (&pixel_rgn, dest,
  1228.                  0, 0, drawable->width, drawable->height);
  1229.  
  1230.     g_free (dest);
  1231.  
  1232.     
  1233.     gimp_drawable_flush (drawable);
  1234.     gimp_drawable_detach (drawable);
  1235.  
  1236.     if (psd_image.colmaplen > 0)
  1237.       g_free(psd_image.colmapdata);
  1238.  
  1239.     return(image_ID);
  1240. }
  1241.  
  1242.  
  1243.  
  1244. static void
  1245. decode(long clen, long uclen, char * src, char * dst, int step)
  1246. {
  1247.     gint i, j;
  1248.     gint32 l;
  1249.     gushort * w;
  1250.  
  1251.     l = clen;
  1252.     for (i = 0; i < PSDheader.rows*PSDheader.channels; ++i)
  1253.     l -= PSDheader.rowlength[i];
  1254.     if (l)
  1255.     printf("*** %ld should be zero\n", (long)l);
  1256.  
  1257.     w = PSDheader.rowlength;
  1258.     
  1259.     packbitsdecode(&clen, uclen, src, dst++, step);
  1260.     for (j = 0; j < step-1; ++j) {
  1261.     for (i = 0; i < PSDheader.rows; ++i)
  1262.         src += *w++;
  1263.     packbitsdecode(&clen, uclen, src, dst++, step);
  1264.     }
  1265.     printf("clen %ld\n", clen);
  1266. }
  1267.  
  1268.  
  1269.  
  1270. /*
  1271.  * Decode a PackBits data stream.
  1272.  */
  1273. static void
  1274. packbitsdecode(long * clenp, long uclen, char * src, char * dst, int step)
  1275. {
  1276.     gint n, b;
  1277.     gint32 clen = *clenp;
  1278.     
  1279.     while ((clen > 0) && (uclen > 0)) {
  1280.     n = (int) *src++;
  1281.     if (n >= 128)
  1282.         n -= 256;
  1283.     if (n < 0) {        /* replicate next guchar -n+1 times */
  1284.         clen -= 2;
  1285.         if (n == -128)    /* nop */
  1286.         continue;
  1287.         n = -n + 1;
  1288.         uclen -= n;
  1289.         for (b = *src++; n > 0; --n) {
  1290.         *dst = b;
  1291.         dst += step;
  1292.         }
  1293.     } else {        /* copy next n+1 guchars literally */
  1294.         for (b = ++n; b > 0; --b) {
  1295.         *dst = *src++;
  1296.         dst += step;
  1297.         }
  1298.         uclen -= n;
  1299.         clen -= n+1;
  1300.     }
  1301.     }
  1302.     if (uclen > 0) {
  1303.     printf("%s: unexpected EOF while reading image data\n", prog_name);
  1304.     gimp_quit();
  1305.     }
  1306.     *clenp = clen;
  1307. }
  1308.  
  1309.  
  1310.  
  1311. /*
  1312.  * Decode a PackBits channel from file.
  1313.  */
  1314. static void
  1315. unpack_pb_channel(FILE *fd, guchar *dst, gint32 unpackedlen, guint32 *offset)
  1316. {
  1317.     int n, b;
  1318.     gint32 upremain = unpackedlen;
  1319.  
  1320.     while (upremain > 0)
  1321.       {
  1322.     (*offset)++;
  1323.     n = (int) getguchar(fd, "packbits1");
  1324.  
  1325.     if (n >= 128)
  1326.       n -= 256;
  1327.     if (n < 0)
  1328.       {        /* replicate next guchar -n+1 times */
  1329.         if (n == -128)    /* nop */
  1330.           continue;
  1331.         n = -n + 1;
  1332.         /*        upremain -= n;*/
  1333.  
  1334.         b = getguchar(fd, "packbits2");
  1335.         (*offset)++;
  1336.         for (; n > 0; --n)
  1337.           {
  1338.         *dst = b;
  1339.         dst ++;
  1340.         upremain--;
  1341.           }
  1342.       }
  1343.     else
  1344.       {        /* copy next n+1 guchars literally */
  1345.         for (b = ++n; b > 0; --b)
  1346.           {
  1347.         *dst = getguchar(fd, "packbits3");;
  1348.         (*offset)++;
  1349.         dst ++;
  1350.         upremain--;
  1351.           }
  1352.         /*        upremain -= n;*/
  1353.       }
  1354.       }
  1355.  
  1356.     if (upremain < 0)
  1357.       {
  1358.     printf("*** Unpacking overshot destination (%d) buffer by %d bytes!\n",
  1359.            unpackedlen,
  1360.            -upremain);
  1361.       }
  1362. }
  1363.  
  1364. static void
  1365. cmyk2rgb(unsigned char * src, unsigned char * dst,
  1366.      long width, long height, int alpha)
  1367. {
  1368.     int r, g, b, k;
  1369.     int i, j;
  1370.  
  1371.  
  1372.     for (i = 0; i < height; i++) {
  1373.     for (j = 0; j < width; j++) {
  1374.         r = *src++;
  1375.         g = *src++;
  1376.         b = *src++;
  1377.         k = *src++;
  1378.  
  1379.         cmyk_to_rgb (&r, &g, &b, &k);
  1380.       
  1381.         *dst++ = r;
  1382.         *dst++ = g;
  1383.         *dst++ = b;
  1384.  
  1385.         if (alpha)
  1386.         *dst++ = *src++;
  1387.     }
  1388.     if ((i % 5) == 0)
  1389.         gimp_progress_update ((double)(2.0*(double)height)/((double)height+(double)i));
  1390.     }
  1391. }
  1392.  
  1393.  
  1394. /*
  1395.  * Decode planar CMYK(A) to RGB(A).
  1396.  */
  1397. static void
  1398. cmykp2rgb(unsigned char * src, unsigned char * dst,
  1399.       long width, long height, int alpha)
  1400. {
  1401.     int r, g, b, k;
  1402.     int i, j;
  1403.     long n;
  1404.     char *rp, *gp, *bp, *kp, *ap;
  1405.  
  1406.     n = width * height;
  1407.     rp = src;
  1408.     gp = rp + n;
  1409.     bp = gp + n;
  1410.     kp = bp + n;
  1411.     ap = kp + n;
  1412.     
  1413.     for (i = 0; i < height; i++) {
  1414.     for (j = 0; j < width; j++) {
  1415.         r = *rp++;
  1416.         g = *gp++;
  1417.         b = *bp++;
  1418.         k = *kp++;
  1419.  
  1420.         cmyk_to_rgb (&r, &g, &b, &k);
  1421.       
  1422.         *dst++ = r;
  1423.         *dst++ = g;
  1424.         *dst++ = b;
  1425.  
  1426.         if (alpha)
  1427.         *dst++ = *ap++;
  1428.     }
  1429.     if ((i % 5) == 0)
  1430.       gimp_progress_update ((double)(2.0*(double)height)/((double)height+(double)i));
  1431.     }
  1432. }
  1433.  
  1434.  
  1435. static void
  1436. cmyk_to_rgb(gint *c, gint *m, gint *y, gint *k)
  1437. {
  1438. #if 1
  1439.     gint cyan, magenta, yellow, black;
  1440.  
  1441.     cyan = *c;
  1442.     magenta = *m;
  1443.     yellow = *y;
  1444.     black = *k;
  1445.  
  1446.     if (black > 0) {
  1447.     cyan -= black;
  1448.     magenta -= black;
  1449.     yellow -= black;
  1450.     }
  1451.     *c = 255 - cyan;
  1452.     *m = 255 - magenta;
  1453.     *y = 255 - yellow;
  1454.     if (*c < 0) *c = 0; else if (*c > 255) *c = 255;
  1455.     if (*m < 0) *m = 0; else if (*m > 255) *m = 255;
  1456.     if (*y < 0) *y = 0; else if (*y > 255) *y = 255;
  1457. #endif
  1458. }
  1459.  
  1460.  
  1461. void
  1462. dumpchunk(size_t n, FILE * fd, guchar *why)
  1463. {
  1464.   guint32 i;
  1465.  
  1466.   printf("\n");
  1467.  
  1468.   for (i=0;i<n;i++)
  1469.     {
  1470.       printf("%02x ",(int)getguchar(fd, why));
  1471.     }
  1472.  
  1473.   printf("\n");
  1474. }
  1475.  
  1476.  
  1477. void
  1478. throwchunk(size_t n, FILE * fd, guchar *why)
  1479. {
  1480.   guchar *tmpchunk;
  1481.  
  1482.   if (n==0)
  1483.     {
  1484.       return;
  1485.     }
  1486.  
  1487.   tmpchunk = xmalloc(n);
  1488.   xfread(fd, tmpchunk, n, why);
  1489.   g_free(tmpchunk);
  1490. }
  1491.  
  1492.  
  1493. /*
  1494. static guchar *
  1495. getchunk(size_t n, FILE * fd, char *why)
  1496. {
  1497.   guchar *tmpchunk;
  1498.  
  1499.   tmpchunk = xmalloc(n);
  1500.   xfread(fd, tmpchunk, n, why);
  1501.   return(tmpchunk); */  /* caller should free memory */ /*
  1502. }
  1503. */
  1504.  
  1505.  
  1506. /* FIXME: This is dumb.  I guess I wish there were a g_realloc */
  1507. /*static guchar *
  1508. xgrowstr(guchar *src)
  1509. {
  1510.   guint32 i,oldlen;
  1511.   guchar *new;
  1512.  
  1513.   oldlen = strlen(src);
  1514.   new = xmalloc(oldlen+2);
  1515.  
  1516.   for (i=0;i<oldlen;i++)
  1517.     new[i] = src[i];
  1518.   
  1519.   new[oldlen]=0;
  1520.  
  1521.   g_free(src);
  1522.   return (new);
  1523. }*/
  1524.  
  1525.  
  1526. static guchar *
  1527. getpascalstring(FILE *fd, guchar *why)
  1528. {
  1529.   guchar *tmpchunk;
  1530.   guchar len;
  1531.  
  1532.   xfread(fd, &len, 1, why);
  1533.  
  1534.   tmpchunk = xmalloc(len+1);
  1535.  
  1536.   if (len==0)
  1537.     {
  1538.       tmpchunk[0]=0;
  1539.       return(tmpchunk);
  1540.     }
  1541.  
  1542.   xfread(fd, tmpchunk, len, why);
  1543.   tmpchunk[len]=0;
  1544.   
  1545.   return(tmpchunk); /* caller should free memory */
  1546. }
  1547.  
  1548.  
  1549. /*
  1550. static guchar *
  1551. getstring(FILE *fd, guchar *why)
  1552. {
  1553.   guchar *tmpchunk;
  1554.   guint pos;
  1555.   guchar ch;
  1556.  
  1557.   tmpchunk = xmalloc(1);
  1558.  
  1559.   pos = 0;
  1560.  
  1561.   do
  1562.     {
  1563.       xfread(fd, &ch, 1, why);
  1564.       tmpchunk = xgrowstr(tmpchunk);
  1565.       tmpchunk[pos] = ch;
  1566.       pos++;
  1567.     }
  1568.   while (ch != 0);
  1569.   
  1570.   return(tmpchunk);
  1571. }*/
  1572.  
  1573.  
  1574. static guchar
  1575. getguchar(FILE *fd, char *why)
  1576. {
  1577.   guchar tmp;
  1578.  
  1579.   xfread(fd, &tmp, 1, why);
  1580.  
  1581.   return(tmp);
  1582. }
  1583.  
  1584.  
  1585. static gshort
  1586. getgshort(FILE *fd, char *why)
  1587. {
  1588. #if (BYTE_ORDER == LITTLE_ENDIAN)
  1589.     union {
  1590.     struct {
  1591.         unsigned char b1, b2;
  1592.     } b;
  1593.     gshort w;
  1594.     } s;
  1595. #endif
  1596.     gushort w;
  1597.     guchar b;
  1598.     
  1599.     xfread(fd, &w, 2, why);
  1600.     
  1601. #if (BYTE_ORDER == BIG_ENDIAN)
  1602.     return (gshort) w;
  1603. #else
  1604.     s.w = w;
  1605.     b = s.b.b2;
  1606.     s.b.b2 = s.b.b1;
  1607.     s.b.b1 = b;
  1608.     return s.w;
  1609. #endif
  1610. }
  1611.  
  1612.  
  1613. static gulong
  1614. getglong(FILE *fd, char * why)
  1615. {
  1616. #if (BYTE_ORDER == LITTLE_ENDIAN)
  1617.     union {
  1618.     struct {
  1619.         unsigned char b1, b2, b3, b4;
  1620.     } b;
  1621.     gulong w;
  1622.     } s;
  1623.     unsigned char s1, s2, s3, s4;
  1624. #endif
  1625.     gulong w;
  1626.  
  1627.     xfread(fd, &w, 4, why);
  1628.  
  1629. #if (BYTE_ORDER == BIG_ENDIAN)
  1630.     return (glong) w;
  1631. #else
  1632.     s.w = w;
  1633.     s1 = s.b.b1;
  1634.     s2 = s.b.b2;
  1635.     s3 = s.b.b3;
  1636.     s4 = s.b.b4;
  1637.     s.b.b3 = s2;
  1638.     s.b.b4 = s1;
  1639.     s.b.b1 = s4;
  1640.     s.b.b2 = s3;
  1641.     return s.w;
  1642. #endif
  1643. }
  1644.  
  1645.  
  1646. static void
  1647. xfread(FILE * fd, void * buf, long len, char * why)
  1648. {
  1649.     if (fread(buf, len, 1, fd) == 0) {
  1650.     printf("%s: unexpected EOF while reading '%s' chunk\n",
  1651.            prog_name, why);
  1652.     gimp_quit();
  1653.     }
  1654. }
  1655.  
  1656.  
  1657. static void *
  1658. xmalloc(size_t n)
  1659. {
  1660.     void *p;
  1661.  
  1662.     if (n == 0)
  1663.       {
  1664.     printf("%s: xmalloc asked for zero-sized chunk\n", prog_name);
  1665.     gimp_quit();
  1666.       }
  1667.  
  1668.     if ((p = g_malloc(n)) != NULL)
  1669.     return p;
  1670.     printf("%s: out of memory\n", prog_name);
  1671.     gimp_quit();
  1672.     exit(1);
  1673. }
  1674.  
  1675.  
  1676. static void
  1677. read_whole_file(FILE * fd)
  1678. {
  1679.     guint16 w;
  1680.     gint32 pos;
  1681.     gchar dummy[6];
  1682.     gint i;
  1683.     
  1684.     xfread(fd, &PSDheader.signature, 4, "signature");
  1685.     PSDheader.version = getgshort(fd, "version");
  1686.     xfread(fd, &dummy, 6, "reserved");
  1687.     PSDheader.channels = getgshort(fd, "channels");
  1688.     PSDheader.rows = getglong(fd, "rows");
  1689.     PSDheader.columns = getglong(fd, "columns");
  1690.     PSDheader.bpp = getgshort(fd, "depth");
  1691.     PSDheader.mode = getgshort(fd, "mode");
  1692.  
  1693.  
  1694.     psd_image.num_layers = 0;
  1695.     psd_image.type = PSDheader.mode;
  1696.     psd_image.colmaplen = 0;
  1697.     psd_image.num_aux_channels = 0;
  1698.  
  1699.  
  1700.     psd_image.colmaplen = getglong(fd, "color data length");
  1701.  
  1702.     if (psd_image.colmaplen > 0)
  1703.       {
  1704.     psd_image.colmapdata = xmalloc(psd_image.colmaplen);
  1705.     xfread(fd, psd_image.colmapdata, psd_image.colmaplen, "colormap");
  1706.       }
  1707.  
  1708.  
  1709.     PSDheader.imgreslen = getglong(fd, "image resource length");
  1710.     if (PSDheader.imgreslen > 0)
  1711.       {
  1712.     do_image_resources(fd);
  1713.       }
  1714.  
  1715.  
  1716.     PSDheader.miscsizelen = getglong(fd, "misc size data length");
  1717.     if (PSDheader.miscsizelen > 0)
  1718.       {
  1719.     do_layer_and_mask(fd);
  1720.       }
  1721.  
  1722.  
  1723.     PSDheader.compression = getgshort(fd, "compression");
  1724.     printf("<<%d>>", (int)PSDheader.compression);
  1725.     if (PSDheader.compression)
  1726.       {
  1727.     PSDheader.rowlength = xmalloc(PSDheader.rows *
  1728.                       PSDheader.channels * sizeof(gushort));
  1729.     for (i = 0; i < PSDheader.rows*PSDheader.channels; ++i)
  1730.       PSDheader.rowlength[i] = getgshort(fd, "x");
  1731.       }
  1732.     pos = ftell(fd);
  1733.     fseek(fd, 0, SEEK_END);
  1734.     PSDheader.imgdatalen = ftell(fd)-pos;
  1735.     fseek(fd, pos, SEEK_SET);
  1736.  
  1737.     if (strncmp(PSDheader.signature, "8BPS", 4) != 0)
  1738.       {
  1739.     printf("%s: not an Adobe Photoshop PSD file\n", prog_name);
  1740.     gimp_quit();
  1741.       }
  1742.     if (PSDheader.version != 1)
  1743.       {
  1744.     printf("%s: bad version number '%d', not 1\n",
  1745.            prog_name, PSDheader.version);
  1746.     gimp_quit();
  1747.       }
  1748.     w = PSDheader.mode;
  1749.     printf("HEAD:\n"
  1750.        "\tChannels %d\n\tRows %ld\n\tColumns %ld\n\tDepth %d\n\tMode %d (%s)\n"
  1751.        "\tColour data %ld guchars\n",
  1752.        PSDheader.channels, PSDheader.rows,
  1753.        PSDheader.columns, PSDheader.bpp,
  1754.        w, modename[w < 10 ? w : 10],
  1755.        psd_image.colmaplen);
  1756.     /*    printf("\tImage resource length: %lu\n", PSDheader.imgreslen);*/
  1757.     printf("\tLayer/Mask Data length: %lu\n", PSDheader.miscsizelen);
  1758.     w = PSDheader.compression;
  1759.     printf("\tCompression %d (%s)\n", w, w ? "RLE" : "raw");
  1760. }
  1761.