psd.c 55.7 KB
Newer Older
1
/*
Manish Singh's avatar
Manish Singh committed
2
 * PSD Plugin version 1.9.9.9b (BETA)
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 * This GIMP plug-in is designed to load Adobe Photoshop(tm) files (.PSD)
 *
 * Adam D. Moss <adam@gimp.org> <adam@foxbox.org>
 *
 *     If this plug-in fails to load a file which you think it should,
 *     please tell me what seemed to go wrong, and anything you know
 *     about the image you tried to load.  Please don't send big PSD
 *     files to me without asking first.
 *
 *          Copyright (C) 1997-98 Adam D. Moss
 *          Copyright (C) 1996    Torsten Martinsen
 * Portions Copyright (C) 1995    Peter Mattis
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
Manish Singh's avatar
Manish Singh committed
28
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 30 31 32 33 34 35 36 37 38
 */

/*
 * Adobe and Adobe Photoshop are trademarks of Adobe Systems
 * Incorporated that may be registered in certain jurisdictions.
 */

/*
 * Revision history:
 *
Manish Singh's avatar
Manish Singh committed
39 40 41 42 43 44
 *  98.05.04 / v1.9.9.9b / Adam D. Moss
 *       Changed the Pascal-style string-reading stuff.  That fixed
 *       some file-padding problems.  Made all debugging output
 *       compile-time optional (please leave it enabled for now).
 *       Reduced memory requirements; still much room for improvement.
 *
Manish Singh's avatar
Manish Singh committed
45 46 47 48 49
 *  98.04.28 / v1.9.9.9 / Adam D. Moss
 *       Fixed the correct channel interlacing of 'raw' flat images.
 *       Thanks to Christian Kirsch and Jay Cox for spotting this.
 *       Changed some of the I/O routines.
 *
50 51 52 53 54
 *  98.04.26 / v1.9.9.8 / Adam D. Moss
 *       Implemented Aux-channels for layered files.  Got rid
 *       of <endian.h> nonsense.  Improved Layer Mask padding.
 *       Enforced num_layers/num_channels limit checks.
 *
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
 *  98.04.23 / v1.9.9.5 / Adam D. Moss
 *       Got Layer Masks working, got Aux-channels working
 *       for unlayered files, fixed 'raw' channel loading, fixed
 *       some other mini-bugs, slightly better progress meters.
 *       Thanks to everyone who is helping with the testing!
 *
 *  98.04.21 / v1.9.9.1 / Adam D. Moss
 *       A little cleanup.  Implemented Layer Masks but disabled
 *       them again - PS masks can be a different size to their
 *       owning layer, unlike those in GIMP.
 *
 *  98.04.19 / v1.9.9.0 / Adam D. Moss
 *       Much happier now.
 *
 *  97.03.13 / v1.9.0 / Adam D. Moss
 *       Layers, channels and masks, oh my.
 *       + Bugfixes & rearchitecturing.
 *
 *  97.01.30 / v1.0.12 / Torsten Martinsen
 *       Flat PSD image loading.
 */

77 78 79 80 81 82 83
/*
 * TODO:
 *
 *      Crush 16bpp channels
 *	CMYK -> RGB
 *	Load BITMAP mode
 *
Manish Singh's avatar
Manish Singh committed
84
 *      File saving.  (I am unlikely to be able to do this for
85 86 87 88 89 90 91 92 93 94 95 96 97
 *         practical reasons.  Suggest someone works on it as a
 *         separate plugin - please let me know.)
 *
 *      Reduce memory requirements!
 */

/*
 * BUGS:
 *
 *      Sometimes creates a superfluous aux channel?  Harmless.
 */


98 99

/* *** DEFINES *** */
Manish Singh's avatar
Manish Singh committed
100 101

/* set to TRUE if you want debugging, FALSE otherwise */
102
#define PSD_DEBUG FALSE
Manish Singh's avatar
Manish Singh committed
103

104 105
/* the max number of layers that this plugin should try to load */
#define MAX_LAYERS 100
Manish Singh's avatar
Manish Singh committed
106

107
/* the max number of channels that this plugin should let a layer have */
108
#define MAX_CHANNELS 30
Manish Singh's avatar
Manish Singh committed
109

110 111 112
/* *** END OF DEFINES *** */


Manish Singh's avatar
Manish Singh committed
113 114 115

#define IFDBG if (PSD_DEBUG)

116 117
#include <stdio.h>
#include <stdlib.h>
Manish Singh's avatar
Manish Singh committed
118
#include <unistd.h>
Manish Singh's avatar
Manish Singh committed
119
#include <string.h>
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
#include <glib.h>
#include "libgimp/gimp.h"


/* Local types etc
 */
typedef enum
{
  PSD_UNKNOWN_IMAGE,
  PSD_RGB_IMAGE,
  PSD_RGBA_IMAGE,
  PSD_GRAY_IMAGE,
  PSD_GRAYA_IMAGE,
  PSD_INDEXED_IMAGE,
  PSD_INDEXEDA_IMAGE
} psd_imagetype;



/* Declare some local functions.
 */
static void   query      (void);
static void   run        (char    *name,
                          int      nparams,
                          GParam  *param,
                          int     *nreturn_vals,
                          GParam **return_vals);
GDrawableType psd_type_to_gimp_type
                         (psd_imagetype psdtype);
GImageType psd_type_to_gimp_base_type
                         (psd_imagetype psdtype);
GLayerMode psd_lmode_to_gimp_lmode
                         (gchar modekey[4]);
static gint32 load_image (char   *filename);



GPlugInInfo PLUG_IN_INFO =
{
  NULL,    /* init_proc */
  NULL,    /* quit_proc */
  query,   /* query_proc */
  run,     /* run_proc */
};



typedef struct PsdChannel
{
  gchar *name;
  guchar *data;
  gint type;

  guint32 compressedsize;
  
} PSDchannel;



typedef struct PsdLayer
{
  gint num_channels;
  PSDchannel channel[MAX_CHANNELS];
  
  gint32 x;
  gint32 y;
  guint32 width;
  guint32 height;
  
  gchar blendkey[4];
  guchar opacity;
  gchar clipping;

  gboolean protecttrans;
  gboolean visible;

Manish Singh's avatar
Manish Singh committed
196
  gchar* name;
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234

  gint32 lm_x;
  gint32 lm_y;
  gint32 lm_width;
  gint32 lm_height;

} PSDlayer;



typedef struct PsdImage
{
  gint num_layers;
  PSDlayer layer[MAX_LAYERS];

  gboolean absolute_alpha;

  gint type;
  
  gulong colmaplen;
  guchar *colmapdata;

  guint num_aux_channels;
  PSDchannel aux_channel[MAX_CHANNELS];

  gchar *caption;

  guint active_layer_num;

} PSDimage;



static PSDimage psd_image;



static struct {
Manish Singh's avatar
Manish Singh committed
235
    gchar signature[4];
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    gushort version;
    guchar reserved[6];
    gushort channels;
    gulong rows;
    gulong columns;
    gushort bpp;
    gushort mode;
    gulong imgreslen;
    gulong miscsizelen;
    gushort compression;
    gushort * rowlength;
    long  imgdatalen;
} PSDheader;


