io-png.c 36.7 KB
Newer Older
1
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */
2
/* GdkPixbuf library - PNG image loader
3
 *
4
 * Copyright (C) 1999 Mark Crichton
5 6 7 8
 * Copyright (C) 1999 The Free Software Foundation
 *
 * Authors: Mark Crichton <crichton@gimp.org>
 *          Federico Mena-Quintero <federico@gimp.org>
9
 *
10
 * This library is free software; you can redistribute it and/or
11
 * modify it under the terms of the GNU Lesser General Public
12 13 14 15 16 17
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18
 * Lesser General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Lesser General Public
21 22 23
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
24
 */
25

26 27
#include <config.h>
#include <stdio.h>
28
#include <stdlib.h>
29
#include <png.h>
30
#include "gdk-pixbuf-private.h"
31
#include "gdk-pixbuf-io.h"
32 33 34



35
static gboolean
36
setup_png_transformations(png_structp png_read_ptr, png_infop png_info_ptr,
37
                          GError **error,
38 39 40 41 42 43 44 45 46
                          png_uint_32* width_p, png_uint_32* height_p,
                          int* color_type_p)
{
        png_uint_32 width, height;
        int bit_depth, color_type, interlace_type, compression_type, filter_type;
        int channels;
        
        /* Get the image info */

47 48 49 50 51 52 53 54 55 56 57
        /* Must check bit depth, since png_get_IHDR generates an 
           FPE on bit_depth 0.
        */
        bit_depth = png_get_bit_depth (png_read_ptr, png_info_ptr);
        if (bit_depth < 1 || bit_depth > 16) {
                g_set_error (error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                             _("Bits per channel of PNG image is invalid."));
                return FALSE;
        }
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
        png_get_IHDR (png_read_ptr, png_info_ptr,
                      &width, &height,
                      &bit_depth,
                      &color_type,
                      &interlace_type,
                      &compression_type,
                      &filter_type);

        /* set_expand() basically needs to be called unless
           we are already in RGB/RGBA mode
        */
        if (color_type == PNG_COLOR_TYPE_PALETTE &&
            bit_depth <= 8) {

                /* Convert indexed images to RGB */
                png_set_expand (png_read_ptr);

        } else if (color_type == PNG_COLOR_TYPE_GRAY &&
                   bit_depth < 8) {

                /* Convert grayscale to RGB */
                png_set_expand (png_read_ptr);

        } else if (png_get_valid (png_read_ptr, 
                                  png_info_ptr, PNG_INFO_tRNS)) {

                /* If we have transparency header, convert it to alpha
                   channel */
                png_set_expand(png_read_ptr);
                
        } else if (bit_depth < 8) {

                /* If we have < 8 scale it up to 8 */
                png_set_expand(png_read_ptr);


                /* Conceivably, png_set_packing() is a better idea;
                 * God only knows how libpng works
                 */
        }

        /* If we are 16-bit, convert to 8-bit */
        if (bit_depth == 16) {
                png_set_strip_16(png_read_ptr);
        }

        /* If gray scale, convert to RGB */
        if (color_type == PNG_COLOR_TYPE_GRAY ||
            color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
                png_set_gray_to_rgb(png_read_ptr);
        }
        
        /* If interlaced, handle that */
        if (interlace_type != PNG_INTERLACE_NONE) {
                png_set_interlace_handling(png_read_ptr);
        }
        
        /* Update the info the reflect our transformations */
        png_read_update_info(png_read_ptr, png_info_ptr);
        
        png_get_IHDR (png_read_ptr, png_info_ptr,
                      &width, &height,
                      &bit_depth,
                      &color_type,
                      &interlace_type,
                      &compression_type,
                      &filter_type);

        *width_p = width;
        *height_p = height;
        *color_type_p = color_type;
        
        /* Check that the new info is what we want */
        
132 133 134 135 136 137 138 139
        if (width == 0 || height == 0) {
                g_set_error (error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                             _("Transformed PNG has zero width or height."));
                return FALSE;
        }

140
        if (bit_depth != 8) {
141 142 143 144 145
                g_set_error (error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                             _("Bits per channel of transformed PNG is not 8."));
                return FALSE;
146 147 148 149
        }

        if ( ! (color_type == PNG_COLOR_TYPE_RGB ||
                color_type == PNG_COLOR_TYPE_RGB_ALPHA) ) {
150 151 152 153 154
                g_set_error (error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                             _("Transformed PNG not RGB or RGBA."));
                return FALSE;
155 156 157 158
        }

        channels = png_get_channels(png_read_ptr, png_info_ptr);
        if ( ! (channels == 3 || channels == 4) ) {
159 160 161 162 163
                g_set_error (error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                             _("Transformed PNG has unsupported number of channels, must be 3 or 4."));
                return FALSE;
164
        }
165
        return TRUE;
166 167
}

