tiff.c 43 KB
Newer Older
Elliot Lee's avatar
Elliot Lee committed
1
2
/* tiff loading and saving for the GIMP
 *  -Peter Mattis
Sven Neumann's avatar
Sven Neumann committed
3
4
 * The TIFF loading code has been completely revamped by Nick Lamb
 * njl195@zepler.org.uk -- 18 May 1998
Elliot Lee's avatar
Elliot Lee committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
 *
 * The code for this filter is based on "tifftopnm" and "pnmtotiff",
 *  2 programs that are a part of the netpbm package.
 */

/*
** tifftopnm.c - converts a Tagged Image File to a portable anymap
**
** Derived by Jef Poskanzer from tif2ras.c, which is:
**
** Copyright (c) 1990 by Sun Microsystems, Inc.
**
** Author: Patrick J. Naughton
** naughton@wind.sun.com
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted,
** provided that the above copyright notice appear in all copies and that
** both that copyright notice and this permission notice appear in
** supporting documentation.
**
** This file is provided AS IS with no warranties of any kind.  The author
** shall have no liability with respect to the infringement of copyrights,
** trade secrets or any patents by this file or any part thereof.  In no
** event will the author be liable for any lost revenue or profits or
** other special, indirect and consequential damages.
*/

#include <stdlib.h>
#include <string.h>
#include <tiffio.h>
#include "gtk/gtk.h"
#include "libgimp/gimp.h"
38
39
40
#ifdef GIMP_HAVE_RESOLUTION_INFO
#include "libgimp/gimpunit.h"
#endif
41

Elliot Lee's avatar
Elliot Lee committed
42
43
44
45
46
47
48
49
50
51
52
typedef struct
{
  gint  compression;
  gint  fillorder;
} TiffSaveVals;

typedef struct
{
  gint  run;
} TiffSaveInterface;

53
54
55
56
57
58
59
60
typedef struct {
  gint32 ID;
  GDrawable *drawable;
  GPixelRgn pixel_rgn;
  guchar *pixels;
  guchar *pixel;
} channel_data;

Elliot Lee's avatar
Elliot Lee committed
61
62
63
64
65
66
67
68
69
/* Declare some local functions.
 */
static void   query      (void);
static void   run        (char    *name,
                          int      nparams,
                          GParam  *param,
                          int     *nreturn_vals,
                          GParam **return_vals);
static gint32 load_image (char   *filename);
70
71
72
73
74
75
76
77
78
79
80
81
static void   load_separate (TIFF *tif, GDrawable *drawable,
                             channel_data *channel,
                             unsigned short bps, unsigned short photomet,
                             int rows, int cols, int alpha, int extra);
static void   load_8bit (TIFF *tif, GDrawable *drawable,
                         channel_data *channel,
                         unsigned short bps, unsigned short photomet,
                         int rows, int cols, int alpha, int extra);
static void   load_default (TIFF *tif, GDrawable *drawable,
                            channel_data *channel,
                            unsigned short bps, unsigned short photomet,
                            int rows, int cols, int alpha, int extra);
Elliot Lee's avatar
Elliot Lee committed
82
static gint   save_image (char   *filename,
Sven Neumann's avatar
Sven Neumann committed
83
84
			  gint32  image,
			  gint32  drawable);
Elliot Lee's avatar
Elliot Lee committed
85
86
87
88
89
90
91
92
93

static gint   save_dialog ();

static void   save_close_callback  (GtkWidget *widget,
				    gpointer   data);
static void   save_ok_callback     (GtkWidget *widget,
				    gpointer   data);
static void   save_toggle_update   (GtkWidget *widget,
				    gpointer   data);
94
95
static void   comment_entry_callback  (GtkWidget *widget,
				       gpointer   data);
Elliot Lee's avatar
Elliot Lee committed
96

97
#define DEFAULT_COMMENT "Created with The GIMP"
Elliot Lee's avatar
Elliot Lee committed
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117

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

static TiffSaveVals tsvals =
{
  COMPRESSION_LZW,    /*  compression  */
  FILLORDER_LSB2MSB,  /*  fillorder    */
};

static TiffSaveInterface tsint =
{
  FALSE                /*  run  */
};

118
static char *image_comment= NULL;
Elliot Lee's avatar
Elliot Lee committed
119
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

MAIN ()

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_tiff_load",
                          "loads files of the tiff file format",
                          "FIXME: write help for tiff_load",
Sven Neumann's avatar
Sven Neumann committed
153
                          "Spencer Kimball, Peter Mattis & Nick Lamb",
Manish Singh's avatar
Manish Singh committed
154
                          "Nick Lamb <njl195@zepler.org.uk>",
Sven Neumann's avatar
Sven Neumann committed
155
                          "1995-1996,1998",
Elliot Lee's avatar
Elliot Lee committed
156
157
158
159
160
161
162
163
164
165
166
167
168
                          "<Load>/Tiff",
			  NULL,
                          PROC_PLUG_IN,
                          nload_args, nload_return_vals,
                          load_args, load_return_vals);

  gimp_install_procedure ("file_tiff_save",
                          "saves files in the tiff file format",
                          "FIXME: write help for tiff_save",
                          "Spencer Kimball & Peter Mattis",
                          "Spencer Kimball & Peter Mattis",
                          "1995-1996",
                          "<Save>/Tiff",
Sven Neumann's avatar
Sven Neumann committed
169
			  "RGB*, GRAY*, INDEXED",
Elliot Lee's avatar
Elliot Lee committed
170
171
172
173
174
175
176
177
178
                          PROC_PLUG_IN,
                          nsave_args, 0,
                          save_args, NULL);

  gimp_register_magic_load_handler ("file_tiff_load", "tif,tiff", "",
             "0,string,II*\\0,0,string,MM\\0*");
  gimp_register_save_handler ("file_tiff_save", "tif,tiff", "");
}

179
180
181



Elliot Lee's avatar
Elliot Lee committed
182
183
184
185
186
187
188
189
190
191
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;
192
193
194
#ifdef GIMP_HAVE_PARASITES
  Parasite *parasite;
#endif /* GIMP_HAVE_PARASITES */
Sven Neumann's avatar
Sven Neumann committed
195
  gint32 image;