static gchar * modename[] = {
    "Bitmap", 
    "Grayscale", 
    "Indexed Colour", 
    "RGB Colour", 
    "CMYK Colour", 
    "<invalid>", 
    "<invalid>", 
    "Multichannel", 
    "Duotone", 
    "Lab Colour", 
    "<invalid>"
};


static const gchar *prog_name = "PSD";


static void unpack_pb_channel(FILE *fd, guchar *dst, gint32 unpackedlen,
				  guint32 *offset);
Manish Singh's avatar
Manish Singh committed
271
static void decode(long clen, long uclen, gchar *src, gchar *dst, int step);
272
static void packbitsdecode(long *clenp, long uclen,
Manish Singh's avatar
Manish Singh committed
273
			   gchar *src, gchar *dst, int step);
274 275 276 277 278 279 280
static void cmyk2rgb(guchar *src, guchar *destp,
		     long width, long height, int alpha);
static void cmykp2rgb(guchar *src, guchar *destp,
		      long width, long height, int alpha);
static void cmyk_to_rgb(int *c, int *m, int *y, int *k);
static guchar getguchar(FILE *fd, gchar *why);
static gshort getgshort(FILE *fd, gchar *why);
281
static glong getglong(FILE *fd, gchar *why);
282
static void xfread(FILE *fd, void *buf, long len, gchar *why);
Manish Singh's avatar
Manish Singh committed
283 284
static void xfread_interlaced(FILE *fd, guchar *buf, long len, gchar *why,
			      gint step);
285 286 287
static void *xmalloc(size_t n);
static void read_whole_file(FILE *fd);
static void reshuffle_cmap(guchar *map256);
Manish Singh's avatar
Manish Singh committed
288 289 290
static guchar *getpascalstring(FILE *fd, gchar *why);
void throwchunk(size_t n, FILE * fd, gchar *why);
void dumpchunk(size_t n, FILE * fd, gchar *why);
291 292


293 294
MAIN()

295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426

static void
query ()
{
  static GParamDef load_args[] =
  {
    { PARAM_INT32, "run_mode", "Interactive, non-interactive" },
    { PARAM_STRING, "filename", "The name of the file to load" },
    { PARAM_STRING, "raw_filename", "The name of the file to load" },
  };
  static GParamDef load_return_vals[] =
  {
    { PARAM_IMAGE, "image", "Output image" },
  };
  static int nload_args = sizeof (load_args) / sizeof (load_args[0]);
  static int nload_return_vals = sizeof (load_return_vals) / sizeof (load_return_vals[0]);

  /*  static GParamDef save_args[] =
  {
    { PARAM_INT32, "run_mode", "Interactive, non-interactive" },
    { PARAM_IMAGE, "image", "Input image" },
    { PARAM_DRAWABLE, "drawable", "Drawable to save" },
    { PARAM_STRING, "filename", "The name of the file to save the image in" },
    { PARAM_STRING, "raw_filename", "The name of the file to save the image in" },
    { PARAM_INT32, "compression", "Compression type: { NONE (0), LZW (1), PACKBITS (2)" },
    { PARAM_INT32, "fillorder", "Fill Order: { MSB to LSB (0), LSB to MSB (1)" }
  };
  static int nsave_args = sizeof (save_args) / sizeof (save_args[0]);*/

  gimp_install_procedure ("file_psd_load",
                          "loads files of the Photoshop(tm) PSD file format",
                          "FIXME: write help for psd_load",
                          "Adam D. Moss & Torsten Martinsen",
                          "Adam D. Moss & Torsten Martinsen",
                          "1996-1997",
                          "<Load>/PSD",
			  NULL,
                          PROC_PLUG_IN,
                          nload_args, nload_return_vals,
                          load_args, load_return_vals);

  /*  gimp_install_procedure ("file_psd_save",
                          "saves files in the Photoshop(tm) PSD file format",
                          "FIXME: write help for psd_save",
                          "Adam D. Moss & Torsten Martinsen",
                          "Adam D. Moss & Torsten Martinsen",
                          "1996-1997",
                          "<Save>/PSD",
			  "RGB, GRAY, INDEXED",
                          PROC_PLUG_IN,
                          nsave_args, 0,
                          save_args, NULL);*/

  gimp_register_load_handler ("file_psd_load", "psd", "");
  /*  gimp_register_save_handler ("file_psd_save", "psd", "");*/
}



static void
run (char    *name,
     int      nparams,
     GParam  *param,
     int     *nreturn_vals,
     GParam **return_vals)
{
  static GParam values[2];
  GRunModeType run_mode;
  /*  GStatusType status = STATUS_SUCCESS;*/
  gint32 image_ID;

  run_mode = param[0].data.d_int32;

  *nreturn_vals = 1;
  *return_vals = values;
  values[0].type = PARAM_STATUS;
  values[0].data.d_status = STATUS_CALLING_ERROR;

  if (strcmp (name, "file_psd_load") == 0)
    {
      image_ID = load_image (param[1].data.d_string);

      if (image_ID != -1)
	{
	  *nreturn_vals = 2;
	  values[0].data.d_status = STATUS_SUCCESS;
	  values[1].type = PARAM_IMAGE;
	  values[1].data.d_image = image_ID;
	}
      else
	{
	  values[0].data.d_status = STATUS_EXECUTION_ERROR;
	}
    }
}


GDrawableType
psd_type_to_gimp_type (psd_imagetype psdtype)
{
  switch(psdtype)
    {
    case PSD_RGBA_IMAGE: return(RGBA_IMAGE);
    case PSD_RGB_IMAGE: return(RGB_IMAGE);
    case PSD_GRAYA_IMAGE: return(GRAYA_IMAGE);
    case PSD_GRAY_IMAGE: return(GRAY_IMAGE);
    case PSD_INDEXEDA_IMAGE: return(INDEXEDA_IMAGE);
    case PSD_INDEXED_IMAGE: return(INDEXED_IMAGE);
    default: return(RGB_IMAGE);
    }
}



GLayerMode
psd_lmode_to_gimp_lmode (gchar modekey[4])
{
  if (strncmp(modekey, "norm", 4)==0) return(NORMAL_MODE);
  if (strncmp(modekey, "dark", 4)==0) return(DARKEN_ONLY_MODE);
  if (strncmp(modekey, "lite", 4)==0) return(LIGHTEN_ONLY_MODE);
  if (strncmp(modekey, "hue ", 4)==0) return(HUE_MODE);
  if (strncmp(modekey, "sat ", 4)==0) return(SATURATION_MODE);
  if (strncmp(modekey, "colr", 4)==0) return(COLOR_MODE);
  if (strncmp(modekey, "mul ", 4)==0) return(MULTIPLY_MODE);
  if (strncmp(modekey, "scrn", 4)==0) return(SCREEN_MODE);
  if (strncmp(modekey, "diss", 4)==0) return(DISSOLVE_MODE);
  if (strncmp(modekey, "diff", 4)==0) return(DIFFERENCE_MODE);

  if (strncmp(modekey, "lum ", 4)==0) return(VALUE_MODE);    /* ? */

  printf("PSD: Warning - unsupported layer-blend mode '%c%c%c%c', using 'addition' mode\n", modekey[0], modekey[1], modekey[2], modekey[3]);

427
  if (strncmp(modekey, "over", 4)==0) return(ADDITION_MODE); /* ? */
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
  if (strncmp(modekey, "hLit", 4)==0) return(/**/ADDITION_MODE);
  if (strncmp(modekey, "sLit", 4)==0) return(/**/ADDITION_MODE);

  printf("PSD: Warning - UNKNOWN layer-blend mode, reverting to 'normal'\n");

  return(NORMAL_MODE);
}