Havoc Pennington's avatar
Havoc Pennington committed
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
static void
png_simple_error_callback(png_structp png_save_ptr,
                          png_const_charp error_msg)
{
        GError **error;
        
        error = png_get_error_ptr(png_save_ptr);

        /* I don't trust libpng to call the error callback only once,
         * so check for already-set error
         */
        if (error && *error == NULL) {
                g_set_error (error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_FAILED,
183
                             _("Fatal error in PNG image file: %s"),
Havoc Pennington's avatar
Havoc Pennington committed
184 185
                             error_msg);
        }
186 187

        longjmp (png_save_ptr->jmpbuf, 1);
Havoc Pennington's avatar
Havoc Pennington committed
188 189 190 191 192 193 194 195 196 197 198 199 200 201
}

static void
png_simple_warning_callback(png_structp png_save_ptr,
                            png_const_charp warning_msg)
{
        /* Don't print anything; we should not be dumping junk to
         * stderr, since that may be bad for some apps. If it's
         * important enough to display, we need to add a GError
         * **warning return location wherever we have an error return
         * location.
         */
}

202 203 204 205 206
static gboolean
png_text_to_pixbuf_option (png_text   text_ptr,
                           gchar    **key,
                           gchar    **value)
{
Michael Natterer's avatar
Michael Natterer committed
207 208 209 210 211 212 213 214 215 216 217
        gboolean is_ascii = TRUE;
        int i;

        /* Avoid loading iconv if the text is plain ASCII */
        for (i = 0; i < text_ptr.text_length; i++)
                if (text_ptr.text[i] & 0x80) {
                        is_ascii = FALSE;
                        break;
                }

        if (is_ascii) {
218
                *value = g_strdup (text_ptr.text);
Michael Natterer's avatar
Michael Natterer committed
219 220 221 222
        } else {
                *value = g_convert (text_ptr.text, -1,
                                     "UTF-8", "ISO-8859-1",
                                     NULL, NULL, NULL);
223
        }
Michael Natterer's avatar
Michael Natterer committed
224

225 226 227 228
        if (*value) {
                *key = g_strconcat ("tEXt::", text_ptr.key, NULL);
                return TRUE;
        } else {
229
                g_warning ("Couldn't convert text chunk value to UTF-8.");
230 231 232 233 234
                *key = NULL;
                return FALSE;
        }
}

235 236 237 238 239 240 241 242 243 244 245 246
static png_voidp
png_malloc_callback (png_structp o, png_size_t size)
{
        return g_try_malloc (size);
}

static void
png_free_callback (png_structp o, png_voidp x)
{
        g_free (x);
}

247
/* Shared library entry point */
248
static GdkPixbuf *
Havoc Pennington's avatar
Havoc Pennington committed
249
gdk_pixbuf__png_image_load (FILE *f, GError **error)
250
{
251
        GdkPixbuf * volatile pixbuf = NULL;
252
	png_structp png_ptr;
Matthias Clasen's avatar
Matthias Clasen committed
253
	png_infop info_ptr;
254
        png_textp text_ptr;
255
	gint i, ctype;
256
	png_uint_32 w, h;
257
	png_bytepp volatile rows = NULL;
258
        gint    num_texts;
259 260
        gchar *key;
        gchar *value;
261

262 263 264 265 266 267 268 269 270
#ifdef PNG_USER_MEM_SUPPORTED
	png_ptr = png_create_read_struct_2 (PNG_LIBPNG_VER_STRING,
                                            error,
                                            png_simple_error_callback,
                                            png_simple_warning_callback,
                                            NULL, 
                                            png_malloc_callback, 
                                            png_free_callback);
#else
Havoc Pennington's avatar
Havoc Pennington committed
271 272 273 274
	png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
                                          error,
                                          png_simple_error_callback,
                                          png_simple_warning_callback);
275
#endif
276 277 278 279 280 281 282 283 284 285
	if (!png_ptr)
		return NULL;

	info_ptr = png_create_info_struct (png_ptr);
	if (!info_ptr) {
		png_destroy_read_struct (&png_ptr, NULL, NULL);
		return NULL;
	}

	if (setjmp (png_ptr->jmpbuf)) {
286
	    	g_free (rows);
287

288 289
		if (pixbuf)
			g_object_unref (pixbuf);
290

Matthias Clasen's avatar
Matthias Clasen committed
291
		png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
292 293 294
		return NULL;
	}

295
	png_init_io (png_ptr, f);
296
	png_read_info (png_ptr, info_ptr);
297

298
        if (!setup_png_transformations(png_ptr, info_ptr, error, &w, &h, &ctype)) {
Matthias Clasen's avatar
Matthias Clasen committed
299
                png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
300 301 302
                return NULL;
        }
        
