]> Pileus Git - ~andy/gtk/blob - gdk-pixbuf/io-png.c
Support for separately installed loaders. (#77486)
[~andy/gtk] / gdk-pixbuf / io-png.c
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  * Copyright (C) 1999 The Free Software Foundation
6  *
7  * Authors: Mark Crichton <crichton@gimp.org>
8  *          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  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * 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  * License along with this library; if not, write to the
22  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23  * Boston, MA 02111-1307, USA.
24  */
25
26 #include <config.h>
27 #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 \f
34
35 static gboolean
36 setup_png_transformations(png_structp png_read_ptr, png_infop png_info_ptr,
37                           GError **error,
38                           png_uint_32* width_p, png_uint_32* height_p,
39                           int* color_type_p)
40 {
41         png_uint_32 width, height;
42         int bit_depth, color_type, interlace_type, compression_type, filter_type;
43         int channels;
44         
45         /* Get the image info */
46
47         /* Must check bit depth, since png_get_IHDR generates an 
48            FPE on bit_depth 0.
49         */
50         bit_depth = png_get_bit_depth (png_read_ptr, png_info_ptr);
51         if (bit_depth < 1 || bit_depth > 16) {
52                 g_set_error (error,
53                              GDK_PIXBUF_ERROR,
54                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
55                              _("Bits per channel of PNG image is invalid."));
56                 return FALSE;
57         }
58         png_get_IHDR (png_read_ptr, png_info_ptr,
59                       &width, &height,
60                       &bit_depth,
61                       &color_type,
62                       &interlace_type,
63                       &compression_type,
64                       &filter_type);
65
66         /* set_expand() basically needs to be called unless
67            we are already in RGB/RGBA mode
68         */
69         if (color_type == PNG_COLOR_TYPE_PALETTE &&
70             bit_depth <= 8) {
71
72                 /* Convert indexed images to RGB */
73                 png_set_expand (png_read_ptr);
74
75         } else if (color_type == PNG_COLOR_TYPE_GRAY &&
76                    bit_depth < 8) {
77
78                 /* Convert grayscale to RGB */
79                 png_set_expand (png_read_ptr);
80
81         } else if (png_get_valid (png_read_ptr, 
82                                   png_info_ptr, PNG_INFO_tRNS)) {
83
84                 /* If we have transparency header, convert it to alpha
85                    channel */
86                 png_set_expand(png_read_ptr);
87                 
88         } else if (bit_depth < 8) {
89
90                 /* If we have < 8 scale it up to 8 */
91                 png_set_expand(png_read_ptr);
92
93
94                 /* Conceivably, png_set_packing() is a better idea;
95                  * God only knows how libpng works
96                  */
97         }
98
99         /* If we are 16-bit, convert to 8-bit */
100         if (bit_depth == 16) {
101                 png_set_strip_16(png_read_ptr);
102         }
103
104         /* If gray scale, convert to RGB */
105         if (color_type == PNG_COLOR_TYPE_GRAY ||
106             color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
107                 png_set_gray_to_rgb(png_read_ptr);
108         }
109         
110         /* If interlaced, handle that */
111         if (interlace_type != PNG_INTERLACE_NONE) {
112                 png_set_interlace_handling(png_read_ptr);
113         }
114         
115         /* Update the info the reflect our transformations */
116         png_read_update_info(png_read_ptr, png_info_ptr);
117         
118         png_get_IHDR (png_read_ptr, png_info_ptr,
119                       &width, &height,
120                       &bit_depth,
121                       &color_type,
122                       &interlace_type,
123                       &compression_type,
124                       &filter_type);
125
126         *width_p = width;
127         *height_p = height;
128         *color_type_p = color_type;
129         
130         /* Check that the new info is what we want */
131         
132         if (width == 0 || height == 0) {
133                 g_set_error (error,
134                              GDK_PIXBUF_ERROR,
135                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
136                              _("Transformed PNG has zero width or height."));
137                 return FALSE;
138         }
139
140         if (bit_depth != 8) {
141                 g_set_error (error,
142                              GDK_PIXBUF_ERROR,
143                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
144                              _("Bits per channel of transformed PNG is not 8."));
145                 return FALSE;
146         }
147
148         if ( ! (color_type == PNG_COLOR_TYPE_RGB ||
149                 color_type == PNG_COLOR_TYPE_RGB_ALPHA) ) {
150                 g_set_error (error,
151                              GDK_PIXBUF_ERROR,
152                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
153                              _("Transformed PNG not RGB or RGBA."));
154                 return FALSE;
155         }
156
157         channels = png_get_channels(png_read_ptr, png_info_ptr);
158         if ( ! (channels == 3 || channels == 4) ) {
159                 g_set_error (error,
160                              GDK_PIXBUF_ERROR,
161                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
162                              _("Transformed PNG has unsupported number of channels, must be 3 or 4."));
163                 return FALSE;
164         }
165         return TRUE;
166 }
167
168 static void
169 png_simple_error_callback(png_structp png_save_ptr,
170                           png_const_charp error_msg)
171 {
172         GError **error;
173         
174         error = png_get_error_ptr(png_save_ptr);
175
176         /* I don't trust libpng to call the error callback only once,
177          * so check for already-set error
178          */
179         if (error && *error == NULL) {
180                 g_set_error (error,
181                              GDK_PIXBUF_ERROR,
182                              GDK_PIXBUF_ERROR_FAILED,
183                              _("Fatal error in PNG image file: %s"),
184                              error_msg);
185         }
186
187         longjmp (png_save_ptr->jmpbuf, 1);
188 }
189
190 static void
191 png_simple_warning_callback(png_structp png_save_ptr,
192                             png_const_charp warning_msg)
193 {
194         /* Don't print anything; we should not be dumping junk to
195          * stderr, since that may be bad for some apps. If it's
196          * important enough to display, we need to add a GError
197          * **warning return location wherever we have an error return
198          * location.
199          */
200 }
201
202 static gboolean
203 png_text_to_pixbuf_option (png_text   text_ptr,
204                            gchar    **key,
205                            gchar    **value)
206 {
207         if (text_ptr.text_length > 0) {
208                 *value = g_convert (text_ptr.text, -1, 
209                                     "UTF-8", "ISO-8859-1", 
210                                     NULL, NULL, NULL);
211         }
212         else {
213                 *value = g_strdup (text_ptr.text);
214         }
215         if (*value) {
216                 *key = g_strconcat ("tEXt::", text_ptr.key, NULL);
217                 return TRUE;
218         } else {
219                 g_warning ("Couldn't convert text chunk value to UTF-8.");
220                 *key = NULL;
221                 return FALSE;
222         }
223 }
224
225 static png_voidp
226 png_malloc_callback (png_structp o, png_size_t size)
227 {
228         return g_try_malloc (size);
229 }
230
231 static void
232 png_free_callback (png_structp o, png_voidp x)
233 {
234         g_free (x);
235 }
236
237 /* Shared library entry point */
238 static GdkPixbuf *
239 gdk_pixbuf__png_image_load (FILE *f, GError **error)
240 {
241         GdkPixbuf * volatile pixbuf = NULL;
242         png_structp png_ptr;
243         png_infop info_ptr;
244         png_textp text_ptr;
245         gint i, ctype;
246         png_uint_32 w, h;
247         png_bytepp volatile rows = NULL;
248         gint    num_texts;
249         gchar *key;
250         gchar *value;
251
252 #ifdef PNG_USER_MEM_SUPPORTED
253         png_ptr = png_create_read_struct_2 (PNG_LIBPNG_VER_STRING,
254                                             error,
255                                             png_simple_error_callback,
256                                             png_simple_warning_callback,
257                                             NULL, 
258                                             png_malloc_callback, 
259                                             png_free_callback);
260 #else
261         png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
262                                           error,
263                                           png_simple_error_callback,
264                                           png_simple_warning_callback);
265 #endif
266         if (!png_ptr)
267                 return NULL;
268
269         info_ptr = png_create_info_struct (png_ptr);
270         if (!info_ptr) {
271                 png_destroy_read_struct (&png_ptr, NULL, NULL);
272                 return NULL;
273         }
274
275         if (setjmp (png_ptr->jmpbuf)) {
276                 if (rows)
277                         g_free (rows);
278
279                 if (pixbuf)
280                         g_object_unref (pixbuf);
281
282                 png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
283                 return NULL;
284         }
285
286         png_init_io (png_ptr, f);
287         png_read_info (png_ptr, info_ptr);
288
289         if (!setup_png_transformations(png_ptr, info_ptr, error, &w, &h, &ctype)) {
290                 png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
291                 return NULL;
292         }
293         
294         pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, ctype & PNG_COLOR_MASK_ALPHA, 8, w, h);
295
296         if (!pixbuf) {
297                 if (error && *error == NULL) {
298                         g_set_error (error,
299                                      GDK_PIXBUF_ERROR,
300                                      GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
301                                      _("Insufficient memory to load PNG file"));
302                 }
303                 
304
305                 png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
306                 return NULL;
307         }
308
309         rows = g_new (png_bytep, h);
310
311         for (i = 0; i < h; i++)
312                 rows[i] = pixbuf->pixels + i * pixbuf->rowstride;
313
314         png_read_image (png_ptr, rows);
315         png_read_end (png_ptr, info_ptr);
316
317         if (png_get_text (png_ptr, info_ptr, &text_ptr, &num_texts)) {
318                 for (i = 0; i < num_texts; i++) {
319                         png_text_to_pixbuf_option (text_ptr[i], &key, &value);
320                         gdk_pixbuf_set_option (pixbuf, key, value);
321                         g_free (key);
322                         g_free (value);
323                 }
324         }
325
326         g_free (rows);
327         png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
328
329         return pixbuf;
330 }
331
332 /* I wish these avoided the setjmp()/longjmp() crap in libpng instead
333    just allow you to change the error reporting. */
334 static void png_error_callback  (png_structp png_read_ptr,
335                                  png_const_charp error_msg);
336
337 static void png_warning_callback(png_structp png_read_ptr,
338                                  png_const_charp warning_msg);
339
340 /* Called at the start of the progressive load */
341 static void png_info_callback   (png_structp png_read_ptr,
342                                  png_infop   png_info_ptr);
343
344 /* Called for each row; note that you will get duplicate row numbers
345    for interlaced PNGs */
346 static void png_row_callback   (png_structp png_read_ptr,
347                                 png_bytep   new_row,
348                                 png_uint_32 row_num,
349                                 int pass_num);
350
351 /* Called after reading the entire image */
352 static void png_end_callback   (png_structp png_read_ptr,
353                                 png_infop   png_info_ptr);
354
355 typedef struct _LoadContext LoadContext;
356
357 struct _LoadContext {
358         png_structp png_read_ptr;
359         png_infop   png_info_ptr;
360
361         GdkPixbufModulePreparedFunc prepare_func;
362         GdkPixbufModuleUpdatedFunc update_func;
363         gpointer notify_user_data;
364
365         GdkPixbuf* pixbuf;
366
367         /* row number of first row seen, or -1 if none yet seen */
368
369         gint first_row_seen_in_chunk;
370
371         /* pass number for the first row seen */
372
373         gint first_pass_seen_in_chunk;
374         
375         /* row number of last row seen */
376         gint last_row_seen_in_chunk;
377
378         gint last_pass_seen_in_chunk;
379
380         /* highest row number seen */
381         gint max_row_seen_in_chunk;
382         
383         guint fatal_error_occurred : 1;
384
385         GError **error;
386 };
387
388 static gpointer
389 gdk_pixbuf__png_image_begin_load (GdkPixbufModuleSizeFunc size_func,
390                                   GdkPixbufModulePreparedFunc prepare_func,
391                                   GdkPixbufModuleUpdatedFunc update_func,
392                                   gpointer user_data,
393                                   GError **error)
394 {
395         LoadContext* lc;
396         
397         lc = g_new0(LoadContext, 1);
398         
399         lc->fatal_error_occurred = FALSE;
400
401         lc->prepare_func = prepare_func;
402         lc->update_func = update_func;
403         lc->notify_user_data = user_data;
404
405         lc->first_row_seen_in_chunk = -1;
406         lc->last_row_seen_in_chunk = -1;
407         lc->first_pass_seen_in_chunk = -1;
408         lc->last_pass_seen_in_chunk = -1;
409         lc->max_row_seen_in_chunk = -1;
410         lc->error = error;
411         
412         /* Create the main PNG context struct */
413
414 #ifdef PNG_USER_MEM_SUPPORTED
415         lc->png_read_ptr = png_create_read_struct_2 (PNG_LIBPNG_VER_STRING,
416                                                      lc, /* error/warning callback data */
417                                                      png_error_callback,
418                                                      png_warning_callback,
419                                                      NULL,
420                                                      png_malloc_callback,
421                                                      png_free_callback);
422 #else
423         lc->png_read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
424                                                   lc, /* error/warning callback data */
425                                                   png_error_callback,
426                                                   png_warning_callback);
427 #endif
428         if (lc->png_read_ptr == NULL) {
429                 g_free(lc);
430                 /* error callback should have set the error */
431                 return NULL;
432         }
433         
434         if (setjmp (lc->png_read_ptr->jmpbuf)) {
435                 if (lc->png_info_ptr)
436                         png_destroy_read_struct(&lc->png_read_ptr, NULL, NULL);
437                 g_free(lc);
438                 /* error callback should have set the error */
439                 return NULL;
440         }
441
442         /* Create the auxiliary context struct */
443
444         lc->png_info_ptr = png_create_info_struct(lc->png_read_ptr);
445
446         if (lc->png_info_ptr == NULL) {
447                 png_destroy_read_struct(&lc->png_read_ptr, NULL, NULL);
448                 g_free(lc);
449                 /* error callback should have set the error */
450                 return NULL;
451         }
452
453         png_set_progressive_read_fn(lc->png_read_ptr,
454                                     lc, /* callback data */
455                                     png_info_callback,
456                                     png_row_callback,
457                                     png_end_callback);
458         
459
460         /* We don't want to keep modifying error after returning here,
461          * it may no longer be valid.
462          */
463         lc->error = NULL;
464         
465         return lc;
466 }
467
468 static gboolean
469 gdk_pixbuf__png_image_stop_load (gpointer context, GError **error)
470 {
471         LoadContext* lc = context;
472
473         g_return_val_if_fail(lc != NULL, TRUE);
474
475         /* FIXME this thing needs to report errors if
476          * we have unused image data
477          */
478         
479         if (lc->pixbuf)
480                 g_object_unref (lc->pixbuf);
481         
482         png_destroy_read_struct(&lc->png_read_ptr, &lc->png_info_ptr, NULL);
483         g_free(lc);
484
485         return TRUE;
486 }
487
488 static gboolean
489 gdk_pixbuf__png_image_load_increment(gpointer context,
490                                      const guchar *buf, guint size,
491                                      GError **error)
492 {
493         LoadContext* lc = context;
494
495         g_return_val_if_fail(lc != NULL, FALSE);
496
497         /* reset */
498         lc->first_row_seen_in_chunk = -1;
499         lc->last_row_seen_in_chunk = -1;
500         lc->first_pass_seen_in_chunk = -1;
501         lc->last_pass_seen_in_chunk = -1;
502         lc->max_row_seen_in_chunk = -1;
503         lc->error = error;
504         
505         /* Invokes our callbacks as needed */
506         if (setjmp (lc->png_read_ptr->jmpbuf)) {
507                 lc->error = NULL;
508                 return FALSE;
509         } else {
510                 png_process_data(lc->png_read_ptr, lc->png_info_ptr,
511                                  (guchar*) buf, size);
512         }
513
514         if (lc->fatal_error_occurred) {
515                 lc->error = NULL;
516                 return FALSE;
517         } else {
518                 if (lc->first_row_seen_in_chunk >= 0) {
519                         /* We saw at least one row */
520                         gint pass_diff = lc->last_pass_seen_in_chunk - lc->first_pass_seen_in_chunk;
521                         
522                         g_assert(pass_diff >= 0);
523                         
524                         if (pass_diff == 0) {
525                                 /* start and end row were in the same pass */
526                                 (lc->update_func)(lc->pixbuf, 0,
527                                                   lc->first_row_seen_in_chunk,
528                                                   lc->pixbuf->width,
529                                                   (lc->last_row_seen_in_chunk -
530                                                    lc->first_row_seen_in_chunk) + 1,
531                                                   lc->notify_user_data);
532                         } else if (pass_diff == 1) {
533                                 /* We have from the first row seen to
534                                    the end of the image (max row
535                                    seen), then from the top of the
536                                    image to the last row seen */
537                                 /* first row to end */
538                                 (lc->update_func)(lc->pixbuf, 0,
539                                                   lc->first_row_seen_in_chunk,
540                                                   lc->pixbuf->width,
541                                                   (lc->max_row_seen_in_chunk -
542                                                    lc->first_row_seen_in_chunk) + 1,
543                                                   lc->notify_user_data);
544                                 /* top to last row */
545                                 (lc->update_func)(lc->pixbuf,
546                                                   0, 0, 
547                                                   lc->pixbuf->width,
548                                                   lc->last_row_seen_in_chunk + 1,
549                                                   lc->notify_user_data);
550                         } else {
551                                 /* We made at least one entire pass, so update the
552                                    whole image */
553                                 (lc->update_func)(lc->pixbuf,
554                                                   0, 0, 
555                                                   lc->pixbuf->width,
556                                                   lc->max_row_seen_in_chunk + 1,
557                                                   lc->notify_user_data);
558                         }
559                 }
560
561                 lc->error = NULL;
562                 
563                 return TRUE;
564         }
565 }
566
567 /* Called at the start of the progressive load, once we have image info */
568 static void
569 png_info_callback   (png_structp png_read_ptr,
570                      png_infop   png_info_ptr)
571 {
572         LoadContext* lc;
573         png_uint_32 width, height;
574         png_textp png_text_ptr;
575         int i, num_texts;
576         int color_type;
577         gboolean have_alpha = FALSE;
578         
579         lc = png_get_progressive_ptr(png_read_ptr);
580
581         if (lc->fatal_error_occurred)
582                 return;
583
584         if (!setup_png_transformations(lc->png_read_ptr,
585                                        lc->png_info_ptr,
586                                        lc->error,
587                                        &width, &height, &color_type)) {
588                 lc->fatal_error_occurred = TRUE;
589                 return;
590         }
591
592         /* If we have alpha, set a flag */
593         if (color_type & PNG_COLOR_MASK_ALPHA)
594                 have_alpha = TRUE;
595         
596         lc->pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, have_alpha, 8, width, height);
597
598         if (lc->pixbuf == NULL) {
599                 /* Failed to allocate memory */
600                 lc->fatal_error_occurred = TRUE;
601                 if (lc->error && *lc->error == NULL) {
602                         g_set_error (lc->error,
603                                      GDK_PIXBUF_ERROR,
604                                      GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
605                                      _("Insufficient memory to store a %ld by %ld image; try exiting some applications to reduce memory usage"),
606                                      width, height);
607                 }
608                 return;
609         }
610
611         /* Extract text chunks and attach them as pixbuf options */
612         
613         if (png_get_text (png_read_ptr, png_info_ptr, &png_text_ptr, &num_texts)) {
614                 for (i = 0; i < num_texts; i++) {
615                         gchar *key, *value;
616
617                         if (png_text_to_pixbuf_option (png_text_ptr[i],
618                                                        &key, &value)) {
619                                 gdk_pixbuf_set_option (lc->pixbuf, key, value);
620                                 g_free (key);
621                                 g_free (value);
622                         }
623                 }
624         }
625
626         /* Notify the client that we are ready to go */
627
628         if (lc->prepare_func)
629                 (* lc->prepare_func) (lc->pixbuf, NULL, lc->notify_user_data);
630         
631         return;
632 }
633
634 /* Called for each row; note that you will get duplicate row numbers
635    for interlaced PNGs */
636 static void
637 png_row_callback   (png_structp png_read_ptr,
638                     png_bytep   new_row,
639                     png_uint_32 row_num,
640                     int pass_num)
641 {
642         LoadContext* lc;
643         guchar* old_row = NULL;
644
645         lc = png_get_progressive_ptr(png_read_ptr);
646
647         if (lc->fatal_error_occurred)
648                 return;
649
650         if (row_num < 0 || row_num >= lc->pixbuf->height) {
651                 lc->fatal_error_occurred = TRUE;
652                 if (lc->error && *lc->error == NULL) {
653                         g_set_error (lc->error,
654                                      GDK_PIXBUF_ERROR,
655                                      GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
656                                      _("Fatal error reading PNG image file"));
657                 }
658                 return;
659         }
660
661         if (lc->first_row_seen_in_chunk < 0) {
662                 lc->first_row_seen_in_chunk = row_num;
663                 lc->first_pass_seen_in_chunk = pass_num;
664         }
665
666         lc->max_row_seen_in_chunk = MAX(lc->max_row_seen_in_chunk, ((gint)row_num));
667         lc->last_row_seen_in_chunk = row_num;
668         lc->last_pass_seen_in_chunk = pass_num;
669         
670         old_row = lc->pixbuf->pixels + (row_num * lc->pixbuf->rowstride);
671
672         png_progressive_combine_row(lc->png_read_ptr, old_row, new_row);
673 }
674
675 /* Called after reading the entire image */
676 static void
677 png_end_callback   (png_structp png_read_ptr,
678                     png_infop   png_info_ptr)
679 {
680         LoadContext* lc;
681
682         lc = png_get_progressive_ptr(png_read_ptr);
683
684         if (lc->fatal_error_occurred)
685                 return;
686 }
687
688 static void
689 png_error_callback(png_structp png_read_ptr,
690                    png_const_charp error_msg)
691 {
692         LoadContext* lc;
693         
694         lc = png_get_error_ptr(png_read_ptr);
695         
696         lc->fatal_error_occurred = TRUE;
697
698         /* I don't trust libpng to call the error callback only once,
699          * so check for already-set error
700          */
701         if (lc->error && *lc->error == NULL) {
702                 g_set_error (lc->error,
703                              GDK_PIXBUF_ERROR,
704                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
705                              _("Fatal error reading PNG image file: %s"),
706                              error_msg);
707         }
708
709         longjmp (png_read_ptr->jmpbuf, 1);
710 }
711
712 static void
713 png_warning_callback(png_structp png_read_ptr,
714                      png_const_charp warning_msg)
715 {
716         LoadContext* lc;
717         
718         lc = png_get_error_ptr(png_read_ptr);
719
720         /* Don't print anything; we should not be dumping junk to
721          * stderr, since that may be bad for some apps. If it's
722          * important enough to display, we need to add a GError
723          * **warning return location wherever we have an error return
724          * location.
725          */
726 }
727
728
729 /* Save */
730
731 static gboolean
732 gdk_pixbuf__png_image_save (FILE          *f, 
733                             GdkPixbuf     *pixbuf, 
734                             gchar        **keys,
735                             gchar        **values,
736                             GError       **error)
737 {
738        png_structp png_ptr;
739        png_infop info_ptr;
740        png_textp text_ptr = NULL;
741        guchar *ptr;
742        guchar *pixels;
743        int y;
744        int i;
745        png_bytep row_ptr;
746        png_color_8 sig_bit;
747        int w, h, rowstride;
748        int has_alpha;
749        int bpc;
750        int num_keys;
751        gboolean success = TRUE;
752
753        num_keys = 0;
754
755        if (keys && *keys) {
756                gchar **kiter;
757                gchar  *key;
758                int     len;
759
760                for (kiter = keys; *kiter; kiter++) {
761                        if (strncmp (*kiter, "tEXt::", 6) != 0) {
762                                g_warning ("Bad option name '%s' passed to PNG saver", *kiter);
763                                return FALSE;
764                        }
765                        key = *kiter + 6;
766                        len = strlen (key);
767                        if (len <= 1 || len > 79) {
768                                g_set_error (error,
769                                             GDK_PIXBUF_ERROR,
770                                             GDK_PIXBUF_ERROR_BAD_OPTION,
771                                             _("Keys for PNG text chunks must have at least 1 and at most 79 characters."));
772                                return FALSE;
773                        }
774                        for (i = 0; i < len; i++) {
775                                if ((guchar) key[i] > 127) {
776                                        g_set_error (error,
777                                                     GDK_PIXBUF_ERROR,
778                                                     GDK_PIXBUF_ERROR_BAD_OPTION,
779                                                     _("Keys for PNG text chunks must be ASCII characters."));
780                                        return FALSE;
781                                }
782                        }
783                        num_keys++;
784                }
785        }
786
787        if (num_keys > 0) {
788                text_ptr = g_new0 (png_text, num_keys);
789                for (i = 0; i < num_keys; i++) {
790                        text_ptr[i].compression = PNG_TEXT_COMPRESSION_NONE;
791                        text_ptr[i].key  = keys[i] + 6;
792                        text_ptr[i].text = g_convert (values[i], -1, 
793                                                      "ISO-8859-1", "UTF-8", 
794                                                      NULL, &text_ptr[i].text_length, 
795                                                      NULL);
796
797 #ifdef PNG_iTXt_SUPPORTED 
798                        if (!text_ptr[i].text) {
799                                text_ptr[i].compression = PNG_ITXT_COMPRESSION_NONE;
800                                text_ptr[i].text = g_strdup (values[i]);
801                                text_ptr[i].text_length = 0;
802                                text_ptr[i].itxt_length = strlen (text_ptr[i].text);
803                                text_ptr[i].lang = NULL;
804                                text_ptr[i].lang_key = NULL;
805                        }
806 #endif
807
808                        if (!text_ptr[i].text) {
809                                g_set_error (error,
810                                             GDK_PIXBUF_ERROR,
811                                             GDK_PIXBUF_ERROR_BAD_OPTION,
812                                             _("Value for PNG text chunk %s can not be converted to ISO-8859-1 encoding."), keys[i] + 6);
813                                num_keys = i;
814                                for (i = 0; i < num_keys; i++)
815                                        g_free (text_ptr[i].text);
816                                g_free (text_ptr);
817                                return FALSE;
818                        }
819                }
820        }
821
822        bpc = gdk_pixbuf_get_bits_per_sample (pixbuf);
823        w = gdk_pixbuf_get_width (pixbuf);
824        h = gdk_pixbuf_get_height (pixbuf);
825        rowstride = gdk_pixbuf_get_rowstride (pixbuf);
826        has_alpha = gdk_pixbuf_get_has_alpha (pixbuf);
827        pixels = gdk_pixbuf_get_pixels (pixbuf);
828
829        png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING,
830                                           error,
831                                           png_simple_error_callback,
832                                           png_simple_warning_callback);
833
834        g_return_val_if_fail (png_ptr != NULL, FALSE);
835
836        info_ptr = png_create_info_struct (png_ptr);
837        if (info_ptr == NULL) {
838                success = FALSE;
839                goto cleanup;
840        }
841        if (setjmp (png_ptr->jmpbuf)) {
842                success = FALSE;
843                goto cleanup;
844        }
845
846        if (num_keys > 0) {
847                png_set_text (png_ptr, info_ptr, text_ptr, num_keys);
848        }
849
850        png_init_io (png_ptr, f);
851
852        if (has_alpha) {
853                png_set_IHDR (png_ptr, info_ptr, w, h, bpc,
854                              PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
855                              PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
856        } else {
857                png_set_IHDR (png_ptr, info_ptr, w, h, bpc,
858                              PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
859                              PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
860        }
861        sig_bit.red = bpc;
862        sig_bit.green = bpc;
863        sig_bit.blue = bpc;
864        sig_bit.alpha = bpc;
865        png_set_sBIT (png_ptr, info_ptr, &sig_bit);
866        png_write_info (png_ptr, info_ptr);
867        png_set_shift (png_ptr, &sig_bit);
868        png_set_packing (png_ptr);
869
870        ptr = pixels;
871        for (y = 0; y < h; y++) {
872                row_ptr = (png_bytep)ptr;
873                png_write_rows (png_ptr, &row_ptr, 1);
874                ptr += rowstride;
875        }
876
877        png_write_end (png_ptr, info_ptr);
878
879 cleanup:
880        png_destroy_write_struct (&png_ptr, &info_ptr);
881
882        if (num_keys > 0) {
883                for (i = 0; i < num_keys; i++)
884                        g_free (text_ptr[i].text);
885                g_free (text_ptr);
886        }
887
888        return success;
889 }
890
891 void
892 MODULE_ENTRY (png, fill_vtable) (GdkPixbufModule *module)
893 {
894         module->load = gdk_pixbuf__png_image_load;
895         module->begin_load = gdk_pixbuf__png_image_begin_load;
896         module->stop_load = gdk_pixbuf__png_image_stop_load;
897         module->load_increment = gdk_pixbuf__png_image_load_increment;
898         module->save = gdk_pixbuf__png_image_save;
899 }
900
901 void
902 MODULE_ENTRY (png, fill_info) (GdkPixbufFormat *info)
903 {
904         static GdkPixbufModulePattern signature[] = {
905                 { "\x89PNG\r\n\x1a\x0a", NULL, 100 },
906                 { NULL, NULL, 0 }
907         };
908         static gchar * mime_types[] = {
909                 "image/png",
910                 NULL
911         };
912         static gchar * extensions[] = {
913                 "png",
914                 NULL
915         };
916
917         info->name = "png";
918         info->signature = signature;
919         info->description = N_("The PNG image format");
920         info->mime_types = mime_types;
921         info->extensions = extensions;
922         info->flags = GDK_PIXBUF_FORMAT_WRITABLE;
923 }