GImageType
psd_type_to_gimp_base_type (psd_imagetype psdtype)
{
  switch(psdtype)
    {
    case PSD_RGBA_IMAGE:
    case PSD_RGB_IMAGE: return(RGB);
    case PSD_GRAYA_IMAGE:
    case PSD_GRAY_IMAGE: return(GRAY);
    case PSD_INDEXEDA_IMAGE:
    case PSD_INDEXED_IMAGE: return(INDEXED);
    default:
      printf("PSD: Error: Can't convert PSD imagetype to GIMP imagetype\n");
      gimp_quit();
      return(RGB);
    }
}



GImageType
psd_mode_to_gimp_base_type (gushort psdtype)
{
  switch(psdtype)
    {
    case 1: return(GRAY);
    case 2: return(INDEXED);
    case 3: return(RGB);
    default:
      printf("PSD: Error: Can't convert PSD mode to GIMP base imagetype\n");
      gimp_quit();
      return(RGB);
    }
}



static void
reshuffle_cmap(guchar *map256)
{
  guchar *tmpmap;
  int i;

  tmpmap = xmalloc(768);

  for (i=0;i<256;i++)
    {
      tmpmap[i*3  ] = map256[i];
      tmpmap[i*3+1] = map256[i+256];
      tmpmap[i*3+2] = map256[i+512];
    }

  for (i=0;i<768;i++)
    {
      map256[i] = tmpmap[i];
    }

  g_free(tmpmap);
}



static void
dispatch_resID(guint ID, FILE *fd, guint32 *offset, guint32 Size)
{
  if ( (ID < 0x0bb6) && (ID >0x07d0) )
    {
Manish Singh's avatar
Manish Singh committed
505
      IFDBG printf ("\t\tPath data is irrelevant to GIMP at this time.\n");
506 507 508 509 510 511 512 513 514 515
      throwchunk(Size, fd, "dispatch_res path throw");
      (*offset) += Size;
    }
  else
    switch (ID)
      {
      case 0x03ee:
	{
	  gint32 remaining = Size;
	  
Manish Singh's avatar
Manish Singh committed
516
	  IFDBG printf ("\t\tALPHA CHANNEL NAMES:\n");
517 518 519 520 521 522
	  if (Size > 0)
	    {
	      do
		{
		  psd_image.aux_channel[psd_image.num_aux_channels].name =
		    getpascalstring(fd, "alpha channel name");
Manish Singh's avatar
Manish Singh committed
523 524 525 526 527 528
		  (*offset)++;
		  remaining--;

		  if (psd_image.aux_channel[psd_image.num_aux_channels].name)
		    {
		      guint32 alpha_name_len;
529
		  
Manish Singh's avatar
Manish Singh committed
530 531 532 533 534
		      alpha_name_len =
			strlen(psd_image.aux_channel[psd_image.num_aux_channels].name);
		      
		      IFDBG printf("\t\t\tname: \"%s\"\n",
				   psd_image.aux_channel[psd_image.num_aux_channels].name);
535
		  
Manish Singh's avatar
Manish Singh committed
536 537 538 539
		      (*offset) += alpha_name_len;
		      remaining -= alpha_name_len;
		    }

540
		  psd_image.num_aux_channels++;
541 542 543 544 545 546

		  if (psd_image.num_aux_channels > MAX_CHANNELS)
		    {
		      printf("\nPSD: Sorry - this image has too many aux channels.  Tell Adam!\n");
		      gimp_quit();
		    }
547 548 549 550 551 552 553 554 555
		}
	      while (remaining > 0);
	    }

	  if (remaining)
	    throwchunk(remaining, fd, "alphaname padding 0 throw");
	}
	break;
      case 0x03ef:
Manish Singh's avatar
Manish Singh committed
556 557 558
	IFDBG printf("\t\tDISPLAYINFO STRUCTURE: unhandled\n");
	throwchunk(Size, fd, "dispatch_res");
	(*offset) += Size;
559 560 561 562
	break;
      case 0x03f0: /* FIXME: untested */
	{
	  psd_image.caption = getpascalstring(fd, "caption string");
Manish Singh's avatar
Manish Singh committed
563 564 565 566 567 568 569
	  (*offset)++;

	  if (psd_image.caption)
	    {
	      IFDBG printf("\t\t\tcontent: \"%s\"\n",psd_image.caption);
	      (*offset) += strlen(psd_image.caption);
	    }
570 571 572
	}
	break;
      case 0x03f2:
Manish Singh's avatar
Manish Singh committed
573
	IFDBG printf("\t\tBACKGROUND COLOR: unhandled\n");
574 575 576 577
	throwchunk(Size, fd, "dispatch_res");
	(*offset) += Size;
	break;	
      case 0x03f4:
Manish Singh's avatar
Manish Singh committed
578
	IFDBG printf("\t\tGREY/MULTICHANNEL HALFTONING INFO: unhandled\n");
579 580 581 582
	throwchunk(Size, fd, "dispatch_res");
	(*offset) += Size;
	break;
      case 0x03f5:
Manish Singh's avatar
Manish Singh committed
583
	IFDBG printf("\t\tCOLOUR HALFTONING INFO: unhandled\n");
584 585 586 587
	throwchunk(Size, fd, "dispatch_res");
	(*offset) += Size;
	break;
      case 0x03f6:
Manish Singh's avatar
Manish Singh committed
588
	IFDBG printf("\t\tDUOTONE HALFTONING INFO: unhandled\n");
589 590 591 592
	throwchunk(Size, fd, "dispatch_res");
	(*offset) += Size;
	break;
      case 0x03f7:
Manish Singh's avatar
Manish Singh committed
593
	IFDBG printf("\t\tGREYSCALE/MULTICHANNEL TRANSFER FUNCTION: unhandled\n");
594 595 596 597
	throwchunk(Size, fd, "dispatch_res");
	(*offset) += Size;
	break;
      case 0x03f8:
Manish Singh's avatar
Manish Singh committed
598
	IFDBG printf("\t\tCOLOUR TRANSFER FUNCTION: unhandled\n");
599 600 601 602
	throwchunk(Size, fd, "dispatch_res");
	(*offset) += Size;
	break;
      case 0x03f9:
Manish Singh's avatar
Manish Singh committed
603
	IFDBG printf("\t\tDUOTONE TRANSFER FUNCTION: unhandled\n");
604 605 606 607
	throwchunk(Size, fd, "dispatch_res");
	(*offset) += Size;
	break;
      case 0x03fa:
Manish Singh's avatar
Manish Singh committed
608
	IFDBG printf("\t\tDUOTONE IMAGE INFO: unhandled\n");
609 610 611 612
	throwchunk(Size, fd, "dispatch_res");
	(*offset) += Size;
	break;
      case 0x03fb:
Manish Singh's avatar
Manish Singh committed
613
	IFDBG printf("\t\tEFFECTIVE BLACK/WHITE VALUES: unhandled\n");
614 615 616 617
	throwchunk(Size, fd, "dispatch_res");
	(*offset) += Size;
	break;
      case 0x03fe:
Manish Singh's avatar
Manish Singh committed
618
	IFDBG printf("\t\tQUICK MASK INFO: unhandled\n");
619 620 621 622 623
	throwchunk(Size, fd, "dispatch_res");
	(*offset) += Size;
	break;
      case 0x0400:
	{
Manish Singh's avatar
Manish Singh committed
624
	  IFDBG printf("\t\tLAYER STATE INFO:\n");
625 626
	  psd_image.active_layer_num = getgshort(fd, "ID target_layer_num");

Manish Singh's avatar
Manish Singh committed
627
	  IFDBG printf("\t\t\ttarget: %d\n",(gint)psd_image.active_layer_num);
628 629 630 631
	  (*offset) += 2;
	}
	break;
      case 0x0402:
Manish Singh's avatar
Manish Singh committed
632 633
	IFDBG printf("\t\tLAYER GROUP INFO: unhandled\n");
	IFDBG printf("\t\t\t(Inferred number of layers: %d)\n",(gint)(Size/2));
634 635 636 637
	throwchunk(Size, fd, "dispatch_res");
	(*offset) += Size;
	break;
      case 0x0405:
Manish Singh's avatar
Manish Singh committed
638
	IFDBG printf ("\t\tIMAGE MODE FOR RAW FORMAT: unhandled\n");
639 640 641 642 643 644 645 646 647 648 649 650 651 652
	throwchunk(Size, fd, "dispatch_res");
	(*offset) += Size;
	break;

      case 0x03e9:
      case 0x03ed:
      case 0x03f1:
      case 0x03f3:
      case 0x03fd:
      case 0x0401:
      case 0x0404:
      case 0x0406:
      case 0x0bb7:
      case 0x2710:
Manish Singh's avatar
Manish Singh committed
653
	IFDBG printf ("\t\t<Field is irrelevant to GIMP at this time.>\n");
654 655 656 657 658 659
	throwchunk(Size, fd, "dispatch_res");	
	(*offset) += Size;
	break;
	
      case 0x03e8:
      case 0x03eb:
Manish Singh's avatar
Manish Singh committed
660
	IFDBG printf ("\t\t<Obsolete Photoshop 2.0 field.>\n");
661 662 663 664 665 666 667
	throwchunk(Size, fd, "dispatch_res");
	(*offset) += Size;
	break;
	
      case 0x03fc:
      case 0x03ff:
      case 0x0403:
Manish Singh's avatar
Manish Singh committed
668
	IFDBG printf ("\t\t<Obsolete field.>\n");
669 670 671 672 673
	throwchunk(Size, fd, "dispatch_res");
	(*offset) += Size;
	break;
	
      default:
Manish Singh's avatar
Manish Singh committed
674
	IFDBG printf ("\t\t<Undocumented field.>\n");
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
	throwchunk(Size, fd, "dispatch_res");
	(*offset) += Size;
	break;
      }
}