303 304 305
        pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, ctype & PNG_COLOR_MASK_ALPHA, 8, w, h);

	if (!pixbuf) {
Havoc Pennington's avatar
Havoc Pennington committed
306 307 308 309 310 311 312
                if (error && *error == NULL) {
                        g_set_error (error,
                                     GDK_PIXBUF_ERROR,
                                     GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
                                     _("Insufficient memory to load PNG file"));
                }
                
313

Matthias Clasen's avatar
Matthias Clasen committed
314
		png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
315 316
		return NULL;
	}
317

318
	rows = g_new (png_bytep, h);
319

320
	for (i = 0; i < h; i++)
321
		rows[i] = pixbuf->pixels + i * pixbuf->rowstride;
322

323
	png_read_image (png_ptr, rows);
Matthias Clasen's avatar
Matthias Clasen committed
324
        png_read_end (png_ptr, info_ptr);
325 326 327

        if (png_get_text (png_ptr, info_ptr, &text_ptr, &num_texts)) {
                for (i = 0; i < num_texts; i++) {
328
                        png_text_to_pixbuf_option (text_ptr[i], &key, &value);
329
                        gdk_pixbuf_set_option (pixbuf, key, value);
330 331
                        g_free (key);
                        g_free (value);
332 333 334
                }
        }

335 336
	g_free (rows);
	png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
337 338

        return pixbuf;
339
}
340

341 342
/* I wish these avoided the setjmp()/longjmp() crap in libpng instead
   just allow you to change the error reporting. */
343 344 345
static void png_error_callback  (png_structp png_read_ptr,
                                 png_const_charp error_msg);

346 347
static void png_warning_callback (png_structp png_read_ptr,
                                  png_const_charp warning_msg);
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369

/* Called at the start of the progressive load */
static void png_info_callback   (png_structp png_read_ptr,
                                 png_infop   png_info_ptr);

/* Called for each row; note that you will get duplicate row numbers
   for interlaced PNGs */
static void png_row_callback   (png_structp png_read_ptr,
                                png_bytep   new_row,
                                png_uint_32 row_num,
                                int pass_num);

/* Called after reading the entire image */
static void png_end_callback   (png_structp png_read_ptr,
                                png_infop   png_info_ptr);

typedef struct _LoadContext LoadContext;

struct _LoadContext {
        png_structp png_read_ptr;
        png_infop   png_info_ptr;

370
        GdkPixbufModuleSizeFunc size_func;
371 372
        GdkPixbufModulePreparedFunc prepare_func;
        GdkPixbufModuleUpdatedFunc update_func;
373 374 375
        gpointer notify_user_data;

        GdkPixbuf* pixbuf;
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391

        /* row number of first row seen, or -1 if none yet seen */

        gint first_row_seen_in_chunk;

        /* pass number for the first row seen */

        gint first_pass_seen_in_chunk;
        
        /* row number of last row seen */
        gint last_row_seen_in_chunk;

        gint last_pass_seen_in_chunk;

        /* highest row number seen */
        gint max_row_seen_in_chunk;
392 393 394
        
        guint fatal_error_occurred : 1;

Havoc Pennington's avatar
Havoc Pennington committed
395
        GError **error;
396 397
};

398
static gpointer
399 400 401
gdk_pixbuf__png_image_begin_load (GdkPixbufModuleSizeFunc size_func,
                                  GdkPixbufModulePreparedFunc prepare_func,
				  GdkPixbufModuleUpdatedFunc update_func,
Havoc Pennington's avatar
Havoc Pennington committed
402 403
				  gpointer user_data,
                                  GError **error)
404 405 406 407 408 409 410
{
        LoadContext* lc;
        
        lc = g_new0(LoadContext, 1);
        
        lc->fatal_error_occurred = FALSE;

411
        lc->size_func = size_func;
412 413
        lc->prepare_func = prepare_func;
        lc->update_func = update_func;
414 415
        lc->notify_user_data = user_data;

416 417 418 419 420
        lc->first_row_seen_in_chunk = -1;
        lc->last_row_seen_in_chunk = -1;
        lc->first_pass_seen_in_chunk = -1;
        lc->last_pass_seen_in_chunk = -1;
        lc->max_row_seen_in_chunk = -1;
Havoc Pennington's avatar
Havoc Pennington committed
421
        lc->error = error;
422
        
423 424
        /* Create the main PNG context struct */

425 426 427 428 429 430 431 432 433
#ifdef PNG_USER_MEM_SUPPORTED
        lc->png_read_ptr = png_create_read_struct_2 (PNG_LIBPNG_VER_STRING,
                                                     lc, /* error/warning callback data */
                                                     png_error_callback,
                                                     png_warning_callback,
                                                     NULL,
                                                     png_malloc_callback,
                                                     png_free_callback);
#else
434 435 436 437
        lc->png_read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
                                                  lc, /* error/warning callback data */
                                                  png_error_callback,
                                                  png_warning_callback);
