1 /*
2  * PSD Export Plugin version 1.0 (BETA)
3  * This GIMP plug-in is designed to export Adobe Photoshop(tm) files (.PSD)
4  *
5  * Monigotes
6  *
7  *     If this plug-in fails to export a file which you think it should,
8  *     please tell me what seemed to go wrong, and anything you know
9  *     about the image you tried to export.  Please don't send big PSD
10  *     files to me without asking first.
11  *
12  *          Copyright (C) 2000 Monigotes
13  *
14  * This program is free software: you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 3 of the License, or
17  * (at your option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
26  */
27 
28 /*
29  * Adobe and Adobe Photoshop are trademarks of Adobe Systems
30  * Incorporated that may be registered in certain jurisdictions.
31  */
32 
33 /*
34  * Revision history:
35  *
36  *  2000.02 / v1.0 / Monigotes
37  *       First version.
38  *
39  *  2003-05-10  Pedro Gimeno  <pggimeno@wanadoo.es>
40  *       - Cleaned up and GNUstylized.
41  *       - Translated all comments and vars in Spanish to English.
42  *
43  *  2005-2-11 Jay Cox <jaycox@gimp.org>
44  *       Rewrote all the code that deals with pixels to be stingy with
45  *       memory and operate on tile-size chunks.  Create a flattened
46  *       copy of the image when necessary. Fixes file corruption bug
47  *       #167139 and memory bug #121871
48  *
49  *  2006-03-29 Guillermo S. Romero <gsr.bugs@infernal-iceberg.com>
50  *       - Added/enabled basic support for layer masks based in psd.c
51  *         and whatever was already here.
52  *         Layers that are not canvas sized need investigation, here
53  *         or in the import plugin something seems wrong.
54  *       - Cosmetic changes about the debug messages, more like psd.c.
55  */
56 
57 /*
58  * TODO:
59  *       Export preview
60  */
61 
62 /*
63  * BUGS:
64  */
65 
66 #include "config.h"
67 
68 #include <errno.h>
69 #include <string.h>
70 
71 #include <glib/gstdio.h>
72 
73 #include "libgimp/gimp.h"
74 #include "libgimp/gimpui.h"
75 
76 #include "libgimpmath/gimpmath.h"
77 
78 #include "psd.h"
79 #include "psd-util.h"
80 #include "psd-save.h"
81 
82 #include "libgimp/stdplugins-intl.h"
83 
84 
85 /* set to TRUE if you want debugging, FALSE otherwise */
86 #define DEBUG FALSE
87 
88 /* 1: Normal debuggin, 2: Deep debuggin */
89 #define DEBUG_LEVEL 2
90 
91 #undef IFDBG /* previously defined in psd.h */
92 
93 #define IFDBG if (DEBUG)
94 #define IF_DEEP_DBG if (DEBUG && DEBUG_LEVEL == 2)
95 
96 #define PSD_UNIT_INCH 1
97 #define PSD_UNIT_CM   2
98 
99 
100 /* Local types etc
101  */
102 
103 typedef enum PsdLayerType
104 {
105   PSD_LAYER_TYPE_LAYER,
106   PSD_LAYER_TYPE_GROUP_START,
107   PSD_LAYER_TYPE_GROUP_END
108 } PSD_Layer_Type;
109 
110 typedef struct PsdLayer
111 {
112   gint           id;
113   PSD_Layer_Type type;
114 } PSD_Layer;
115 
116 typedef struct PsdImageData
117 {
118   gboolean           compression;
119 
120   gint32             image_height;
121   gint32             image_width;
122 
123   GimpImageBaseType  baseType;
124 
125   gint32             merged_layer;/* Merged image,
126                                      to be used for the image data section */
127 
128   gint               nChannels;   /* Number of user channels in the image */
129   gint32            *lChannels;   /* User channels in the image */
130 
131   gint               nLayers;     /* Number of layers in the image */
132   PSD_Layer         *lLayers;     /* Layer list */
133 } PSD_Image_Data;
134 
135 static PSD_Image_Data PSDImageData;
136 
137 /* Declare some local functions.
138  */
139 
140 static const gchar * psd_lmode_layer      (gint32         idLayer,
141                                            gboolean       section_divider);
142 
143 static void          reshuffle_cmap_write (guchar        *mapGimp);
144 
145 static void          save_header          (FILE          *fd,
146                                            gint32         image_id);
147 
148 static void          save_color_mode_data (FILE          *fd,
149                                            gint32         image_id);
150 
151 static void          save_resources       (FILE          *fd,
152                                            gint32         image_id);
153 
154 static void          save_layer_and_mask  (FILE          *fd,
155                                            gint32         image_id);
156 
157 static void          save_data            (FILE          *fd,
158                                            gint32         image_id);
159 
160 static void          xfwrite              (FILE          *fd,
161                                            gconstpointer  buf,
162                                            glong          len,
163                                            const gchar   *why);
164 
165 static void          write_pascalstring   (FILE          *fd,
166                                            const gchar   *val,
167                                            gint           padding,
168                                            const gchar   *why);
169 
170 static void          write_string         (FILE          *fd,
171                                            const gchar   *val,
172                                            const gchar   *why);
173 
174 static void          write_gchar          (FILE          *fd,
175                                            guchar         val,
176                                            const gchar   *why);
177 
178 static void          write_gint16         (FILE          *fd,
179                                            gint16         val,
180                                            const gchar   *why);
181 
182 static void          write_gint32         (FILE          *fd,
183                                            gint32         val,
184                                            const gchar   *why);
185 
186 static void          write_datablock_luni (FILE          *fd,
187                                            const gchar   *val,
188                                            const gchar   *why);
189 
190 
191 static void          write_pixel_data     (FILE          *fd,
192                                            gint32         drawableID,
193                                            glong         *ChanLenPosition,
194                                            gint32         rowlenOffset,
195                                            gboolean       write_mask);
196 
197 static gint32        create_merged_image  (gint32         imageID);
198 
199 static gint          get_bpc              (gint32         imageID);
200 static const Babl  * get_pixel_format     (gint32         drawableID);
201 static const Babl  * get_channel_format   (gint32         drawableID);
202 static const Babl  * get_mask_format      (gint32         drawableID);
203 
204 static PSD_Layer   * image_get_all_layers (gint32         imageID,
205                                            gint          *n_layers);
206 
207 static const gchar *
psd_lmode_layer(gint32 idLayer,gboolean section_divider)208 psd_lmode_layer (gint32   idLayer,
209                  gboolean section_divider)
210 {
211   LayerModeInfo mode_info;
212 
213   mode_info.mode            = gimp_layer_get_mode (idLayer);
214   mode_info.blend_space     = gimp_layer_get_blend_space (idLayer);
215   mode_info.composite_space = gimp_layer_get_composite_space (idLayer);
216   mode_info.composite_mode  = gimp_layer_get_composite_mode (idLayer);
217 
218   /* pass-through groups use normal mode in their layer record; the
219    * pass-through mode is specified in their section divider resource.
220    */
221   if (mode_info.mode == GIMP_LAYER_MODE_PASS_THROUGH && ! section_divider)
222     mode_info.mode = GIMP_LAYER_MODE_NORMAL;
223 
224   return gimp_to_psd_blend_mode (&mode_info);
225 }
226 
227 static void
write_string(FILE * fd,const gchar * val,const gchar * why)228 write_string (FILE        *fd,
229               const gchar *val,
230               const gchar *why)
231 {
232   write_gchar (fd, strlen (val), why);
233   xfwrite (fd, val, strlen (val), why);
234 }
235 
236 static void
write_pascalstring(FILE * fd,const gchar * val,gint padding,const gchar * why)237 write_pascalstring (FILE        *fd,
238                     const gchar *val,
239                     gint         padding,
240                     const gchar *why)
241 {
242   guchar len;
243   gint   i;
244 
245   /* Calculate string length to write and limit it to 255 */
246 
247   len = (strlen (val) > 255) ? 255 : (guchar) strlen (val);
248 
249   /* Perform actual writing */
250 
251   if (len !=  0)
252     {
253       write_gchar (fd, len, why);
254       xfwrite (fd, val, len, why);
255     }
256   else
257     {
258       write_gchar (fd, 0, why);
259     }
260 
261   /* If total length (length byte + content) is not a multiple of PADDING,
262      add zeros to pad it.  */
263 
264   len++;           /* Add the length field */
265 
266   if ((len % padding) == 0)
267     return;
268 
269   for (i = 0; i < (padding - (len % padding)); i++)
270     write_gchar (fd, 0, why);
271 }
272 
273 static void
xfwrite(FILE * fd,gconstpointer buf,glong len,const gchar * why)274 xfwrite (FILE          *fd,
275          gconstpointer  buf,
276          glong          len,
277          const gchar   *why)
278 {
279   if (len == 0)
280     return;
281 
282   if (fwrite (buf, len, 1, fd) == 0)
283     {
284       g_printerr ("%s: Error while writing '%s'\n", G_STRFUNC, why);
285       gimp_quit ();
286     }
287 }
288 
289 static void
write_gchar(FILE * fd,guchar val,const gchar * why)290 write_gchar (FILE        *fd,
291              guchar       val,
292              const gchar *why)
293 {
294   guchar b[2];
295   glong  pos;
296 
297   b[0] = val;
298   b[1] = 0;
299 
300   pos = ftell (fd);
301   if (fwrite (&b, 1, 2, fd) == 0)
302     {
303       g_printerr ("%s: Error while writing '%s'\n", G_STRFUNC, why);
304       gimp_quit ();
305     }
306   fseek (fd, pos + 1, SEEK_SET);
307 }
308 
309 static void
write_gint16(FILE * fd,gint16 val,const gchar * why)310 write_gint16 (FILE        *fd,
311               gint16       val,
312               const gchar *why)
313 {
314   guchar b[2];
315   /*  b[0] = val & 255;
316       b[1] = (val >> 8) & 255;*/
317 
318   b[1] = val & 255;
319   b[0] = (val >> 8) & 255;
320 
321   if (fwrite (&b, 1, 2, fd) == 0)
322     {
323       g_printerr ("%s: Error while writing '%s'\n", G_STRFUNC, why);
324       gimp_quit ();
325     }
326 }
327 
328 static void
write_gint32(FILE * fd,gint32 val,const gchar * why)329 write_gint32 (FILE        *fd,
330               gint32       val,
331               const gchar *why)
332 {
333   guchar b[4];
334 
335   b[3] = val & 255;
336   b[2] = (val >> 8) & 255;
337   b[1] = (val >> 16) & 255;
338   b[0] = (val >> 24) & 255;
339 
340   if (fwrite (&b, 1, 4, fd) == 0)
341     {
342       g_printerr ("%s: Error while writing '%s'\n", G_STRFUNC, why);
343       gimp_quit ();
344     }
345 }
346 
347 static void
write_datablock_luni(FILE * fd,const gchar * val,const gchar * why)348 write_datablock_luni (FILE        *fd,
349                       const gchar *val,
350                       const gchar *why)
351 {
352   if (val)
353     {
354       guint32    count;
355       guint32    xdBlockSize;
356       glong      numchars;
357       gunichar2 *luniName;
358 
359       luniName = g_utf8_to_utf16 (val, -1, NULL, &numchars, NULL);
360 
361       if (luniName)
362         {
363           guchar len = MIN (numchars, 255);
364 
365           /* Only pad to even num of chars */
366           if( len % 2 )
367             xdBlockSize = len + 1;
368           else
369             xdBlockSize = len;
370 
371           /* 2 bytes / char + 4 bytes for pascal num chars */
372           xdBlockSize = (xdBlockSize * 2) + 4;
373 
374           xfwrite (fd, "8BIMluni", 8, "luni xdb signature");
375           write_gint32 (fd, xdBlockSize, "luni xdb size");
376           write_gint32 (fd, len, "luni xdb pascal string");
377 
378           for (count = 0; count < len; count++)
379             write_gint16 (fd, luniName[count], "luni xdb pascal string");
380 
381           /* Pad to an even number of chars */
382           if (len % 2)
383             write_gint16 (fd, 0x0000, "luni xdb pascal string padding");
384         }
385     }
386 }
387 
388 static gint32
pack_pb_line(guchar * start,gint32 length,guchar * dest_ptr)389 pack_pb_line (guchar *start,
390               gint32  length,
391               guchar *dest_ptr)
392 {
393   gint32  remaining = length;
394   gint    i, j;
395 
396   length = 0;
397   while (remaining > 0)
398     {
399       /* Look for characters matching the first */
400 
401       i = 0;
402       while ((i < 128) &&
403              (remaining - i > 0) &&
404              (start[0] == start[i]))
405         i++;
406 
407       if (i > 1)              /* Match found */
408         {
409 
410           *dest_ptr++ = -(i - 1);
411           *dest_ptr++ = *start;
412 
413           start += i;
414           remaining -= i;
415           length += 2;
416         }
417       else       /* Look for characters different from the previous */
418         {
419           i = 0;
420           while ((i < 128)                 &&
421                  (remaining - (i + 1) > 0) &&
422                  (start[i] != start[i + 1] ||
423                   remaining - (i + 2) <= 0 || start[i] != start[i+2]))
424             i++;
425 
426           /* If there's only 1 remaining, the previous WHILE stmt doesn't
427              catch it */
428 
429           if (remaining == 1)
430             {
431               i = 1;
432             }
433 
434           if (i > 0)               /* Some distinct ones found */
435             {
436               *dest_ptr++ = i - 1;
437               for (j = 0; j < i; j++)
438                 {
439                   *dest_ptr++ = start[j];
440                 }
441               start += i;
442               remaining -= i;
443               length += i + 1;
444             }
445 
446         }
447     }
448   return length;
449 }
450 
451 static gint
gimpBaseTypeToPsdMode(GimpImageBaseType gimpBaseType)452 gimpBaseTypeToPsdMode (GimpImageBaseType gimpBaseType)
453 {
454   switch (gimpBaseType)
455     {
456     case GIMP_RGB:
457       return 3;                                         /* RGB */
458     case GIMP_GRAY:
459       return 1;                                         /* Grayscale */
460     case GIMP_INDEXED:
461       return 2;                                         /* Indexed */
462     default:
463       g_message (_("Error: Can't convert GIMP base imagetype to PSD mode"));
464       IFDBG printf ("PSD Export: gimpBaseType value is %d, "
465                     "can't convert to PSD mode", gimpBaseType);
466       gimp_quit ();
467       return 3;                            /* Return RGB by default */
468     }
469 }
470 
471 static gint
nChansLayer(gint gimpBaseType,gint hasAlpha,gint hasMask)472 nChansLayer (gint gimpBaseType,
473              gint hasAlpha,
474              gint hasMask)
475 {
476   gint incAlpha = 0;
477   gint incMask = 0;
478 
479   incAlpha = (hasAlpha == 0) ? 0 : 1;
480   incMask = (hasMask == 0) ? 0 : 1;
481 
482   switch (gimpBaseType)
483     {
484     case GIMP_RGB:
485       return 3 + incAlpha + incMask;     /* R,G,B & Alpha & Mask (if any) */
486     case GIMP_GRAY:
487       return 1 + incAlpha + incMask;     /* G & Alpha & Mask (if any) */
488     case GIMP_INDEXED:
489       return 1 + incAlpha + incMask;     /* I & Alpha & Mask (if any) */
490     default:
491       return 0;                          /* Return 0 channels by default */
492     }
493 }
494 
495 static void
reshuffle_cmap_write(guchar * mapGimp)496 reshuffle_cmap_write (guchar *mapGimp)
497 {
498   guchar *mapPSD;
499   gint    i;
500 
501   mapPSD = g_malloc (768);
502 
503   for (i = 0; i < 256; i++)
504     {
505       mapPSD[i] = mapGimp[i * 3];
506       mapPSD[i + 256] = mapGimp[i * 3 + 1];
507       mapPSD[i + 512] = mapGimp[i * 3 + 2];
508     }
509 
510   for (i = 0; i < 768; i++)
511     {
512       mapGimp[i] = mapPSD[i];
513     }
514 
515   g_free (mapPSD);
516 }
517 
518 static void
save_header(FILE * fd,gint32 image_id)519 save_header (FILE   *fd,
520              gint32  image_id)
521 {
522   IFDBG printf (" Function: save_header\n");
523   IFDBG printf ("\tRows: %d\n", PSDImageData.image_height);
524   IFDBG printf ("\tColumns: %d\n", PSDImageData.image_width);
525   IFDBG printf ("\tBase type: %d\n", PSDImageData.baseType);
526   IFDBG printf ("\tNumber of channels: %d\n", PSDImageData.nChannels);
527 
528   xfwrite (fd, "8BPS", 4, "signature");
529   write_gint16 (fd, 1, "version");
530   write_gint32 (fd, 0, "reserved 1");      /* 6 for the 'reserved' field + 4 bytes for a long */
531   write_gint16 (fd, 0, "reserved 1");      /* and 2 bytes for a short */
532   write_gint16 (fd, (PSDImageData.nChannels +
533                      nChansLayer (PSDImageData.baseType,
534                      gimp_drawable_has_alpha (PSDImageData.merged_layer), 0)),
535                 "channels");
536   write_gint32 (fd, PSDImageData.image_height, "rows");
537   write_gint32 (fd, PSDImageData.image_width, "columns");
538   write_gint16 (fd, 8 * get_bpc (image_id), "depth");
539   write_gint16 (fd, gimpBaseTypeToPsdMode (PSDImageData.baseType), "mode");
540 }
541 
542 static void
save_color_mode_data(FILE * fd,gint32 image_id)543 save_color_mode_data (FILE   *fd,
544                       gint32  image_id)
545 {
546   guchar *cmap;
547   guchar *cmap_modified;
548   gint    i;
549   gint32  nColors;
550 
551   IFDBG printf (" Function: save_color_mode_data\n");
552 
553   switch (PSDImageData.baseType)
554     {
555     case GIMP_INDEXED:
556       IFDBG printf ("\tImage type: INDEXED\n");
557 
558       cmap = gimp_image_get_colormap (image_id, &nColors);
559       IFDBG printf ("\t\tLength of colormap returned by gimp_image_get_colormap: %d\n", nColors);
560 
561       if (nColors == 0)
562         {
563           IFDBG printf ("\t\tThe indexed image lacks a colormap\n");
564           write_gint32 (fd, 0, "color data length");
565         }
566       else if (nColors != 256)
567         {
568           IFDBG printf ("\t\tThe indexed image has %d!=256 colors\n", nColors);
569           IFDBG printf ("\t\tPadding with zeros up to 256\n");
570           write_gint32 (fd, 768, "color data length");
571             /* For this type, length is always 768 */
572 
573           cmap_modified = g_malloc (768);
574           for (i = 0; i < nColors * 3; i++)
575             cmap_modified[i] = cmap[i];
576 
577           for (i = nColors * 3; i < 768; i++)
578             cmap_modified[i] = 0;
579 
580           reshuffle_cmap_write (cmap_modified);
581           xfwrite (fd, cmap_modified, 768, "colormap");  /* Write readjusted colormap */
582 
583           g_free (cmap_modified);
584         }
585       else         /* nColors equals 256 */
586         {
587           write_gint32 (fd, 768, "color data length");   /* For this type, length is always 768 */
588           reshuffle_cmap_write (cmap);
589           xfwrite (fd, cmap, 768, "colormap");  /* Write readjusted colormap */
590         }
591       break;
592 
593     default:
594       IFDBG printf ("\tImage type: Not INDEXED\n");
595       write_gint32 (fd, 0, "color data length");
596     }
597 }
598 
599 static void
save_resources(FILE * fd,gint32 image_id)600 save_resources (FILE   *fd,
601                 gint32  image_id)
602 {
603   gint          i;
604   gchar        *fileName;            /* Image file name */
605   gint32        idActLayer;          /* Id of the active layer */
606   guint         nActiveLayer = 0;    /* Number of the active layer */
607   gboolean      ActiveLayerPresent;  /* TRUE if there's an active layer */
608 
609   glong         eof_pos;             /* Position for End of file */
610   glong         rsc_pos;             /* Position for Lengths of Resources section */
611   glong         name_sec;            /* Position for Lengths of Channel Names */
612 
613 
614   /* Only relevant resources in GIMP are: 0x03EE, 0x03F0 & 0x0400 */
615   /* For Adobe Photoshop version 4.0 these can also be considered:
616      0x0408, 0x040A & 0x040B (1006, 1008, 1024, 1032, 1034, and 1035) */
617 
618   IFDBG printf (" Function: save_resources\n");
619 
620 
621   /* Get the image title from its filename */
622 
623   fileName = gimp_image_get_filename (image_id);
624   IFDBG printf ("\tImage title: %s\n", fileName);
625 
626   /* Get the active layer number id */
627 
628   idActLayer = gimp_image_get_active_layer (image_id);
629   IFDBG printf ("\tCurrent layer id: %d\n", idActLayer);
630 
631   ActiveLayerPresent = FALSE;
632   for (i = 0; i < PSDImageData.nLayers; i++)
633     if (idActLayer == PSDImageData.lLayers[i].id)
634       {
635         nActiveLayer = PSDImageData.nLayers - i - 1;
636         ActiveLayerPresent = TRUE;
637         break;
638       }
639 
640   if (ActiveLayerPresent)
641     {
642       IFDBG printf ("\t\tActive layer is number %d\n", nActiveLayer);
643     }
644   else
645     {
646       IFDBG printf ("\t\tNo active layer\n");
647     }
648 
649 
650   /* Here's where actual writing starts */
651 
652   rsc_pos = ftell (fd);
653   write_gint32 (fd, 0, "image resources length");
654 
655 
656   /* --------------- Write Channel names --------------- */
657 
658   if (PSDImageData.nChannels > 0 ||
659       gimp_drawable_has_alpha (PSDImageData.merged_layer))
660     {
661       xfwrite (fd, "8BIM", 4, "imageresources signature");
662       write_gint16 (fd, 0x03EE, "0x03EE Id"); /* 1006 */
663       /* write_pascalstring (fd, Name, "Id name"); */
664       write_gint16 (fd, 0, "Id name"); /* Set to null string (two zeros) */
665 
666       /* Mark current position in the file */
667 
668       name_sec = ftell (fd);
669       write_gint32 (fd, 0, "0x03EE resource size");
670 
671       /* Write all strings */
672 
673       /* if the merged_image contains transparency, write a name for it first */
674       if (gimp_drawable_has_alpha (PSDImageData.merged_layer))
675         write_string (fd, "Transparency", "channel name");
676 
677       for (i = 0; i < PSDImageData.nChannels; i++)
678         {
679           char *chName = gimp_item_get_name (PSDImageData.lChannels[i]);
680           write_string (fd, chName, "channel name");
681           g_free (chName);
682         }
683       /* Calculate and write actual resource's length */
684 
685       eof_pos = ftell (fd);
686 
687       fseek (fd, name_sec, SEEK_SET);
688       write_gint32 (fd, eof_pos - name_sec - sizeof (gint32), "0x03EE resource size");
689       IFDBG printf ("\tTotal length of 0x03EE resource: %d\n",
690                     (int) (eof_pos - name_sec - sizeof (gint32)));
691 
692       /* Return to EOF to continue writing */
693 
694       fseek (fd, eof_pos, SEEK_SET);
695 
696       /* Pad if length is odd */
697 
698       if ((eof_pos - name_sec - sizeof (gint32)) & 1)
699         write_gchar (fd, 0, "pad byte");
700     }
701 
702   /* --------------- Write Channel properties --------------- */
703 
704   if (PSDImageData.nChannels > 0 ||
705       gimp_drawable_has_alpha (PSDImageData.merged_layer))
706     {
707       xfwrite (fd, "8BIM", 4, "imageresources signature");
708       write_gint16 (fd, 0x0435, "0x0435 Id"); /* 1077 */
709       /* write_pascalstring (fd, Name, "Id name"); */
710       write_gint16 (fd, 0, "Id name"); /* Set to null string (two zeros) */
711       write_gint32 (fd,
712                     4  +
713                     13 * (gimp_drawable_has_alpha (PSDImageData.merged_layer) +
714                           PSDImageData.nChannels),
715                     "0x0435 resource size");
716 
717       /* The function of the first 4 bytes is unclear. As per
718        * load_resource_1077() in psd-image-res-load.c, it seems to be a version
719        * number that is always one.
720        */
721       write_gint32 (fd, 1, "0x0435 version");
722 
723       /* Write all channel properties */
724 
725       #define DOUBLE_TO_INT16(x) ROUND (SAFE_CLAMP (x, 0.0, 1.0) * 0xffff)
726 
727       /* if the merged_image contains transparency, write its properties first */
728       if (gimp_drawable_has_alpha (PSDImageData.merged_layer))
729         {
730           write_gint16 (fd, PSD_CS_RGB, "channel color space");
731           write_gint16 (fd, DOUBLE_TO_INT16 (1.0), "channel color r");
732           write_gint16 (fd, DOUBLE_TO_INT16 (0.0), "channel color g");
733           write_gint16 (fd, DOUBLE_TO_INT16 (0.0), "channel color b");
734           write_gint16 (fd, 0,                     "channel color padding");
735           write_gint16 (fd, 100,                   "channel opacity");
736           write_gchar  (fd, 1,                     "channel mode");
737         }
738 
739       for (i = 0; i < PSDImageData.nChannels; i++)
740         {
741           GimpRGB color;
742           gdouble opacity;
743 
744           gimp_channel_get_color (PSDImageData.lChannels[i], &color);
745           opacity = gimp_channel_get_opacity (PSDImageData.lChannels[i]);
746 
747           write_gint16 (fd, PSD_CS_RGB,                "channel color space");
748           write_gint16 (fd, DOUBLE_TO_INT16 (color.r), "channel color r");
749           write_gint16 (fd, DOUBLE_TO_INT16 (color.g), "channel color g");
750           write_gint16 (fd, DOUBLE_TO_INT16 (color.b), "channel color b");
751           write_gint16 (fd, 0,                         "channel color padding");
752           write_gint16 (fd, ROUND (opacity),           "channel opacity");
753           write_gchar  (fd, 1,                         "channel mode");
754         }
755 
756       #undef DOUBLE_TO_INT16
757 
758       /* Pad if length is odd */
759 
760       if (ftell (fd) & 1)
761         write_gchar (fd, 0, "pad byte");
762     }
763 
764   /* --------------- Write Guides --------------- */
765   if (gimp_image_find_next_guide(image_id, 0))
766     {
767       gint n_guides = 0;
768       gint guide_id =0;
769 
770       /* Count the guides */
771       while ((guide_id = gimp_image_find_next_guide(image_id, guide_id)))
772         n_guides++;
773 
774       xfwrite (fd, "8BIM", 4, "imageresources signature");
775       write_gint16 (fd, 0x0408, "0x0408 Id (Guides)"); /* 1032 */
776       /* write_pascalstring (fd, Name, "Id name"); */
777       write_gint16 (fd, 0, "Id name"); /* Set to null string (two zeros) */
778       write_gint32 (fd, 16 + 5 * n_guides, "0x0408 resource size");
779       /* Save grid and guide header */
780       write_gint32 (fd,   1, "grid/guide header version");
781       write_gint32 (fd, 576, "grid custom spacing horizontal");/* dpi*32/4??*/
782       write_gint32 (fd, 576, "grid custom spacing vertical");  /* dpi*32/4??*/
783       write_gint32 (fd, n_guides, "number of guides");
784 
785       /* write the guides */
786       while ((guide_id = gimp_image_find_next_guide(image_id, guide_id)))
787         {
788           gchar orientation;
789           gint32 position;
790           orientation = gimp_image_get_guide_orientation(image_id, guide_id);
791           position    = 32 * gimp_image_get_guide_position(image_id, guide_id);
792           orientation ^= 1; /* in the psd vert =0 , horiz = 1 */
793           write_gint32 (fd, position, "Position of guide");
794           write_gchar (fd, orientation, "Orientation of guide");
795           n_guides--;
796         }
797       if ((ftell(fd) & 1))
798         write_gchar(fd, 0, "pad byte");
799       if (n_guides != 0)
800         g_warning("Screwed up guide resource:: wrong number of guides\n");
801       IFDBG printf ("\tTotal length of 0x0400 resource: %d\n", (int) sizeof (gint16));
802     }
803 
804   /* --------------- Write resolution data ------------------- */
805   {
806     gdouble xres = 0, yres = 0;
807     guint32 xres_fix, yres_fix;
808     GimpUnit g_unit;
809     gint16 psd_unit;
810 
811     g_unit = gimp_image_get_unit (image_id);
812     gimp_image_get_resolution (image_id, &xres, &yres);
813 
814     if (g_unit == GIMP_UNIT_MM)
815       {
816         gdouble factor = gimp_unit_get_factor (g_unit) / 10.0;
817 
818         xres /= factor;
819         yres /= factor;
820 
821         psd_unit = PSD_UNIT_CM;
822       }
823     else
824       {
825         psd_unit = PSD_UNIT_INCH;
826       }
827 
828     xres_fix = xres * 65536.0 + .5; /* Convert to 16.16 fixed point */
829     yres_fix = yres * 65536.0 + .5; /* Convert to 16.16 fixed point */
830 
831     xfwrite (fd, "8BIM", 4, "imageresources signature (for resolution)");
832     write_gint16(fd, 0x03ed, "0x03ed Id (resolution)"); /* 1005 */
833     write_gint16 (fd, 0, "Id name"); /* Set to null string (two zeros) */
834     write_gint32 (fd, 16, "0x0400 resource size");
835     write_gint32 (fd,  xres_fix, "hRes (16.16 fixed point)");
836     write_gint16 (fd, psd_unit, "hRes unit");
837     write_gint16 (fd, psd_unit, "width unit");
838     write_gint32 (fd,  yres_fix, "vRes (16.16 fixed point)");
839     write_gint16 (fd, psd_unit, "vRes unit");
840     write_gint16 (fd, psd_unit, "height unit");
841   }
842 
843   /* --------------- Write Active Layer Number --------------- */
844 
845   if (ActiveLayerPresent)
846     {
847       xfwrite (fd, "8BIM", 4, "imageresources signature");
848       write_gint16 (fd, 0x0400, "0x0400 Id"); /* 1024 */
849       /* write_pascalstring (fd, Name, "Id name"); */
850       write_gint16 (fd, 0, "Id name"); /* Set to null string (two zeros) */
851       write_gint32 (fd, sizeof (gint16), "0x0400 resource size");
852 
853       /* Save title as gint16 (length always even) */
854 
855       write_gint16 (fd, nActiveLayer, "active layer");
856 
857       IFDBG printf ("\tTotal length of 0x0400 resource: %d\n", (int) sizeof (gint16));
858     }
859 
860   /* --------------- Write ICC profile data ------------------- */
861   {
862     GimpColorProfile *profile;
863 
864     profile = gimp_image_get_effective_color_profile (image_id);
865 
866     if (profile)
867       {
868         const guint8 *icc_data;
869         gsize         icc_length;
870 
871         icc_data = gimp_color_profile_get_icc_profile (profile, &icc_length);
872 
873         xfwrite (fd, "8BIM", 4, "imageresources signature");
874         write_gint16 (fd, 0x040f, "0x040f Id");
875         write_gint16 (fd, 0, "Id name"); /* Set to null string (two zeros) */
876         write_gint32 (fd, icc_length, "0x040f resource size");
877         xfwrite (fd, icc_data, icc_length, "ICC profile");
878 
879         g_object_unref (profile);
880       }
881   }
882 
883   /* --------------- Write Total Section Length --------------- */
884 
885   eof_pos = ftell (fd);
886 
887   fseek (fd, rsc_pos, SEEK_SET);
888   write_gint32 (fd, eof_pos - rsc_pos - sizeof (gint32), "image resources length");
889   IFDBG printf ("\tResource section total length: %d\n",
890                 (int) (eof_pos - rsc_pos - sizeof (gint32)));
891 
892   /* Return to EOF to continue writing */
893 
894   fseek (fd, eof_pos, SEEK_SET);
895 }
896 
897 static int
get_compress_channel_data(guchar * channel_data,gint32 channel_cols,gint32 channel_rows,gint32 stride,gint32 bpc,gint16 * LengthsTable,guchar * remdata)898 get_compress_channel_data (guchar  *channel_data,
899                            gint32   channel_cols,
900                            gint32   channel_rows,
901                            gint32   stride,
902                            gint32   bpc,
903                            gint16  *LengthsTable,
904                            guchar  *remdata)
905 {
906   gint    i;
907   gint32  len;                 /* Length of compressed data */
908   guchar *start;               /* Starting position of a row in channel_data */
909 
910   stride /= bpc;
911 
912   /* Pack channel data, and perform byte-order conversion */
913   switch (bpc)
914     {
915     case 1:
916       {
917         if (stride > 1)
918           {
919             const guint8 *src  = (const guint8 *) channel_data;
920             guint8       *dest = (guint8       *) channel_data;
921 
922             for (i = 0; i < channel_rows * channel_cols; i++)
923               {
924                 *dest = *src;
925 
926                 dest++;
927                 src += stride;
928               }
929           }
930       }
931       break;
932 
933     case 2:
934       {
935         const guint16 *src  = (const guint16 *) channel_data;
936         guint16       *dest = (guint16       *) channel_data;
937 
938         for (i = 0; i < channel_rows * channel_cols; i++)
939           {
940             *dest = GUINT16_TO_BE (*src);
941 
942             dest++;
943             src += stride;
944           }
945       }
946       break;
947 
948     case 4:
949       {
950         const guint32 *src  = (const guint32 *) channel_data;
951         guint32       *dest = (guint32       *) channel_data;
952 
953         for (i = 0; i < channel_rows * channel_cols; i++)
954           {
955             *dest = GUINT32_TO_BE (*src);
956 
957             dest++;
958             src += stride;
959           }
960       }
961       break;
962 
963     default:
964       g_return_val_if_reached (0);
965     }
966 
967   /* For every row in the channel */
968 
969   len = 0;
970   for (i = 0; i < channel_rows; i++)
971     {
972       start = channel_data + i * channel_cols * bpc;
973 
974       /* Create packed data for this row */
975       LengthsTable[i] = pack_pb_line (start, channel_cols * bpc,
976                                       &remdata[len]);
977       len += LengthsTable[i];
978     }
979 
980   /*  return((len + channel_rows * sizeof (gint16)) + sizeof (gint16));*/
981   return len;
982 }
983 
984 static void
save_layer_and_mask(FILE * fd,gint32 image_id)985 save_layer_and_mask (FILE   *fd,
986                      gint32  image_id)
987 {
988   gint          i,j;
989   gint          idChannel;
990   gint          offset_x;               /* X offset for each layer */
991   gint          offset_y;               /* Y offset for each layer */
992   gint32        layerWidth;             /* Width of each layer */
993   gint32        layerHeight;            /* Height of each layer */
994   const gchar  *blendMode;              /* Blending mode of the layer */
995   guchar        layerOpacity;           /* Opacity of the layer */
996   guchar        flags;                  /* Layer flags */
997   gint          nChannelsLayer;         /* Number of channels of a layer */
998   gint32        ChanSize;               /* Data length for a channel */
999   gchar        *layerName;              /* Layer name */
1000   gint          mask;                   /* Layer mask */
1001   gint          depth;                  /* Layer group nesting depth */
1002   gint          bpc;                    /* Image BPC */
1003 
1004   glong         eof_pos;                /* Position: End of file */
1005   glong         ExtraDataPos;           /* Position: Extra data length */
1006   glong         LayerMaskPos;           /* Position: Layer & Mask section length */
1007   glong         LayerInfoPos;           /* Position: Layer info section length*/
1008   glong       **ChannelLengthPos;       /* Position: Channel length */
1009 
1010 
1011   IFDBG printf (" Function: save_layer_and_mask\n");
1012 
1013   /* Create first array dimension (layers, channels) */
1014 
1015   ChannelLengthPos = g_newa (glong *, PSDImageData.nLayers);
1016 
1017   /* Layer and mask information section */
1018 
1019   LayerMaskPos = ftell (fd);
1020   write_gint32 (fd, 0, "layers & mask information length");
1021 
1022   /* Layer info section */
1023 
1024   LayerInfoPos = ftell (fd);
1025   write_gint32 (fd, 0, "layers info section length");
1026 
1027   /* Layer structure section */
1028 
1029   if (gimp_drawable_has_alpha (PSDImageData.merged_layer))
1030     write_gint16 (fd, -PSDImageData.nLayers, "Layer structure count");
1031   else
1032     write_gint16 (fd, PSDImageData.nLayers, "Layer structure count");
1033 
1034   depth = 0;
1035 
1036   bpc = get_bpc (image_id);
1037 
1038   /* Layer records section */
1039   /* GIMP layers must be written in reverse order */
1040 
1041   for (i = PSDImageData.nLayers - 1; i >= 0; i--)
1042     {
1043       gint hasMask = 0;
1044 
1045       if (PSDImageData.lLayers[i].type == PSD_LAYER_TYPE_LAYER)
1046         {
1047           gimp_drawable_offsets (PSDImageData.lLayers[i].id, &offset_x, &offset_y);
1048           layerWidth = gimp_drawable_width (PSDImageData.lLayers[i].id);
1049           layerHeight = gimp_drawable_height (PSDImageData.lLayers[i].id);
1050         }
1051       else
1052         {
1053           /* groups don't specify their dimensions, and have empty channel
1054            * data
1055            */
1056           offset_x    = 0;
1057           offset_y    = 0;
1058           layerWidth  = 0;
1059           layerHeight = 0;
1060         }
1061 
1062       IFDBG printf ("\tLayer number: %d\n", i);
1063       IFDBG
1064         {
1065           const gchar *type;
1066 
1067           switch (PSDImageData.lLayers[i].type)
1068             {
1069             case PSD_LAYER_TYPE_LAYER:       type = "normal layer"; break;
1070             case PSD_LAYER_TYPE_GROUP_START: type = "group start marker"; break;
1071             case PSD_LAYER_TYPE_GROUP_END:   type = "group end marker"; break;
1072             }
1073 
1074           printf ("\t\tType: %s\n", type);
1075         }
1076       IFDBG printf ("\t\tX offset: %d\n", offset_x);
1077       IFDBG printf ("\t\tY offset: %d\n", offset_y);
1078       IFDBG printf ("\t\tWidth: %d\n", layerWidth);
1079       IFDBG printf ("\t\tHeight: %d\n", layerHeight);
1080 
1081       write_gint32 (fd, offset_y,               "Layer top");
1082       write_gint32 (fd, offset_x,               "Layer left");
1083       write_gint32 (fd, offset_y + layerHeight, "Layer bottom");
1084       write_gint32 (fd, offset_x + layerWidth,  "Layer right");
1085 
1086       hasMask = (PSDImageData.lLayers[i].type != PSD_LAYER_TYPE_GROUP_END &&
1087                  gimp_layer_get_mask (PSDImageData.lLayers[i].id) != -1);
1088       nChannelsLayer = nChansLayer (PSDImageData.baseType,
1089                                     gimp_drawable_has_alpha (PSDImageData.lLayers[i].id),
1090                                     hasMask);
1091 
1092 
1093       write_gint16 (fd, nChannelsLayer, "Number channels in the layer");
1094       IFDBG printf ("\t\tNumber of channels: %d\n", nChannelsLayer);
1095 
1096       /* Create second array dimension (layers, channels) */
1097 
1098       ChannelLengthPos[i] = g_new (glong, nChannelsLayer);
1099 
1100       /* Try with gimp_drawable_bpp() */
1101 
1102       for (j = 0; j < nChannelsLayer; j++)
1103         {
1104           if (gimp_drawable_has_alpha (PSDImageData.lLayers[i].id))
1105             idChannel = j - 1;
1106           else
1107             idChannel = j;
1108           if (hasMask && (j+1 == nChannelsLayer)) /* Last channel ... */
1109             idChannel = -2; /* ... will be layer mask */
1110 
1111           write_gint16 (fd, idChannel, "Channel ID");
1112           IFDBG printf ("\t\t\tChannel Identifier: %d\n", idChannel);
1113 
1114           /* Write the length assuming no compression.  In case there is,
1115              will modify it later when writing data.  */
1116 
1117           ChannelLengthPos[i][j] = ftell (fd);
1118           ChanSize = sizeof (gint16) + (layerWidth * layerHeight * bpc);
1119 
1120           write_gint32 (fd, ChanSize, "Channel Size");
1121           IFDBG printf ("\t\t\tLength: %d\n", ChanSize);
1122         }
1123 
1124       xfwrite (fd, "8BIM", 4, "blend mode signature");
1125 
1126       blendMode = psd_lmode_layer (PSDImageData.lLayers[i].id, FALSE);
1127       IFDBG printf ("\t\tBlend mode: %s\n", blendMode);
1128       xfwrite (fd, blendMode, 4, "blend mode key");
1129 
1130       layerOpacity = RINT ((gimp_layer_get_opacity (PSDImageData.lLayers[i].id) * 255.0) / 100.0);
1131       IFDBG printf ("\t\tOpacity: %u\n", layerOpacity);
1132       write_gchar (fd, layerOpacity, "Opacity");
1133 
1134       /* Apparently this field is not used in GIMP */
1135       write_gchar (fd, 0, "Clipping");
1136 
1137       flags = 0;
1138       if (gimp_layer_get_lock_alpha (PSDImageData.lLayers[i].id)) flags |= 1;
1139       if (! gimp_item_get_visible (PSDImageData.lLayers[i].id)) flags |= 2;
1140       if (PSDImageData.lLayers[i].type != PSD_LAYER_TYPE_LAYER) flags |= 0x18;
1141       IFDBG printf ("\t\tFlags: %u\n", flags);
1142       write_gchar (fd, flags, "Flags");
1143 
1144       /* Padding byte to make the length even */
1145       write_gchar (fd, 0, "Filler");
1146 
1147       ExtraDataPos = ftell (fd); /* Position of Extra Data size */
1148       write_gint32 (fd, 0, "Extra data size");
1149 
1150       if (hasMask)
1151         {
1152           gint     maskOffset_x;
1153           gint     maskOffset_y;
1154           gint     maskWidth;
1155           gint     maskHeight;
1156           gboolean apply;
1157 
1158           mask = gimp_layer_get_mask (PSDImageData.lLayers[i].id);
1159 
1160           gimp_drawable_offsets (mask, &maskOffset_x, &maskOffset_y);
1161 
1162           maskWidth  = gimp_drawable_width  (mask);
1163           maskHeight = gimp_drawable_height (mask);
1164           apply      = gimp_layer_get_apply_mask (PSDImageData.lLayers[i].id);
1165 
1166           IFDBG printf ("\t\tLayer mask size: %d\n", 20);
1167           write_gint32 (fd, 20,                        "Layer mask size");
1168           write_gint32 (fd, maskOffset_y,              "Layer mask top");
1169           write_gint32 (fd, maskOffset_x,              "Layer mask left");
1170           write_gint32 (fd, maskOffset_y + maskHeight, "Layer mask bottom");
1171           write_gint32 (fd, maskOffset_x + maskWidth,  "Layer mask right");
1172           write_gchar  (fd, 0,                         "Layer mask default color");
1173           flags = (0                    |  /* position relative to layer */
1174                    (apply ? 0 : 1) << 1 |  /* layer mask disabled        */
1175                    0 << 2);                /* invert layer mask          */
1176           write_gchar  (fd, flags,                     "Layer mask flags");
1177           write_gint16 (fd, 0,                         "Layer mask Padding");
1178         }
1179       else
1180         {
1181           /* NOTE Writing empty Layer mask / adjustment layer data */
1182           write_gint32 (fd, 0, "Layer mask size");
1183           IFDBG printf ("\t\tLayer mask size: %d\n", 0);
1184         }
1185 
1186       /* NOTE Writing empty Layer blending ranges data */
1187       write_gint32 (fd, 0, "Layer blending size");
1188       IFDBG printf ("\t\tLayer blending size: %d\n", 0);
1189 
1190       if (PSDImageData.lLayers[i].type != PSD_LAYER_TYPE_GROUP_END)
1191         layerName = gimp_item_get_name (PSDImageData.lLayers[i].id);
1192       else
1193         layerName = g_strdup ("</Layer group>");
1194       write_pascalstring (fd, layerName, 4, "layer name");
1195       IFDBG printf ("\t\tLayer name: %s\n", layerName);
1196 
1197       /* Additional layer information blocks */
1198       /* Unicode layer name */
1199       write_datablock_luni(fd, layerName, "luni extra data block");
1200 
1201       g_free (layerName);
1202 
1203       /* Layer color tag */
1204       xfwrite (fd, "8BIMlclr", 8, "sheet color signature");
1205       write_gint32 (fd, 8, "sheet color size");
1206       write_gint16 (fd,
1207                     gimp_to_psd_layer_color_tag(gimp_item_get_color_tag(PSDImageData.lLayers[i].id)),
1208                     "sheet color code");
1209       write_gint16 (fd, 0, "sheet color unused value");
1210       write_gint16 (fd, 0, "sheet color unused value");
1211       write_gint16 (fd, 0, "sheet color unused value");
1212 
1213       /* Group layer section divider */
1214       if (PSDImageData.lLayers[i].type != PSD_LAYER_TYPE_LAYER)
1215         {
1216           gint32 size;
1217           gint32 type;
1218 
1219           size = 12;
1220 
1221           if (PSDImageData.lLayers[i].type == PSD_LAYER_TYPE_GROUP_START)
1222             {
1223               type = gimp_item_get_expanded (PSDImageData.lLayers[i].id) ? 1 : 2;
1224 
1225               depth--;
1226             }
1227           else
1228             {
1229               type = 3;
1230 
1231               depth++;
1232             }
1233 
1234           blendMode = psd_lmode_layer (PSDImageData.lLayers[i].id, TRUE);
1235 
1236           if (type < 3 || depth <= 5)
1237             {
1238               xfwrite (fd, "8BIMlsct", 8, "section divider");
1239             }
1240           else
1241             {
1242               /* layer groups whose nesting depth is above 5 are only supported
1243                * by Photoshop CS5 and up, and their end markers use the
1244                * (undocumented) "lsdk" key, instead of "lsct".
1245                */
1246               xfwrite (fd, "8BIMlsdk", 8, "nested section divider");
1247             }
1248           write_gint32 (fd, size, "section divider size");
1249           write_gint32 (fd, type, "section divider type");
1250           xfwrite (fd, "8BIM", 4, "section divider blend mode signature");
1251           xfwrite (fd, blendMode, 4, "section divider blend mode key");
1252         }
1253 
1254       /* Write real length for: Extra data */
1255 
1256       eof_pos = ftell (fd);
1257 
1258       fseek (fd, ExtraDataPos, SEEK_SET);
1259       write_gint32 (fd, eof_pos - ExtraDataPos - sizeof (gint32), "Extra data size");
1260       IFDBG printf ("\t\tExtraData size: %d\n",
1261                     (int) (eof_pos - ExtraDataPos - sizeof (gint32)));
1262 
1263       /* Return to EOF to continue writing */
1264 
1265       fseek (fd, eof_pos, SEEK_SET);
1266     }
1267 
1268 
1269   /* Channel image data section */
1270   /* Gimp layers must be written in reverse order */
1271 
1272   for (i = PSDImageData.nLayers - 1; i >= 0; i--)
1273     {
1274       gimp_progress_update ((PSDImageData.nLayers - i - 1.0) / (PSDImageData.nLayers + 1.0));
1275 
1276       IFDBG printf ("\t\tWriting pixel data for layer slot %d\n", i);
1277       write_pixel_data (fd, PSDImageData.lLayers[i].id, ChannelLengthPos[i], 0,
1278                         PSDImageData.lLayers[i].type != PSD_LAYER_TYPE_GROUP_END);
1279       g_free (ChannelLengthPos[i]);
1280     }
1281 
1282   gimp_progress_update (PSDImageData.nLayers / (PSDImageData.nLayers + 1.0));
1283   eof_pos = ftell (fd);
1284 
1285   /* Write actual size of Layer info section */
1286 
1287   fseek (fd, LayerInfoPos, SEEK_SET);
1288   write_gint32 (fd, eof_pos - LayerInfoPos - sizeof (gint32), "layers info section length");
1289   IFDBG printf ("\t\tTotal layers info section length: %d\n",
1290                 (int) (eof_pos - LayerInfoPos - sizeof (gint32)));
1291 
1292   /* Write actual size of Layer and mask information section */
1293 
1294   fseek (fd, LayerMaskPos, SEEK_SET);
1295   write_gint32 (fd, eof_pos - LayerMaskPos - sizeof (gint32), "layers & mask information length");
1296   IFDBG printf ("\t\tTotal layers & mask information length: %d\n",
1297                 (int) (eof_pos - LayerMaskPos - sizeof (gint32)));
1298 
1299   /* Return to EOF to continue writing */
1300 
1301   fseek (fd, eof_pos, SEEK_SET);
1302 }
1303 
1304 static void
write_pixel_data(FILE * fd,gint32 drawableID,glong * ChanLenPosition,gint32 ltable_offset,gboolean write_mask)1305 write_pixel_data (FILE     *fd,
1306                   gint32    drawableID,
1307                   glong    *ChanLenPosition,
1308                   gint32    ltable_offset,
1309                   gboolean  write_mask)
1310 {
1311   GeglBuffer   *buffer = gimp_drawable_get_buffer (drawableID);
1312   const Babl   *format;
1313   gint32        maskID;
1314   gint32        tile_height = gimp_tile_height ();
1315   gint32        height = gegl_buffer_get_height (buffer);
1316   gint32        width  = gegl_buffer_get_width (buffer);
1317   gint32        bytes;
1318   gint32        components;
1319   gint32        bpc;
1320   gint32        colors;
1321   gint32        y;
1322   gint32        len;                  /* Length of compressed data */
1323   gint16       *LengthsTable;         /* Lengths of every compressed row */
1324   guchar       *rledata;              /* Compressed data from a region */
1325   guchar       *data;                 /* Temporary copy of pixel data */
1326   glong         length_table_pos;     /* position in file of the length table */
1327   int           i, j;
1328 
1329   IFDBG printf (" Function: write_pixel_data, drw %d, lto %d\n",
1330                 drawableID, ltable_offset);
1331 
1332   if (write_mask)
1333     maskID = gimp_layer_get_mask (drawableID);
1334   else
1335     maskID = -1;
1336 
1337   /* groups have empty channel data, but may have a mask */
1338   if (gimp_item_is_group (drawableID) && maskID == -1)
1339     {
1340       width  = 0;
1341       height = 0;
1342     }
1343 
1344   if (gimp_item_is_channel (drawableID))
1345     format = get_channel_format (drawableID);
1346   else
1347     format = get_pixel_format (drawableID);
1348 
1349   bytes      = babl_format_get_bytes_per_pixel (format);
1350   components = babl_format_get_n_components    (format);
1351   bpc        = bytes / components;
1352 
1353   colors = components;
1354 
1355   if (gimp_drawable_has_alpha  (drawableID) &&
1356       ! gimp_drawable_is_indexed (drawableID))
1357     colors -= 1;
1358 
1359   LengthsTable = g_new (gint16, height);
1360   rledata = g_new (guchar, (MIN (height, tile_height) *
1361                             (width + 10 + (width / 100))) * bpc);
1362 
1363   data = g_new (guchar, MIN (height, tile_height) * width * bytes);
1364 
1365   /* groups have empty channel data */
1366   if (gimp_item_is_group (drawableID))
1367     {
1368       width  = 0;
1369       height = 0;
1370     }
1371 
1372   for (i = 0; i < components; i++)
1373     {
1374       gint chan;
1375 
1376       len = 0;
1377 
1378       if (components != colors && ltable_offset == 0) /* Need to write alpha channel first, except in image data section */
1379         {
1380           if (i == 0)
1381             {
1382               chan = components - 1;
1383             }
1384           else
1385             {
1386               chan = i - 1;
1387             }
1388         }
1389       else
1390         {
1391           chan = i;
1392         }
1393 
1394       if (ChanLenPosition)
1395         {
1396           write_gint16 (fd, 1, "Compression type (RLE)");
1397           len += 2;
1398         }
1399 
1400       if (ltable_offset > 0)
1401         {
1402           length_table_pos = ltable_offset + 2 * chan * height;
1403         }
1404       else
1405         {
1406           length_table_pos = ftell(fd);
1407 
1408           xfwrite (fd, LengthsTable, height * sizeof(gint16),
1409                    "Dummy RLE length");
1410           len += height * sizeof(gint16);
1411           IF_DEEP_DBG printf ("\t\t\t\t. ltable, pos %ld len %d\n", length_table_pos, len);
1412         }
1413 
1414       for (y = 0; y < height; y += tile_height)
1415         {
1416           int tlen;
1417           gegl_buffer_get (buffer,
1418                            GEGL_RECTANGLE (0, y,
1419                                            width,
1420                                            MIN (height - y, tile_height)),
1421                            1.0, format, data,
1422                            GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE);
1423           tlen = get_compress_channel_data (&data[chan * bpc],
1424                                             width,
1425                                             MIN(height - y, tile_height),
1426                                             bytes, bpc,
1427                                             &LengthsTable[y],
1428                                             rledata);
1429           len += tlen;
1430           xfwrite (fd, rledata, tlen, "Compressed pixel data");
1431           IF_DEEP_DBG printf ("\t\t\t\t. Writing compressed pixels, stream of %d\n", tlen);
1432         }
1433 
1434       /* Write compressed lengths table */
1435       fseek (fd, length_table_pos, SEEK_SET);
1436       for (j = 0; j < height; j++) /* write real length table */
1437         write_gint16 (fd, LengthsTable[j], "RLE length");
1438 
1439       if (ChanLenPosition)    /* Update total compressed length */
1440         {
1441           fseek (fd, ChanLenPosition[i], SEEK_SET);
1442           write_gint32 (fd, len, "channel data length");
1443           IFDBG printf ("\t\tUpdating data len to %d\n", len);
1444         }
1445       fseek (fd, 0, SEEK_END);
1446       IF_DEEP_DBG printf ("\t\t\t\t. Cur pos %ld\n", ftell(fd));
1447     }
1448 
1449   /* Write layer mask, as last channel, id -2 */
1450   if (maskID != -1)
1451     {
1452       GeglBuffer *mbuffer = gimp_drawable_get_buffer (maskID);
1453       const Babl *mformat = get_mask_format(maskID);
1454 
1455       width  = gegl_buffer_get_width (buffer);
1456       height = gegl_buffer_get_height (buffer);
1457 
1458       len = 0;
1459 
1460       if (ChanLenPosition)
1461         {
1462           write_gint16 (fd, 1, "Compression type (RLE)");
1463           len += 2;
1464           IF_DEEP_DBG printf ("\t\t\t\t. ChanLenPos, len %d\n", len);
1465         }
1466 
1467       if (ltable_offset > 0)
1468         {
1469           length_table_pos = ltable_offset + 2 * (components+1) * height;
1470           IF_DEEP_DBG printf ("\t\t\t\t. ltable, pos %ld\n",
1471                               length_table_pos);
1472         }
1473       else
1474         {
1475           length_table_pos = ftell(fd);
1476 
1477           xfwrite (fd, LengthsTable, height * sizeof(gint16),
1478                    "Dummy RLE length");
1479           len += height * sizeof(gint16);
1480           IF_DEEP_DBG printf ("\t\t\t\t. ltable, pos %ld len %d\n",
1481                               length_table_pos, len);
1482         }
1483 
1484       for (y = 0; y < height; y += tile_height)
1485         {
1486           int tlen;
1487           gegl_buffer_get (mbuffer,
1488                            GEGL_RECTANGLE (0, y,
1489                                            width,
1490                                            MIN (height - y, tile_height)),
1491                            1.0, mformat, data,
1492                            GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE);
1493           tlen = get_compress_channel_data (&data[0],
1494                                             width,
1495                                             MIN(height - y, tile_height),
1496                                             bpc, bpc,
1497                                             &LengthsTable[y],
1498                                             rledata);
1499           len += tlen;
1500           xfwrite (fd, rledata, tlen, "Compressed mask data");
1501           IF_DEEP_DBG printf ("\t\t\t\t. Writing compressed mask, stream of %d\n", tlen);
1502         }
1503 
1504       /* Write compressed lengths table */
1505       fseek (fd, length_table_pos, SEEK_SET); /*POS WHERE???*/
1506       for (j = 0; j < height; j++) /* write real length table */
1507         {
1508           write_gint16 (fd, LengthsTable[j], "RLE length");
1509           IF_DEEP_DBG printf ("\t\t\t\t. Updating RLE len %d\n",
1510                               LengthsTable[j]);
1511         }
1512 
1513       if (ChanLenPosition)    /* Update total compressed length */
1514         {
1515           /* Mask follows other components so use that as offset. */
1516           fseek (fd, ChanLenPosition[components], SEEK_SET);
1517 
1518           write_gint32 (fd, len, "channel data length");
1519           IFDBG printf ("\t\tUpdating data len to %d, at %ld\n", len, ftell(fd));
1520         }
1521       fseek (fd, 0, SEEK_END);
1522       IF_DEEP_DBG printf ("\t\t\t\t. Cur pos %ld\n", ftell(fd));
1523 
1524       g_object_unref (mbuffer);
1525     }
1526 
1527   g_object_unref (buffer);
1528 
1529   g_free (data);
1530   g_free (rledata);
1531   g_free (LengthsTable);
1532 }
1533 
1534 static void
save_data(FILE * fd,gint32 image_id)1535 save_data (FILE   *fd,
1536            gint32  image_id)
1537 {
1538   gint ChanCount;
1539   gint i, j;
1540   gint32 imageHeight;                   /* Height of image */
1541   glong offset;                         /* offset in file of rle lengths */
1542   gint chan;
1543 
1544   IFDBG printf (" Function: save_data\n");
1545 
1546   ChanCount = (PSDImageData.nChannels +
1547                nChansLayer (PSDImageData.baseType,
1548                             gimp_drawable_has_alpha (PSDImageData.merged_layer),
1549                             0));
1550 
1551   imageHeight = gimp_image_height (image_id);
1552 
1553   write_gint16 (fd, 1, "RLE compression");
1554 
1555   /* All line lengths go before the rle pixel data */
1556 
1557   offset = ftell(fd); /* Offset in file of line lengths */
1558 
1559   for (i = 0; i < ChanCount; i++)
1560     for (j = 0; j < imageHeight; j++)
1561       write_gint16 (fd, 0, "junk line lengths");
1562 
1563   IFDBG printf ("\t\tWriting compressed image data\n");
1564   write_pixel_data (fd, PSDImageData.merged_layer,
1565                     NULL, offset, FALSE);
1566 
1567   chan = nChansLayer (PSDImageData.baseType,
1568                       gimp_drawable_has_alpha(PSDImageData.merged_layer), 0);
1569 
1570   for (i = 0; i < PSDImageData.nChannels; i++)
1571     {
1572       IFDBG printf ("\t\tWriting compressed channel data for channel %d\n",
1573                     i);
1574       write_pixel_data (fd, PSDImageData.lChannels[i], NULL,
1575                         offset + 2*imageHeight*chan, FALSE); //check how imgs are channels here
1576       chan++;
1577     }
1578 }
1579 
1580 static gint32
create_merged_image(gint32 image_id)1581 create_merged_image (gint32 image_id)
1582 {
1583   gint32  projection;
1584 
1585   projection = gimp_layer_new_from_visible (image_id, image_id, "psd-save");
1586 
1587   if (! gimp_drawable_has_alpha (projection))
1588     return projection;
1589 
1590   if (gimp_image_base_type (image_id) != GIMP_INDEXED)
1591     {
1592       GeglBuffer         *buffer             = gimp_drawable_get_buffer (projection);
1593       const Babl         *format             = get_pixel_format (projection);
1594       gboolean            transparency_found = FALSE;
1595       gint                bpp                = babl_format_get_bytes_per_pixel (format);
1596       GeglBufferIterator *iter;
1597 
1598       iter = gegl_buffer_iterator_new (buffer, NULL, 0, format,
1599                                        GEGL_ACCESS_READWRITE, GEGL_ABYSS_NONE, 1);
1600 
1601       while (gegl_buffer_iterator_next (iter))
1602         {
1603           guchar *d = iter->items[0].data;
1604           gint    i;
1605 
1606           for (i = 0; i < iter->length; i++)
1607             {
1608               gint32 alpha = d[bpp - 1];
1609 
1610               if (alpha < 255)
1611                 {
1612                   gint c;
1613 
1614                   transparency_found = TRUE;
1615 
1616                   /* blend against white, photoshop does this. */
1617                   for (c = 0; c < bpp - 1; c++)
1618                     d[c] = ((guint32) d[c] * alpha + 128) / 255 + 255 - alpha;
1619                 }
1620 
1621               d += bpp;
1622             }
1623         }
1624 
1625       g_object_unref (buffer);
1626 
1627       if (! transparency_found)
1628         gimp_layer_flatten (projection);
1629     }
1630   else
1631     {
1632       gimp_layer_flatten (projection);  /* PSDs don't support transparency information in indexed images*/
1633     }
1634 
1635   return projection;
1636 }
1637 
1638 static void
get_image_data(gint32 image_id)1639 get_image_data (gint32 image_id)
1640 {
1641   IFDBG printf (" Function: get_image_data\n");
1642 
1643   PSDImageData.compression = FALSE;
1644 
1645   PSDImageData.image_height = gimp_image_height (image_id);
1646   IFDBG printf ("\tGot number of rows: %d\n", PSDImageData.image_height);
1647 
1648   PSDImageData.image_width = gimp_image_width (image_id);
1649   IFDBG printf ("\tGot number of cols: %d\n", PSDImageData.image_width);
1650 
1651   PSDImageData.baseType = gimp_image_base_type (image_id);
1652   IFDBG printf ("\tGot base type: %d\n", PSDImageData.baseType);
1653 
1654   PSDImageData.merged_layer = create_merged_image (image_id);
1655 
1656   PSDImageData.lChannels = gimp_image_get_channels (image_id,
1657                                                     &PSDImageData.nChannels);
1658   IFDBG printf ("\tGot number of channels: %d\n", PSDImageData.nChannels);
1659 
1660   PSDImageData.lLayers = image_get_all_layers (image_id,
1661                                                &PSDImageData.nLayers);
1662   IFDBG printf ("\tGot number of layers: %d\n", PSDImageData.nLayers);
1663 }
1664 
1665 static void
clear_image_data(void)1666 clear_image_data (void)
1667 {
1668   IFDBG printf (" Function: clear_image_data\n");
1669 
1670   g_free (PSDImageData.lChannels);
1671   PSDImageData.lChannels = NULL;
1672 
1673   g_free (PSDImageData.lLayers);
1674   PSDImageData.lLayers = NULL;
1675 }
1676 
1677 gboolean
save_image(const gchar * filename,gint32 image_id,GError ** error)1678 save_image (const gchar  *filename,
1679             gint32        image_id,
1680             GError      **error)
1681 {
1682   FILE       *fd;
1683   gint        i;
1684   GeglBuffer *buffer;
1685 
1686   IFDBG printf (" Function: save_image\n");
1687 
1688   if (gimp_image_width (image_id) > 30000 ||
1689       gimp_image_height (image_id) > 30000)
1690     {
1691       g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
1692                    _("Unable to export '%s'.  The PSD file format does not "
1693                      "support images that are more than 30,000 pixels wide "
1694                      "or tall."),
1695                    gimp_filename_to_utf8 (filename));
1696       return FALSE;
1697     }
1698 
1699   gimp_progress_init_printf (_("Exporting '%s'"),
1700                              gimp_filename_to_utf8 (filename));
1701 
1702   get_image_data (image_id);
1703 
1704   /* Need to check each of the layers size individually also */
1705   for (i = 0; i < PSDImageData.nLayers; i++)
1706     {
1707       if (PSDImageData.lLayers[i].type == PSD_LAYER_TYPE_LAYER)
1708         {
1709           buffer = gimp_drawable_get_buffer (PSDImageData.lLayers[i].id);
1710           if (gegl_buffer_get_width (buffer) > 30000 || gegl_buffer_get_height (buffer) > 30000)
1711             {
1712               g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
1713                            _("Unable to export '%s'.  The PSD file format does not "
1714                              "support images with layers that are more than 30,000 "
1715                              "pixels wide or tall."),
1716                            gimp_filename_to_utf8 (filename));
1717               clear_image_data ();
1718               return FALSE;
1719             }
1720           g_object_unref (buffer);
1721         }
1722     }
1723 
1724   fd = g_fopen (filename, "wb");
1725   if (fd == NULL)
1726     {
1727       g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (errno),
1728                    _("Could not open '%s' for writing: %s"),
1729                    gimp_filename_to_utf8 (filename), g_strerror (errno));
1730       clear_image_data ();
1731       return FALSE;
1732     }
1733 
1734   IFDBG g_print ("\tFile '%s' has been opened\n",
1735                  gimp_filename_to_utf8 (filename));
1736 
1737   save_header (fd, image_id);
1738   save_color_mode_data (fd, image_id);
1739   save_resources (fd, image_id);
1740 
1741   /* PSD format does not support layers in indexed images */
1742 
1743   if (PSDImageData.baseType == GIMP_INDEXED)
1744     write_gint32 (fd, 0, "layers info section length");
1745   else
1746     save_layer_and_mask (fd, image_id);
1747 
1748   /* If this is an indexed image, write now channel and layer info */
1749 
1750   save_data (fd, image_id);
1751 
1752   /* Delete merged image now */
1753 
1754   gimp_item_delete (PSDImageData.merged_layer);
1755 
1756   clear_image_data ();
1757 
1758   IFDBG printf ("----- Closing PSD file, done -----\n\n");
1759 
1760   fclose (fd);
1761 
1762   gimp_progress_update (1.0);
1763 
1764   return TRUE;
1765 }
1766 
1767 static gint
get_bpc(gint32 image_id)1768 get_bpc (gint32 image_id)
1769 {
1770   switch (gimp_image_get_precision (image_id))
1771     {
1772     case GIMP_PRECISION_U8_LINEAR:
1773     case GIMP_PRECISION_U8_GAMMA:
1774       return 1;
1775 
1776     case GIMP_PRECISION_U16_LINEAR:
1777     case GIMP_PRECISION_U16_GAMMA:
1778     case GIMP_PRECISION_HALF_LINEAR:
1779     case GIMP_PRECISION_HALF_GAMMA:
1780       return 2;
1781 
1782     case GIMP_PRECISION_U32_LINEAR:
1783     case GIMP_PRECISION_U32_GAMMA:
1784     case GIMP_PRECISION_FLOAT_LINEAR:
1785     case GIMP_PRECISION_FLOAT_GAMMA:
1786     default:
1787       /* FIXME: we *should* encode the image as u32 in this case, but simply
1788        * using the same code as for the other cases produces invalid psd files
1789        * (they're rejected by photoshop, although they can be read by the
1790        * corresponding psd-load.c code, which in turn can't actually read
1791        * photoshop-generated u32 files.)
1792        *
1793        * simply encode the image as u16 for now.
1794        */
1795       /* return 4; */
1796       return 2;
1797     }
1798 }
1799 
1800 static const Babl *
get_pixel_format(gint32 drawableID)1801 get_pixel_format (gint32 drawableID)
1802 {
1803   gint32       image_id = gimp_item_get_image (drawableID);
1804   const gchar *model;
1805   gint         bpc;
1806   gchar        format[32];
1807 
1808   switch (gimp_drawable_type (drawableID))
1809     {
1810     case GIMP_GRAY_IMAGE:
1811       model = "Y'";
1812       break;
1813 
1814     case GIMP_GRAYA_IMAGE:
1815       model = "Y'A";
1816       break;
1817 
1818     case GIMP_RGB_IMAGE:
1819       model = "R'G'B'";
1820       break;
1821 
1822     case GIMP_RGBA_IMAGE:
1823       model = "R'G'B'A";
1824       break;
1825 
1826     case GIMP_INDEXED_IMAGE:
1827     case GIMP_INDEXEDA_IMAGE:
1828       return gimp_drawable_get_format (drawableID);
1829 
1830     default:
1831       g_return_val_if_reached (NULL);
1832     }
1833 
1834   bpc = get_bpc (image_id);
1835 
1836   sprintf (format, "%s u%d", model, 8 * bpc);
1837 
1838   return babl_format (format);
1839 }
1840 
1841 static const Babl *
get_channel_format(gint32 drawableID)1842 get_channel_format (gint32 drawableID)
1843 {
1844   gint32 image_id = gimp_item_get_image (drawableID);
1845   gint   bpc;
1846   gchar  format[32];
1847 
1848   /* see gimp_image_get_channel_format() */
1849   if (gimp_image_get_precision (image_id) == GIMP_PRECISION_U8_GAMMA)
1850     return babl_format ("Y' u8");
1851 
1852   bpc = get_bpc (image_id);
1853 
1854   sprintf (format, "Y u%d", 8 * bpc);
1855 
1856   return babl_format (format);
1857 }
1858 
1859 static const Babl *
get_mask_format(gint32 drawableID)1860 get_mask_format (gint32 drawableID)
1861 {
1862   gint32 image_id = gimp_item_get_image (drawableID);
1863   gint   bpc;
1864   gchar  format[32];
1865 
1866   bpc = get_bpc (image_id);
1867 
1868   sprintf (format, "Y u%d", 8 * bpc);
1869 
1870   return babl_format (format);
1871 }
1872 
1873 static void
append_layers(const gint * layers,gint n_layers,GArray * array)1874 append_layers (const gint *layers,
1875                gint        n_layers,
1876                GArray     *array)
1877 {
1878   gint i;
1879 
1880   for (i = 0; i < n_layers; i++)
1881     {
1882       PSD_Layer layer = {};
1883       gboolean  is_group;
1884 
1885       layer.id = layers[i];
1886 
1887       is_group = gimp_item_is_group (layer.id);
1888 
1889       if (! is_group)
1890         layer.type = PSD_LAYER_TYPE_LAYER;
1891       else
1892         layer.type = PSD_LAYER_TYPE_GROUP_START;
1893 
1894       g_array_append_val (array, layer);
1895 
1896       if (is_group)
1897         {
1898           gint32 *group_layers;
1899           gint    n;
1900 
1901           group_layers = gimp_item_get_children (layer.id, &n);
1902           append_layers (group_layers, n, array);
1903           g_free (group_layers);
1904 
1905           layer.type = PSD_LAYER_TYPE_GROUP_END;
1906           g_array_append_val (array, layer);
1907         }
1908     }
1909 }
1910 
1911 static PSD_Layer *
image_get_all_layers(gint32 image_id,gint * n_layers)1912 image_get_all_layers (gint32  image_id,
1913                       gint   *n_layers)
1914 {
1915   GArray *array = g_array_new (FALSE, FALSE, sizeof (PSD_Layer));
1916   gint32 *layers;
1917   gint    n;
1918 
1919   layers = gimp_image_get_layers (image_id, &n);
1920 
1921   append_layers (layers, n, array);
1922 
1923   g_free (layers);
1924 
1925   *n_layers = array->len;
1926 
1927   return (PSD_Layer *) g_array_free (array, FALSE);
1928 }
1929