]> Pileus Git - ~andy/gtk/blob - gdk-pixbuf/io-pnm.c
Apply a cleanup patch by Kjartan Maraas (#341812)
[~andy/gtk] / gdk-pixbuf / io-pnm.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /* GdkPixbuf library - PNM image loader
3  *
4  * Copyright (C) 1999 Red Hat, Inc.
5  *
6  * Authors: Jeffrey Stedfast <fejj@helixcode.com>
7  *          Michael Fulbright <drmike@redhat.com>
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, USA.
23  */
24
25 #include <config.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <setjmp.h>
30 #include "gdk-pixbuf-private.h"
31 #include "gdk-pixbuf-io.h"
32
33
34 #define PNM_BUF_SIZE 4096
35
36 #define PNM_FATAL_ERR  -1
37 #define PNM_SUSPEND     0
38 #define PNM_OK          1
39
40 typedef enum {
41         PNM_FORMAT_PGM = 1,
42         PNM_FORMAT_PGM_RAW,
43         PNM_FORMAT_PPM,
44         PNM_FORMAT_PPM_RAW,
45         PNM_FORMAT_PBM,
46         PNM_FORMAT_PBM_RAW
47 } PnmFormat;
48
49 typedef struct {
50         guchar buffer[PNM_BUF_SIZE];
51         guchar *byte;
52         guint nbytes;
53 } PnmIOBuffer;
54
55 typedef struct {
56         GdkPixbufModuleUpdatedFunc updated_func;
57         GdkPixbufModulePreparedFunc prepared_func;
58         GdkPixbufModuleSizeFunc size_func;
59         gpointer user_data;
60         
61         GdkPixbuf *pixbuf;
62         guchar *pixels;        /* incoming pixel data buffer */
63         guchar *dptr;          /* current position in pixbuf */
64         
65         PnmIOBuffer inbuf;
66         
67         guint width;
68         guint height;
69         guint maxval;
70         guint rowstride;
71         PnmFormat type;
72         
73         guint output_row;      /* last row to be completed */
74         guint output_col;
75         gboolean did_prescan;  /* are we in image data yet? */
76         gboolean got_header;   /* have we loaded pnm header? */
77         
78         guint scan_state;
79
80         GError **error;
81         
82 } PnmLoaderContext;
83
84 static GdkPixbuf   *gdk_pixbuf__pnm_image_load          (FILE *f, GError **error);
85 static gpointer    gdk_pixbuf__pnm_image_begin_load     (GdkPixbufModuleSizeFunc size_func, 
86                                                          GdkPixbufModulePreparedFunc func, 
87                                                          GdkPixbufModuleUpdatedFunc func2,
88                                                          gpointer user_data,
89                                                          GError **error);
90 static gboolean    gdk_pixbuf__pnm_image_stop_load      (gpointer context, GError **error);
91 static gboolean    gdk_pixbuf__pnm_image_load_increment (gpointer context,
92                                                          const guchar *buf, guint size,
93                                                          GError **error);
94
95 static void explode_bitmap_into_buf              (PnmLoaderContext *context);
96 static void explode_gray_into_buf                (PnmLoaderContext *context);
97
98
99 /* explode bitmap data into rgb components         */
100 /* we need to know what the row so we can          */
101 /* do sub-byte expansion (since 1 byte = 8 pixels) */
102 /* context->dptr MUST point at first byte in incoming data  */
103 /* which corresponds to first pixel of row y       */
104 static void
105 explode_bitmap_into_buf (PnmLoaderContext *context)
106 {
107         gint j;
108         guchar *from, *to, data;
109         gint bit;
110         guchar *dptr;
111         gint wid, x, y;
112         
113         g_return_if_fail (context != NULL);
114         g_return_if_fail (context->dptr != NULL);
115         
116         /* I'm no clever bit-hacker so I'm sure this can be optimized */
117         dptr = context->dptr;
118         y    = context->output_row;
119         wid  = context->width;
120         
121         from = dptr + ((wid - 1) / 8);
122         to   = dptr + (wid - 1) * 3;
123 /*      bit  = 7 - (((y+1)*wid-1) % 8); */
124         bit  = 7 - ((wid-1) % 8);
125         
126         /* get first byte and align properly */
127         data = from[0];
128         for (j = 0; j < bit; j++, data >>= 1);
129         
130         for (x = wid-1; x >= 0; x--) {
131 /*              g_print ("%c",  (data & 1) ? '*' : ' '); */
132                 
133                 to[0] = to[1] = to[2] = (data & 0x01) ? 0x00 : 0xff;
134                 
135                 to -= 3;
136                 bit++;
137                 
138                 if (bit > 7) {
139                         from--;
140                         data = from[0];
141                         bit = 0;
142                 } else {
143                         data >>= 1;
144                 }
145         }
146         
147 /*      g_print ("\n"); */
148 }
149
150 /* explode gray image row into rgb components in pixbuf */
151 static void
152 explode_gray_into_buf (PnmLoaderContext *context)
153 {
154         gint j;
155         guchar *from, *to;
156         guint w;
157         
158         g_return_if_fail (context != NULL);
159         g_return_if_fail (context->dptr != NULL);
160         
161         /* Expand grey->colour.  Expand from the end of the
162          * memory down, so we can use the same buffer.
163          */
164         w = context->width;
165         from = context->dptr + w - 1;
166         to = context->dptr + (w - 1) * 3;
167         for (j = w - 1; j >= 0; j--) {
168                 to[0] = from[0];
169                 to[1] = from[0];
170                 to[2] = from[0];
171                 to -= 3;
172                 from--;
173         }
174 }
175
176 /* skip over whitespace and comments in input buffer */
177 static gint
178 pnm_skip_whitespace (PnmIOBuffer *inbuf, GError **error)
179 {
180         register guchar *inptr;
181         guchar *inend;
182         
183         g_return_val_if_fail (inbuf != NULL, PNM_FATAL_ERR);
184         g_return_val_if_fail (inbuf->byte != NULL, PNM_FATAL_ERR);
185         
186         inend = inbuf->byte + inbuf->nbytes;
187         inptr = inbuf->byte;
188         
189         for ( ; inptr < inend; inptr++) {
190                 if (*inptr == '#') {
191                         /* in comment - skip to the end of this line */
192                         for ( ; *inptr != '\n' && inptr < inend; inptr++)
193                                 ;
194                         
195                         if ( inptr == inend || *inptr != '\n' ) {
196                                 /* couldn't read whole comment */
197                                 return PNM_SUSPEND;
198                         }
199                         
200                 } else if (!g_ascii_isspace (*inptr)) {
201                         inbuf->byte = inptr;
202                         inbuf->nbytes = (guint) (inend - inptr);
203                         return PNM_OK;
204                 }
205         }
206         
207         inbuf->byte = inptr;
208         inbuf->nbytes = (guint) (inend - inptr);
209         
210         return PNM_SUSPEND;
211 }
212
213 /* read next number from buffer */
214 static gint
215 pnm_read_next_value (PnmIOBuffer *inbuf, gint max_length, guint *value, GError **error)
216 {
217         register guchar *inptr, *word, *p;
218         guchar *inend, buf[129];
219         gchar *endptr;
220         gint retval;
221         glong result;
222         
223         g_return_val_if_fail (inbuf != NULL, PNM_FATAL_ERR);
224         g_return_val_if_fail (inbuf->byte != NULL, PNM_FATAL_ERR);
225         g_return_val_if_fail (value != NULL, PNM_FATAL_ERR);
226         
227         if (max_length < 0)
228                 max_length = 128;
229
230         /* skip white space */
231         if ((retval = pnm_skip_whitespace (inbuf, error)) != PNM_OK)
232                 return retval;
233         
234         inend = inbuf->byte + inbuf->nbytes;
235         inptr = inbuf->byte;
236         
237         /* copy this pnm 'word' into a temp buffer */
238         for (p = inptr, word = buf; (p < inend) && !g_ascii_isspace (*p) && (*p != '#') && (p - inptr < max_length); p++, word++)
239                 *word = *p;
240         *word = '\0';
241         
242         /* hmmm, there must be more data to this 'word' */
243         if (p == inend || (!g_ascii_isspace (*p) && (*p != '#')  && (p - inptr < max_length)))
244             return PNM_SUSPEND;
245         
246         /* get the value */
247         result = strtol (buf, &endptr, 10);
248         if (*endptr != '\0' || result < 0 || result > G_MAXUINT) {
249                 g_set_error (error,
250                              GDK_PIXBUF_ERROR,
251                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
252                              _("PNM loader expected to find an integer, but didn't"));
253                 return PNM_FATAL_ERR;
254         }
255         *value = result;
256
257         inbuf->byte = p;
258         inbuf->nbytes = (guint) (inend - p);
259         
260         return PNM_OK;
261 }
262
263 /* returns PNM_OK, PNM_SUSPEND, or PNM_FATAL_ERR */
264 static gint
265 pnm_read_header (PnmLoaderContext *context)
266 {
267         PnmIOBuffer *inbuf;
268         gint retval;
269         
270         g_return_val_if_fail (context != NULL, PNM_FATAL_ERR);
271         
272         inbuf = &context->inbuf;
273         
274         if (!context->type) {
275                 /* file must start with a 'P' followed by a numeral  */
276                 /* so loop till we get enough data to determine type */
277                 if (inbuf->nbytes < 2)
278                         return PNM_SUSPEND;
279                 
280                 if (*inbuf->byte != 'P') {
281                         g_set_error (context->error,
282                                      GDK_PIXBUF_ERROR,
283                                      GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
284                                      _("PNM file has an incorrect initial byte"));
285                         return PNM_FATAL_ERR;
286                 }
287                 
288                 inbuf->byte++;
289                 inbuf->nbytes--;
290                 
291                 switch (*inbuf->byte) {
292                 case '1':
293                         context->type = PNM_FORMAT_PBM;
294                         break;
295                 case '2':
296                         context->type = PNM_FORMAT_PGM;
297                         break;
298                 case '3':
299                         context->type = PNM_FORMAT_PPM;
300                         break;
301                 case '4':
302                         context->type = PNM_FORMAT_PBM_RAW;
303                         break;
304                 case '5':
305                         context->type = PNM_FORMAT_PGM_RAW;
306                         break;
307                 case '6':
308                         context->type = PNM_FORMAT_PPM_RAW;
309                         break;
310                 default:
311                         g_set_error (context->error,
312                                      GDK_PIXBUF_ERROR,
313                                      GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
314                                      _("PNM file is not in a recognized PNM subformat"));
315                         return PNM_FATAL_ERR;
316                 }
317                 
318                 if (!inbuf->nbytes)
319                         return PNM_SUSPEND;
320                 
321                 inbuf->byte++;
322                 inbuf->nbytes--;
323         }
324         
325         if (!context->width) {
326                 /* read the pixmap width */
327                 guint width = 0;
328                 
329                 retval = pnm_read_next_value (inbuf, -1, &width,
330                                               context->error);
331                 
332                 if (retval != PNM_OK) 
333                         return retval;
334                 
335                 if (!width) {
336                         g_set_error (context->error,
337                                      GDK_PIXBUF_ERROR,
338                                      GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
339                                      _("PNM file has an image width of 0"));
340                         return PNM_FATAL_ERR;
341                 }
342                 
343                 context->width = width;
344         }
345         
346         if (!context->height) {
347                 /* read the pixmap height */
348                 guint height = 0;
349                 
350                 retval = pnm_read_next_value (inbuf, -1, &height,
351                                               context->error);
352                 
353                 if (retval != PNM_OK)
354                         return retval;
355                 
356                 if (!height) {
357                         g_set_error (context->error,
358                                      GDK_PIXBUF_ERROR,
359                                      GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
360                                      _("PNM file has an image height of 0"));
361                         return PNM_FATAL_ERR;
362                 }
363                 
364                 context->height = height;
365         }
366         
367         switch (context->type) {
368         case PNM_FORMAT_PPM:
369         case PNM_FORMAT_PPM_RAW:
370         case PNM_FORMAT_PGM:
371         case PNM_FORMAT_PGM_RAW:
372                 if (!context->maxval) {
373                         retval = pnm_read_next_value (inbuf, -1, &context->maxval,
374                                                       context->error);
375                         
376                         if (retval != PNM_OK)
377                                 return retval;
378                         
379                         if (context->maxval == 0) {
380                                 g_set_error (context->error,
381                                              GDK_PIXBUF_ERROR,
382                                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
383                                              _("Maximum color value in PNM file is 0"));
384                                 return PNM_FATAL_ERR;
385                         }
386
387                         if (context->maxval > 65535) {
388                                 g_set_error (context->error,
389                                              GDK_PIXBUF_ERROR,
390                                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
391                                              _("Maximum color value in PNM file is too large"));
392                                 return PNM_FATAL_ERR;
393                         }
394
395                 }
396                 break;
397         default:
398                 break;
399         }
400         
401         return PNM_OK;
402 }
403
404 static gint
405 pnm_read_raw_scanline (PnmLoaderContext *context)
406 {
407         PnmIOBuffer *inbuf;
408         guint numbytes, offset;
409         guint numpix = 0;
410         guchar *dest;
411         guint i;
412         
413         g_return_val_if_fail (context != NULL, PNM_FATAL_ERR);
414         
415         inbuf = &context->inbuf;
416         
417         switch (context->type) {
418         case PNM_FORMAT_PBM_RAW:
419                 numpix = inbuf->nbytes * 8;
420                 break;
421         case PNM_FORMAT_PGM_RAW:
422                 numpix = inbuf->nbytes;
423                 break;
424         case PNM_FORMAT_PPM_RAW:
425                 numpix = inbuf->nbytes / 3;
426                 break;
427         default:
428                 g_set_error (context->error,
429                              GDK_PIXBUF_ERROR,
430                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
431                              _("Raw PNM image type is invalid"));
432                 return PNM_FATAL_ERR;
433         }
434         if(context->maxval>255) 
435                 numpix/=2;
436         
437         numpix = MIN (numpix, context->width - context->output_col);
438         
439         if (!numpix)
440                 return PNM_SUSPEND;
441         
442         context->dptr = context->pixels + context->output_row * context->rowstride;
443         
444         switch (context->type) {
445         case PNM_FORMAT_PBM_RAW:
446                 numbytes = (numpix / 8) + ((numpix % 8) ? 1 : 0);
447                 offset = context->output_col / 8;
448                 break;
449         case PNM_FORMAT_PGM_RAW:
450                 numbytes = numpix;
451                 offset = context->output_col;
452                 break;
453         case PNM_FORMAT_PPM_RAW:
454                 numbytes = numpix * 3;
455                 offset = context->output_col * 3;
456                 break;
457         default:
458                 g_set_error (context->error,
459                              GDK_PIXBUF_ERROR,
460                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
461                              _("Raw PNM image type is invalid"));
462                 return PNM_FATAL_ERR;
463         }
464         if(context->maxval>255) 
465                 numbytes*=2;                            
466         
467         switch (context->type) {
468         case PNM_FORMAT_PBM_RAW:
469                 dest = context->dptr + offset;          
470                 memcpy (dest, inbuf->byte, numbytes);
471                 break;
472         case PNM_FORMAT_PGM_RAW:
473         case PNM_FORMAT_PPM_RAW:
474                 dest = context->dptr + offset;
475                 
476                 if (context->maxval == 255) {
477                         /* special-case optimization */
478                         memcpy (dest, inbuf->byte, numbytes);
479                 } else if(context->maxval == 65535) {
480                         /* optimized version of the next case */
481                         for(i=0; i < numbytes ; i+=2) {
482                                 *dest++=inbuf->byte[i];
483                         }
484                 } else if(context->maxval > 255) {
485                         /* scale down to 256 colors */
486                         for(i=0; i < numbytes ; i+=2) {
487                                 guint v=inbuf->byte[i]*256+inbuf->byte[i+1];
488                                 *dest++=v*255/context->maxval;
489                         }
490                 } else {
491                         for (i = 0; i < numbytes; i++) {
492                                 guchar *byte = inbuf->byte + i;
493                                 
494                                 /* scale the color to an 8-bit color depth */
495                                 if (*byte > context->maxval)
496                                         *dest++ = 255;
497                                 else
498                                         *dest++ = (guchar) (255 * *byte / context->maxval);
499                         }
500                 }
501                 break;
502         default:
503                 g_set_error (context->error,
504                              GDK_PIXBUF_ERROR,
505                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
506                              _("Raw PNM image type is invalid"));
507                 return PNM_FATAL_ERR;
508         }
509         
510         inbuf->byte += numbytes;
511         inbuf->nbytes -= numbytes;
512         
513         context->output_col += numpix;
514         if (context->output_col == context->width) {
515                 if (context->type == PNM_FORMAT_PBM_RAW)
516                         explode_bitmap_into_buf (context);
517                 else if (context->type == PNM_FORMAT_PGM_RAW)
518                         explode_gray_into_buf (context);
519                 
520                 context->output_col = 0;
521                 context->output_row++;
522         } else {
523                 return PNM_SUSPEND;
524         }
525         
526         return PNM_OK;
527 }
528
529 static gint
530 pnm_read_ascii_mono_scanline (PnmLoaderContext *context)
531 {
532         PnmIOBuffer *inbuf;
533         guint value;
534         gint retval;
535         guchar *dptr;
536         gint max_length;
537
538         if (context->type == PNM_FORMAT_PBM)
539                 max_length = 1;
540         else
541                 max_length = -1;
542
543         inbuf = &context->inbuf;
544
545         context->dptr = context->pixels + context->output_row * context->rowstride;
546
547         dptr = context->dptr + context->output_col * 3;
548
549         while (TRUE) {
550                 retval = pnm_read_next_value (inbuf, max_length, &value, context->error);
551                 if (retval != PNM_OK)
552                         return retval;
553
554                 if (context->type == PNM_FORMAT_PBM) {
555                         value = value ? 0 : 0xff;
556                 }
557                 else {
558                         /* scale the color up or down to an 8-bit color depth */
559                         if (value > context->maxval)
560                                 value = 255;
561                         else
562                                 value = (guchar)(255 * value / context->maxval);
563                 }
564                         
565                 *dptr++ = value;
566                 *dptr++ = value;
567                 *dptr++ = value;
568
569                 context->output_col++;
570
571                 if (context->output_col == context->width) {
572                         context->output_col = 0;
573                         context->output_row++;
574                         break;
575                 }
576         }
577
578         return PNM_OK;
579 }
580
581 static gint
582 pnm_read_ascii_color_scanline (PnmLoaderContext *context)
583 {
584         PnmIOBuffer *inbuf;
585         guint value, i;
586         guchar *dptr;
587         gint retval;
588         
589         inbuf = &context->inbuf;
590         
591         context->dptr = context->pixels + context->output_row * context->rowstride;
592         
593         dptr = context->dptr + context->output_col * 3 + context->scan_state;
594         
595         while (TRUE) {
596                 for (i = context->scan_state; i < 3; i++) {
597                         retval = pnm_read_next_value (inbuf, -1, &value, context->error);
598                         if (retval != PNM_OK) {
599                                 /* save state and return */
600                                 context->scan_state = i;
601                                 return retval;
602                         }
603                         
604                         if (value > context->maxval)
605                                 *dptr++ = 255;
606                         else
607                                 *dptr++ = (guchar)(255 * value / context->maxval);
608                 }
609                 
610                 context->scan_state = 0;
611                 context->output_col++;
612                 
613                 if (context->output_col == context->width) {
614                         context->output_col = 0;
615                         context->output_row++;
616                         break;
617                 }
618         }
619         
620         return PNM_OK;
621 }
622
623 /* returns 1 if a scanline was converted, 0 means we ran out of data */
624 static gint
625 pnm_read_scanline (PnmLoaderContext *context)
626 {
627         gint retval;
628         
629         g_return_val_if_fail (context != NULL, PNM_FATAL_ERR);
630         
631         /* read in image data */
632         /* for raw formats this is trivial */
633         switch (context->type) {
634         case PNM_FORMAT_PBM_RAW:
635         case PNM_FORMAT_PGM_RAW:
636         case PNM_FORMAT_PPM_RAW:
637                 retval = pnm_read_raw_scanline (context);
638                 if (retval != PNM_OK)
639                         return retval;
640                 break;
641         case PNM_FORMAT_PBM:
642         case PNM_FORMAT_PGM:
643                 retval = pnm_read_ascii_mono_scanline (context);
644                 if (retval != PNM_OK)
645                         return retval;
646                 break;          
647         case PNM_FORMAT_PPM:
648                 retval = pnm_read_ascii_color_scanline (context);
649                 if (retval != PNM_OK)
650                         return retval;
651                 break;
652         default:
653                 g_set_error (context->error,
654                              GDK_PIXBUF_ERROR,
655                              GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
656                              _("PNM image loader does not support this PNM subformat"));
657
658                 return PNM_FATAL_ERR;
659         }
660         
661         return PNM_OK;
662 }
663
664 /* Shared library entry point */
665 static GdkPixbuf *
666 gdk_pixbuf__pnm_image_load (FILE *f, GError **error)
667 {
668         PnmLoaderContext context;
669         PnmIOBuffer *inbuf;
670         gint nbytes;
671         gint retval;
672         
673         /* pretend to be doing progressive loading */
674         context.updated_func = NULL;
675         context.prepared_func = NULL;
676         context.user_data = NULL;
677         context.type = 0;
678         context.inbuf.nbytes = 0;
679         context.inbuf.byte = NULL;
680         context.width = 0;
681         context.height = 0;
682         context.maxval = 0;
683         context.pixels = NULL;
684         context.pixbuf = NULL;
685         context.got_header = FALSE;
686         context.did_prescan = FALSE;
687         context.scan_state = 0;
688         context.error = error;
689         
690         inbuf = &context.inbuf;
691         
692         while (TRUE) {
693                 guint num_to_read;
694                 
695                 /* keep buffer as full as possible */
696                 num_to_read = PNM_BUF_SIZE - inbuf->nbytes;
697                 
698                 if (inbuf->byte != NULL && inbuf->nbytes > 0)
699                         memmove (inbuf->buffer, inbuf->byte, inbuf->nbytes);
700                 
701                 nbytes = fread (inbuf->buffer + inbuf->nbytes, 1, num_to_read, f);
702                 
703                 /* error checking */
704                 if (nbytes == 0) {
705                         /* we ran out of data? */
706                         if (context.pixbuf)
707                                 g_object_unref (context.pixbuf);
708                         g_set_error (error,
709                                      GDK_PIXBUF_ERROR,
710                                      GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
711                                      _("Premature end-of-file encountered"));
712                         return NULL;
713                 }
714                 
715                 inbuf->nbytes += nbytes;
716                 inbuf->byte = inbuf->buffer;
717                 
718                 /* get header if needed */
719                 if (!context.got_header) {
720                         retval = pnm_read_header (&context);
721                         if (retval == PNM_FATAL_ERR)
722                                 return NULL;
723                         else if (retval == PNM_SUSPEND)
724                                 continue;
725                         
726                         context.got_header = TRUE;
727                 }
728                 
729                 /* scan until we hit image data */
730                 if (!context.did_prescan) {
731                         switch (context.type) {
732                         case PNM_FORMAT_PBM_RAW:
733                         case PNM_FORMAT_PGM_RAW:
734                         case PNM_FORMAT_PPM_RAW:
735                                 if (inbuf->nbytes <= 0)
736                                         continue;
737                                 /* raw formats require exactly one whitespace */
738                                 if (!g_ascii_isspace(*(inbuf->byte))) 
739                                         {
740                                                 g_set_error (error,
741                                                              GDK_PIXBUF_ERROR,
742                                                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
743                                                              _("Raw PNM formats require exactly one whitespace before sample data"));
744                                                 return NULL;
745                                         }
746                                 inbuf->nbytes--;
747                                 inbuf->byte++;
748                                 break;
749                         default:
750                                 retval = pnm_skip_whitespace (inbuf,
751                                                               context.error);
752                                 if (retval == PNM_FATAL_ERR)
753                                         return NULL;
754                                 else if (retval == PNM_SUSPEND)
755                                         continue;
756                                 break;
757                         }
758                         context.did_prescan = TRUE;
759                         context.output_row = 0;
760                         context.output_col = 0;
761                         
762                         context.pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, FALSE, 8,
763                                                          context.width, context.height);
764                         
765                         if (!context.pixbuf) {
766                                 /* Failed to allocate memory */
767                                 g_set_error (error,
768                                              GDK_PIXBUF_ERROR,
769                                              GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
770                                              _("Cannot allocate memory for loading PNM image"));
771                                 return NULL;
772                         }
773
774                         context.rowstride = context.pixbuf->rowstride;
775                         context.pixels = context.pixbuf->pixels;
776                 }
777                 
778                 /* if we got here we're reading image data */
779                 while (context.output_row < context.height) {
780                         retval = pnm_read_scanline (&context);
781                         
782                         if (retval == PNM_SUSPEND) {
783                                 break;
784                         } else if (retval == PNM_FATAL_ERR) {
785                                 if (context.pixbuf)
786                                         g_object_unref (context.pixbuf);
787
788                                 return NULL;
789                         }
790                 }
791                 
792                 if (context.output_row < context.height)
793                         continue;
794                 else
795                         break;
796         }
797         
798         return context.pixbuf;
799 }
800
801 /* 
802  * func - called when we have pixmap created (but no image data)
803  * user_data - passed as arg 1 to func
804  * return context (opaque to user)
805  */
806
807 static gpointer
808 gdk_pixbuf__pnm_image_begin_load (GdkPixbufModuleSizeFunc size_func, 
809                                   GdkPixbufModulePreparedFunc prepared_func, 
810                                   GdkPixbufModuleUpdatedFunc  updated_func,
811                                   gpointer user_data,
812                                   GError **error)
813 {
814         PnmLoaderContext *context;
815         
816         context = g_try_malloc (sizeof (PnmLoaderContext));
817         if (!context) {
818                 g_set_error(error, GDK_PIXBUF_ERROR, 
819                             GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
820                             _("Insufficient memory to load PNM context struct"));
821                 return NULL;
822         }
823         memset (context, 0, sizeof (PnmLoaderContext));
824         context->size_func = size_func;
825         context->prepared_func = prepared_func;
826         context->updated_func  = updated_func;
827         context->user_data = user_data;
828         context->width = 0;
829         context->height = 0;
830         context->maxval = 0;
831         context->pixbuf = NULL;
832         context->pixels = NULL;
833         context->got_header = FALSE;
834         context->did_prescan = FALSE;
835         context->scan_state = 0;
836         
837         context->inbuf.nbytes = 0;
838         context->inbuf.byte  = NULL;
839
840         context->error = error;
841         
842         return (gpointer) context;
843 }
844
845 /*
846  * context - returned from image_begin_load
847  *
848  * free context, unref gdk_pixbuf
849  */
850 static gboolean
851 gdk_pixbuf__pnm_image_stop_load (gpointer data,
852                                  GError **error)
853 {
854         PnmLoaderContext *context = (PnmLoaderContext *) data;
855         gboolean retval = TRUE;
856         
857         g_return_val_if_fail (context != NULL, TRUE);
858         
859         if (context->pixbuf)
860                 g_object_unref (context->pixbuf);
861
862 #if 0
863         /* We should ignore trailing newlines and we can't
864            generally complain about trailing stuff at all, since 
865            pnm allows to put multiple images in a file
866         */
867         if (context->inbuf.nbytes > 0) {
868                 g_set_error (error,
869                              GDK_PIXBUF_ERROR,
870                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
871                              _("Unexpected end of PNM image data"));
872                 retval = FALSE;
873         }
874 #endif
875         
876         g_free (context);
877
878         return retval;
879 }
880
881 /*
882  * context - from image_begin_load
883  * buf - new image data
884  * size - length of new image data
885  *
886  * append image data onto inrecrementally built output image
887  */
888 static gboolean
889 gdk_pixbuf__pnm_image_load_increment (gpointer data,
890                                       const guchar *buf, guint size,
891                                       GError **error)
892 {
893         PnmLoaderContext *context = (PnmLoaderContext *)data;
894         PnmIOBuffer *inbuf;
895         guchar *old_byte;
896         guint old_nbytes;
897         const guchar *bufhd;
898         guint num_left, spinguard;
899         gint retval;
900         
901         g_return_val_if_fail (context != NULL, FALSE);
902         g_return_val_if_fail (buf != NULL, FALSE);
903
904         context->error = error;
905         
906         bufhd = buf;
907         inbuf = &context->inbuf;
908         old_nbytes = inbuf->nbytes;
909         old_byte  = inbuf->byte;
910         
911         num_left = size;
912         spinguard = 0;
913         while (TRUE) {
914                 guint num_to_copy;
915                 
916                 /* keep buffer as full as possible */
917                 num_to_copy = MIN (PNM_BUF_SIZE - inbuf->nbytes, num_left);
918                 
919                 if (num_to_copy == 0)
920                         spinguard++;
921                 
922                 if (spinguard > 1)
923                         return TRUE;
924                 
925                 if (inbuf->byte != NULL && inbuf->nbytes > 0)
926                         memmove (inbuf->buffer, inbuf->byte, inbuf->nbytes);
927                 
928                 memcpy (inbuf->buffer + inbuf->nbytes, bufhd, num_to_copy);
929                 bufhd += num_to_copy;
930                 inbuf->nbytes += num_to_copy;
931                 inbuf->byte = inbuf->buffer;
932                 num_left -= num_to_copy;
933                 
934                 /* ran out of data and we haven't exited main loop */
935                 if (inbuf->nbytes == 0)
936                         return TRUE;
937                 
938                 /* get header if needed */
939                 if (!context->got_header) {
940                         retval = pnm_read_header (context);
941                         
942                         if (retval == PNM_FATAL_ERR)
943                                 return FALSE;
944                         else if (retval == PNM_SUSPEND)
945                                 continue;
946                         
947                         context->got_header = TRUE;
948                 }
949
950                 if (context->size_func) {
951                         gint w = context->width;
952                         gint h = context->height;
953                         (*context->size_func) (&w, &h, context->user_data);
954                         
955                         if (w == 0 || h == 0) 
956                                 return FALSE;
957                 }
958                 
959                 
960                 /* scan until we hit image data */
961                 if (!context->did_prescan) {
962                         switch (context->type) {
963                         case PNM_FORMAT_PBM_RAW:
964                         case PNM_FORMAT_PGM_RAW:
965                         case PNM_FORMAT_PPM_RAW:
966                                 if (inbuf->nbytes <= 0)
967                                         continue;
968                                 /* raw formats require exactly one whitespace */
969                                 if (!g_ascii_isspace(*(inbuf->byte)))
970                                         {
971                                                 g_set_error (error,
972                                                              GDK_PIXBUF_ERROR,
973                                                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
974                                                              _("Raw PNM formats require exactly one whitespace before sample data"));
975                                                 return FALSE;
976                                         }
977                                 inbuf->nbytes--;
978                                 inbuf->byte++;
979                                 break;
980                         default:
981                                 retval = pnm_skip_whitespace (inbuf,
982                                                               context->error);
983                                 if (retval == PNM_FATAL_ERR)
984                                         return FALSE;
985                                 else if (retval == PNM_SUSPEND)
986                                         continue;
987                                 break;
988                         }
989                         context->did_prescan = TRUE;
990                         context->output_row = 0;
991                         context->output_col = 0;
992                         
993                         context->pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, 
994                                                           FALSE,
995                                                           8, 
996                                                           context->width,
997                                                           context->height);
998                         
999                         if (context->pixbuf == NULL) {
1000                                 g_set_error (error,
1001                                              GDK_PIXBUF_ERROR,
1002                                              GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
1003                                              _("Insufficient memory to load PNM file"));
1004                                 return FALSE;
1005                         }
1006                         
1007                         context->pixels = context->pixbuf->pixels;
1008                         context->rowstride = context->pixbuf->rowstride;
1009                         
1010                         /* Notify the client that we are ready to go */
1011                         if (context->prepared_func)
1012                                 (* context->prepared_func) (context->pixbuf,
1013                                                             NULL,
1014                                                             context->user_data);
1015                 }
1016                 
1017                 /* if we got here we're reading image data */
1018                 while (context->output_row < context->height) {
1019                         retval = pnm_read_scanline (context);
1020                         
1021                         if (retval == PNM_SUSPEND) {
1022                                 break;
1023                         } else if (retval == PNM_FATAL_ERR) {
1024                                 return FALSE;
1025                         } else if (retval == PNM_OK && context->updated_func) { 
1026                                 /* send updated signal */
1027                                 (* context->updated_func) (context->pixbuf,
1028                                                            0, 
1029                                                            context->output_row-1,
1030                                                            context->width, 
1031                                                            1,
1032                                                            context->user_data);
1033                         }
1034                 }
1035                 
1036                 if (context->output_row < context->height)
1037                         continue;
1038                 else
1039                         break;
1040         }
1041         
1042         return TRUE;
1043 }
1044
1045 void
1046 MODULE_ENTRY (pnm, fill_vtable) (GdkPixbufModule *module)
1047 {
1048         module->load = gdk_pixbuf__pnm_image_load;
1049         module->begin_load = gdk_pixbuf__pnm_image_begin_load;
1050         module->stop_load = gdk_pixbuf__pnm_image_stop_load;
1051         module->load_increment = gdk_pixbuf__pnm_image_load_increment;
1052 }
1053
1054 void
1055 MODULE_ENTRY (pnm, fill_info) (GdkPixbufFormat *info)
1056 {
1057         static GdkPixbufModulePattern signature[] = {
1058                 { "P1", NULL, 100 },
1059                 { "P2", NULL, 100 },
1060                 { "P3", NULL, 100 },
1061                 { "P4", NULL, 100 },
1062                 { "P5", NULL, 100 },
1063                 { "P6", NULL, 100 },
1064                 { NULL, NULL, 0 }
1065         };
1066         static gchar * mime_types[] = {
1067                 "image/x-portable-anymap",
1068                 "image/x-portable-bitmap",
1069                 "image/x-portable-graymap",
1070                 "image/x-portable-pixmap",
1071                 NULL
1072         };
1073         static gchar * extensions[] = {
1074                 "pnm",
1075                 "pbm",
1076                 "pgm",
1077                 "ppm",
1078                 NULL
1079         };
1080
1081         info->name = "pnm";
1082         info->signature = signature;
1083         info->description = N_("The PNM/PBM/PGM/PPM image format family");
1084         info->mime_types = mime_types;
1085         info->extensions = extensions;
1086         info->flags = GDK_PIXBUF_FORMAT_THREADSAFE;
1087         info->license = "LGPL";
1088 }