438
#endif
439 440
        if (lc->png_read_ptr == NULL) {
                g_free(lc);
Havoc Pennington's avatar
Havoc Pennington committed
441
                /* error callback should have set the error */
442 443
                return NULL;
        }
Havoc Pennington's avatar
Havoc Pennington committed
444
        
445 446 447 448
	if (setjmp (lc->png_read_ptr->jmpbuf)) {
		if (lc->png_info_ptr)
			png_destroy_read_struct(&lc->png_read_ptr, NULL, NULL);
                g_free(lc);
Havoc Pennington's avatar
Havoc Pennington committed
449
                /* error callback should have set the error */
450 451 452
                return NULL;
	}

453
        /* Create the auxiliary context struct */
454 455 456 457 458 459

        lc->png_info_ptr = png_create_info_struct(lc->png_read_ptr);

        if (lc->png_info_ptr == NULL) {
                png_destroy_read_struct(&lc->png_read_ptr, NULL, NULL);
                g_free(lc);
Havoc Pennington's avatar
Havoc Pennington committed
460
                /* error callback should have set the error */
461 462 463 464 465 466 467 468 469 470
                return NULL;
        }

        png_set_progressive_read_fn(lc->png_read_ptr,
                                    lc, /* callback data */
                                    png_info_callback,
                                    png_row_callback,
                                    png_end_callback);
        

Havoc Pennington's avatar
Havoc Pennington committed
471 472 473 474 475
        /* We don't want to keep modifying error after returning here,
         * it may no longer be valid.
         */
        lc->error = NULL;
        
476 477 478
        return lc;
}

479 480
static gboolean
gdk_pixbuf__png_image_stop_load (gpointer context, GError **error)
481 482 483
{
        LoadContext* lc = context;

484
        g_return_val_if_fail(lc != NULL, TRUE);
485

486 487 488 489
        /* FIXME this thing needs to report errors if
         * we have unused image data
         */
        
490
        if (lc->pixbuf)
491
                g_object_unref (lc->pixbuf);
492
        
Matthias Clasen's avatar
Matthias Clasen committed
493
        png_destroy_read_struct(&lc->png_read_ptr, &lc->png_info_ptr, NULL);
494
        g_free(lc);
495 496

        return TRUE;
497 498
}

499 500 501
static gboolean
gdk_pixbuf__png_image_load_increment(gpointer context,
                                     const guchar *buf, guint size,
Havoc Pennington's avatar
Havoc Pennington committed
502
                                     GError **error)
503 504 505 506 507
{
        LoadContext* lc = context;

        g_return_val_if_fail(lc != NULL, FALSE);

508 509 510 511 512 513
        /* reset */
        lc->first_row_seen_in_chunk = -1;
        lc->last_row_seen_in_chunk = -1;
        lc->first_pass_seen_in_chunk = -1;
        lc->last_pass_seen_in_chunk = -1;
        lc->max_row_seen_in_chunk = -1;
Havoc Pennington's avatar
Havoc Pennington committed
514
        lc->error = error;
515
        
516
        /* Invokes our callbacks as needed */
517
	if (setjmp (lc->png_read_ptr->jmpbuf)) {
Havoc Pennington's avatar
Havoc Pennington committed
518
                lc->error = NULL;
519 520
		return FALSE;
	} else {
521 522
		png_process_data(lc->png_read_ptr, lc->png_info_ptr,
                                 (guchar*) buf, size);
523
	}
524

Havoc Pennington's avatar
Havoc Pennington committed
525 526
        if (lc->fatal_error_occurred) {
                lc->error = NULL;
527
                return FALSE;
Havoc Pennington's avatar
Havoc Pennington committed
528
        } else {
529
                if (lc->first_row_seen_in_chunk >= 0 && lc->update_func) {
530 531 532 533 534 535 536
                        /* We saw at least one row */
                        gint pass_diff = lc->last_pass_seen_in_chunk - lc->first_pass_seen_in_chunk;
                        
                        g_assert(pass_diff >= 0);
                        
                        if (pass_diff == 0) {
                                /* start and end row were in the same pass */
537
                                (lc->update_func)(lc->pixbuf, 0,
538
                                                  lc->first_row_seen_in_chunk,
539
                                                  lc->pixbuf->width,
540
                                                  (lc->last_row_seen_in_chunk -
541 542
                                                   lc->first_row_seen_in_chunk) + 1,
						  lc->notify_user_data);
543 544 545 546 547 548
                        } else if (pass_diff == 1) {
                                /* We have from the first row seen to
                                   the end of the image (max row
                                   seen), then from the top of the
                                   image to the last row seen */
                                /* first row to end */
549
                                (lc->update_func)(lc->pixbuf, 0,
550
                                                  lc->first_row_seen_in_chunk,
551
                                                  lc->pixbuf->width,
552
                                                  (lc->max_row_seen_in_chunk -
553 554
                                                   lc->first_row_seen_in_chunk) + 1,
						  lc->notify_user_data);
555
                                /* top to last row */
556
                                (lc->update_func)(lc->pixbuf,
557
                                                  0, 0, 
558
                                                  lc->pixbuf->width,
559 560
                                                  lc->last_row_seen_in_chunk + 1,
						  lc->notify_user_data);
561 562 563
                        } else {
                                /* We made at least one entire pass, so update the
                                   whole image */
564
                                (lc->update_func)(lc->pixbuf,
565
                                                  0, 0, 
566
                                                  lc->pixbuf->width,
567 568
                                                  lc->max_row_seen_in_chunk + 1,
						  lc->notify_user_data);
569 570
                        }
                }
Havoc Pennington's avatar
Havoc Pennington committed
571 572

                lc->error = NULL;
573
                
574
                return TRUE;
575
        }
576 577 578 579 580 581 582 583 584
}