static void
do_layer_record(FILE *fd, guint32 *offset, gint layernum)
{
  gint32 top, left, bottom, right;
  guint32 extradatasize, layermaskdatasize, layerrangesdatasize;
  guint32 totaloff;
  gchar sig[4];
  guchar flags;
  gint i;

Manish Singh's avatar
Manish Singh committed
692
  IFDBG printf("\t\t\tLAYER RECORD (layer %d)\n", (int)layernum);
693 694


695 696 697 698 699 700 701 702 703
  /* table 11-12 */
  top = getglong (fd, "layer top");
  (*offset)+=4;
  left = getglong (fd, "layer left");
  (*offset)+=4;
  bottom = getglong (fd, "layer bottom");
  (*offset)+=4;
  right = getglong (fd, "layer right");
  (*offset)+=4;
704 705 706 707 708 709

  psd_image.layer[layernum].x = left;
  psd_image.layer[layernum].y = top;
  psd_image.layer[layernum].width = right-left;
  psd_image.layer[layernum].height = bottom-top;
  
Manish Singh's avatar
Manish Singh committed
710
  IFDBG printf("\t\t\t\tLayer extents: (%d,%d) -> (%d,%d)\n",left,top,right,bottom);
711 712 713 714
  
  psd_image.layer[layernum].num_channels =
    getgshort (fd, "layer num_channels");
  (*offset)+=2;
715 716 717 718 719 720

  if (psd_image.layer[layernum].num_channels > MAX_CHANNELS)
    {
      printf("\nPSD: Sorry - this image has too many channels.  Tell Adam!\n");
      gimp_quit();
    }
721
  
Manish Singh's avatar
Manish Singh committed
722
  IFDBG printf("\t\t\t\tNumber of channels: %d\n",
723 724 725 726
	 (int)psd_image.layer[layernum].num_channels);

  for (i=0;i<psd_image.layer[layernum].num_channels;i++)
    {
727
      /* table 11-13 */
Manish Singh's avatar
Manish Singh committed
728
      IFDBG printf("\t\t\t\tCHANNEL LENGTH INFO (%d)\n", i);
729 730 731

      psd_image.layer[layernum].channel[i].type	= getgshort(fd, "channel id");
      (*offset)+=2;
Manish Singh's avatar
Manish Singh committed
732
      IFDBG printf("\t\t\t\t\tChannel TYPE: %d\n",
733 734 735 736 737
	     psd_image.layer[layernum].channel[i].type);

      psd_image.layer[layernum].channel[i].compressedsize =
	getglong(fd, "channeldatalength");
      (*offset)+=4;
Manish Singh's avatar
Manish Singh committed
738
      IFDBG printf("\t\t\t\t\tChannel Data Length: %d\n",
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
	     psd_image.layer[layernum].channel[i].compressedsize);
    }

  xfread(fd, sig, 4, "layer blend sig");
  (*offset)+=4;
  
  if (strncmp(sig, "8BIM", 4)!=0)
    {
      printf("PSD: Error - layer blend signature is incorrect. :-(\n");
      gimp_quit();
    }

  xfread(fd, psd_image.layer[layernum].blendkey, 4, "layer blend key");
  (*offset)+=4;

Manish Singh's avatar
Manish Singh committed
754
  IFDBG printf("\t\t\t\tBlend type: PSD(\"%c%c%c%c\") = GIMP(%d)\n",
755 756 757 758 759 760 761 762 763
	 psd_image.layer[layernum].blendkey[0],
	 psd_image.layer[layernum].blendkey[1],
	 psd_image.layer[layernum].blendkey[2],
	 psd_image.layer[layernum].blendkey[3],
	 psd_lmode_to_gimp_lmode(psd_image.layer[layernum].blendkey));

  psd_image.layer[layernum].opacity = getguchar(fd, "layer opacity");
  (*offset)++;

Manish Singh's avatar
Manish Singh committed
764
  IFDBG printf("\t\t\t\tLayer Opacity: %d\n", psd_image.layer[layernum].opacity);
765 766 767 768

  psd_image.layer[layernum].clipping = getguchar(fd, "layer clipping");
  (*offset)++;

Manish Singh's avatar
Manish Singh committed
769
  IFDBG printf("\t\t\t\tLayer Clipping: %d (%s)\n",
770 771 772 773 774 775
	 psd_image.layer[layernum].clipping,
	 psd_image.layer[layernum].clipping==0?"base":"non-base");

  flags = getguchar(fd, "layer flags");
  (*offset)++;

Manish Singh's avatar
Manish Singh committed
776
  IFDBG printf("\t\t\t\tLayer Flags: %d (%s, %s)\n", flags,
777 778 779 780 781 782 783 784 785 786 787
	 flags&1?"preserve transparency":"don't preserve transparency",
	 flags&2?"visible":"not visible");

  psd_image.layer[layernum].protecttrans = (flags&1) ? TRUE : FALSE;
  psd_image.layer[layernum].visible = (flags&2) ? FALSE : TRUE;

  getguchar(fd, "layer record filler");
  (*offset)++;

  extradatasize = getglong(fd, "layer extra data size");
  (*offset)+=4;
Manish Singh's avatar
Manish Singh committed
788
  IFDBG printf("\t\t\t\tEXTRA DATA SIZE: %d\n",extradatasize);
789 790 791 792 793 794 795 796 797 798

  /* FIXME: should do something with this data */
  /*throwchunk(extradatasize, fd, "layer extradata throw");
  (*offset) += extradatasize;*/

  totaloff = (*offset) + extradatasize;

  /* table 11-14 */
  layermaskdatasize = getglong(fd, "layer mask data size");
  (*offset)+=4;
Manish Singh's avatar
Manish Singh committed
799
  IFDBG printf("\t\t\t\t\tLAYER MASK DATA SIZE: %d\n",layermaskdatasize);
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
  
  if (layermaskdatasize)
    {
      top    = getglong(fd, "lmask top");
      (*offset) += 4;
      left   = getglong(fd, "lmask left");
      (*offset) += 4;
      bottom = getglong(fd, "lmask bottom");
      (*offset) += 4;
      right  = getglong(fd, "lmask right");
      (*offset) += 4;

      psd_image.layer[layernum].lm_x = left;
      psd_image.layer[layernum].lm_y = top;
      psd_image.layer[layernum].lm_width = right-left;
      psd_image.layer[layernum].lm_height = bottom-top;

      getglong(fd, "lmask data throw");
      (*offset) += 4;

      /*      throwchunk(layermaskdatasize, fd, "layer mask data throw");
      (*offset) += layermaskdatasize;*/
    }


  layerrangesdatasize = getglong(fd, "layer ranges data size");
  (*offset)+=4;
Manish Singh's avatar
Manish Singh committed
827
  IFDBG printf("\t\t\t\t\t\tLAYER RANGES DATA SIZE: %d\n",layermaskdatasize);
828 829 830 831 832 833 834 835
  
  if (layerrangesdatasize)
    {
      throwchunk(layerrangesdatasize, fd, "layer ranges data throw");
      (*offset) += layerrangesdatasize;
    }

  psd_image.layer[layernum].name = getpascalstring(fd, "layer name");
Manish Singh's avatar
Manish Singh committed
836
  (*offset)++;
837

Manish Singh's avatar
Manish Singh committed
838 839 840 841 842
  if (psd_image.layer[layernum].name)
    {
      (*offset) += strlen(psd_image.layer[layernum].name);
      IFDBG printf("\t\t\t\t\t\tLAYER NAME: '%s'\n",psd_image.layer[layernum].name);
    }
843
  
844 845
  if (totaloff-(*offset) > 0)
    {
Manish Singh's avatar
Manish Singh committed
846 847 848 849 850 851 852 853 854
      IFDBG 
	{
	  printf("Warning: layer record dross: ");
	  dumpchunk(totaloff-(*offset), fd, "layer record dross throw");
	}
	else
	{
	  throwchunk(totaloff-(*offset), fd, "layer record dross throw");
	}
855 856
      (*offset) = totaloff;
    }
857 858 859 860 861 862 863 864
}