Elliot Lee's avatar
Elliot Lee committed
196
197
198
199
200
201
202
203
204
205

  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_tiff_load") == 0)
    {
Sven Neumann's avatar
Sven Neumann committed
206
      image = load_image (param[1].data.d_string);
Elliot Lee's avatar
Elliot Lee committed
207

Sven Neumann's avatar
Sven Neumann committed
208
      if (image != -1)
Elliot Lee's avatar
Elliot Lee committed
209
210
211
212
	{
	  *nreturn_vals = 2;
	  values[0].data.d_status = STATUS_SUCCESS;
	  values[1].type = PARAM_IMAGE;
Sven Neumann's avatar
Sven Neumann committed
213
	  values[1].data.d_image = image;
Elliot Lee's avatar
Elliot Lee committed
214
215
216
217
218
219
220
221
	}
      else
	{
	  values[0].data.d_status = STATUS_EXECUTION_ERROR;
	}
    }
  else if (strcmp (name, "file_tiff_save") == 0)
    {
222
223
224
225
226

/* Do this right this time, if POSSIBLE query for parasites, otherwise
   or if there isn't one, choose the DEFAULT_COMMENT */

#ifdef GIMP_HAVE_PARASITES
227
      int image = param[1].data.d_int32;
228

229
      parasite = gimp_image_find_parasite(image, "gimp-comment");
230
      if (parasite)
231
232
233
234
235
        image_comment = g_strdup(parasite->data);
      parasite_free(parasite);
#endif /* GIMP_HAVE_PARASITES */

      if (!image_comment) image_comment = g_strdup(DEFAULT_COMMENT);	  
236

Elliot Lee's avatar
Elliot Lee committed
237
238
239
      switch (run_mode)
	{
	case RUN_INTERACTIVE:
240
	{
Elliot Lee's avatar
Elliot Lee committed
241
242
	  /*  Possibly retrieve data  */
	  gimp_get_data ("file_tiff_save", &tsvals);
243
#ifdef GIMP_HAVE_PARASITES
244
	  parasite = gimp_image_find_parasite(image, "tiff-save-options");
245
	  if (parasite)
246
247
248
249
	  {
	    tsvals.compression = ((TiffSaveVals *)parasite->data)->compression;
	    tsvals.fillorder   = ((TiffSaveVals *)parasite->data)->fillorder;
	  }
250
	  parasite_free(parasite);
251
#endif /* GIMP_HAVE_PARASITES */
Elliot Lee's avatar
Elliot Lee committed
252
253
254
255

	  /*  First acquire information with a dialog  */
	  if (! save_dialog ())
	    return;
256
	} break;
Elliot Lee's avatar
Elliot Lee committed
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280

	case RUN_NONINTERACTIVE:
	  /*  Make sure all the arguments are there!  */
	  if (nparams != 7)
	    status = STATUS_CALLING_ERROR;
	  if (status == STATUS_SUCCESS)
	    {
	      switch (param[5].data.d_int32)
		{
		case 0: tsvals.compression = COMPRESSION_NONE;     break;
		case 1: tsvals.compression = COMPRESSION_LZW;      break;
		case 2: tsvals.compression = COMPRESSION_PACKBITS; break;
		default: status = STATUS_CALLING_ERROR; break;
		}
	      switch (param[6].data.d_int32)
		{
		case 0: tsvals.fillorder = FILLORDER_MSB2LSB; break;
		case 1: tsvals.fillorder = FILLORDER_LSB2MSB; break;
		default: status = STATUS_CALLING_ERROR; break;
		}
	    }

	case RUN_WITH_LAST_VALS:
	  /*  Possibly retrieve data  */
281
	{
Elliot Lee's avatar
Elliot Lee committed
282
	  gimp_get_data ("file_tiff_save", &tsvals);
283
#ifdef GIMP_HAVE_PARASITES
284
	  parasite = gimp_image_find_parasite(image, "tiff-save-options");
285
	  if (parasite)
286
287
288
289
	  {
	    tsvals.compression = ((TiffSaveVals *)parasite->data)->compression;
	    tsvals.fillorder   = ((TiffSaveVals *)parasite->data)->fillorder;
	  }
290
	  parasite_free(parasite);
291
#endif /* GIMP_HAVE_PARASITES */
292
	}
Elliot Lee's avatar
Elliot Lee committed
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
	  break;

	default:
	  break;
	}

      *nreturn_vals = 1;
      if (save_image (param[3].data.d_string, param[1].data.d_int32, param[2].data.d_int32))
	{
	  /*  Store mvals data  */
	  gimp_set_data ("file_tiff_save", &tsvals, sizeof (TiffSaveVals));

	  values[0].data.d_status = STATUS_SUCCESS;
	}
      else
	values[0].data.d_status = STATUS_EXECUTION_ERROR;
    }
}