/* Called at the start of the progressive load, once we have image info */
static void
png_info_callback   (png_structp png_read_ptr,
                     png_infop   png_info_ptr)
{
        LoadContext* lc;
        png_uint_32 width, height;
585 586
        png_textp png_text_ptr;
        int i, num_texts;
587
        int color_type;
588 589 590 591 592 593 594
        gboolean have_alpha = FALSE;
        
        lc = png_get_progressive_ptr(png_read_ptr);

        if (lc->fatal_error_occurred)
                return;

595 596 597 598
        if (!setup_png_transformations(lc->png_read_ptr,
                                       lc->png_info_ptr,
                                       lc->error,
                                       &width, &height, &color_type)) {
599 600
                lc->fatal_error_occurred = TRUE;
                return;
601 602 603 604
        }

        /* If we have alpha, set a flag */
        if (color_type & PNG_COLOR_MASK_ALPHA)
605
                have_alpha = TRUE;
606
        
607 608 609 610 611 612 613
        if (lc->size_func) {
                gint w = width;
                gint h = height;
                (* lc->size_func) (&w, &h, lc->notify_user_data);
                
                if (w == 0 || h == 0) {
                        lc->fatal_error_occurred = TRUE;
Michael Natterer's avatar
Michael Natterer committed
614 615 616 617 618 619
                        if (lc->error && *lc->error == NULL) {
                                g_set_error (lc->error,
                                             GDK_PIXBUF_ERROR,
                                             GDK_PIXBUF_ERROR_FAILED,
                                             _("Transformed PNG has zero width or height."));
                        }
620 621 622 623 624
                        return;
                }
        }

        lc->pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, have_alpha, 8, width, height);
625 626 627 628

        if (lc->pixbuf == NULL) {
                /* Failed to allocate memory */
                lc->fatal_error_occurred = TRUE;
Havoc Pennington's avatar
Havoc Pennington committed
629 630 631 632 633 634 635
                if (lc->error && *lc->error == NULL) {
                        g_set_error (lc->error,
                                     GDK_PIXBUF_ERROR,
                                     GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
                                     _("Insufficient memory to store a %ld by %ld image; try exiting some applications to reduce memory usage"),
                                     width, height);
                }
636 637
                return;
        }
638

639
        /* Extract text chunks and attach them as pixbuf options */
640
        
641 642 643 644 645 646
        if (png_get_text (png_read_ptr, png_info_ptr, &png_text_ptr, &num_texts)) {
                for (i = 0; i < num_texts; i++) {
                        gchar *key, *value;

                        if (png_text_to_pixbuf_option (png_text_ptr[i],
                                                       &key, &value)) {
647
                                gdk_pixbuf_set_option (lc->pixbuf, key, value);
648 649 650 651 652 653
                                g_free (key);
                                g_free (value);
                        }
                }
        }

654 655
        /* Notify the client that we are ready to go */

656
        if (lc->prepare_func)
Havoc Pennington's avatar
Havoc Pennington committed
657
                (* lc->prepare_func) (lc->pixbuf, NULL, lc->notify_user_data);
658 659 660 661 662 663 664 665 666 667 668 669 670 671
        
        return;
}

/* Called for each row; note that you will get duplicate row numbers
   for interlaced PNGs */