static void
do_layer_struct(FILE *fd, guint32 *offset)
{
  gint i;

Manish Singh's avatar
Manish Singh committed
865
  IFDBG printf("\t\tLAYER STRUCTURE SECTION\n");
866 867 868 869
  
  psd_image.num_layers = getgshort(fd, "layer struct numlayers");
  (*offset)+=2;

Manish Singh's avatar
Manish Singh committed
870
  IFDBG printf("\t\t\tCanonical number of layers: %d%s\n",
871 872 873 874 875 876 877 878 879 880 881 882 883 884
	 psd_image.num_layers>0?
	 (int)psd_image.num_layers:abs(psd_image.num_layers),
	 psd_image.num_layers>0?"":" (absolute/alpha)");

  if (psd_image.num_layers<0)
    {
      psd_image.num_layers = -psd_image.num_layers;
      psd_image.absolute_alpha = TRUE;
    }
  else
    {
      psd_image.absolute_alpha = FALSE;
    }

885 886 887 888 889 890
  if (psd_image.num_layers > MAX_LAYERS)
    {
      printf("\nPSD: Sorry - this image has too many layers.  Tell Adam!\n");
      gimp_quit();
    }

891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
  for (i=0; i<psd_image.num_layers; i++)
    {
      do_layer_record(fd, offset, i);
    }
}


static void
do_layer_pixeldata(FILE *fd, guint32 *offset)
{
  guint16 compression;
  gint layeri, channeli;
  guchar *tmpline;

  for (layeri=0; layeri<psd_image.num_layers; layeri++)
    {
      tmpline = xmalloc(psd_image.layer[layeri].width + 1);

      for (channeli=0;
	   channeli<psd_image.layer[layeri].num_channels;
	   channeli++)
	{
	  int width, height;

	  if (psd_image.layer[layeri].channel[channeli].type == -2)
	    {
	      width = psd_image.layer[layeri].lm_width;
	      height = psd_image.layer[layeri].lm_height;
	    }
	  else
	    {
	      width = psd_image.layer[layeri].width;
	      height = psd_image.layer[layeri].height;
	    }

	  compression = getgshort(fd, "layer channel compression type");
	  (*offset)+=2;
	      
Manish Singh's avatar
Manish Singh committed
929 930 931 932 933 934 935 936 937
	  IFDBG
	    printf("\t\t\tLayer (%d) Channel (%d:%d) Compression: %d (%s)\n",
		   layeri,
		   channeli,
		   psd_image.layer[layeri].channel[channeli].type,
		   compression,
		   compression==0?"raw":(compression==1?"RLE":"UNKNOWN!"));
	  
	  IFDBG printf("\t\t\t\tLoading channel data (%d bytes)...\n",
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
		 width*height);
	      
	  psd_image.layer[layeri].channel[channeli].data =
	    xmalloc (width * height);
	      
	  switch (compression)
	    {
	    case 0: /* raw data */
	      {
		/* FIXME: only lightly tested */
		gint linei;
		    
		for (linei=0;
		     linei<height;
		     linei++)
		  {
		    xfread(fd,
			   (psd_image.layer[layeri].channel[channeli].data+
			    linei * width),
			   width,
			   "raw channel line");
		    (*offset) += width;
		  }

		/* Pad raw data to multiple of 2? */
#if 0
		if ((height *
		     width) & 1)
		  {
		    getguchar(fd, "raw channel padding");
		    (*offset)++;
		  }
#endif
	      }
	      break;
	    case 1: /* RLE, one row at a time, padded to an even width */
	      {
		gint linei;
		gint blockread;
		    
		/* we throw this away because in theory we can trust the
		   data to unpack to the right length... hmm... */
		throwchunk(height * 2,
			   fd, "widthlist");
		(*offset) += height * 2;
983

984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
		blockread = (*offset);
		    
		for (linei=0;
		     linei<height;
		     linei++)
		  {
		    /*printf(" %d ", *offset);*/
		    unpack_pb_channel(fd, tmpline,
				      width 
				      /*(width&1)*/,
				      offset);
		    memcpy((psd_image.layer[layeri].channel[channeli].data+
			    linei * width),
			   tmpline,
			   width);
		  }
		    
Manish Singh's avatar
Manish Singh committed
1001
		IFDBG printf("\t\t\t\t\tActual compressed size was %d bytes\n",
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
		       (*offset)-blockread);
	      }
	      break;
	    default: /* *unknown* */
	      printf("*** Unknown compression type in channel.\n");
	      gimp_quit();
	      break;
	    }
	}
	  
      g_free(tmpline);
    }
1014 1015 1016

  /*  printf("\n[[%ld]]\n", getglong(fd, "uhhhh"));
  (*offset)+=4;*/
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
}