Sven Neumann's avatar
Sven Neumann committed
312
static gint32 load_image (char *filename) {
Elliot Lee's avatar
Elliot Lee committed
313
  TIFF *tif;
314
315
  unsigned short bps, spp, photomet, planar;
  int cols, rows, alpha;
Sven Neumann's avatar
Sven Neumann committed
316
317
318
319
  int image, layer, tile_height;
  unsigned short *redmap, *greenmap, *bluemap;
  guchar cmap[768];
  int image_type= 0, layer_type= 0;
Manish Singh's avatar
Manish Singh committed
320
  unsigned short extra, *extra_types;
Sven Neumann's avatar
Sven Neumann committed
321

322
  int i, j;
Sven Neumann's avatar
Sven Neumann committed
323

Elliot Lee's avatar
Elliot Lee committed
324
325
326
  GDrawable *drawable;
  char *name;

Sven Neumann's avatar
Sven Neumann committed
327
328
329
  guchar colors[3]= {0, 0, 0};

  channel_data *channel= NULL;
Elliot Lee's avatar
Elliot Lee committed
330

331
  TiffSaveVals save_vals;
332
#ifdef GIMP_HAVE_PARASITES
333
  Parasite *parasite;
334
#endif /* GIMP_HAVE_PARASITES */
335
  guint16 tmp;
Elliot Lee's avatar
Elliot Lee committed
336
  tif = TIFFOpen (filename, "r");
Sven Neumann's avatar
Sven Neumann committed
337
  if (!tif) {
338
    g_message("TIFF Can't open %s\n", filename);
Sven Neumann's avatar
Sven Neumann committed
339
340
    gimp_quit ();
  }
Elliot Lee's avatar
Elliot Lee committed
341

Sven Neumann's avatar
Sven Neumann committed
342
  name = g_malloc (strlen (filename) + 12);
Elliot Lee's avatar
Elliot Lee committed
343
344
  sprintf (name, "Loading %s:", filename);
  gimp_progress_init (name);
Sven Neumann's avatar
Sven Neumann committed
345
  g_free (name);
Elliot Lee's avatar
Elliot Lee committed
346
347
348

  if (!TIFFGetField (tif, TIFFTAG_BITSPERSAMPLE, &bps))
    bps = 1;
Sven Neumann's avatar
Sven Neumann committed
349
350

  if (bps > 8) {
351
    g_message("TIFF Can't handle samples wider than 8-bit\n");
Sven Neumann's avatar
Sven Neumann committed
352
353
354
    gimp_quit();
  }

355
356
  if (!TIFFGetField (tif, TIFFTAG_PLANARCONFIG, &planar))
    planar = PLANARCONFIG_SEPARATE;
Elliot Lee's avatar
Elliot Lee committed
357
358
  if (!TIFFGetField (tif, TIFFTAG_SAMPLESPERPIXEL, &spp))
    spp = 1;
Sven Neumann's avatar
Sven Neumann committed
359
360
361
362
  if (!TIFFGetField (tif, TIFFTAG_EXTRASAMPLES, &extra, &extra_types))
    extra = 0;

  if (!TIFFGetField (tif, TIFFTAG_IMAGEWIDTH, &cols)) {
Manish Singh's avatar
Manish Singh committed
363
    g_message("TIFF Can't get image width");
Sven Neumann's avatar
Sven Neumann committed
364
365
366
367
    gimp_quit ();
  }

  if (!TIFFGetField (tif, TIFFTAG_IMAGELENGTH, &rows)) {
Manish Singh's avatar
Manish Singh committed
368
    g_message("TIFF Can't get image length");
Sven Neumann's avatar
Sven Neumann committed
369
370
371
372
    gimp_quit ();
  }

  if (!TIFFGetField (tif, TIFFTAG_PHOTOMETRIC, &photomet)) {
373
374
375
376
377
378
    g_message("TIFF Can't get photometric\nassuming min-is-black");
    /* old AppleScan software misses out the photometric tag (and
     * incidentally assumes min-is-white, but xv assumes min-is-black,
     * so we follow xv's lead.  It's not much hardship to invert the
     * image later). */
    photomet = PHOTOMETRIC_MINISBLACK;
Sven Neumann's avatar
Sven Neumann committed
379
  }
Elliot Lee's avatar
Elliot Lee committed
380
381

  /* test if the extrasample represents an associated alpha channel... */
Sven Neumann's avatar
Sven Neumann committed
382
  if (extra > 0 && (extra_types[0] == EXTRASAMPLE_ASSOCALPHA)) {
Elliot Lee's avatar
Elliot Lee committed
383
    alpha = 1;
384
    --extra;
Sven Neumann's avatar
Sven Neumann committed
385
  } else {
Elliot Lee's avatar
Elliot Lee committed
386
    alpha = 0;
Sven Neumann's avatar
Sven Neumann committed
387
  }
Elliot Lee's avatar
Elliot Lee committed
388

389
  if (photomet == PHOTOMETRIC_RGB && spp > 3 + extra) {
Manish Singh's avatar
Manish Singh committed
390
    alpha= 1;
391
392
    extra= spp - 4; 
  } else if (photomet != PHOTOMETRIC_RGB && spp > 1 + extra) {
Manish Singh's avatar
Manish Singh committed
393
    alpha= 1;
394
    extra= spp - 2;
Sven Neumann's avatar
Sven Neumann committed
395
  }
Elliot Lee's avatar
Elliot Lee committed
396

Sven Neumann's avatar
Sven Neumann committed
397
398
399
  switch (photomet) {
    case PHOTOMETRIC_MINISBLACK:
    case PHOTOMETRIC_MINISWHITE:
Elliot Lee's avatar
Elliot Lee committed
400
401
      image_type = GRAY;
      layer_type = (alpha) ? GRAYA_IMAGE : GRAY_IMAGE;
Sven Neumann's avatar
Sven Neumann committed
402
      break;
Elliot Lee's avatar
Elliot Lee committed
403

Sven Neumann's avatar
Sven Neumann committed
404
405
406
407
    case PHOTOMETRIC_RGB:
      image_type = RGB;
      layer_type = (alpha) ? RGBA_IMAGE : RGB_IMAGE;
      break;
Elliot Lee's avatar
Elliot Lee committed
408

Sven Neumann's avatar
Sven Neumann committed
409
410
411
412
    case PHOTOMETRIC_PALETTE:
      image_type = INDEXED;
      layer_type = (alpha) ? INDEXEDA_IMAGE : INDEXED_IMAGE;
      break;
Elliot Lee's avatar
Elliot Lee committed
413

Sven Neumann's avatar
Sven Neumann committed
414
    case PHOTOMETRIC_MASK:
Manish Singh's avatar
Manish Singh committed
415
      g_message ("TIFF Can't handle PHOTOMETRIC_MASK");
Sven Neumann's avatar
Sven Neumann committed
416
417
418
      gimp_quit ();
      break;
    default:
Manish Singh's avatar
Manish Singh committed
419
      g_message ("TIFF Unknown photometric\n Number %d", photomet);
Sven Neumann's avatar
Sven Neumann committed
420
421
      gimp_quit ();
  }
Elliot Lee's avatar
Elliot Lee committed
422

Sven Neumann's avatar
Sven Neumann committed
423
  if ((image = gimp_image_new (cols, rows, image_type)) == -1) {
Manish Singh's avatar
Manish Singh committed
424
    g_message("TIFF Can't create a new image\n");
Sven Neumann's avatar
Sven Neumann committed
425
426
427
    gimp_quit ();
  }
  gimp_image_set_filename (image, filename);
Elliot Lee's avatar
Elliot Lee committed
428

429
430
431
432
433
434
435
436
437
  /* attach a parasite containing the compression/fillorder */
  if (!TIFFGetField (tif, TIFFTAG_COMPRESSION, &tmp))
    save_vals.compression = COMPRESSION_NONE;
  else
    save_vals.compression = tmp;
  if (!TIFFGetField (tif, TIFFTAG_FILLORDER, &tmp))
    save_vals.fillorder = FILLORDER_LSB2MSB;
  else
    save_vals.fillorder = tmp;
438
#ifdef GIMP_HAVE_PARASITES
439
440
  parasite = parasite_new("tiff-save-options", 0,
			  sizeof(save_vals), &save_vals);
441
  gimp_image_attach_parasite(image, parasite);
442
  parasite_free(parasite);
443
#endif /* GIMP_HAVE_PARASITES */
444

445

446
  /* Attach a parasite containing the image description.  Pretend to
447
   * be a gimp comment so other plugins will use this description as
448
   * an image comment where appropriate. */
449
#ifdef GIMP_HAVE_PARASITES
450
451
452
453
454
455
456
457
458
459
460
  {
    char *img_desc;

    if (TIFFGetField (tif, TIFFTAG_IMAGEDESCRIPTION, &img_desc))
    {
      int len;

      len = strlen(img_desc) + 1;
      len = MIN(len, 241);
      img_desc[len-1] = '\000';

461
462
      parasite = parasite_new("gimp-comment", PARASITE_PERSISTENT,
			      len, img_desc);
463
      gimp_image_attach_parasite(image, parasite);
464
      parasite_free(parasite);
465
466
    }
  }
467
#endif /* GIMP_HAVE_PARASITES */
468

469
  /* any resolution info in the file? */
470
#ifdef GIMP_HAVE_RESOLUTION_INFO
471
  {
472
473
474
    float xres = 72.0, yres = 72.0;
    unsigned short read_unit;
    GUnit unit = UNIT_PIXEL; /* invalid unit */
475
476
477
478

    if (TIFFGetField (tif, TIFFTAG_XRESOLUTION, &xres)) {
      if (TIFFGetField (tif, TIFFTAG_YRESOLUTION, &yres)) {

479
480
	if (TIFFGetField (tif, TIFFTAG_RESOLUTIONUNIT, &read_unit)) {
	  switch(read_unit) {
481
482
483
484
485
486
487
	  case RESUNIT_NONE:
	    /* ImageMagick writes files with this silly resunit */
	    g_message("TIFF warning: resolution units meaningless, "
		      "forcing 72 dpi\n");
	    break;

	  case RESUNIT_INCH:
488
	    unit = UNIT_INCH;
489
490
491
	    break;

	  case RESUNIT_CENTIMETER:
492
493
	    xres *= 2.54;
	    yres *= 2.54;
494
	    unit = UNIT_MM; /* as this is our default metric unit */
495
496
497
498
	    break;

	  default:
	    g_message("TIFF file error: unknown resolution unit type %d, "
499
		      "assuming dpi\n", read_unit);
500
501
502
503
504
505
506
507
	  }
	} else { /* no res unit tag */
	  /* old AppleScan software produces these */
	  g_message("TIFF warning: resolution specified without\n"
		    "any units tag, assuming dpi\n");
	}
      } else { /* xres but no yres */
	g_message("TIFF warning: no y resolution info, assuming same as x\n");
508
	yres = xres;
509
510
511
      }

      /* sanity check, since division by zero later could be embarrassing */
512
      if (xres < 1e-5 || yres < 1e-5) {
513
	g_message("TIFF: image resolution is zero: forcing 72 dpi\n");
514
515
	xres = 72.0;
	yres = 72.0;
516
517
518
      }

      /* now set the new image's resolution info */
519
      gimp_image_set_resolution (image, xres, yres);
520
      if (unit != UNIT_PIXEL)
521
	gimp_image_set_unit (image, unit);
522
523
524
525
526
527
528
529
530
531
532
    }

    /* no x res tag => we assume we have no resolution info, so we
     * don't care.  Older versions of this plugin used to write files
     * with no resolution tags at all. */

    /* TODO: haven't caught the case where yres tag is present, but
       not xres.  This is left as an exercise for the reader - they
       should feel free to shoot the author of the broken program
       that produced the damaged TIFF file in the first place. */
  }
533
#endif /* GIMP_HAVE_RESOLUTION_INFO */
534
535


Sven Neumann's avatar
Sven Neumann committed
536
537
538
  /* Install colormap for INDEXED images only */
  if (image_type == INDEXED) {
    if (!TIFFGetField (tif, TIFFTAG_COLORMAP, &redmap, &greenmap, &bluemap)) {
Manish Singh's avatar
Manish Singh committed
539
      g_message("TIFF Can't get colormaps");
Elliot Lee's avatar
Elliot Lee committed
540
541
542
      gimp_quit ();
    }

543
    for (i = 0, j = 0; i < (1 << bps); i++) {
Sven Neumann's avatar
Sven Neumann committed
544
545
546
      cmap[j++] = redmap[i] >> 8;
      cmap[j++] = greenmap[i] >> 8;
      cmap[j++] = bluemap[i] >> 8;
Elliot Lee's avatar
Elliot Lee committed
547
    }
548
    gimp_image_set_cmap (image, cmap, (1 << bps));
Sven Neumann's avatar
Sven Neumann committed
549
  }
Elliot Lee's avatar
Elliot Lee committed
550

Sven Neumann's avatar
Sven Neumann committed
551
  layer = gimp_layer_new (image, "Background", cols, rows, layer_type,
Elliot Lee's avatar
Elliot Lee committed
552
			     100, NORMAL_MODE);
Sven Neumann's avatar
Sven Neumann committed
553
554
  gimp_image_add_layer (image, layer, 0);
  drawable = gimp_drawable_get (layer);
Elliot Lee's avatar
Elliot Lee committed
555
556

  tile_height = gimp_tile_height ();
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607

  if (extra > 0) {
    channel = g_new (channel_data, extra);

    /* Add alpha channels as appropriate */
    for (i= 0; i < extra; ++i) {
      channel[i].ID= gimp_channel_new(image, "TIFF Channel", cols, rows,
                                                            100.0, colors);
      gimp_image_add_channel(image, channel[i].ID, 0);
      channel[i].drawable= gimp_drawable_get (channel[i].ID);
      channel[i].pixels= g_new(guchar, tile_height * cols);

      gimp_pixel_rgn_init (&(channel[i].pixel_rgn), channel[i].drawable, 0, 0,
  			   cols, rows, TRUE, FALSE);
    }
  }

  if (planar == PLANARCONFIG_SEPARATE) {
    load_separate(tif, drawable, channel, bps, photomet,
                  rows, cols, alpha, extra);
  } else if (bps == 8) {
    load_8bit(tif, drawable, channel, bps, photomet, rows, cols, alpha, extra);
  } else {
    load_default(tif, drawable, channel, bps, photomet,
                 rows, cols, alpha, extra);
  }

  gimp_drawable_flush (drawable);
  gimp_drawable_detach (drawable);

  for (i= 0; i < extra; ++i) {
    gimp_drawable_flush (channel[i].drawable);
    gimp_drawable_detach (channel[i].drawable);
  }

  return image;
}

