io-png.c 29.2 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 36 37 38 39 40 41 42
static void
setup_png_transformations(png_structp png_read_ptr, png_infop png_info_ptr,
                          gboolean *fatal_error_occurred,
                          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;
43
#ifndef G_DISABLE_CHECKS
44
        int channels;
45
#endif
46 47 48 49 50 51 52 53 54 55 56 57 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 132 133 134 135 136 137 138 139 140 141 142 143 144 145
        
        /* Get the image info */

        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;
        
#ifndef G_DISABLE_CHECKS
        /* Check that the new info is what we want */
        
        if (bit_depth != 8) {
                g_warning("Bits per channel of transformed PNG is %d, not 8.", bit_depth);
                *fatal_error_occurred = TRUE;
                return;
        }

        if ( ! (color_type == PNG_COLOR_TYPE_RGB ||
                color_type == PNG_COLOR_TYPE_RGB_ALPHA) ) {
                g_warning("Transformed PNG not RGB or RGBA.");
                *fatal_error_occurred = TRUE;
                return;
        }

        channels = png_get_channels(png_read_ptr, png_info_ptr);
        if ( ! (channels == 3 || channels == 4) ) {
                g_warning("Transformed PNG has %d channels, must be 3 or 4.", channels);
                *fatal_error_occurred = TRUE;
                return;
        }
#endif
}

Havoc Pennington's avatar
Havoc Pennington committed
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
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,
161
                             _("Fatal error in PNG image file: %s"),
Havoc Pennington's avatar
Havoc Pennington committed
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
                             error_msg);
        }
}

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.
         */
}

178
/* Destroy notification function for the pixbuf */
179
static void
180
free_buffer (guchar *pixels, gpointer data)
181
{
182
	g_free (pixels);
183
}
184

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
static gboolean
png_text_to_pixbuf_option (png_text   text_ptr,
                           gchar    **key,
                           gchar    **value)
{
        *value = g_convert (text_ptr.text, -1, 
                            "UTF-8", "ISO-8859-1", 
                            NULL, NULL, NULL);
        if (*value) {
                *key = g_strconcat ("tEXt::", text_ptr.key, NULL);
                return TRUE;
        } else {
                g_warning ("Couldn't convert tEXt chunk value to UTF-8.");
                *key = NULL;
                return FALSE;
        }
}

203
/* Shared library entry point */
204
static GdkPixbuf *
Havoc Pennington's avatar
Havoc Pennington committed
205
gdk_pixbuf__png_image_load (FILE *f, GError **error)
206
{
207
        GdkPixbuf *pixbuf;
208 209
	png_structp png_ptr;
	png_infop info_ptr, end_info;
210
        png_textp text_ptr;
211
        gboolean failed = FALSE;
212
	gint i, ctype, bpp;
213
	png_uint_32 w, h;
214
	png_bytepp rows;
215
	guchar *pixels;
216 217
        gint    num_texts;
        gchar **options = NULL;
218

Havoc Pennington's avatar
Havoc Pennington committed
219 220 221 222
	png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
                                          error,
                                          png_simple_error_callback,
                                          png_simple_warning_callback);
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
	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;
	}

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

	if (setjmp (png_ptr->jmpbuf)) {
		png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
		return NULL;
	}

243
	png_init_io (png_ptr, f);
244
	png_read_info (png_ptr, info_ptr);
245

246
        setup_png_transformations(png_ptr, info_ptr, &failed, &w, &h, &ctype);
247

248 249 250 251 252
        if (failed) {
                png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
                return NULL;
        }
        
253 254 255 256 257
	if (ctype & PNG_COLOR_MASK_ALPHA)
		bpp = 4;
	else
		bpp = 3;

258
	pixels = g_try_malloc (w * h * bpp);
259
	if (!pixels) {
Havoc Pennington's avatar
Havoc Pennington committed
260 261 262 263 264 265 266 267 268 269
                /* Check error NULL, normally this would be broken,
                 * but libpng makes me want to code defensively.
                 */
                if (error && *error == NULL) {
                        g_set_error (error,
                                     GDK_PIXBUF_ERROR,
                                     GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
                                     _("Insufficient memory to load PNG file"));
                }
                
270 271 272
		png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
		return NULL;
	}
273

274
	rows = g_new (png_bytep, h);
275

276 277
	for (i = 0; i < h; i++)
		rows[i] = pixels + i * w * bpp;
278

279
	png_read_image (png_ptr, rows);