static void
do_layers(FILE *fd, guint32 *offset)
{
  guint32 section_length;

  section_length = getglong(fd, "layerinfo sectionlength");
  (*offset)+=4;

Manish Singh's avatar
Manish Singh committed
1028 1029
  IFDBG printf("\tLAYER INFO SECTION\n");
  IFDBG printf("\t\tSECTION LENGTH: %u\n",section_length);
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
  
  do_layer_struct(fd, offset);

  do_layer_pixeldata(fd, offset);
}



static void
do_layer_and_mask(FILE *fd)
{
  guint32 offset = 0;
  guint32 Size = PSDheader.miscsizelen;


1045 1046 1047
  guint32 offset_now = ftell(fd);


Manish Singh's avatar
Manish Singh committed
1048 1049
  IFDBG printf("LAYER AND MASK INFO\n");
  IFDBG printf("\tSECTION LENGTH: %u\n",Size);
1050 1051 1052 1053 1054

  if (Size == 0) return;

  do_layers(fd, &offset);

1055

1056 1057
  if (offset < Size)
    {
Manish Singh's avatar
Manish Singh committed
1058 1059 1060 1061 1062 1063 1064 1065 1066
      IFDBG
	{
	  printf("PSD: Supposedly there are %d bytes of mask info left.\n",
		 Size-offset);
	  if ((Size-offset == 4) || (Size-offset == 24))
	    printf("     That sounds good to me.\n");
	  else
	    printf("     That sounds strange to me.\n");
	}
1067 1068


1069
      /*      if ((getguchar(fd, "mask info throw")!=0) ||
1070 1071 1072 1073 1074
	  (getguchar(fd, "mask info throw")!=0) ||
	  (getguchar(fd, "mask info throw")!=0) ||
	  (getguchar(fd, "mask info throw")!=0))
	{
	  printf("*** This mask info block looks pretty bogus.\n");
1075
	}*/
1076 1077 1078
    }
  else
    printf("PSD: Stern warning - no mask info.\n");
1079 1080 1081 1082


  /* If 'offset' wasn't being buggily updated, we wouldn't need this. */
  fseek(fd, Size+offset_now, SEEK_SET);
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
}



static void
do_image_resources(FILE *fd)
{
  guint16 ID;
  gchar *Name;
  guint32 Size;

  guint32 offset = 0;

Manish Singh's avatar
Manish Singh committed
1096
  IFDBG printf("IMAGE RESOURCE BLOCK:\n");
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115

  /* FIXME: too trusting that the file isn't corrupt */
  while (offset < PSDheader.imgreslen-1)
    {
      gchar sig[4];
      
      xfread(fd, sig, 4, "imageresources signature");

      if (strncmp(sig, "8BIM", 4) != 0)
	{
	  printf("PSD: Error - imageresources block has invalid signature.\n");
	  gimp_quit();
	}
      offset += 4;

      /* generic information about a block ID */


      ID = getgshort(fd, "ID num");
Manish Singh's avatar
Manish Singh committed
1116 1117
      offset += 2;
      IFDBG printf("\tID: 0x%04x / ",ID);
1118 1119 1120


      Name = getpascalstring(fd, "ID name");
Manish Singh's avatar
Manish Singh committed
1121
      offset++;
1122

Manish Singh's avatar
Manish Singh committed
1123
      if (Name)
1124
	{
Manish Singh's avatar
Manish Singh committed
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
	  IFDBG printf("\"%s\" ", Name);
	  offset += strlen(Name);

	  if (!(strlen(Name)&1))
	    {
	      throwchunk(1, fd, "ID name throw");
	      offset ++;
	    }
	  g_free(Name);
	}
      else
	{
	  throwchunk(1, fd, "ID name throw2");
	  offset++;
1139 1140 1141
	}

      Size = getglong(fd, "ID Size");
Manish Singh's avatar
Manish Singh committed
1142 1143
      offset += 4;
      IFDBG printf("Size: %d\n", Size);
1144 1145 1146 1147 1148

      dispatch_resID(ID, fd, &offset, Size);

      if (Size&1)
	{
Manish Singh's avatar
Manish Singh committed
1149
	  IFDBG printf("+1");
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
	  throwchunk(1, fd, "ID content throw");
	  offset ++;
	}
    }

  /*  if (offset != PSDheader.imgreslen)
    {
      printf("\tSucking imageres byte...\n");
      throwchunk(1, fd, "imageres suck");
      offset ++;
    }*/

}


static
guchar* chans_to_GRAYA (guchar* grey, guchar* alpha, gint numpix)
{
  guchar* rtn;
  int i; /* clearly, 'i' stands for 'Imaginative loop variable' */

  if ((grey==NULL)||(alpha==NULL))
    {
      printf("NULL channel - eep!");
      return NULL;
    }

  rtn = xmalloc(numpix * 2);

  for (i=0; i<numpix; i++)
    {
      rtn[i*2  ] = grey[i];
      rtn[i*2+1] = alpha[i];
    }

  return (rtn);
}


static
guchar* chans_to_RGB (guchar* red, guchar* green, guchar* blue, gint numpix)
{
  guchar* rtn;
  int i;

  if ((red==NULL)||(green==NULL)||(blue==NULL))
    {
      printf("NULL channel - eep!");
      return NULL;
    }

  rtn = xmalloc(numpix * 3);

  for (i=0; i<numpix; i++)
    {
      rtn[i*3  ] = red[i];
      rtn[i*3+1] = green[i];
      rtn[i*3+2] = blue[i];
    }

  return (rtn);
}



static
guchar* chans_to_RGBA (guchar* red, guchar* green, guchar* blue,
		       guchar* alpha,
		       gint numpix)
{
  guchar* rtn;
  int i;
  gboolean careful = FALSE;

  if ((red==NULL)||(green==NULL)||(blue==NULL)||(alpha==NULL))
    {
      printf("chans_to_RGBA : NULL channel - eep!");
      careful = TRUE;
    }

  rtn = xmalloc(numpix * 4);

  if (!careful)
    {
      for (i=0; i<numpix; i++)
	{
	  rtn[i*4  ] = red[i];
	  rtn[i*4+1] = green[i];
	  rtn[i*4+2] = blue[i];
	  rtn[i*4+3] = alpha[i];
	}
    }
  else
    {
      for (i=0; i<numpix; i++)
	{
	  rtn[i*4  ] = (red==NULL) ? 0 : red[i];
	  rtn[i*4+1] = (green==NULL) ? 0 : green[i];
	  rtn[i*4+2] = (blue==NULL) ? 0 : blue[i];
	  rtn[i*4+3] = (alpha==NULL) ? 0 : alpha[i];
	}
    }

  return (rtn);
}