static void
load_8bit(TIFF *tif, GDrawable *drawable,
             channel_data *channel,
             unsigned short bps, unsigned short photomet,
             int rows, int cols, int alpha, int extra)
{
  guchar *source, *dest, *s, *d;
  GPixelRgn pixel_rgn;
  int gray_val, red_val, green_val, blue_val, alpha_val;
  int col, row, start, i;
  int tile_height = gimp_tile_height ();

  source= g_new (guchar, TIFFScanlineSize (tif));
Elliot Lee's avatar
Elliot Lee committed
608
609
610
  dest = g_new (guchar, tile_height * cols * drawable->bpp);
  gimp_pixel_rgn_init (&pixel_rgn, drawable, 0, 0, cols, rows, TRUE, FALSE);

611
612
613
614
615
616
617
618
619
620
621
622
623
  for (start= 0, row = 0; row < rows; ++row) {
    d= dest + cols * (row % tile_height) * drawable->bpp;

    if (TIFFReadScanline (tif, source, row, 0) < 0) {
      g_message("TIFF Bad data read on line %d\n", row);
      gimp_quit ();
    }

    for (i= 0; i < extra; ++i) {
      channel[i].pixel= channel[i].pixels + cols * (row % tile_height);
    }

    s= source;
Elliot Lee's avatar
Elliot Lee committed
624

625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
    for (col = 0; col < cols; col++) {
      switch (photomet) {
        case PHOTOMETRIC_MINISBLACK:
          if (alpha) {
            gray_val= *s++;
            alpha_val= *s++;
            if (alpha_val)
              *d++ = gray_val * 255 / alpha_val;
            else
              *d++ = 0;
            *d++ = alpha_val;
          } else {
            *d++ = *s++;
          }
          break;
Elliot Lee's avatar
Elliot Lee committed
640

641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
        case PHOTOMETRIC_MINISWHITE:
          if (alpha) {
            gray_val= *s++;
            alpha_val= *s++;
            if (alpha_val)
              *d++ = ((255 - gray_val) * 255) / alpha_val;
            else
              *d++ = 0;
            *d++ = alpha_val;
          } else {
            *d++ = ~(*s++);
          }
          break;

        case PHOTOMETRIC_PALETTE:
          *d++= *s++;
          if (alpha) *d++= *s++;
          break;
  
        case PHOTOMETRIC_RGB:
          if (alpha) {
            red_val= *s++;
            green_val= *s++;
            blue_val= *s++;
            alpha_val= *s++;
            if (alpha_val) {
              *d++ = (red_val * 255) / alpha_val;
              *d++ = (green_val * 255) / alpha_val;
              *d++ = (blue_val * 255) / alpha_val;
            } else {
              *d++ = 0;
              *d++ = 0;
              *d++ = 0;
	    }
	    *d++ = alpha_val;
	  } else {
	    *d++ = *s++;
	    *d++ = *s++;
	    *d++ = *s++;
	  }
          break;

        default:
          /* This case was handled earlier */
          g_assert_not_reached();
      }
      for (i= 0; i < extra; ++i) {
        *channel[i].pixel++ = *s++;
      }
    }
    
    if (((row + 1) % tile_height) == 0 || row + 1 == rows) {
      gimp_pixel_rgn_set_rect (&pixel_rgn, dest, 0, start, cols, 1+row-start);
      for (i= 0; alpha + i < extra; ++i) {
	gimp_pixel_rgn_set_rect(&(channel[i].pixel_rgn), channel[i].pixels,
                                0, start, cols, 1+row-start);
      }
      gimp_progress_update ((double) row / (double) rows);
      start= row + 1;
    }
Sven Neumann's avatar
Sven Neumann committed
701
  }
702
}
Elliot Lee's avatar
Elliot Lee committed
703

Sven Neumann's avatar
Sven Neumann committed
704
705
706
/* Step through all <= 8-bit samples in an image */

#define NEXTSAMPLE(var)                       \
Elliot Lee's avatar
Elliot Lee committed
707
  {                                           \
Sven Neumann's avatar
Sven Neumann committed
708
      if (bitsleft == 0)                      \
Elliot Lee's avatar
Elliot Lee committed
709
710
711
712
713
      {                                       \
	  s++;                                \
	  bitsleft = 8;                       \
      }                                       \
      bitsleft -= bps;                        \
Sven Neumann's avatar
Sven Neumann committed
714
      var = ( *s >> bitsleft ) & maxval;      \
Elliot Lee's avatar
Elliot Lee committed
715
716
  }