static void
png_row_callback   (png_structp png_read_ptr,
                    png_bytep   new_row,
                    png_uint_32 row_num,
                    int pass_num)
{
        LoadContext* lc;
        guchar* old_row = NULL;
672

673 674 675 676
        lc = png_get_progressive_ptr(png_read_ptr);

        if (lc->fatal_error_occurred)
                return;
677

Matthias Clasen's avatar
Matthias Clasen committed
678
        if (row_num >= lc->pixbuf->height) {
679 680 681 682 683 684 685 686 687 688
                lc->fatal_error_occurred = TRUE;
                if (lc->error && *lc->error == NULL) {
                        g_set_error (lc->error,
                                     GDK_PIXBUF_ERROR,
                                     GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                                     _("Fatal error reading PNG image file"));
                }
                return;
        }

689 690 691 692 693 694 695 696 697
        if (lc->first_row_seen_in_chunk < 0) {
                lc->first_row_seen_in_chunk = row_num;
                lc->first_pass_seen_in_chunk = pass_num;
        }

        lc->max_row_seen_in_chunk = MAX(lc->max_row_seen_in_chunk, ((gint)row_num));
        lc->last_row_seen_in_chunk = row_num;
        lc->last_pass_seen_in_chunk = pass_num;
        
698
        old_row = lc->pixbuf->pixels + (row_num * lc->pixbuf->rowstride);
699

700 701 702 703 704 705 706
        png_progressive_combine_row(lc->png_read_ptr, old_row, new_row);
}

/* Called after reading the entire image */
static void
png_end_callback   (png_structp png_read_ptr,
                    png_infop   png_info_ptr)
707
{
708 709 710 711 712 713
        LoadContext* lc;

        lc = png_get_progressive_ptr(png_read_ptr);

        if (lc->fatal_error_occurred)
                return;
714
}
715 716 717 718 719 720 721 722 723 724

static void
png_error_callback(png_structp png_read_ptr,
                   png_const_charp error_msg)
{
        LoadContext* lc;
        
        lc = png_get_error_ptr(png_read_ptr);
        
        lc->fatal_error_occurred = TRUE;
Havoc Pennington's avatar
Havoc Pennington committed
725 726 727 728 729 730 731 732 733 734 735

        /* I don't trust libpng to call the error callback only once,
         * so check for already-set error
         */
        if (lc->error && *lc->error == NULL) {
                g_set_error (lc->error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                             _("Fatal error reading PNG image file: %s"),
                             error_msg);
        }
736 737

        longjmp (png_read_ptr->jmpbuf, 1);
738 739 740
}

static void
741 742
png_warning_callback (png_structp png_read_ptr,
                      png_const_charp warning_msg)
743 744 745 746
{
        LoadContext* lc;
        
        lc = png_get_error_ptr(png_read_ptr);
Havoc Pennington's avatar
Havoc Pennington committed
747 748 749 750 751 752 753

        /* Don't print anything; we should not be dumping junk to
         * stderr, since that may be bad for some apps. If it's
         * important enough to display, we need to add a GError
         * **warning return location wherever we have an error return
         * location.
         */
754
}
755 756


757
/* Save */
Havoc Pennington's avatar
Havoc Pennington committed
758

759 760 761 762 763 764 765 766 767 768 769 770 771
typedef struct {
        GdkPixbufSaveFunc save_func;
        gpointer user_data;
        GError **error;
} SaveToFunctionIoPtr;

static void
png_save_to_callback_write_func (png_structp png_ptr,
                                 png_bytep   data,
                                 png_size_t  length)
{
        SaveToFunctionIoPtr *ioptr = png_get_io_ptr (png_ptr);

772
        if (!ioptr->save_func ((gchar *)data, length, ioptr->error, ioptr->user_data)) {
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
                /* If save_func has already set an error, which it
                   should have done, this won't overwrite it. */
                png_error (png_ptr, "write function failed");
        }
}

static void
png_save_to_callback_flush_func (png_structp png_ptr)
{
        ;
}

static gboolean real_save_png (GdkPixbuf        *pixbuf, 
                               gchar           **keys,
                               gchar           **values,
                               GError          **error,
                               gboolean          to_callback,
                               FILE             *f,
                               GdkPixbufSaveFunc save_func,
                               gpointer          user_data)