static
gboolean psd_layer_has_alpha(PSDlayer* layer)
{
  int i;

  for (i=0; i<layer->num_channels; i++)
    {
      if (layer->channel[i].type == -1)
	{
	  return TRUE;
	}
    }

  return FALSE;
}


static
void extract_data_and_channels(guchar* src, gint gimpstep, gint psstep,
			       gint32 image_ID, GDrawable* drawable,
			       gint width, gint height)
{
  guchar* primary_data;
  guchar* aux_data;
  GPixelRgn pixel_rgn;

Manish Singh's avatar
Manish Singh committed
1283
  IFDBG printf("Extracting primary channel data (%d channels)\n"
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
	 "\tand %d auxiliary channels.\n", gimpstep, psstep-gimpstep);

  primary_data = xmalloc(width * height * gimpstep);
  {
    int pix,chan;

    for (pix=0; pix<width*height; pix++)
      {
	for (chan=0; chan<gimpstep; chan++)
	  {
	    primary_data [pix*gimpstep + chan] =
	      src [pix*psstep + chan];
	  }
      }
    
    gimp_pixel_rgn_init (&pixel_rgn, drawable,
			 0, 0, drawable->width, drawable->height,
			 TRUE, FALSE);
    gimp_pixel_rgn_set_rect (&pixel_rgn, primary_data,
			     0, 0, drawable->width, drawable->height);    
  
    gimp_drawable_flush (drawable);
    gimp_drawable_detach (drawable);
  }
  g_free(primary_data);


  aux_data = xmalloc(width * height);
  {
    int pix, chan;
    gint32 channel_ID;
    GDrawable* chdrawable;
    guchar colour[3]= {0, 0, 0};


    for (chan=gimpstep; chan<psstep; chan++)
      {
	for (pix=0; pix<width*height; pix++)
	  {
	    aux_data [pix] =
	      src [pix*psstep + chan];
	  }
	
	channel_ID = gimp_channel_new(image_ID,
				      psd_image.aux_channel[chan-gimpstep].name,
				      width, height,
				      100.0, colour);
	gimp_image_add_channel(image_ID, channel_ID, 0);
	gimp_channel_set_visible(channel_ID, FALSE);

	chdrawable = gimp_drawable_get(channel_ID);

	gimp_pixel_rgn_init (&pixel_rgn, chdrawable,
			     0, 0, chdrawable->width, chdrawable->height,
			     TRUE, FALSE);
	gimp_pixel_rgn_set_rect (&pixel_rgn, aux_data,
				 0, 0, chdrawable->width, chdrawable->height);
	
	gimp_drawable_flush (chdrawable);
	gimp_drawable_detach (chdrawable);
      }
  }
  g_free(aux_data);

Manish Singh's avatar
Manish Singh committed
1348
  IFDBG printf("Done with that.\n\n");
1349 1350 1351
}


1352 1353 1354 1355 1356 1357 1358 1359
static
void extract_channels(guchar* src, gint num_wanted, gint psstep,
		      gint32 image_ID,
		      gint width, gint height)
{
  guchar* aux_data;
  GPixelRgn pixel_rgn;

Manish Singh's avatar
Manish Singh committed
1360
  IFDBG printf("Extracting %d/%d auxiliary channels.\n", num_wanted, psstep);
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397

  aux_data = xmalloc(width * height);
  {
    int pix, chan;
    gint32 channel_ID;
    GDrawable* chdrawable;
    guchar colour[3]= {0, 0, 0};

    for (chan=psstep-num_wanted; chan<psstep; chan++)
      {
	for (pix=0; pix<width*height; pix++)
	  {
	    aux_data [pix] =
	      src [pix*psstep + chan];
	  }
	
	channel_ID = gimp_channel_new(image_ID,
				      psd_image.aux_channel[chan-(psstep-num_wanted)].name,
				      width, height,
				      100.0, colour);
	gimp_image_add_channel(image_ID, channel_ID, 0);
	gimp_channel_set_visible(channel_ID, FALSE);

	chdrawable = gimp_drawable_get(channel_ID);

	gimp_pixel_rgn_init (&pixel_rgn, chdrawable,
			     0, 0, chdrawable->width, chdrawable->height,
			     TRUE, FALSE);
	gimp_pixel_rgn_set_rect (&pixel_rgn, aux_data,
				 0, 0, chdrawable->width, chdrawable->height);
	
	gimp_drawable_flush (chdrawable);
	gimp_drawable_detach (chdrawable);
      }
  }
  g_free(aux_data);

Manish Singh's avatar
Manish Singh committed
1398
  IFDBG printf("Done with that.\n\n");
1399 1400 1401
}


1402 1403 1404 1405 1406 1407 1408 1409
static void
resize_mask(guchar* src, guchar* dest,
	    gint32 src_x, gint32 src_y,
	    gint32 src_w, gint32 src_h,
	    gint32 dest_w, gint32 dest_h)
{
  int x,y;

Manish Singh's avatar
Manish Singh committed
1410
  IFDBG printf("--> %p %p : %d %d . %d %d . %d %d\n",
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
	 src, dest,
	 src_x, src_y,
	 src_w, src_h,
	 dest_w, dest_h);

  for (y=0; y<dest_h; y++)
    {
      for (x=0; x<dest_w; x++)
	{
	  if ((x>src_x) && (x<src_x+src_w) &&
	      (y>src_y) && (y<src_y+src_h))
	    {
	      dest[dest_w * y + x] =
		src[src_w * (y-src_y) + (x-src_x)];
	    }
	  else
	    {
1428
	      dest[dest_w * y + x] = 255;
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
	    }
	}
    }
}