280 281 282 283 284 285 286 287 288

        if (png_get_text (png_ptr, info_ptr, &text_ptr, &num_texts)) {
                options = g_new (gchar *, num_texts * 2);
                for (i = 0; i < num_texts; i++) {
                        png_text_to_pixbuf_option (text_ptr[i], 
                                                   options + 2*i, 
                                                   options + 2*i + 1);
                }
        }
289
	png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
290
	g_free (rows);
291

292
	if (ctype & PNG_COLOR_MASK_ALPHA)
293 294 295
		pixbuf = gdk_pixbuf_new_from_data (pixels, GDK_COLORSPACE_RGB, TRUE, 8,
                                                   w, h, w * 4,
                                                   free_buffer, NULL);
296
	else
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
		pixbuf = gdk_pixbuf_new_from_data (pixels, GDK_COLORSPACE_RGB, FALSE, 8,
                                                   w, h, w * 3,
                                                   free_buffer, NULL);

        if (options) {
                for (i = 0; i < num_texts; i++) {
                        if (pixbuf) {
                                if (!gdk_pixbuf_set_option (pixbuf, 
                                                            options[2*i], 
                                                            options[2*i+1]))
                                        g_warning ("Got multiple tEXt chunks for the same key.");
                        }
                        g_free (options[2*i]);
                        g_free (options[2*i+1]);
                }
                g_free (options);
        }

        return pixbuf;
316
}
317

318 319
/* I wish these avoided the setjmp()/longjmp() crap in libpng instead
   just allow you to change the error reporting. */
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
static void png_error_callback  (png_structp png_read_ptr,
                                 png_const_charp error_msg);

static void png_warning_callback(png_structp png_read_ptr,
                                 png_const_charp warning_msg);

/* 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;

347 348
        ModulePreparedNotifyFunc prepare_func;
        ModuleUpdatedNotifyFunc update_func;
349 350 351
        gpointer notify_user_data;

        GdkPixbuf* pixbuf;
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367

        /* 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;
368 369 370
        
        guint fatal_error_occurred : 1;

Havoc Pennington's avatar
Havoc Pennington committed
371
        GError **error;
372 373
};

374
static gpointer
Federico Mena Quintero's avatar
Federico Mena Quintero committed
375 376
gdk_pixbuf__png_image_begin_load (ModulePreparedNotifyFunc prepare_func,
				  ModuleUpdatedNotifyFunc update_func,
Havoc Pennington's avatar
Havoc Pennington committed
377 378
				  gpointer user_data,
                                  GError **error)
379 380 381 382 383 384 385
{
        LoadContext* lc;
        
        lc = g_new0(LoadContext, 1);
        
        lc->fatal_error_occurred = FALSE;

386 387
        lc->prepare_func = prepare_func;
        lc->update_func = update_func;
388 389
        lc->notify_user_data = user_data;

390 391 392 393 394
        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
395
        lc->error = error;
396
        
397 398
        /* Create the main PNG context struct */

399
		
400 401 402 403 404 405 406
        lc->png_read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
                                                  lc, /* error/warning callback data */
                                                  png_error_callback,
                                                  png_warning_callback);

        if (lc->png_read_ptr == NULL) {
                g_free(lc);
Havoc Pennington's avatar
Havoc Pennington committed
407
                /* error callback should have set the error */
408 409
                return NULL;
        }
Havoc Pennington's avatar
Havoc Pennington committed
410
        
411 412 413 414
	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
415
                /* error callback should have set the error */
416 417 418
                return NULL;
	}

419
        /* Create the auxiliary context struct */
420 421 422 423 424 425

        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
426
                /* error callback should have set the error */
427 428 429 430 431 432 433 434 435 436
                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
437 438 439 440 441
        /* We don't want to keep modifying error after returning here,
         * it may no longer be valid.
         */
        lc->error = NULL;
        
442 443 444
        return lc;
}

445 446
static gboolean
gdk_pixbuf__png_image_stop_load (gpointer context, GError **error)
447 448 449
{
        LoadContext* lc = context;

450
        g_return_val_if_fail(lc != NULL, TRUE);
451

452 453 454 455
        /* FIXME this thing needs to report errors if
         * we have unused image data
         */
        
456 457
        if (lc->pixbuf)
                gdk_pixbuf_unref (lc->pixbuf);
458 459 460
        
        png_destroy_read_struct(&lc->png_read_ptr, NULL, NULL);
        g_free(lc);
461 462

        return TRUE;
463 464
}

465 466 467
static gboolean
gdk_pixbuf__png_image_load_increment(gpointer context,
                                     const guchar *buf, guint size,
Havoc Pennington's avatar
Havoc Pennington committed
468
                                     GError **error)