793 794 795
{
       png_structp png_ptr;
       png_infop info_ptr;
796
       png_textp text_ptr = NULL;
797 798
       guchar *ptr;
       guchar *pixels;
799 800
       int y;
       int i;
801
       png_bytep row_ptr;
802 803 804 805
       png_color_8 sig_bit;
       int w, h, rowstride;
       int has_alpha;
       int bpc;
806
       int num_keys;
807
       int compression = -1;
808
       gboolean success = TRUE;
809
       SaveToFunctionIoPtr to_callback_ioptr;
810 811

       num_keys = 0;
812 813

       if (keys && *keys) {
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
               gchar **kiter = keys;
               gchar **viter = values;

               while (*kiter) {
                       if (strncmp (*kiter, "tEXt::", 6) == 0) {
                               gchar  *key = *kiter + 6;
                               int     len = strlen (key);
                               if (len <= 1 || len > 79) {
                                       g_set_error (error,
                                                    GDK_PIXBUF_ERROR,
                                                    GDK_PIXBUF_ERROR_BAD_OPTION,
                                                    _("Keys for PNG text chunks must have at least 1 and at most 79 characters."));
                                       return FALSE;
                               }
                               for (i = 0; i < len; i++) {
                                       if ((guchar) key[i] > 127) {
                                               g_set_error (error,
                                                            GDK_PIXBUF_ERROR,
                                                            GDK_PIXBUF_ERROR_BAD_OPTION,
                                                            _("Keys for PNG text chunks must be ASCII characters."));
                                               return FALSE;
                                       }
                               }
                               num_keys++;
                       } else if (strcmp (*kiter, "compression") == 0) {
                               char *endptr = NULL;
                               compression = strtol (*viter, &endptr, 10);
841

842 843 844 845 846 847 848 849 850 851 852 853 854
                               if (endptr == *viter) {
                                       g_set_error (error,
                                                    GDK_PIXBUF_ERROR,
                                                    GDK_PIXBUF_ERROR_BAD_OPTION,
                                                    _("PNG compression level must be a value between 0 and 9; value '%s' could not be parsed."),
                                                    *viter);
                                       return FALSE;
                               }
                               if (compression < 0 || compression > 9) {
                                       /* This is a user-visible error;
                                        * lets people skip the range-checking
                                        * in their app.
                                        */
855 856 857
                                       g_set_error (error,
                                                    GDK_PIXBUF_ERROR,
                                                    GDK_PIXBUF_ERROR_BAD_OPTION,
858 859
                                                    _("PNG compression level must be a value between 0 and 9; value '%d' is not allowed."),
                                                    compression);
860 861
                                       return FALSE;
                               }
862
                       } else {
863
                               g_warning ("Unrecognized parameter (%s) passed to PNG saver.", *kiter);
864
                       }
865 866 867

                       ++kiter;
                       ++viter;
868 869 870 871 872 873 874 875 876 877 878 879
               }
       }

       if (num_keys > 0) {
               text_ptr = g_new0 (png_text, num_keys);
               for (i = 0; i < num_keys; i++) {
                       text_ptr[i].compression = PNG_TEXT_COMPRESSION_NONE;
                       text_ptr[i].key  = keys[i] + 6;
                       text_ptr[i].text = g_convert (values[i], -1, 
                                                     "ISO-8859-1", "UTF-8", 
                                                     NULL, &text_ptr[i].text_length, 
                                                     NULL);
880 881 882 883 884 885 886 887 888 889 890 891

#ifdef PNG_iTXt_SUPPORTED 
                       if (!text_ptr[i].text) {
                               text_ptr[i].compression = PNG_ITXT_COMPRESSION_NONE;
                               text_ptr[i].text = g_strdup (values[i]);
                               text_ptr[i].text_length = 0;
                               text_ptr[i].itxt_length = strlen (text_ptr[i].text);
                               text_ptr[i].lang = NULL;
                               text_ptr[i].lang_key = NULL;
                       }
#endif

892 893 894 895
                       if (!text_ptr[i].text) {
                               g_set_error (error,
                                            GDK_PIXBUF_ERROR,
                                            GDK_PIXBUF_ERROR_BAD_OPTION,
896
                                            _("Value for PNG text chunk %s cannot be converted to ISO-8859-1 encoding."), keys[i] + 6);
897 898 899 900 901 902
                               num_keys = i;
                               for (i = 0; i < num_keys; i++)
                                       g_free (text_ptr[i].text);
                               g_free (text_ptr);
                               return FALSE;
                       }
903 904
               }
       }
905

906 907 908 909 910 911 912 913
       bpc = gdk_pixbuf_get_bits_per_sample (pixbuf);
       w = gdk_pixbuf_get_width (pixbuf);
       h = gdk_pixbuf_get_height (pixbuf);
       rowstride = gdk_pixbuf_get_rowstride (pixbuf);
       has_alpha = gdk_pixbuf_get_has_alpha (pixbuf);
       pixels = gdk_pixbuf_get_pixels (pixbuf);

       png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING,
Havoc Pennington's avatar
Havoc Pennington committed
914 915 916
                                          error,
                                          png_simple_error_callback,
                                          png_simple_warning_callback);
Matthias Clasen's avatar
Matthias Clasen committed
917 918 919 920
       if (png_ptr == NULL) {
	       success = FALSE;
	       goto cleanup;
       }