717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
static void
load_default(TIFF *tif, GDrawable *drawable,
             channel_data *channel,
             unsigned short bps, unsigned short photomet,
             int rows, int cols, int alpha, int extra)
{
  guchar *source, *dest, *s, *d;
  GPixelRgn pixel_rgn;
  int gray_val, red_val, green_val, blue_val, alpha_val;
  int col, row, start, i;
  int bitsleft, maxval = (1 << bps) - 1;
  int tile_height = gimp_tile_height ();

  source= g_new (guchar, TIFFScanlineSize (tif));
  dest = g_new (guchar, tile_height * cols * drawable->bpp);
  gimp_pixel_rgn_init (&pixel_rgn, drawable, 0, 0, cols, rows, TRUE, FALSE);

Sven Neumann's avatar
Sven Neumann committed
734
735
736
  for (start= 0, row = 0; row < rows; ++row) {
    d= dest + cols * (row % tile_height) * drawable->bpp;

737
738
739
740
    if (TIFFReadScanline (tif, source, row, 0) < 0) {
      g_message("TIFF Bad data read on line %d\n", row);
      gimp_quit ();
    }
Sven Neumann's avatar
Sven Neumann committed
741

742
743
744
    for (i= 0; i < extra; ++i) {
      channel[i].pixel= channel[i].pixels + cols * (row % tile_height);
    }
Sven Neumann's avatar
Sven Neumann committed
745

746
    /* Set s/bitsleft ready to use NEXTSAMPLE macro */
Sven Neumann's avatar
Sven Neumann committed
747

748
749
    s= source;
    bitsleft= 8;
Sven Neumann's avatar
Sven Neumann committed
750

751
    for (col = 0; col < cols; col++) {
Sven Neumann's avatar
Sven Neumann committed
752
753
      switch (photomet) {
        case PHOTOMETRIC_MINISBLACK:
754
755
756
757
758
759
760
761
762
763
764
765
          NEXTSAMPLE(gray_val);
          if (alpha) {
            NEXTSAMPLE(alpha_val);
            if (alpha_val)
              *d++ = (gray_val * 65025) / (alpha_val * maxval);
            else
              *d++ = 0;
            *d++ = alpha_val;
          } else {
            *d++ = (gray_val * 255) / maxval;
          }
          break;
Elliot Lee's avatar
Elliot Lee committed
766

Sven Neumann's avatar
Sven Neumann committed
767
        case PHOTOMETRIC_MINISWHITE:
768
769
770
771
772
773
774
775
776
777
          NEXTSAMPLE(gray_val);
          if (alpha) {
            NEXTSAMPLE(alpha_val);
            if (alpha_val)
              *d++ = ((maxval - gray_val) * 65025) / (alpha_val * maxval);
            else
              *d++ = 0;
            *d++ = alpha_val;
          } else {
            *d++ = ((maxval - gray_val) * 255) / maxval;
Sven Neumann's avatar
Sven Neumann committed
778
779
780
781
          }
          break;

        case PHOTOMETRIC_PALETTE:
782
783
          NEXTSAMPLE(*d++);
          if (alpha) {
Sven Neumann's avatar
Sven Neumann committed
784
785
786
787
788
            NEXTSAMPLE(*d++);
          }
          break;
  
        case PHOTOMETRIC_RGB:
789
790
791
792
793
794
795
796
797
798
799
800
801
          NEXTSAMPLE(red_val)
          NEXTSAMPLE(green_val)
          NEXTSAMPLE(blue_val)
          if (alpha) {
            NEXTSAMPLE(alpha_val)
            if (alpha_val) {
              *d++ = (red_val * 255) / alpha_val;
              *d++ = (green_val * 255) / alpha_val;
              *d++ = (blue_val * 255) / alpha_val;
            } else {
              *d++ = 0;
              *d++ = 0;
              *d++ = 0;
Elliot Lee's avatar
Elliot Lee committed
802
	    }
803
804
805
806
807
808
	    *d++ = alpha_val;
	  } else {
	    *d++ = red_val;
	    *d++ = green_val;
	    *d++ = blue_val;
	  }
Sven Neumann's avatar
Sven Neumann committed
809
810
811
812
813
814
          break;

        default:
          /* This case was handled earlier */
          g_assert_not_reached();
      }
815
816
817
818
      for (i= 0; i < extra; ++i) {
        NEXTSAMPLE(alpha_val);
        *channel[i].pixel++ = alpha_val;
      }
Sven Neumann's avatar
Sven Neumann committed
819
820
821
822
823
824
825
826
    }
    
    if (((row + 1) % tile_height) == 0 || row + 1 == rows) {
      gimp_pixel_rgn_set_rect (&pixel_rgn, dest, 0, start, cols, 1+row-start);
      for (i= 0; alpha + i < extra; ++i) {
	gimp_pixel_rgn_set_rect(&(channel[i].pixel_rgn), channel[i].pixels,
                                0, start, cols, 1+row-start);
      }
Elliot Lee's avatar
Elliot Lee committed
827
      gimp_progress_update ((double) row / (double) rows);
Sven Neumann's avatar
Sven Neumann committed
828
      start= row + 1;
Elliot Lee's avatar
Elliot Lee committed
829
    }
Sven Neumann's avatar
Sven Neumann committed
830
  }
831
}
Elliot Lee's avatar
Elliot Lee committed
832

833
834
835
836
837
838
839
840
841
842
843
static void
load_separate(TIFF *tif, GDrawable *drawable,
              channel_data *channel,
              unsigned short bps, unsigned short photomet,
              int rows, int cols, int alpha, int extra)
{
  guchar *source, *dest, *s, *d;
  GPixelRgn pixel_rgn;
  int col, row, start;
  int bitsleft, maxval = (1 << bps) - 1;
  int tile_height = gimp_tile_height ();
Elliot Lee's avatar
Elliot Lee committed
844

845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
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
929
930
931
932
933
934
935
936
937
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
  TIFFPrintDirectory(tif, stdout, 0);
  if (photomet != PHOTOMETRIC_RGB) {
    g_message("So far PLANARCONFIG_SEPARATE only supports RGB images");
    gimp_quit();
  }

  source= g_new (guchar, TIFFScanlineSize (tif));
  dest = g_new (guchar, tile_height * cols * drawable->bpp);
  gimp_pixel_rgn_init (&pixel_rgn, drawable, 0, 0, cols, rows, TRUE, FALSE);

  /* RED channel */
  for (start= 0, row = 0; row < rows; ++row) {
    d= dest + cols * (row % tile_height) * drawable->bpp;

    if (TIFFReadScanline (tif, source, row, 0) < 0) {
      g_message("TIFF Bad data read on line %d\n", row);
      gimp_quit ();
    }

    /* Set s/bitsleft ready to use NEXTSAMPLE macro */

    s= source;
    bitsleft= 8;

    for (col = 0; col < cols; col++) {
      NEXTSAMPLE(d[col * (3 + alpha)])
    }
    
    if (((row + 1) % tile_height) == 0 || row + 1 == rows) {
      gimp_pixel_rgn_set_rect (&pixel_rgn, dest, 0, start, cols, 1+row-start);
      gimp_progress_update ((double) row / (double) rows);
      start= row + 1;
    }
  }

  /* GREEN channel */
  for (start= 0, row = 0; row < rows; ++row) {
    d= dest + cols * (row % tile_height) * drawable->bpp;

    if ((row % tile_height) == 0) {
      if (rows - row < tile_height)
        gimp_pixel_rgn_get_rect(&pixel_rgn, dest, 0, start, cols, rows - row);
      else
        gimp_pixel_rgn_get_rect(&pixel_rgn, dest, 0, start, cols, tile_height);
      gimp_progress_update ((double) row / (double) rows);
    }

    if (TIFFReadScanline (tif, source, row, 1) < 0) {
      g_message("TIFF Bad data read on line %d\n", row);
      gimp_quit ();
    }

    /* Set s/bitsleft ready to use NEXTSAMPLE macro */

    s= source;
    bitsleft= 8;

    for (col = 0; col < cols; col++) {
      NEXTSAMPLE(d[col * (3 + alpha) + 1])
    }
    
    if (((row + 1) % tile_height) == 0 || row + 1 == rows) {
      gimp_pixel_rgn_set_rect (&pixel_rgn, dest, 0, start, cols, 1+row-start);
      gimp_progress_update ((double) row / (double) rows);
      start= row + 1;
    }
  }

  /* BLUE channel */
  for (start= 0, row = 0; row < rows; ++row) {
    d= dest + cols * (row % tile_height) * drawable->bpp;

    if ((row % tile_height) == 0) {
      if (rows - row < tile_height)
        gimp_pixel_rgn_get_rect(&pixel_rgn, dest, 0, start, cols, rows - row);
      else
        gimp_pixel_rgn_get_rect(&pixel_rgn, dest, 0, start, cols, tile_height);
      gimp_progress_update ((double) row / (double) rows);
    }

    if (TIFFReadScanline (tif, source, row, 2) < 0) {
      g_message("TIFF Bad data read on line %d\n", row);
      gimp_quit ();
    }

    /* Set s/bitsleft ready to use NEXTSAMPLE macro */

    s= source;
    bitsleft= 8;

    for (col = 0; col < cols; col++) {
      NEXTSAMPLE(d[col * (3 + alpha) + 2])
    }
    
    if (((row + 1) % tile_height) == 0 || row + 1 == rows) {
      gimp_pixel_rgn_set_rect (&pixel_rgn, dest, 0, start, cols, 1+row-start);
      gimp_progress_update ((double) row / (double) rows);
      start= row + 1;
    }
  }

  /* ALPHA channel */
  if (alpha) {
    for (start= 0, row = 0; row < rows; ++row) {
      d= dest + cols * (row % tile_height) * drawable->bpp;

      if ((row % tile_height) == 0) {
        if (rows - row < tile_height)
          gimp_pixel_rgn_get_rect(&pixel_rgn, dest, 0, start, cols, rows - row);
        else
          gimp_pixel_rgn_get_rect(&pixel_rgn, dest, 0, start, cols, tile_height);
        gimp_progress_update ((double) row / (double) rows);
      }

      if (TIFFReadScanline (tif, source, row, 3) < 0) {
        g_message("TIFF Bad data read on line %d\n", row);
        gimp_quit ();
      }

      /* Set s/bitsleft ready to use NEXTSAMPLE macro */
  
      s= source;
      bitsleft= 8;

      for (col = 0; col < cols; col++) {
        NEXTSAMPLE(d[col * 4 + 3])
      }
    
      if (((row + 1) % tile_height) == 0 || row + 1 == rows) {
        gimp_pixel_rgn_set_rect (&pixel_rgn, dest, 0, start, cols, 1+row-start);
        gimp_progress_update ((double) row / (double) rows);
        start= row + 1;
      }
    }
  }
Elliot Lee's avatar
Elliot Lee committed
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
}