static gint32
load_image(char *name)
{
  FILE *fd;
1439
  gboolean want_aux;
Manish Singh's avatar
Manish Singh committed
1440 1441
  char *name_buf;
  guchar *cmykbuf;
1442
  static int number = 1;
Manish Singh's avatar
Manish Singh committed
1443
  guchar *dest, *temp;
1444
  long channels, nguchars;
1445 1446 1447 1448
  psd_imagetype imagetype;
  int cmyk = 0, step = 1;
  gint32 image_ID = -1;
  gint32 layer_ID = -1;
1449
  GDrawable *drawable = NULL;
1450 1451 1452 1453
  GPixelRgn pixel_rgn;
  gint32 iter;

    
Manish Singh's avatar
Manish Singh committed
1454
  IFDBG printf("------- %s ---------------------------------\n",name);
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499


  name_buf = xmalloc(strlen(name) + 11);
  if (number > 1)
    sprintf (name_buf, "%s-%d", name, number);
  else
    sprintf (name_buf, "%s", name);
  sprintf(name_buf, "Loading %s:", name);

  gimp_progress_init(name_buf);

  fd = fopen(name, "rb");
  if (fd==NULL) {
    printf("%s: can't open \"%s\"\n", prog_name, name);
    return(-1);
  }





  read_whole_file(fd);






  if (psd_image.num_layers > 0) /* PS3-style */
    {
      int lnum;
      GImageType gimagetype;

      gimagetype = psd_mode_to_gimp_base_type(PSDheader.mode);
      image_ID =
	gimp_image_new (PSDheader.columns, PSDheader.rows, gimagetype);
      gimp_image_set_filename (image_ID, name);
      
      for (lnum=0; lnum<psd_image.num_layers; lnum++)
	{
	  gint numc;
	  guchar* merged_data = NULL;

	  numc = psd_image.layer[lnum].num_channels;

Manish Singh's avatar
Manish Singh committed
1500
	  IFDBG printf("Hey, it's a LAYER with %d channels!\n", numc);
1501 1502 1503 1504 1505
	  
	  switch (gimagetype)
	    {
	    case GRAY:
	      {
Manish Singh's avatar
Manish Singh committed
1506
		IFDBG printf("It's GRAY.\n");
1507 1508 1509
		if (!psd_layer_has_alpha(&psd_image.layer[lnum]))
		  {
		    merged_data = xmalloc(psd_image.layer[lnum].width *
1510
					  psd_image.layer[lnum].height);
1511 1512 1513
		    memcpy(merged_data, psd_image.layer[lnum].channel[0].data,
			   psd_image.layer[lnum].width *
			   psd_image.layer[lnum].height);
Manish Singh's avatar
Manish Singh committed
1514 1515 1516

		    if (psd_image.layer[lnum].channel[0].data)
		      g_free(psd_image.layer[lnum].channel[0].data);
1517 1518 1519 1520 1521 1522 1523 1524
		  }
		else
		  {
		    merged_data =
		      chans_to_GRAYA (psd_image.layer[lnum].channel[1].data,
				      psd_image.layer[lnum].channel[0].data,
				      psd_image.layer[lnum].width *
				      psd_image.layer[lnum].height);
Manish Singh's avatar
Manish Singh committed
1525 1526 1527 1528 1529

		    if (psd_image.layer[lnum].channel[0].data)
		      g_free(psd_image.layer[lnum].channel[0].data);
		    if (psd_image.layer[lnum].channel[1].data)
		      g_free(psd_image.layer[lnum].channel[1].data);
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
		  }
		  
		layer_ID = gimp_layer_new (image_ID,
					   psd_image.layer[lnum].name,
					   psd_image.layer[lnum].width,
					   psd_image.layer[lnum].height,
					   (numc==1) ? GRAY_IMAGE:GRAYA_IMAGE,
					   (100.0*(double)psd_image.layer[lnum].opacity)/255.0,
					   psd_lmode_to_gimp_lmode(psd_image.layer[lnum].blendkey));

	      }; break; /* case GRAY */
	    case RGB:
	      {
Manish Singh's avatar
Manish Singh committed
1543
		IFDBG printf("It's RGB.\n");
1544 1545 1546 1547 1548 1549 1550 1551
		if (!psd_layer_has_alpha(&psd_image.layer[lnum]))
		  {
		    merged_data =
		      chans_to_RGB (psd_image.layer[lnum].channel[0].data,
				    psd_image.layer[lnum].channel[1].data,
				    psd_image.layer[lnum].channel[2].data,
				    psd_image.layer[lnum].width *
				    psd_image.layer[lnum].height);
Manish Singh's avatar
Manish Singh committed
1552 1553 1554 1555 1556 1557 1558

		    if (psd_image.layer[lnum].channel[0].data)
		      g_free(psd_image.layer[lnum].channel[0].data);
		    if (psd_image.layer[lnum].channel[1].data)
		      g_free(psd_image.layer[lnum].channel[1].data);
		    if (psd_image.layer[lnum].channel[2].data)
		      g_free(psd_image.layer[lnum].channel[2].data);
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
		  }
		else
		  {
		    merged_data =
		      chans_to_RGBA (psd_image.layer[lnum].channel[1].data,
				     psd_image.layer[lnum].channel[2].data,
				     psd_image.layer[lnum].channel[3].data,
				     psd_image.layer[lnum].channel[0].data,
				     psd_image.layer[lnum].width *
				     psd_image.layer[lnum].height);
Manish Singh's avatar
Manish Singh committed
1569 1570 1571 1572 1573 1574 1575 1576 1577

		    if (psd_image.layer[lnum].channel[0].data)
		      g_free(psd_image.layer[lnum].channel[0].data);
		    if (psd_image.layer[lnum].channel[1].data)
		      g_free(psd_image.layer[lnum].channel[1].data);
		    if (psd_image.layer[lnum].channel[2].data)
		      g_free(psd_image.layer[lnum].channel[2].data);
		    if (psd_image.layer[lnum].channel[3].data)
		      g_free(psd_image.layer[lnum].channel[3].data);
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
		  }
		  
		layer_ID = gimp_layer_new (image_ID,
					   psd_image.layer[lnum].name,
					   psd_image.layer[lnum].width,
					   psd_image.layer[lnum].height,
					   (numc==3) ? RGB_IMAGE:RGBA_IMAGE,
					   (100.0*(double)psd_image.layer[lnum].opacity)/255.0,
					   psd_lmode_to_gimp_lmode(psd_image.layer[lnum].blendkey));

	      }; break; /* case RGB */
	    default:
	      {
		printf("Error: Sorry, can't deal with a layered image of this type.\n");
		gimp_quit();
	      }; break; /* default */
	    }


	  gimp_image_add_layer (image_ID, layer_ID, 0);


	  /* Do a layer mask if it exists */
	  for (iter=0; iter<psd_image.layer[lnum].num_channels; iter++)
	    {
	      if (psd_image.layer[lnum].channel[iter].type == -2) /* is mask */
		{
		  gint32 mask_id;
		  guchar* lm_data;

		  lm_data = xmalloc(psd_image.layer[lnum].width *
				    psd_image.layer[lnum].height);
		  {
		    /* PS layer masks can be a different size to
		       their owning layer, so we have to resize them. */
		    resize_mask(psd_image.layer[lnum].channel[iter].data,
				lm_data,
				psd_image.layer[lnum].lm_x-
				psd_image.layer[lnum].x,
				psd_image.layer[lnum].lm_y-
				psd_image.layer[lnum].y,
				psd_image.layer[lnum].lm_width,
				psd_image.layer[lnum].lm_height,
				psd_image.layer[lnum].width,
				psd_image.layer[lnum].height);
Manish Singh's avatar
Manish Singh committed
1623 1624 1625 1626 1627 1628

		    /* won't be needing the original data any more */
		    if (psd_image.layer[lnum].channel[iter].data)
		      g_free(psd_image.layer[lnum].channel[iter].data);

		    /* give it to GIMP */
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
		    mask_id = gimp_layer_create_mask(layer_ID, 0);
		    gimp_image_add_layer_mask(image_ID, layer_ID, mask_id);
		    
		    drawable = gimp_drawable_get (mask_id);
		    
		    gimp_pixel_rgn_init (&pixel_rgn, drawable,
					 0, 0, 
					 psd_image.layer[lnum].width,
					 psd_image.layer[lnum].height,
					 TRUE, FALSE);
		    gimp_pixel_rgn_set_rect (&pixel_rgn,
					     lm_data,
					     0, 0, 
					     psd_image.layer[lnum].width,
					     psd_image.layer[lnum].height);
		  }
		  g_free(lm_data);
		  
		  gimp_drawable_flush (drawable);
		  gimp_drawable_detach (drawable);
		}
	    }


	  gimp_layer_translate(