921 922 923

       info_ptr = png_create_info_struct (png_ptr);
       if (info_ptr == NULL) {
924 925
	       success = FALSE;
	       goto cleanup;
926 927
       }
       if (setjmp (png_ptr->jmpbuf)) {
928 929
	       success = FALSE;
	       goto cleanup;
930
       }
931 932 933 934 935

       if (num_keys > 0) {
               png_set_text (png_ptr, info_ptr, text_ptr, num_keys);
       }

936 937 938 939 940 941 942 943 944 945
       if (to_callback) {
               to_callback_ioptr.save_func = save_func;
               to_callback_ioptr.user_data = user_data;
               to_callback_ioptr.error = error;
               png_set_write_fn (png_ptr, &to_callback_ioptr,
                                 png_save_to_callback_write_func,
                                 png_save_to_callback_flush_func);
       } else {
               png_init_io (png_ptr, f);
       }
946

947 948 949
       if (compression >= 0)
               png_set_compression_level (png_ptr, compression);

950 951
       if (has_alpha) {
               png_set_IHDR (png_ptr, info_ptr, w, h, bpc,
Havoc Pennington's avatar
Havoc Pennington committed
952 953
                             PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
                             PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
954 955
       } else {
               png_set_IHDR (png_ptr, info_ptr, w, h, bpc,
Havoc Pennington's avatar
Havoc Pennington committed
956 957
                             PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
                             PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
958 959 960 961 962 963 964 965 966 967 968 969
       }
       sig_bit.red = bpc;
       sig_bit.green = bpc;
       sig_bit.blue = bpc;
       sig_bit.alpha = bpc;
       png_set_sBIT (png_ptr, info_ptr, &sig_bit);
       png_write_info (png_ptr, info_ptr);
       png_set_shift (png_ptr, &sig_bit);
       png_set_packing (png_ptr);

       ptr = pixels;
       for (y = 0; y < h; y++) {
970
               row_ptr = (png_bytep)ptr;
971 972 973 974 975
               png_write_rows (png_ptr, &row_ptr, 1);
               ptr += rowstride;
       }

       png_write_end (png_ptr, info_ptr);
976 977

cleanup:
978
       png_destroy_write_struct (&png_ptr, &info_ptr);
979

980 981 982 983 984 985
       if (num_keys > 0) {
               for (i = 0; i < num_keys; i++)
                       g_free (text_ptr[i].text);
               g_free (text_ptr);
       }

986
       return success;
987 988
}

989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
static gboolean
gdk_pixbuf__png_image_save (FILE          *f, 
                            GdkPixbuf     *pixbuf, 
                            gchar        **keys,
                            gchar        **values,
                            GError       **error)
{
        return real_save_png (pixbuf, keys, values, error,
                              FALSE, f, NULL, NULL);
}

static gboolean
gdk_pixbuf__png_image_save_to_callback (GdkPixbufSaveFunc   save_func,
                                        gpointer            user_data,
                                        GdkPixbuf          *pixbuf, 
                                        gchar             **keys,
                                        gchar             **values,
                                        GError            **error)
{
        return real_save_png (pixbuf, keys, values, error,
                              TRUE, NULL, save_func, user_data);
}

1012 1013 1014 1015 1016 1017
#ifndef INCLUDE_png
#define MODULE_ENTRY(type,function) function
#else
#define MODULE_ENTRY(type,function) _gdk_pixbuf__ ## type ## _ ## function
#endif

1018 1019 1020 1021 1022 1023 1024 1025
void
MODULE_ENTRY (png, fill_vtable) (GdkPixbufModule *module)
{
        module->load = gdk_pixbuf__png_image_load;
        module->begin_load = gdk_pixbuf__png_image_begin_load;
        module->stop_load = gdk_pixbuf__png_image_stop_load;
        module->load_increment = gdk_pixbuf__png_image_load_increment;
        module->save = gdk_pixbuf__png_image_save;
1026
        module->save_to_callback = gdk_pixbuf__png_image_save_to_callback;
1027
}
1028

1029
void
1030
MODULE_ENTRY (png, fill_info) (GdkPixbufFormat *info)
1031
{
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
        static GdkPixbufModulePattern signature[] = {
                { "\x89PNG\r\n\x1a\x0a", NULL, 100 },
                { NULL, NULL, 0 }
        };
	static gchar * mime_types[] = {
		"image/png",
		NULL
	};
	static gchar * extensions[] = {
		"png",
		NULL
	};

	info->name = "png";
        info->signature = signature;
	info->description = N_("The PNG image format");
	info->mime_types = mime_types;
	info->extensions = extensions;
1050
	info->flags = GDK_PIXBUF_FORMAT_WRITABLE | GDK_PIXBUF_FORMAT_THREADSAFE;
1051
	info->license = "LGPL";
1052
}