/*
** pnmtotiff.c - converts a portable anymap to a Tagged Image File
**
** Derived by Jef Poskanzer from ras2tif.c, which is:
**
** Copyright (c) 1990 by Sun Microsystems, Inc.
**
** Author: Patrick J. Naughton
** naughton@wind.sun.com
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted,
** provided that the above copyright notice appear in all copies and that
** both that copyright notice and this permission notice appear in
** supporting documentation.
**
** This file is provided AS IS with no warranties of any kind.  The author
** shall have no liability with respect to the infringement of copyrights,
** trade secrets or any patents by this file or any part thereof.  In no
** event will the author be liable for any lost revenue or profits or
** other special, indirect and consequential damages.
*/

Sven Neumann's avatar
Sven Neumann committed
1005
static gint save_image (char *filename, gint32 image, gint32 layer) {
Elliot Lee's avatar
Elliot Lee committed
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
  TIFF *tif;
  unsigned short red[256];
  unsigned short grn[256];
  unsigned short blu[256];
  int cols, col, rows, row, i;
  long g3options;
  long rowsperstrip;
  unsigned short compression;
  unsigned short fillorder;
  unsigned short extra_samples[1];
  int alpha;
  short predictor;
  short photometric;
  short samplesperpixel;
  short bitspersample;
  int bytesperrow;
  guchar *t, *src, *data;
  guchar *cmap;
  int colors;
  int success;
  GDrawable *drawable;
  GDrawableType drawable_type;
  GPixelRgn pixel_rgn;
  int tile_height;
  int y, yend;
  char *name;

  compression = tsvals.compression;
  fillorder = tsvals.fillorder;

  g3options = 0;
  predictor = 0;
  rowsperstrip = 0;

  tif = TIFFOpen (filename, "w");
Manish Singh's avatar
Manish Singh committed
1041
1042
1043
1044
  if (!tif) {
    g_print ("Can't write image to\n%s", filename);
    return 0;
  }
Elliot Lee's avatar
Elliot Lee committed
1045
1046
1047
1048
1049
1050

  name = malloc (strlen (filename) + 11);
  sprintf (name, "Saving %s:", filename);
  gimp_progress_init (name);
  free (name);

Sven Neumann's avatar
Sven Neumann committed
1051
1052
  drawable = gimp_drawable_get (layer);
  drawable_type = gimp_drawable_type (layer);
Elliot Lee's avatar
Elliot Lee committed
1053
1054
1055
1056
1057
1058
1059
1060
  gimp_pixel_rgn_init (&pixel_rgn, drawable, 0, 0, drawable->width, drawable->height, FALSE, FALSE);

  cols = drawable->width;
  rows = drawable->height;

  switch (drawable_type)
    {
    case RGB_IMAGE:
1061
      predictor = 2;
Elliot Lee's avatar
Elliot Lee committed
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
      samplesperpixel = 3;
      bitspersample = 8;
      photometric = PHOTOMETRIC_RGB;
      bytesperrow = cols * 3;
      alpha = 0;
      break;
    case GRAY_IMAGE:
      samplesperpixel = 1;
      bitspersample = 8;
      photometric = PHOTOMETRIC_MINISBLACK;
      bytesperrow = cols;
      alpha = 0;
      break;
    case RGBA_IMAGE:
1076
      predictor = 2;
Elliot Lee's avatar
Elliot Lee committed
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
      samplesperpixel = 4;
      bitspersample = 8;
      photometric = PHOTOMETRIC_RGB;
      bytesperrow = cols * 4;
      alpha = 1;
      break;
    case GRAYA_IMAGE:
      samplesperpixel = 2;
      bitspersample = 8;
      photometric = PHOTOMETRIC_MINISBLACK;
      bytesperrow = cols * 2;
      alpha = 1;
      break;
    case INDEXED_IMAGE:
      samplesperpixel = 1;
      bitspersample = 8;
      photometric = PHOTOMETRIC_PALETTE;
      bytesperrow = cols;
      alpha = 0;

Sven Neumann's avatar
Sven Neumann committed
1097
      cmap = gimp_image_get_cmap (image, &colors);
Elliot Lee's avatar
Elliot Lee committed
1098
1099
1100

      for (i = 0; i < colors; i++)
	{
1101
1102
1103
	  red[i] = *cmap++ * 65535 / 255;
	  grn[i] = *cmap++ * 65535 / 255;
	  blu[i] = *cmap++ * 65535 / 255;
Elliot Lee's avatar
Elliot Lee committed
1104
1105
1106
1107
	}
      break;
    case INDEXEDA_IMAGE:
      return 0;
1108
1109
     default:
       return 0;
Elliot Lee's avatar
Elliot Lee committed
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
    }

  if (rowsperstrip == 0)
    rowsperstrip = (8 * 1024) / bytesperrow;
  if (rowsperstrip == 0)
    rowsperstrip = 1;

  /* Set TIFF parameters. */
  TIFFSetField (tif, TIFFTAG_IMAGEWIDTH, cols);
  TIFFSetField (tif, TIFFTAG_IMAGELENGTH, rows);
  TIFFSetField (tif, TIFFTAG_BITSPERSAMPLE, bitspersample);
  TIFFSetField (tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
  TIFFSetField (tif, TIFFTAG_COMPRESSION, compression);
  if ((compression == COMPRESSION_LZW) && (predictor != 0))
    TIFFSetField (tif, TIFFTAG_PREDICTOR, predictor);
  if (alpha)
    {
      extra_samples [0] = EXTRASAMPLE_ASSOCALPHA;
      TIFFSetField (tif, TIFFTAG_EXTRASAMPLES, 1, extra_samples);
    }
  TIFFSetField (tif, TIFFTAG_PHOTOMETRIC, photometric);
  TIFFSetField (tif, TIFFTAG_FILLORDER, fillorder);
  TIFFSetField (tif, TIFFTAG_DOCUMENTNAME, filename);
  TIFFSetField (tif, TIFFTAG_SAMPLESPERPIXEL, samplesperpixel);
  TIFFSetField (tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
  /* TIFFSetField( tif, TIFFTAG_STRIPBYTECOUNTS, rows / rowsperstrip ); */
  TIFFSetField (tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);

1138
#ifdef GIMP_HAVE_RESOLUTION_INFO
1139
1140
  /* resolution fields */
  {
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
    double xresolution;
    double yresolution;
    unsigned short save_unit = RESUNIT_INCH;
    GUnit unit;
    float factor;

    gimp_image_get_resolution (image, &xresolution, &yresolution);
    unit = gimp_image_get_unit (image);
    factor = gimp_unit_get_factor (unit);

    /*  if we have a metric unit, save the resolution as centimeters
     */
    if ((ABS(factor - 0.0254) < 1e-5) ||  /* m */
	(ABS(factor - 0.254) < 1e-5) ||   /* why not ;) */
	(ABS(factor - 2.54) < 1e-5) ||    /* cm */
	(ABS(factor - 25.4) < 1e-5))      /* mm */
      {
	save_unit = RESUNIT_CENTIMETER;
	xresolution /= 2.54;
	yresolution /= 2.54;
      }
1162

1163
    if (xresolution > 1e-5 && yresolution > 1e-5)
1164
      {
1165
1166
1167
	TIFFSetField (tif, TIFFTAG_XRESOLUTION, xresolution);
	TIFFSetField (tif, TIFFTAG_YRESOLUTION, yresolution);
	TIFFSetField (tif, TIFFTAG_RESOLUTIONUNIT, save_unit);
1168
1169
      }
  }
1170
#endif /* GIMP_HAVE_RESOLUTION_INFO */
1171

1172
1173
1174
  /* do we have a comment?  If so, create a new parasite to hold it,
   * and attach it to the image. The attach function automatically
   * detaches a previous incarnation of the parasite. */
1175
#ifdef GIMP_HAVE_PARASITES
1176
1177
  if (image_comment && *image_comment != '\000')
  {
1178
    Parasite *parasite;
1179
1180

    TIFFSetField (tif, TIFFTAG_IMAGEDESCRIPTION, image_comment);
1181
    parasite = parasite_new ("gimp-comment", 1,
1182
1183
			      strlen(image_comment)+1, image_comment);
    gimp_image_attach_parasite (image, parasite);
1184
    parasite_free (parasite);
1185
  }
1186
#endif /* GIMP_HAVE_PARASITES */
1187

Sven Neumann's avatar
Sven Neumann committed
1188
  if (drawable_type == INDEXED_IMAGE)
Elliot Lee's avatar
Elliot Lee committed
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
    TIFFSetField (tif, TIFFTAG_COLORMAP, red, grn, blu);

  /* array to rearrange data */
  tile_height = gimp_tile_height ();
  src = g_new (guchar, bytesperrow * tile_height);
  data = g_new (guchar, bytesperrow);

  /* Now write the TIFF data. */
  for (y = 0; y < rows; y = yend)
    {
      yend = y + tile_height;
      yend = MIN (yend, rows);

      gimp_pixel_rgn_get_rect (&pixel_rgn, src, 0, y, cols, yend - y);

      for (row = y; row < yend; row++)
	{
	  t = src + bytesperrow * (row - y);

	  switch (drawable_type)
	    {
	    case INDEXED_IMAGE:
	      success = (TIFFWriteScanline (tif, t, row, 0) >= 0);
	      break;
	    case GRAY_IMAGE:
	      success = (TIFFWriteScanline (tif, t, row, 0) >= 0);
	      break;
	    case GRAYA_IMAGE:
	      for (col = 0; col < cols*samplesperpixel; col+=samplesperpixel)
		{
		  /* pre-multiply gray by alpha */
		  data[col + 0] = (t[col + 0] * t[col + 1]) / 255;
		  data[col + 1] = t[col + 1];  /* alpha channel */
		}
	      success = (TIFFWriteScanline (tif, data, row, 0) >= 0);
	      break;
	    case RGB_IMAGE:
	      success = (TIFFWriteScanline (tif, t, row, 0) >= 0);
	      break;
	    case RGBA_IMAGE:
	      for (col = 0; col < cols*samplesperpixel; col+=samplesperpixel)
		{
		  /* pre-multiply rgb by alpha */
		  data[col+0] = t[col + 0] * t[col + 3] / 255;
		  data[col+1] = t[col + 1] * t[col + 3] / 255;
		  data[col+2] = t[col + 2] * t[col + 3] / 255;
		  data[col+3] = t[col + 3];  /* alpha channel */
		}
	      success = (TIFFWriteScanline (tif, data, row, 0) >= 0);
	      break;
	    default:
1240
	      success = FALSE;
Elliot Lee's avatar
Elliot Lee committed
1241
1242
1243
	      break;
	    }

Manish Singh's avatar
Manish Singh committed
1244
1245
	  if (!success) {
	      g_message("TIFF Failed a scanline write on row %d", row);
Elliot Lee's avatar
Elliot Lee committed
1246
	      return 0;
Manish Singh's avatar
Manish Singh committed
1247
	  }
Elliot Lee's avatar
Elliot Lee committed
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
	}

      gimp_progress_update ((double) row / (double) rows);
    }

  TIFFFlushData (tif);
  TIFFClose (tif);

  gimp_drawable_detach (drawable);
  g_free (data);

  return 1;
}

static gint
save_dialog ()
{
  GtkWidget *dlg;
  GtkWidget *button;
  GtkWidget *toggle;
  GtkWidget *frame;
  GtkWidget *toggle_vbox;
1270
1271
1272
  GtkWidget *hbox;
  GtkWidget *label;
  GtkWidget *entry;
Elliot Lee's avatar
Elliot Lee committed
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
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
  GSList *group;
  gchar **argv;
  gint argc;
  gint use_none = (tsvals.compression == COMPRESSION_NONE);
  gint use_lzw = (tsvals.compression == COMPRESSION_LZW);
  gint use_packbits = (tsvals.compression == COMPRESSION_PACKBITS);
  gint use_lsb2msb = (tsvals.fillorder == FILLORDER_LSB2MSB);
  gint use_msb2lsb = (tsvals.fillorder == FILLORDER_MSB2LSB);

  argc = 1;
  argv = g_new (gchar *, 1);
  argv[0] = g_strdup ("save");

  gtk_init (&argc, &argv);
  gtk_rc_parse (gimp_gtkrc ());

  dlg = gtk_dialog_new ();
  gtk_window_set_title (GTK_WINDOW (dlg), "Save as Tiff");
  gtk_window_position (GTK_WINDOW (dlg), GTK_WIN_POS_MOUSE);
  gtk_signal_connect (GTK_OBJECT (dlg), "destroy",
		      (GtkSignalFunc) save_close_callback,
		      NULL);

  /*  Action area  */
  button = gtk_button_new_with_label ("OK");
  GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
  gtk_signal_connect (GTK_OBJECT (button), "clicked",
                      (GtkSignalFunc) save_ok_callback,
                      dlg);
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dlg)->action_area), button, TRUE, TRUE, 0);
  gtk_widget_grab_default (button);
  gtk_widget_show (button);

  button = gtk_button_new_with_label ("Cancel");
  GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
  gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
			     (GtkSignalFunc) gtk_widget_destroy,
			     GTK_OBJECT (dlg));
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dlg)->action_area), button, TRUE, TRUE, 0);
  gtk_widget_show (button);