469 470 471 472 473
{
        LoadContext* lc = context;

        g_return_val_if_fail(lc != NULL, FALSE);

474 475 476 477 478 479
        /* 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
480
        lc->error = error;
481
        
482
        /* Invokes our callbacks as needed */
483
	if (setjmp (lc->png_read_ptr->jmpbuf)) {
Havoc Pennington's avatar
Havoc Pennington committed
484
                lc->error = NULL;
485 486
		return FALSE;
	} else {
487 488
		png_process_data(lc->png_read_ptr, lc->png_info_ptr,
                                 (guchar*) buf, size);
489
	}
490

Havoc Pennington's avatar
Havoc Pennington committed
491 492
        if (lc->fatal_error_occurred) {
                lc->error = NULL;
493
                return FALSE;
Havoc Pennington's avatar
Havoc Pennington committed
494
        } else {
495 496 497 498 499 500 501 502
                if (lc->first_row_seen_in_chunk >= 0) {
                        /* 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 */
503
                                (lc->update_func)(lc->pixbuf, 0,
504
                                                  lc->first_row_seen_in_chunk,
505
                                                  lc->pixbuf->width,
506
                                                  (lc->last_row_seen_in_chunk -
507 508
                                                   lc->first_row_seen_in_chunk) + 1,
						  lc->notify_user_data);
509 510 511 512 513 514
                        } 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 */
515
                                (lc->update_func)(lc->pixbuf, 0,
516
                                                  lc->first_row_seen_in_chunk,
517
                                                  lc->pixbuf->width,
518
                                                  (lc->max_row_seen_in_chunk -
519 520
                                                   lc->first_row_seen_in_chunk) + 1,
						  lc->notify_user_data);
521
                                /* top to last row */
522
                                (lc->update_func)(lc->pixbuf,
523
                                                  0, 0, 
524
                                                  lc->pixbuf->width,
525 526
                                                  lc->last_row_seen_in_chunk + 1,
						  lc->notify_user_data);
527 528 529
                        } else {
                                /* We made at least one entire pass, so update the
                                   whole image */
530
                                (lc->update_func)(lc->pixbuf,
531
                                                  0, 0, 
532
                                                  lc->pixbuf->width,
533 534
                                                  lc->max_row_seen_in_chunk + 1,
						  lc->notify_user_data);
535 536
                        }
                }
Havoc Pennington's avatar
Havoc Pennington committed
537 538

                lc->error = NULL;
539
                
540
                return TRUE;
541
        }
542 543 544 545 546 547 548 549 550
}

/* 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;
551 552
        png_textp png_text_ptr;
        int i, num_texts;
553
        int color_type;
554
        gboolean have_alpha = FALSE;
555
        gboolean failed = FALSE;
556 557 558 559 560 561
        
        lc = png_get_progressive_ptr(png_read_ptr);

        if (lc->fatal_error_occurred)
                return;

562 563 564 565
        setup_png_transformations(lc->png_read_ptr,
                                  lc->png_info_ptr,
                                  &failed,
                                  &width, &height, &color_type);
566

567 568 569
        if (failed) {
                lc->fatal_error_occurred = TRUE;
                return;
570 571 572 573
        }

        /* If we have alpha, set a flag */
        if (color_type & PNG_COLOR_MASK_ALPHA)
574
                have_alpha = TRUE;
575
        
576
        lc->pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, have_alpha, 8, width, height);
577 578 579 580

        if (lc->pixbuf == NULL) {
                /* Failed to allocate memory */
                lc->fatal_error_occurred = TRUE;
Havoc Pennington's avatar
Havoc Pennington committed
581 582 583 584 585 586 587
                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);
                }
588 589
                return;
        }
590 591

        /* Extract tEXt chunks and attach them as pixbuf options */
592
        
593 594 595 596 597 598 599 600 601 602 603 604 605
        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)) {
                                gdk_pixbuf_set_option (lc->pixbuf, key, value);
                                g_free (key);
                                g_free (value);
                        }
                }
        }

606 607
        /* Notify the client that we are ready to go */

608
        if (lc->prepare_func)
Havoc Pennington's avatar
Havoc Pennington committed
609
                (* lc->prepare_func) (lc->pixbuf, NULL, lc->notify_user_data);
610 611 612 613 614 615 616 617 618 619 620 621 622 623
        
        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;
624

625 626 627 628
        lc = png_get_progressive_ptr(png_read_ptr);

        if (lc->fatal_error_occurred)
                return;
629

630 631 632 633 634 635 636 637 638 639 640
        if (row_num < 0 || row_num >= lc->pixbuf->height) {
                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;
        }