1314
1315
1316
  /* hbox for compression and fillorder settings */
  hbox = gtk_hbox_new (FALSE, 5);

Elliot Lee's avatar
Elliot Lee committed
1317
1318
1319
1320
  /*  compression  */
  frame = gtk_frame_new ("Compression");
  gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_ETCHED_IN);
  gtk_container_border_width (GTK_CONTAINER (frame), 10);
1321
  gtk_box_pack_start (GTK_BOX (hbox), frame, TRUE, FALSE, 0);
Elliot Lee's avatar
Elliot Lee committed
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
  toggle_vbox = gtk_vbox_new (FALSE, 5);
  gtk_container_border_width (GTK_CONTAINER (toggle_vbox), 5);
  gtk_container_add (GTK_CONTAINER (frame), toggle_vbox);

  group = NULL;
  toggle = gtk_radio_button_new_with_label (group, "None");
  group = gtk_radio_button_group (GTK_RADIO_BUTTON (toggle));
  gtk_box_pack_start (GTK_BOX (toggle_vbox), toggle, FALSE, FALSE, 0);
  gtk_signal_connect (GTK_OBJECT (toggle), "toggled",
		      (GtkSignalFunc) save_toggle_update,
		      &use_none);
1333
  gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (toggle), use_none);
Elliot Lee's avatar
Elliot Lee committed
1334
1335
1336
1337
1338
1339
1340
1341
  gtk_widget_show (toggle);

  toggle = gtk_radio_button_new_with_label (group, "LZW");
  group = gtk_radio_button_group (GTK_RADIO_BUTTON (toggle));
  gtk_box_pack_start (GTK_BOX (toggle_vbox), toggle, FALSE, FALSE, 0);
  gtk_signal_connect (GTK_OBJECT (toggle), "toggled",
		      (GtkSignalFunc) save_toggle_update,
		      &use_lzw);
1342
  gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (toggle), use_lzw);
Elliot Lee's avatar
Elliot Lee committed
1343
1344
1345
1346
1347
1348
1349
1350
  gtk_widget_show (toggle);

  toggle = gtk_radio_button_new_with_label (group, "Pack Bits");
  group = gtk_radio_button_group (GTK_RADIO_BUTTON (toggle));
  gtk_box_pack_start (GTK_BOX (toggle_vbox), toggle, FALSE, FALSE, 0);
  gtk_signal_connect (GTK_OBJECT (toggle), "toggled",
		      (GtkSignalFunc) save_toggle_update,
		      &use_packbits);
1351
  gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (toggle), use_packbits);
Elliot Lee's avatar
Elliot Lee committed
1352
1353
1354
1355
1356
1357
1358
1359
1360
  gtk_widget_show (toggle);

  gtk_widget_show (toggle_vbox);
  gtk_widget_show (frame);

  /*  fillorder  */
  frame = gtk_frame_new ("Fill Order");
  gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_ETCHED_IN);
  gtk_container_border_width (GTK_CONTAINER (frame), 10);
1361
  gtk_box_pack_start (GTK_BOX (hbox), frame, TRUE, FALSE, 0);
Elliot Lee's avatar
Elliot Lee committed
1362
1363
1364
1365
1366
  toggle_vbox = gtk_vbox_new (FALSE, 5);
  gtk_container_border_width (GTK_CONTAINER (toggle_vbox), 5);
  gtk_container_add (GTK_CONTAINER (frame), toggle_vbox);

  group = NULL;
1367
  toggle = gtk_radio_button_new_with_label (group, "LSB to MSB (PC)");
Elliot Lee's avatar
Elliot Lee committed
1368
1369
1370
1371
1372
  group = gtk_radio_button_group (GTK_RADIO_BUTTON (toggle));
  gtk_box_pack_start (GTK_BOX (toggle_vbox), toggle, FALSE, FALSE, 0);
  gtk_signal_connect (GTK_OBJECT (toggle), "toggled",
		      (GtkSignalFunc) save_toggle_update,
		      &use_lsb2msb);
1373
  gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (toggle), use_lsb2msb);
Elliot Lee's avatar
Elliot Lee committed
1374
1375
  gtk_widget_show (toggle);

1376
  toggle = gtk_radio_button_new_with_label (group, "MSB to LSB (Mac)");
Elliot Lee's avatar
Elliot Lee committed
1377
1378
1379
1380
1381
  group = gtk_radio_button_group (GTK_RADIO_BUTTON (toggle));
  gtk_box_pack_start (GTK_BOX (toggle_vbox), toggle, FALSE, FALSE, 0);
  gtk_signal_connect (GTK_OBJECT (toggle), "toggled",
		      (GtkSignalFunc) save_toggle_update,
		      &use_msb2lsb);
1382
  gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (toggle), use_msb2lsb);
Elliot Lee's avatar
Elliot Lee committed
1383
1384
1385
1386
1387
  gtk_widget_show (toggle);

  gtk_widget_show (toggle_vbox);
  gtk_widget_show (frame);

1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414

  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dlg)->vbox), hbox, FALSE, TRUE, 0);
  gtk_widget_show (hbox);


  /* comment entry */
  frame = gtk_frame_new(NULL);
  gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_NONE);
  gtk_container_border_width (GTK_CONTAINER (frame), 10);
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dlg)->vbox), frame, FALSE, TRUE, 0);

  hbox = gtk_hbox_new (FALSE, 5);
  label = gtk_label_new ("Comment: ");
  gtk_widget_show (label);
  gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, TRUE, 0);
  entry = gtk_entry_new ();
  gtk_widget_show (entry);
  gtk_box_pack_start (GTK_BOX (hbox), entry, TRUE, TRUE, 0);
  gtk_entry_set_text (GTK_ENTRY (entry), image_comment);
  gtk_signal_connect (GTK_OBJECT (entry), "changed",
                      (GtkSignalFunc) comment_entry_callback,
                      NULL);

  gtk_container_add (GTK_CONTAINER (frame), hbox);
  gtk_widget_show (hbox);
  gtk_widget_show (frame);

Elliot Lee's avatar
Elliot Lee committed
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
  gtk_widget_show (dlg);

  gtk_main ();
  gdk_flush ();

  if (use_none)
    tsvals.compression = COMPRESSION_NONE;
  else if (use_lzw)
    tsvals.compression = COMPRESSION_LZW;
  else if (use_packbits)
    tsvals.compression = COMPRESSION_PACKBITS;

  if (use_lsb2msb)
    tsvals.fillorder = FILLORDER_LSB2MSB;
  else if (use_msb2lsb)
    tsvals.fillorder = FILLORDER_MSB2LSB;

  return tsint.run;
}


/*  Save interface functions  */

static void
save_close_callback (GtkWidget *widget,
		     gpointer   data)
{
  gtk_main_quit ();
}

static void
save_ok_callback (GtkWidget *widget,
		  gpointer   data)
{
  tsint.run = TRUE;
  gtk_widget_destroy (GTK_WIDGET (data));
}

static void
save_toggle_update (GtkWidget *widget,
		    gpointer   data)
{
  int *toggle_val;

  toggle_val = (int *) data;

  if (GTK_TOGGLE_BUTTON (widget)->active)
    *toggle_val = TRUE;
  else
    *toggle_val = FALSE;
}
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488

static void
comment_entry_callback (GtkWidget *widget,
			gpointer   data)
{
  int len;
  char *text;

  text = gtk_entry_get_text (GTK_ENTRY (widget));
  len = strlen(text);

  /* Temporary kludge for overlength strings - just return */
  if (len > 240)
    {
      g_message ("TIFF save: Your comment string is too long.\n");
      return;
    }

  g_free(image_comment);
  image_comment = g_strdup(text);

  /* g_print ("COMMENT: %s\n", image_comment); */
}