641 642 643 644 645 646 647 648 649
        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;
        
650
        old_row = lc->pixbuf->pixels + (row_num * lc->pixbuf->rowstride);
651

652 653 654 655 656 657 658
        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)
659
{
660 661 662 663 664 665
        LoadContext* lc;

        lc = png_get_progressive_ptr(png_read_ptr);

        if (lc->fatal_error_occurred)
                return;
666
}
667 668 669 670 671 672 673 674 675 676

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
677 678 679 680 681 682 683 684 685 686 687

        /* 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);
        }
688 689

        longjmp (png_read_ptr->jmpbuf, 1);
690 691 692 693 694 695 696 697 698
}

static void
png_warning_callback(png_structp png_read_ptr,
                     png_const_charp warning_msg)
{
        LoadContext* lc;
        
        lc = png_get_error_ptr(png_read_ptr);
Havoc Pennington's avatar
Havoc Pennington committed
699 700 701 702 703 704 705

        /* 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.
         */
706
}
707 708


709
/* Save */
Havoc Pennington's avatar
Havoc Pennington committed
710

711
static gboolean
712 713 714 715 716 717 718 719
gdk_pixbuf__png_image_save (FILE          *f, 
                            GdkPixbuf     *pixbuf, 
                            gchar        **keys,
                            gchar        **values,
                            GError       **error)
{
       png_structp png_ptr;
       png_infop info_ptr;
720
       png_textp text_ptr = NULL;
721 722
       guchar *ptr;
       guchar *pixels;
723 724
       int y;
       int i;
725
       png_bytep row_ptr;
726 727 728 729
       png_color_8 sig_bit;
       int w, h, rowstride;
       int has_alpha;
       int bpc;
730 731 732
       int num_keys;

       num_keys = 0;
733 734

       if (keys && *keys) {
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
               gchar **kiter;
               gchar  *key;
               int     len;

               for (kiter = keys; *kiter; kiter++) {
                       if (strncmp (*kiter, "tEXt::", 6) != 0) {
                                g_warning ("Bad option name '%s' passed to PNG saver", *kiter);
                                return FALSE;
                       }
                       key = *kiter + 6;
                       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++;
               }
       }

       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);
                       if (!text_ptr[i].text) {
                               g_set_error (error,
                                            GDK_PIXBUF_ERROR,
                                            GDK_PIXBUF_ERROR_BAD_OPTION,
                                            _("Value for PNG tEXt chunk can not be converted to ISO-8859-1 encoding."));
                               num_keys = i;
                               for (i = 0; i < num_keys; i++)
                                       g_free (text_ptr[i].text);
                               g_free (text_ptr);
                               return FALSE;
                       }
786 787
               }
       }
788

789 790 791 792 793 794 795 796
       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
797 798 799
                                          error,
                                          png_simple_error_callback,
                                          png_simple_warning_callback);
800 801 802 803 804 805 806 807 808 809 810 811

       g_return_val_if_fail (png_ptr != NULL, FALSE);

       info_ptr = png_create_info_struct (png_ptr);
       if (info_ptr == NULL) {
               png_destroy_write_struct (&png_ptr, (png_infopp) NULL);
               return FALSE;
       }
       if (setjmp (png_ptr->jmpbuf)) {
               png_destroy_write_struct (&png_ptr, (png_infopp) NULL);
               return FALSE;
       }
812 813 814 815 816

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

817
       png_init_io (png_ptr, f);
818

819 820
       if (has_alpha) {
               png_set_IHDR (png_ptr, info_ptr, w, h, bpc,
Havoc Pennington's avatar
Havoc Pennington committed
821 822
                             PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
                             PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
823 824
       } else {
               png_set_IHDR (png_ptr, info_ptr, w, h, bpc,
Havoc Pennington's avatar
Havoc Pennington committed
825 826
                             PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
                             PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
827 828 829 830 831 832 833 834 835 836 837 838
       }
       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++) {
839
               row_ptr = (png_bytep)ptr;
840 841 842 843 844 845 846
               png_write_rows (png_ptr, &row_ptr, 1);
               ptr += rowstride;
       }

       png_write_end (png_ptr, info_ptr);
       png_destroy_write_struct (&png_ptr, (png_infopp) NULL);

847 848 849 850 851 852
       if (num_keys > 0) {
               for (i = 0; i < num_keys; i++)
                       g_free (text_ptr[i].text);
               g_free (text_ptr);
       }

853 854 855
       return TRUE;
}

856 857


858 859 860 861 862 863 864 865 866
void
gdk_pixbuf__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;
}