]> Pileus Git - ~andy/gtk/blob - gdk-pixbuf/io-gif.c
Remove a pointless check from the previous commit that added a new string.
[~andy/gtk] / gdk-pixbuf / io-gif.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */
2 /* GdkPixbuf library - GIF image loader
3  *
4  * Copyright (C) 1999 Mark Crichton
5  * Copyright (C) 1999 The Free Software Foundation
6  *
7  * Authors: Jonathan Blandford <jrb@redhat.com>
8  *          Adapted from the gimp gif filter written by Adam Moss <adam@gimp.org>
9  *          Gimp work based on earlier work.
10  *          Permission to relicense under the LGPL obtained.
11  *
12  * This library is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public
14  * License as published by the Free Software Foundation; either
15  * version 2 of the License, or (at your option) any later version.
16  *
17  * This library is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with this library; if not, write to the
24  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25  * Boston, MA 02111-1307, USA.
26  */
27
28 /* This loader is very hairy code.
29  *
30  * The main loop was not designed for incremental loading, so when it was hacked
31  * in it got a bit messy.  Basicly, every function is written to expect a failed
32  * read_gif, and lets you call it again assuming that the bytes are there.
33  *
34  * Return vals.
35  * Unless otherwise specified, these are the return vals for most functions:
36  *
37  *  0 -> success
38  * -1 -> more bytes needed.
39  * -2 -> failure; abort the load
40  * -3 -> control needs to be passed back to the main loop
41  *        \_ (most of the time returning 0 will get this, but not always)
42  *
43  * >1 -> for functions that get a guchar, the char will be returned.
44  *
45  * -jrb (11/03/1999)
46  */
47
48 /*
49  * If you have any images that crash this code, please, please let me know and
50  * send them to me.
51  *                                            <jrb@redhat.com>
52  */
53
54 \f
55
56 #include <config.h>
57 #include <stdio.h>
58 #include <string.h>
59 #include <errno.h>
60 #include "gdk-pixbuf-private.h"
61 #include "gdk-pixbuf-io.h"
62 #include "io-gif-animation.h"
63
64 \f
65
66 #undef DUMP_IMAGE_DETAILS 
67 #undef IO_GIFDEBUG
68
69 #define MAXCOLORMAPSIZE  256
70 #define MAX_LZW_BITS     12
71
72 #define INTERLACE          0x40
73 #define LOCALCOLORMAP      0x80
74 #define BitSet(byte, bit)  (((byte) & (bit)) == (bit))
75 #define LM_to_uint(a,b)         (((b)<<8)|(a))
76
77 \f
78
79 typedef unsigned char CMap[3][MAXCOLORMAPSIZE];
80
81 /* Possible states we can be in. */
82 enum {
83         GIF_START,
84         GIF_GET_COLORMAP,
85         GIF_GET_NEXT_STEP,
86         GIF_GET_FRAME_INFO,
87         GIF_GET_EXTENSION,
88         GIF_GET_COLORMAP2,
89         GIF_PREPARE_LZW,
90         GIF_LZW_FILL_BUFFER,
91         GIF_LZW_CLEAR_CODE,
92         GIF_GET_LZW,
93         GIF_DONE
94 };
95
96
97 typedef struct _Gif89 Gif89;
98 struct _Gif89
99 {
100         int transparent;
101         int delay_time;
102         int input_flag;
103         int disposal;
104 };
105
106 typedef struct _GifContext GifContext;
107 struct _GifContext
108 {
109         int state; /* really only relevant for progressive loading */
110         unsigned int width;
111         unsigned int height;
112
113         gboolean has_global_cmap;
114
115         CMap global_color_map;
116         gint global_colormap_size;
117         unsigned int global_bit_pixel;
118         unsigned int global_color_resolution;
119         unsigned int background_index;
120         gboolean stop_after_first_frame;
121
122         gboolean frame_cmap_active;
123         CMap frame_color_map;
124         gint frame_colormap_size;
125         unsigned int frame_bit_pixel;
126
127         unsigned int aspect_ratio;
128         GdkPixbufGifAnim *animation;
129         GdkPixbufFrame *frame;
130         Gif89 gif89;
131
132         /* stuff per frame. */
133         int frame_len;
134         int frame_height;
135         int frame_interlace;
136         int x_offset;
137         int y_offset;
138
139         /* Static read only */
140         FILE *file;
141
142         /* progressive read, only. */
143         GdkPixbufModulePreparedFunc prepare_func;
144         GdkPixbufModuleUpdatedFunc update_func;
145         gpointer user_data;
146         guchar *buf;
147         guint ptr;
148         guint size;
149         guint amount_needed;
150
151         /* extension context */
152         guchar extension_label;
153         guchar extension_flag;
154         gboolean in_loop_extension;
155
156         /* get block context */
157         guchar block_count;
158         guchar block_buf[280];
159         gint block_ptr;
160
161         int old_state; /* used by lzw_fill buffer */
162         /* get_code context */
163         int code_curbit;
164         int code_lastbit;
165         int code_done;
166         int code_last_byte;
167         int lzw_code_pending;
168
169         /* lzw context */
170         gint lzw_fresh;
171         gint lzw_code_size;
172         guchar lzw_set_code_size;
173         gint lzw_max_code;
174         gint lzw_max_code_size;
175         gint lzw_firstcode;
176         gint lzw_oldcode;
177         gint lzw_clear_code;
178         gint lzw_end_code;
179         gint *lzw_sp;
180
181         gint lzw_table[2][(1 << MAX_LZW_BITS)];
182         gint lzw_stack[(1 << (MAX_LZW_BITS)) * 2 + 1];
183
184         /* painting context */
185         gint draw_xpos;
186         gint draw_ypos;
187         gint draw_pass;
188
189         /* error pointer */
190         GError **error;
191 };
192
193 static int GetDataBlock (GifContext *, unsigned char *);
194
195 \f
196
197 #ifdef IO_GIFDEBUG
198 static int count = 0;
199 #endif
200
201 /* Returns TRUE if read is OK,
202  * FALSE if more memory is needed. */
203 static gboolean
204 gif_read (GifContext *context, guchar *buffer, size_t len)
205 {
206         gboolean retval;
207 #ifdef IO_GIFDEBUG
208         gint i;
209 #endif
210         if (context->file) {
211 #ifdef IO_GIFDEBUG
212                 count += len;
213                 g_print ("Fsize :%d\tcount :%d\t", len, count);
214 #endif
215                 retval = (fread(buffer, len, 1, context->file) != 0);
216
217                 if (!retval && ferror (context->file)) {
218                         gint save_errno = errno;
219                         g_set_error (context->error,
220                                      G_FILE_ERROR,
221                                      g_file_error_from_errno (save_errno),
222                                      _("Failure reading GIF: %s"), 
223                                      strerror (save_errno));
224                 }
225                 
226 #ifdef IO_GIFDEBUG
227                 if (len < 100) {
228                         for (i = 0; i < len; i++)
229                                 g_print ("%d ", buffer[i]);
230                 }
231                 g_print ("\n");
232 #endif
233                 
234                 return retval;
235         } else {
236 #ifdef IO_GIFDEBUG
237 /*              g_print ("\tlooking for %d bytes.  size == %d, ptr == %d\n", len, context->size, context->ptr); */
238 #endif
239                 if ((context->size - context->ptr) >= len) {
240 #ifdef IO_GIFDEBUG
241                         count += len;
242 #endif
243                         memcpy (buffer, context->buf + context->ptr, len);
244                         context->ptr += len;
245                         context->amount_needed = 0;
246 #ifdef IO_GIFDEBUG
247                         g_print ("Psize :%d\tcount :%d\t", len, count);
248                         if (len < 100) {
249                                 for (i = 0; i < len; i++)
250                                         g_print ("%d ", buffer[i]);
251                         }
252                         g_print ("\n");
253 #endif
254                         return TRUE;
255                 }
256                 context->amount_needed = len - (context->size - context->ptr);
257         }
258         return FALSE;
259 }
260
261 /* Changes the stage to be GIF_GET_COLORMAP */
262 static void
263 gif_set_get_colormap (GifContext *context)
264 {
265         context->global_colormap_size = 0;
266         context->state = GIF_GET_COLORMAP;
267 }
268
269 static void
270 gif_set_get_colormap2 (GifContext *context)
271 {
272         context->frame_colormap_size = 0;
273         context->state = GIF_GET_COLORMAP2;
274 }
275
276 static gint
277 gif_get_colormap (GifContext *context)
278 {
279         unsigned char rgb[3];
280
281         while (context->global_colormap_size < context->global_bit_pixel) {
282                 if (!gif_read (context, rgb, sizeof (rgb))) {
283                         return -1;
284                 }
285
286                 context->global_color_map[0][context->global_colormap_size] = rgb[0];
287                 context->global_color_map[1][context->global_colormap_size] = rgb[1];
288                 context->global_color_map[2][context->global_colormap_size] = rgb[2];
289
290                 if (context->global_colormap_size == context->background_index) {
291                         context->animation->bg_red = rgb[0];
292                         context->animation->bg_green = rgb[1];
293                         context->animation->bg_blue = rgb[2];
294                 }
295
296                 context->global_colormap_size ++;
297         }
298
299         return 0;
300 }
301
302
303 static gint
304 gif_get_colormap2 (GifContext *context)
305 {
306         unsigned char rgb[3];
307
308         while (context->frame_colormap_size < context->frame_bit_pixel) {
309                 if (!gif_read (context, rgb, sizeof (rgb))) {
310                         return -1;
311                 }
312
313                 context->frame_color_map[0][context->frame_colormap_size] = rgb[0];
314                 context->frame_color_map[1][context->frame_colormap_size] = rgb[1];
315                 context->frame_color_map[2][context->frame_colormap_size] = rgb[2];
316
317                 context->frame_colormap_size ++;
318         }
319
320         return 0;
321 }
322
323 /*
324  * in order for this function to work, we need to perform some black magic.
325  * We want to return -1 to let the calling function know, as before, that it needs
326  * more bytes.  If we return 0, we were able to successfully read all block->count bytes.
327  * Problem is, we don't want to reread block_count every time, so we check to see if
328  * context->block_count is 0 before we read in the function.
329  *
330  * As a result, context->block_count MUST be 0 the first time the get_data_block is called
331  * within a context, and cannot be 0 the second time it's called.
332  */
333
334 static int
335 get_data_block (GifContext *context,
336                 unsigned char *buf,
337                 gint *empty_block)
338 {
339
340         if (context->block_count == 0) {
341                 if (!gif_read (context, &context->block_count, 1)) {
342                         return -1;
343                 }
344         }
345
346         if (context->block_count == 0)
347                 if (empty_block) {
348                         *empty_block = TRUE;
349                         return 0;
350                 }
351
352         if (!gif_read (context, buf, context->block_count)) {
353                 return -1;
354         }
355
356         return 0;
357 }
358
359 static void
360 gif_set_get_extension (GifContext *context)
361 {
362         context->state = GIF_GET_EXTENSION;
363         context->extension_flag = TRUE;
364         context->extension_label = 0;
365         context->block_count = 0;
366         context->block_ptr = 0;
367 }
368
369 static int
370 gif_get_extension (GifContext *context)
371 {
372         gint retval;
373         gint empty_block = FALSE;
374
375         if (context->extension_flag) {
376                 if (context->extension_label == 0) {
377                         /* I guess bad things can happen if we have an extension of 0 )-: */
378                         /* I should look into this sometime */
379                         if (!gif_read (context, & context->extension_label , 1)) {
380                                 return -1;
381                         }
382                 }
383
384                 switch (context->extension_label) {
385                 case 0xf9:                      /* Graphic Control Extension */
386                         retval = get_data_block (context, (unsigned char *) context->block_buf, NULL);
387                         if (retval != 0)
388                                 return retval;
389
390                         if (context->frame == NULL) {
391                                 /* I only want to set the transparency if I haven't
392                                  * created the frame yet.
393                                  */
394                                 context->gif89.disposal = (context->block_buf[0] >> 2) & 0x7;
395                                 context->gif89.input_flag = (context->block_buf[0] >> 1) & 0x1;
396                                 context->gif89.delay_time = LM_to_uint (context->block_buf[1], context->block_buf[2]);
397                                 
398                                 if ((context->block_buf[0] & 0x1) != 0) {
399                                         context->gif89.transparent = context->block_buf[3];
400                                 } else {
401                                         context->gif89.transparent = -1;
402                                 }
403                         }
404
405                         /* Now we've successfully loaded this one, we continue on our way */
406                         context->block_count = 0;
407                         context->extension_flag = FALSE;
408                         break;
409                 case 0xff: /* application extension */
410                         if (!context->in_loop_extension) { 
411                                 retval = get_data_block (context, (unsigned char *) context->block_buf, NULL);
412                                 if (retval != 0)
413                                         return retval;
414                                 if (!strncmp (context->block_buf, "NETSCAPE2.0", 11) ||
415                                     !strncmp (context->block_buf, "ANIMEXTS1.0", 11)) {
416                                         context->in_loop_extension = TRUE;
417                                 }
418                                 context->block_count = 0;
419                         }
420                         if (context->in_loop_extension) {
421                                 do {
422                                         retval = get_data_block (context, (unsigned char *) context->block_buf, &empty_block);
423                                         if (retval != 0)
424                                                 return retval;
425                                         if (context->block_buf[0] == 0x01) {
426                                                 context->animation->loop = context->block_buf[1] + (context->block_buf[2] << 8);
427                                                 if (context->animation->loop != 0) 
428                                                         context->animation->loop++;
429                                         }
430                                         context->block_count = 0;
431                                 }
432                                 while (!empty_block);
433                                 context->in_loop_extension = FALSE;
434                                 context->extension_flag = FALSE;
435                                 return 0;
436                         }
437                         break;                          
438                 default:
439                         /* Unhandled extension */
440                         break;
441                 }
442         }
443         /* read all blocks, until I get an empty block, in case there was an extension I didn't know about. */
444         do {
445                 retval = get_data_block (context, (unsigned char *) context->block_buf, &empty_block);
446                 if (retval != 0)
447                         return retval;
448                 context->block_count = 0;
449         } while (!empty_block);
450
451         return 0;
452 }
453
454 static int ZeroDataBlock = FALSE;
455
456 static int
457 GetDataBlock (GifContext *context,
458               unsigned char *buf)
459 {
460 /*      unsigned char count; */
461
462         if (!gif_read (context, &context->block_count, 1)) {
463                 /*g_message (_("GIF: error in getting DataBlock size\n"));*/
464                 return -1;
465         }
466
467         ZeroDataBlock = context->block_count == 0;
468
469         if ((context->block_count != 0) && (!gif_read (context, buf, context->block_count))) {
470                 /*g_message (_("GIF: error in reading DataBlock\n"));*/
471                 return -1;
472         }
473
474         return context->block_count;
475 }
476
477
478 static void
479 gif_set_lzw_fill_buffer (GifContext *context)
480 {
481         context->block_count = 0;
482         context->old_state = context->state;
483         context->state = GIF_LZW_FILL_BUFFER;
484 }
485
486 static int
487 gif_lzw_fill_buffer (GifContext *context)
488 {
489         gint retval;
490
491         if (context->code_done) {
492                 if (context->code_curbit >= context->code_lastbit) {
493                         g_set_error (context->error,
494                                      GDK_PIXBUF_ERROR,
495                                      GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
496                                      _("GIF file was missing some data (perhaps it was truncated somehow?)"));
497
498                         return -2;
499                 }
500                 /* Is this supposed to be an error or what? */
501                 /* g_message ("trying to read more data after we've done stuff\n"); */
502                 g_set_error (context->error,
503                              GDK_PIXBUF_ERROR,
504                              GDK_PIXBUF_ERROR_FAILED,
505                              _("Internal error in the GIF loader (%s)"),
506                              G_STRLOC);
507                 
508                 return -2;
509         }
510
511         context->block_buf[0] = context->block_buf[context->code_last_byte - 2];
512         context->block_buf[1] = context->block_buf[context->code_last_byte - 1];
513
514         retval = get_data_block (context, &context->block_buf[2], NULL);
515
516         if (retval == -1)
517                 return -1;
518
519         if (context->block_count == 0)
520                 context->code_done = TRUE;
521
522         context->code_last_byte = 2 + context->block_count;
523         context->code_curbit = (context->code_curbit - context->code_lastbit) + 16;
524         context->code_lastbit = (2 + context->block_count) * 8;
525
526         context->state = context->old_state;
527         return 0;
528 }
529
530 static int
531 get_code (GifContext *context,
532           int   code_size)
533 {
534         int i, j, ret;
535
536         if ((context->code_curbit + code_size) >= context->code_lastbit){
537                 gif_set_lzw_fill_buffer (context);
538                 return -3;
539         }
540
541         ret = 0;
542         for (i = context->code_curbit, j = 0; j < code_size; ++i, ++j)
543                 ret |= ((context->block_buf[i / 8] & (1 << (i % 8))) != 0) << j;
544
545         context->code_curbit += code_size;
546
547         return ret;
548 }
549
550
551 static void
552 set_gif_lzw_clear_code (GifContext *context)
553 {
554         context->state = GIF_LZW_CLEAR_CODE;
555         context->lzw_code_pending = -1;
556 }
557
558 static int
559 gif_lzw_clear_code (GifContext *context)
560 {
561         gint code;
562
563         code = get_code (context, context->lzw_code_size);
564         if (code == -3)
565                 return -0;
566
567         context->lzw_firstcode = context->lzw_oldcode = code;
568         context->lzw_code_pending = code;
569         context->state = GIF_GET_LZW;
570         return 0;
571 }
572
573 #define CHECK_LZW_SP() G_STMT_START {                                           \
574         if ((guchar *)context->lzw_sp >=                                        \
575             (guchar *)context->lzw_stack + sizeof (context->lzw_stack)) {       \
576                  g_set_error (context->error,                                   \
577                              GDK_PIXBUF_ERROR,                                  \
578                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,                    \
579                              _("Stack overflow"));                              \
580                 return -2;                                                      \
581         }                                                                       \
582 } G_STMT_END
583
584 static int
585 lzw_read_byte (GifContext *context)
586 {
587         int code, incode;
588         gint retval;
589         gint my_retval;
590         register int i;
591
592         if (context->lzw_code_pending != -1) {
593                 retval = context->lzw_code_pending;
594                 context->lzw_code_pending = -1;
595                 return retval;
596         }
597
598         if (context->lzw_fresh) {
599                 context->lzw_fresh = FALSE;
600                 do {
601                         retval = get_code (context, context->lzw_code_size);
602                         if (retval < 0) {
603                                 return retval;
604                         }
605
606                         context->lzw_firstcode = context->lzw_oldcode = retval;
607                 } while (context->lzw_firstcode == context->lzw_clear_code);
608                 return context->lzw_firstcode;
609         }
610
611         if (context->lzw_sp > context->lzw_stack) {
612                 my_retval = *--(context->lzw_sp);
613                 return my_retval;
614         }
615
616         while ((code = get_code (context, context->lzw_code_size)) >= 0) {
617                 if (code == context->lzw_clear_code) {
618                         for (i = 0; i < context->lzw_clear_code; ++i) {
619                                 context->lzw_table[0][i] = 0;
620                                 context->lzw_table[1][i] = i;
621                         }
622                         for (; i < (1 << MAX_LZW_BITS); ++i)
623                                 context->lzw_table[0][i] = context->lzw_table[1][i] = 0;
624                         context->lzw_code_size = context->lzw_set_code_size + 1;
625                         context->lzw_max_code_size = 2 * context->lzw_clear_code;
626                         context->lzw_max_code = context->lzw_clear_code + 2;
627                         context->lzw_sp = context->lzw_stack;
628
629                         set_gif_lzw_clear_code (context);
630                         return -3;
631                 } else if (code == context->lzw_end_code) {
632                         int count;
633                         unsigned char buf[260];
634
635                         /*  FIXME - we should handle this case */
636                         g_set_error (context->error,
637                                      GDK_PIXBUF_ERROR,
638                                      GDK_PIXBUF_ERROR_FAILED,
639                                      _("GIF image loader cannot understand this image."));
640                         return -2;
641                         
642                         if (ZeroDataBlock) {
643                                 return -2;
644                         }
645
646                         while ((count = GetDataBlock (context, buf)) > 0)
647                                 ;
648
649                         if (count != 0) {
650                                 /*g_print (_("GIF: missing EOD in data stream (common occurence)"));*/
651                                 return -2;
652                         }
653                 }
654
655                 incode = code;
656
657                 if (code >= context->lzw_max_code) {
658                         CHECK_LZW_SP ();
659                         *(context->lzw_sp)++ = context->lzw_firstcode;
660                         code = context->lzw_oldcode;
661                 }
662
663                 while (code >= context->lzw_clear_code) {
664                         if (code >= (1 << MAX_LZW_BITS)) {
665                                 g_set_error (context->error,
666                                              GDK_PIXBUF_ERROR,
667                                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
668                                              _("Bad code encountered"));
669                                 return -2;
670                         }
671                         CHECK_LZW_SP ();
672                         *(context->lzw_sp)++ = context->lzw_table[1][code];
673
674                         if (code == context->lzw_table[0][code]) {
675                                 g_set_error (context->error,
676                                              GDK_PIXBUF_ERROR,
677                                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
678                                              _("Circular table entry in GIF file"));
679                                 return -2;
680                         }
681                         code = context->lzw_table[0][code];
682                 }
683
684                 CHECK_LZW_SP ();
685                 *(context->lzw_sp)++ = context->lzw_firstcode = context->lzw_table[1][code];
686
687                 if ((code = context->lzw_max_code) < (1 << MAX_LZW_BITS)) {
688                         context->lzw_table[0][code] = context->lzw_oldcode;
689                         context->lzw_table[1][code] = context->lzw_firstcode;
690                         ++context->lzw_max_code;
691                         if ((context->lzw_max_code >= context->lzw_max_code_size) &&
692                             (context->lzw_max_code_size < (1 << MAX_LZW_BITS))) {
693                                 context->lzw_max_code_size *= 2;
694                                 ++context->lzw_code_size;
695                         }
696                 }
697
698                 context->lzw_oldcode = incode;
699
700                 if (context->lzw_sp > context->lzw_stack) {
701                         my_retval = *--(context->lzw_sp);
702                         return my_retval;
703                 }
704         }
705         return code;
706 }
707
708 static void
709 gif_set_get_lzw (GifContext *context)
710 {
711         context->state = GIF_GET_LZW;
712         context->draw_xpos = 0;
713         context->draw_ypos = 0;
714         context->draw_pass = 0;
715 }
716
717 static void
718 gif_fill_in_pixels (GifContext *context, guchar *dest, gint offset, guchar v)
719 {
720         guchar *pixel = NULL;
721         guchar (*cmap)[MAXCOLORMAPSIZE];
722
723         if (context->frame_cmap_active)
724                 cmap = context->frame_color_map;
725         else
726                 cmap = context->global_color_map;
727         
728         if (context->gif89.transparent != -1) {
729                 pixel = dest + (context->draw_ypos + offset) * gdk_pixbuf_get_rowstride (context->frame->pixbuf) + context->draw_xpos * 4;
730                 *pixel = cmap [0][(guchar) v];
731                 *(pixel+1) = cmap [1][(guchar) v];
732                 *(pixel+2) = cmap [2][(guchar) v];
733                 *(pixel+3) = (guchar) ((v == context->gif89.transparent) ? 0 : 255);
734         } else {
735                 pixel = dest + (context->draw_ypos + offset) * gdk_pixbuf_get_rowstride (context->frame->pixbuf) + context->draw_xpos * 3;
736                 *pixel = cmap [0][(guchar) v];
737                 *(pixel+1) = cmap [1][(guchar) v];
738                 *(pixel+2) = cmap [2][(guchar) v];
739         }
740 }
741
742
743 /* only called if progressive and interlaced */
744 static void
745 gif_fill_in_lines (GifContext *context, guchar *dest, guchar v)
746 {
747         switch (context->draw_pass) {
748         case 0:
749                 if (context->draw_ypos > 4) {
750                         gif_fill_in_pixels (context, dest, -4, v);
751                         gif_fill_in_pixels (context, dest, -3, v);
752                 }
753                 if (context->draw_ypos < (context->frame_height - 4)) {
754                         gif_fill_in_pixels (context, dest, 3, v);
755                         gif_fill_in_pixels (context, dest, 4, v);
756                 }
757                 /* we don't need a break here.  We draw the outer pixels first, then the
758                  * inner ones, then the innermost ones.  case 0 needs to draw all 3 bands.
759                  * case 1, just the last two, and case 2 just draws the last one*/
760         case 1:
761                 if (context->draw_ypos > 2)
762                         gif_fill_in_pixels (context, dest, -2, v);
763                 if (context->draw_ypos < (context->frame_height - 2))
764                         gif_fill_in_pixels (context, dest, 2, v);
765                 /* no break as above. */
766         case 2:
767                 if (context->draw_ypos > 1)
768                         gif_fill_in_pixels (context, dest, -1, v);
769                 if (context->draw_ypos < (context->frame_height - 1))
770                         gif_fill_in_pixels (context, dest, 1, v);
771         case 3:
772         default:
773                 break;
774         }
775 }
776
777 /* Clips a rectancle to the base dimensions. Returns TRUE if the clipped rectangle is non-empty. */
778 static gboolean
779 clip_frame (GifContext *context, 
780             gint       *x, 
781             gint       *y, 
782             gint       *width, 
783             gint       *height)
784 {
785         gint orig_x, orig_y;
786         
787         orig_x = *x;
788         orig_y = *y;
789         *x = MAX (0, *x);
790         *y = MAX (0, *y);
791         *width = MIN (context->width, orig_x + *width) - *x;
792         *height = MIN (context->height, orig_y + *height) - *y;
793
794         if (*width > 0 && *height > 0)
795                 return TRUE;
796
797         /* The frame is completely off-bounds */
798
799         *x = 0;
800         *y = 0;
801         *width = 0;
802         *height = 0;
803
804         return FALSE;
805 }
806
807 /* Call update_func on the given rectangle, unless it is completely off-bounds */
808 static void
809 maybe_update (GifContext *context,
810               gint        x,
811               gint        y,
812               gint        width,
813               gint        height)
814 {
815         if (clip_frame (context, &x, &y, &width, &height))
816                 (*context->update_func) (context->frame->pixbuf, 
817                                          x, y, width, height,
818                                          context->user_data);
819 }
820
821 static int
822 gif_get_lzw (GifContext *context)
823 {
824         guchar *dest, *temp;
825         gint lower_bound, upper_bound; /* bounds for emitting the area_updated signal */
826         gboolean bound_flag;
827         gint first_pass; /* bounds for emitting the area_updated signal */
828         gint v;
829
830         if (context->frame == NULL) {
831                 context->frame = g_new (GdkPixbufFrame, 1);
832
833                 context->frame->composited = NULL;
834                 context->frame->revert = NULL;
835                 
836                 if (context->frame_len == 0 || context->frame_height == 0) {
837                         /* An empty frame, we just output a single transparent
838                          * pixel at (0, 0).
839                          */
840                         context->x_offset = 0;
841                         context->y_offset = 0;
842                         context->frame_len = 1;
843                         context->frame_height = 1;
844                         context->frame->pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8, 1, 1);
845                         if (context->frame->pixbuf) {
846                                 guchar *pixels;
847
848                                 pixels = gdk_pixbuf_get_pixels (context->frame->pixbuf);
849                                 pixels[0] = 0;
850                                 pixels[1] = 0;
851                                 pixels[2] = 0;
852                                 pixels[3] = 0;
853                         }
854                 } else
855                         context->frame->pixbuf =
856                                 gdk_pixbuf_new (GDK_COLORSPACE_RGB,
857                                                 TRUE,
858                                                 8,
859                                                 context->frame_len,
860                                                 context->frame_height);
861                 if (!context->frame->pixbuf) {
862                         g_free (context->frame);
863                         g_set_error (context->error,
864                                      GDK_PIXBUF_ERROR,
865                                      GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
866                                      _("Not enough memory to load GIF file"));
867                         return -2;
868                 }
869
870                 context->frame->x_offset = context->x_offset;
871                 context->frame->y_offset = context->y_offset;
872                 context->frame->need_recomposite = TRUE;
873                 
874                 /* GIF delay is in hundredths, we want thousandths */
875                 context->frame->delay_time = context->gif89.delay_time * 10;
876
877                 /* Some GIFs apparently have delay time of 0,
878                  * that crashes everything so set it to "fast".
879                  * Also, timeouts less than 20 or so just lock up
880                  * the app or make the animation choppy, so fix them.
881                  */
882                 if (context->frame->delay_time < 20)
883                         context->frame->delay_time = 20; /* 20 = "fast" */
884                 
885                 context->frame->elapsed = context->animation->total_time;
886                 context->animation->total_time += context->frame->delay_time;                
887                 
888                 switch (context->gif89.disposal) {
889                 case 0:
890                 case 1:
891                         context->frame->action = GDK_PIXBUF_FRAME_RETAIN;
892                         break;
893                 case 2:
894                         context->frame->action = GDK_PIXBUF_FRAME_DISPOSE;
895                         break;
896                 case 3:
897                         context->frame->action = GDK_PIXBUF_FRAME_REVERT;
898                         break;
899                 default:
900                         context->frame->action = GDK_PIXBUF_FRAME_RETAIN;
901                         break;
902                 }
903
904                 context->frame->bg_transparent = (context->gif89.transparent == context->background_index);
905                 
906                 context->animation->n_frames ++;
907                 context->animation->frames = g_list_append (context->animation->frames, context->frame);
908
909                 /* Only call prepare_func for the first frame */
910                 if (context->animation->frames->next == NULL) { 
911                         if (context->animation->width == 0 )
912                                 context->animation->width = gdk_pixbuf_get_width(context->frame->pixbuf);
913                         if (context->animation->height == 0)
914                                 context->animation->height = gdk_pixbuf_get_height (context->frame->pixbuf);
915
916                         if (context->prepare_func)
917                                 (* context->prepare_func) (context->frame->pixbuf,
918                                                            GDK_PIXBUF_ANIMATION (context->animation),
919                                                            context->user_data);
920                 } else {
921                         /* Otherwise init frame with last frame */
922                         GList *link;
923                         GdkPixbufFrame *prev_frame;
924                         gint x, y, w, h;
925                         
926                         link = g_list_find (context->animation->frames, context->frame);
927
928                         prev_frame = link->prev->data;
929
930                         gdk_pixbuf_gif_anim_frame_composite (context->animation, prev_frame);
931
932                         /* Composite failed */
933                         if (prev_frame->composited == NULL) {
934                                 GdkPixbufFrame *frame = NULL;
935                                 link = g_list_first (context->animation->frames);
936                                 while (link != NULL) {
937                                         frame = (GdkPixbufFrame *)link->data;
938                                         if (frame != NULL) {
939                                                 if (frame->pixbuf != NULL)
940                                                         g_object_unref (frame->pixbuf);
941                                                 if (frame->composited != NULL)
942                                                         g_object_unref (frame->composited);
943                                                 if (frame->revert != NULL)
944                                                         g_object_unref (frame->revert);
945                                                 g_free (frame);
946                                         }
947                                         link = link->next;
948                                 }
949                                 
950                                 g_list_free (context->animation->frames);
951                                 context->animation->frames = NULL;
952                                 
953                                 g_set_error (context->error,
954                                              GDK_PIXBUF_ERROR,
955                                              GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
956                                              _("Not enough memory to composite a frame in GIF file"));
957                                 return -2;
958                         }
959                     
960                         x = context->frame->x_offset;
961                         y = context->frame->y_offset;
962                         w = gdk_pixbuf_get_width (context->frame->pixbuf);
963                         h = gdk_pixbuf_get_height (context->frame->pixbuf);
964                         if (clip_frame (context, &x, &y, &w, &h))
965                                 gdk_pixbuf_copy_area (prev_frame->composited,
966                                                       x, y, w, h,
967                                                       context->frame->pixbuf,
968                                                       0, 0);
969                 }
970         }
971
972         dest = gdk_pixbuf_get_pixels (context->frame->pixbuf);
973
974         bound_flag = FALSE;
975         lower_bound = upper_bound = context->draw_ypos;
976         first_pass = context->draw_pass;
977
978         while (TRUE) {
979                 guchar (*cmap)[MAXCOLORMAPSIZE];
980
981                 if (context->frame_cmap_active)
982                         cmap = context->frame_color_map;
983                 else
984                         cmap = context->global_color_map;
985                 
986                 v = lzw_read_byte (context);
987                 if (v < 0) {
988                         goto finished_data;
989                 }
990                 bound_flag = TRUE;
991
992                 g_assert (gdk_pixbuf_get_has_alpha (context->frame->pixbuf));
993                 
994                 temp = dest + context->draw_ypos * gdk_pixbuf_get_rowstride (context->frame->pixbuf) + context->draw_xpos * 4;
995                 *temp = cmap [0][(guchar) v];
996                 *(temp+1) = cmap [1][(guchar) v];
997                 *(temp+2) = cmap [2][(guchar) v];
998                 *(temp+3) = (guchar) ((v == context->gif89.transparent) ? 0 : 255);
999
1000                 if (context->prepare_func && context->frame_interlace)
1001                         gif_fill_in_lines (context, dest, v);
1002
1003                 context->draw_xpos++;
1004                 
1005                 if (context->draw_xpos == context->frame_len) {
1006                         context->draw_xpos = 0;
1007                         if (context->frame_interlace) {
1008                                 switch (context->draw_pass) {
1009                                 case 0:
1010                                 case 1:
1011                                         context->draw_ypos += 8;
1012                                         break;
1013                                 case 2:
1014                                         context->draw_ypos += 4;
1015                                         break;
1016                                 case 3:
1017                                         context->draw_ypos += 2;
1018                                         break;
1019                                 }
1020
1021                                 if (context->draw_ypos >= context->frame_height) {
1022                                         context->draw_pass++;
1023                                         switch (context->draw_pass) {
1024                                         case 1:
1025                                                 context->draw_ypos = 4;
1026                                                 break;
1027                                         case 2:
1028                                                 context->draw_ypos = 2;
1029                                                 break;
1030                                         case 3:
1031                                                 context->draw_ypos = 1;
1032                                                 break;
1033                                         default:
1034                                                 goto done;
1035                                         }
1036                                 }
1037                         } else {
1038                                 context->draw_ypos++;
1039                         }
1040                         if (context->draw_pass != first_pass) {
1041                                 if (context->draw_ypos > lower_bound) {
1042                                         lower_bound = 0;
1043                                         upper_bound = context->frame_height;
1044                                 } else {
1045                                         
1046                                 }
1047                         } else
1048                                 upper_bound = context->draw_ypos;
1049                 }
1050                 if (context->draw_ypos >= context->frame_height)
1051                         break;
1052         }
1053
1054  done:
1055
1056         context->state = GIF_GET_NEXT_STEP;
1057
1058         v = 0;
1059
1060  finished_data:
1061         
1062         if (bound_flag)
1063                 context->frame->need_recomposite = TRUE;
1064         
1065         if (bound_flag && context->update_func) {
1066                 if (lower_bound <= upper_bound && first_pass == context->draw_pass) {
1067                         maybe_update (context, 
1068                                       context->frame->x_offset,
1069                                       context->frame->y_offset + lower_bound,
1070                                       gdk_pixbuf_get_width (context->frame->pixbuf),
1071                                       upper_bound - lower_bound);
1072                 } else {
1073                         if (lower_bound <= upper_bound) {
1074                                 maybe_update (context,
1075                                               context->frame->x_offset,
1076                                               context->frame->y_offset,
1077                                               gdk_pixbuf_get_width (context->frame->pixbuf),
1078                                               gdk_pixbuf_get_height (context->frame->pixbuf));
1079                         } else {
1080                                 maybe_update (context,
1081                                               context->frame->x_offset,
1082                                               context->frame->y_offset,
1083                                               gdk_pixbuf_get_width (context->frame->pixbuf),
1084                                               upper_bound);
1085                                 maybe_update (context,
1086                                               context->frame->x_offset,
1087                                               context->frame->y_offset + lower_bound,
1088                                               gdk_pixbuf_get_width (context->frame->pixbuf),
1089                                               gdk_pixbuf_get_height (context->frame->pixbuf) - lower_bound);
1090                         }
1091                 }
1092         }
1093
1094         if (context->state == GIF_GET_NEXT_STEP) {
1095                 /* Will be freed with context->animation, we are just
1096                  * marking that we're done with it (no current frame)
1097                  */
1098                 context->frame = NULL;
1099                 context->frame_cmap_active = FALSE;
1100
1101                 if (context->stop_after_first_frame)
1102                         context->state =  GIF_DONE;
1103         }
1104         
1105         return v;
1106 }
1107
1108 static void
1109 gif_set_prepare_lzw (GifContext *context)
1110 {
1111         context->state = GIF_PREPARE_LZW;
1112         context->lzw_code_pending = -1;
1113 }
1114 static int
1115 gif_prepare_lzw (GifContext *context)
1116 {
1117         gint i;
1118
1119         if (!gif_read (context, &(context->lzw_set_code_size), 1)) {
1120                 /*g_message (_("GIF: EOF / read error on image data\n"));*/
1121                 return -1;
1122         }
1123         
1124         if (context->lzw_set_code_size > MAX_LZW_BITS) {
1125                 g_set_error (context->error,
1126                              GDK_PIXBUF_ERROR,
1127                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
1128                              _("GIF image is corrupt (incorrect LZW compression)"));
1129                 return -2;
1130         }
1131
1132         context->lzw_code_size = context->lzw_set_code_size + 1;
1133         context->lzw_clear_code = 1 << context->lzw_set_code_size;
1134         context->lzw_end_code = context->lzw_clear_code + 1;
1135         context->lzw_max_code_size = 2 * context->lzw_clear_code;
1136         context->lzw_max_code = context->lzw_clear_code + 2;
1137         context->lzw_fresh = TRUE;
1138         context->code_curbit = 0;
1139         context->code_lastbit = 0;
1140         context->code_last_byte = 0;
1141         context->code_done = FALSE;
1142
1143         g_assert (context->lzw_clear_code <= 
1144                   G_N_ELEMENTS (context->lzw_table[0]));
1145
1146         for (i = 0; i < context->lzw_clear_code; ++i) {
1147                 context->lzw_table[0][i] = 0;
1148                 context->lzw_table[1][i] = i;
1149         }
1150         for (; i < (1 << MAX_LZW_BITS); ++i)
1151                 context->lzw_table[0][i] = context->lzw_table[1][0] = 0;
1152
1153         context->lzw_sp = context->lzw_stack;
1154         gif_set_get_lzw (context);
1155
1156         return 0;
1157 }
1158
1159 /* needs 13 bytes to proceed. */
1160 static gint
1161 gif_init (GifContext *context)
1162 {
1163         unsigned char buf[16];
1164         char version[4];
1165
1166         if (!gif_read (context, buf, 6)) {
1167                 /* Unable to read magic number,
1168                  * gif_read() should have set error
1169                  */
1170                 return -1;
1171         }
1172
1173         if (strncmp ((char *) buf, "GIF", 3) != 0) {
1174                 /* Not a GIF file */
1175                 g_set_error (context->error,
1176                              GDK_PIXBUF_ERROR,
1177                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
1178                              _("File does not appear to be a GIF file"));
1179                 return -2;
1180         }
1181
1182         strncpy (version, (char *) buf + 3, 3);
1183         version[3] = '\0';
1184
1185         if ((strcmp (version, "87a") != 0) && (strcmp (version, "89a") != 0)) {
1186                 /* bad version number, not '87a' or '89a' */
1187                 g_set_error (context->error,
1188                              GDK_PIXBUF_ERROR,
1189                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
1190                              _("Version %s of the GIF file format is not supported"),
1191                              version);
1192                 return -2;
1193         }
1194
1195         /* read the screen descriptor */
1196         if (!gif_read (context, buf, 7)) {
1197                 /* Failed to read screen descriptor, error set */
1198                 return -1;
1199         }
1200
1201         context->width = LM_to_uint (buf[0], buf[1]);
1202         context->height = LM_to_uint (buf[2], buf[3]);
1203         /* The 4th byte is
1204          * high bit: whether to use the background index
1205          * next 3:   color resolution
1206          * next:     whether colormap is sorted by priority of allocation
1207          * last 3:   size of colormap
1208          */
1209         context->global_bit_pixel = 2 << (buf[4] & 0x07);
1210         context->global_color_resolution = (((buf[4] & 0x70) >> 3) + 1);
1211         context->has_global_cmap = (buf[4] & 0x80) != 0;
1212         context->background_index = buf[5];
1213         context->aspect_ratio = buf[6];
1214
1215         /* Use background of transparent black as default, though if
1216          * one isn't set explicitly no one should ever use it.
1217          */
1218         context->animation->bg_red = 0;
1219         context->animation->bg_green = 0;
1220         context->animation->bg_blue = 0;
1221
1222         context->animation->width = context->width;
1223         context->animation->height = context->height;
1224
1225         if (context->has_global_cmap) {
1226                 gif_set_get_colormap (context);
1227         } else {
1228                 context->state = GIF_GET_NEXT_STEP;
1229         }
1230
1231 #ifdef DUMP_IMAGE_DETAILS
1232         g_print (">Image width: %d height: %d global_cmap: %d background: %d\n",
1233                  context->width, context->height, context->has_global_cmap, context->background_index);
1234 #endif
1235         
1236         return 0;
1237 }
1238
1239 static void
1240 gif_set_get_frame_info (GifContext *context)
1241 {
1242         context->state = GIF_GET_FRAME_INFO;
1243 }
1244
1245 static gint
1246 gif_get_frame_info (GifContext *context)
1247 {
1248         unsigned char buf[9];
1249         
1250         if (!gif_read (context, buf, 9)) {
1251                 return -1;
1252         }
1253         
1254         /* Okay, we got all the info we need.  Lets record it */
1255         context->frame_len = LM_to_uint (buf[4], buf[5]);
1256         context->frame_height = LM_to_uint (buf[6], buf[7]);
1257         context->x_offset = LM_to_uint (buf[0], buf[1]);
1258         context->y_offset = LM_to_uint (buf[2], buf[3]);
1259
1260         if (context->animation->frames == NULL &&
1261             context->gif89.disposal == 3) {
1262                 /* First frame can't have "revert to previous" as its
1263                  * dispose mode. Silently use "retain" instead.
1264                  */
1265                 context->gif89.disposal = 0;
1266         }
1267
1268         context->frame_interlace = BitSet (buf[8], INTERLACE);
1269
1270 #ifdef DUMP_IMAGE_DETAILS
1271         g_print (">width: %d height: %d xoffset: %d yoffset: %d disposal: %d delay: %d transparent: %d interlace: %d\n",
1272                  context->frame_len, context->frame_height, context->x_offset, context->y_offset,
1273                  context->gif89.disposal, context->gif89.delay_time, context->gif89.transparent, context->frame_interlace);
1274 #endif
1275         
1276         if (BitSet (buf[8], LOCALCOLORMAP)) {
1277
1278 #ifdef DUMP_IMAGE_DETAILS
1279                 g_print (">has local colormap\n");
1280 #endif
1281                 
1282                 /* Does this frame have it's own colormap. */
1283                 /* really only relevant when looking at the first frame
1284                  * of an animated gif. */
1285                 /* if it does, we need to re-read in the colormap,
1286                  * the gray_scale, and the bit_pixel */
1287                 context->frame_cmap_active = TRUE;
1288                 context->frame_bit_pixel = 1 << ((buf[8] & 0x07) + 1);
1289                 gif_set_get_colormap2 (context);
1290                 return 0;
1291         }
1292
1293         if (!context->has_global_cmap) {
1294                 context->state = GIF_DONE;
1295                 
1296                 g_set_error (context->error,
1297                              GDK_PIXBUF_ERROR,
1298                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
1299                              _("GIF image has no global colormap, and a frame inside it has no local colormap."));
1300                 
1301                 return -2;
1302         }
1303
1304         gif_set_prepare_lzw (context);
1305         return 0;
1306
1307 }
1308
1309 static gint
1310 gif_get_next_step (GifContext *context)
1311 {
1312         unsigned char c;
1313         while (TRUE) {
1314                 if (!gif_read (context, &c, 1)) {
1315                         return -1;
1316                 }
1317                 if (c == ';') {
1318                         /* GIF terminator */
1319                         /* hmm.  Not 100% sure what to do about this.  Should
1320                          * i try to return a blank image instead? */
1321                         context->state = GIF_DONE;
1322                         return 0;
1323                 }
1324
1325                 if (c == '!') {
1326                         /* Check the extension */
1327                         gif_set_get_extension (context);
1328                         return 0;
1329                 }
1330
1331                 /* look for frame */
1332                 if (c != ',') {
1333                         /* Not a valid start character */
1334                         continue;
1335                 }
1336                 /* load the frame */
1337                 gif_set_get_frame_info (context);
1338                 return 0;
1339         }
1340 }
1341
1342
1343 #define LOG(x) /* g_print ("%d: %s\n", __LINE__, x); */
1344
1345 static gint
1346 gif_main_loop (GifContext *context)
1347 {
1348         gint retval = 0;
1349
1350         do {
1351                 switch (context->state) {
1352                 case GIF_START:
1353                         LOG("start\n");
1354                         retval = gif_init (context);
1355                         break;
1356
1357                 case GIF_GET_COLORMAP:
1358                         LOG("get_colormap\n");
1359                         retval = gif_get_colormap (context);
1360                         if (retval == 0)
1361                                 context->state = GIF_GET_NEXT_STEP;
1362                         break;
1363
1364                 case GIF_GET_NEXT_STEP:
1365                         LOG("next_step\n");
1366                         retval = gif_get_next_step (context);
1367                         break;
1368
1369                 case GIF_GET_FRAME_INFO:
1370                         LOG("frame_info\n");
1371                         retval = gif_get_frame_info (context);
1372                         break;
1373
1374                 case GIF_GET_EXTENSION:
1375                         LOG("get_extension\n");
1376                         retval = gif_get_extension (context);
1377                         if (retval == 0)
1378                                 context->state = GIF_GET_NEXT_STEP;
1379                         break;
1380
1381                 case GIF_GET_COLORMAP2:
1382                         LOG("get_colormap2\n");
1383                         retval = gif_get_colormap2 (context);
1384                         if (retval == 0)
1385                                 gif_set_prepare_lzw (context);
1386                         break;
1387
1388                 case GIF_PREPARE_LZW:
1389                         LOG("prepare_lzw\n");
1390                         retval = gif_prepare_lzw (context);
1391                         break;
1392
1393                 case GIF_LZW_FILL_BUFFER:
1394                         LOG("fill_buffer\n");
1395                         retval = gif_lzw_fill_buffer (context);
1396                         break;
1397
1398                 case GIF_LZW_CLEAR_CODE:
1399                         LOG("clear_code\n");
1400                         retval = gif_lzw_clear_code (context);
1401                         break;
1402
1403                 case GIF_GET_LZW:
1404                         LOG("get_lzw\n");
1405                         retval = gif_get_lzw (context);
1406                         break;
1407
1408                 case GIF_DONE:
1409                         LOG("done\n");
1410                 default:
1411                         retval = 0;
1412                         goto done;
1413                 };
1414         } while ((retval == 0) || (retval == -3));
1415  done:
1416         return retval;
1417 }
1418
1419 static GifContext *
1420 new_context (void)
1421 {
1422         GifContext *context;
1423
1424         context = g_try_malloc (sizeof (GifContext));
1425         if (context == NULL)
1426                 return NULL;
1427
1428         memset (context, 0, sizeof (GifContext));
1429         
1430         context->animation = g_object_new (GDK_TYPE_PIXBUF_GIF_ANIM, NULL);
1431         context->frame = NULL;
1432         context->file = NULL;
1433         context->state = GIF_START;
1434         context->prepare_func = NULL;
1435         context->update_func = NULL;
1436         context->user_data = NULL;
1437         context->buf = NULL;
1438         context->amount_needed = 0;
1439         context->gif89.transparent = -1;
1440         context->gif89.delay_time = -1;
1441         context->gif89.input_flag = -1;
1442         context->gif89.disposal = -1;
1443         context->animation->loop = 1;
1444         context->in_loop_extension = FALSE;
1445         context->stop_after_first_frame = FALSE;
1446
1447         return context;
1448 }
1449 /* Shared library entry point */
1450 static GdkPixbuf *
1451 gdk_pixbuf__gif_image_load (FILE *file, GError **error)
1452 {
1453         GifContext *context;
1454         GdkPixbuf *pixbuf;
1455
1456         g_return_val_if_fail (file != NULL, NULL);
1457
1458         context = new_context ();
1459
1460         if (context == NULL) {
1461                 g_set_error (error,
1462                              GDK_PIXBUF_ERROR,
1463                              GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
1464                              _("Not enough memory to load GIF file"));
1465                 return NULL;
1466         }
1467         
1468         context->file = file;
1469         context->error = error;
1470         context->stop_after_first_frame = TRUE;
1471
1472         if (gif_main_loop (context) == -1 || context->animation->frames == NULL) {
1473                 if (context->error && *(context->error) == NULL)
1474                         g_set_error (context->error,
1475                                      GDK_PIXBUF_ERROR,
1476                                      GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
1477                                      _("GIF file was missing some data (perhaps it was truncated somehow?)"));
1478         }
1479         
1480         pixbuf = gdk_pixbuf_animation_get_static_image (GDK_PIXBUF_ANIMATION (context->animation));
1481
1482         if (pixbuf)
1483                 g_object_ref (pixbuf);
1484
1485         g_object_unref (context->animation);
1486         
1487         g_free (context->buf);
1488         g_free (context);
1489  
1490         return pixbuf;
1491 }
1492
1493 static gpointer
1494 gdk_pixbuf__gif_image_begin_load (GdkPixbufModuleSizeFunc size_func,
1495                                   GdkPixbufModulePreparedFunc prepare_func,
1496                                   GdkPixbufModuleUpdatedFunc update_func,
1497                                   gpointer user_data,
1498                                   GError **error)
1499 {
1500         GifContext *context;
1501
1502 #ifdef IO_GIFDEBUG
1503         count = 0;
1504 #endif
1505         context = new_context ();
1506
1507         if (context == NULL) {
1508                 g_set_error (error,
1509                              GDK_PIXBUF_ERROR,
1510                              GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
1511                              _("Not enough memory to load GIF file"));
1512                 return NULL;
1513         }
1514         
1515         context->error = error;
1516         context->prepare_func = prepare_func;
1517         context->update_func = update_func;
1518         context->user_data = user_data;
1519
1520         return (gpointer) context;
1521 }
1522
1523 static gboolean
1524 gdk_pixbuf__gif_image_stop_load (gpointer data, GError **error)
1525 {
1526         GifContext *context = (GifContext *) data;
1527         gboolean retval = TRUE;
1528         
1529         if (context->state != GIF_DONE || context->animation->frames == NULL) {
1530                 g_set_error (error,
1531                              GDK_PIXBUF_ERROR,
1532                              GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
1533                              _("GIF image was truncated or incomplete."));
1534
1535                 retval = FALSE;
1536         }
1537         
1538         g_object_unref (context->animation);
1539
1540         g_free (context->buf);
1541         g_free (context);
1542
1543         return retval;
1544 }
1545
1546 static gboolean
1547 gdk_pixbuf__gif_image_load_increment (gpointer data,
1548                                       const guchar *buf, guint size,
1549                                       GError **error)
1550 {
1551         gint retval;
1552         GifContext *context = (GifContext *) data;
1553
1554         context->error = error;
1555         
1556         if (context->amount_needed == 0) {
1557                 /* we aren't looking for some bytes. */
1558                 /* we can use buf now, but we don't want to keep it around at all.
1559                  * it will be gone by the end of the call. */
1560                 context->buf = (guchar*) buf; /* very dubious const cast */
1561                 context->ptr = 0;
1562                 context->size = size;
1563         } else {
1564                 /* we need some bytes */
1565                 if (size < context->amount_needed) {
1566                         context->amount_needed -= size;
1567                         /* copy it over and return */
1568                         memcpy (context->buf + context->size, buf, size);
1569                         context->size += size;
1570                         return TRUE;
1571                 } else if (size == context->amount_needed) {
1572                         memcpy (context->buf + context->size, buf, size);
1573                         context->size += size;
1574                 } else {
1575                         context->buf = g_realloc (context->buf, context->size + size);
1576                         memcpy (context->buf + context->size, buf, size);
1577                         context->size += size;
1578                 }
1579         }
1580
1581         retval = gif_main_loop (context);
1582
1583         if (retval == -2) {
1584                 if (context->buf == buf)
1585                         context->buf = NULL;
1586                 return FALSE;
1587         }
1588         if (retval == -1) {
1589                 /* we didn't have enough memory */
1590                 /* prepare for the next image_load_increment */
1591                 if (context->buf == buf) {
1592                         g_assert (context->size == size);
1593                         context->buf = g_new (guchar, context->amount_needed + (context->size - context->ptr));
1594                         memcpy (context->buf, buf + context->ptr, context->size - context->ptr);
1595                 } else {
1596                         /* copy the left overs to the begining of the buffer */
1597                         /* and realloc the memory */
1598                         memmove (context->buf, context->buf + context->ptr, context->size - context->ptr);
1599                         context->buf = g_realloc (context->buf, context->amount_needed + (context->size - context->ptr));
1600                 }
1601                 context->size = context->size - context->ptr;
1602                 context->ptr = 0;
1603         } else {
1604                 /* we are prolly all done */
1605                 if (context->buf == buf)
1606                         context->buf = NULL;
1607         }
1608         return TRUE;
1609 }
1610
1611 static GdkPixbufAnimation *
1612 gdk_pixbuf__gif_image_load_animation (FILE *file,
1613                                       GError **error)
1614 {
1615         GifContext *context;
1616         GdkPixbufAnimation *animation;
1617
1618         g_return_val_if_fail (file != NULL, NULL);
1619
1620         context = new_context ();
1621
1622         if (context == NULL) {
1623                 g_set_error (error,
1624                              GDK_PIXBUF_ERROR,
1625                              GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
1626                              _("Not enough memory to load GIF file"));
1627                 return NULL;
1628         }
1629         
1630         context->error = error;
1631         context->file = file;
1632
1633         if (gif_main_loop (context) == -1 || context->animation->frames == NULL) {
1634                 if (context->error && *(context->error) == NULL)
1635                         g_set_error (context->error,
1636                                      GDK_PIXBUF_ERROR,
1637                                      GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
1638                                      _("GIF file was missing some data (perhaps it was truncated somehow?)"));
1639
1640                 g_object_unref (context->animation);
1641                 context->animation = NULL;
1642         }
1643
1644         if (context->animation)
1645                 animation = GDK_PIXBUF_ANIMATION (context->animation);
1646         else
1647                 animation = NULL;
1648
1649         if (context->error && *(context->error))
1650                 g_print ("%s\n", (*(context->error))->message);
1651         
1652         g_free (context->buf);
1653         g_free (context);
1654         return animation;
1655 }
1656
1657 #ifndef INCLUDE_gif
1658 #define MODULE_ENTRY(type,function) function
1659 #else
1660 #define MODULE_ENTRY(type,function) _gdk_pixbuf__ ## type ## _ ## function
1661 #endif
1662
1663 void
1664 MODULE_ENTRY (gif, fill_vtable) (GdkPixbufModule *module)
1665 {
1666         module->load = gdk_pixbuf__gif_image_load;
1667         module->begin_load = gdk_pixbuf__gif_image_begin_load;
1668         module->stop_load = gdk_pixbuf__gif_image_stop_load;
1669         module->load_increment = gdk_pixbuf__gif_image_load_increment;
1670         module->load_animation = gdk_pixbuf__gif_image_load_animation;
1671 }
1672
1673 void
1674 MODULE_ENTRY (gif, fill_info) (GdkPixbufFormat *info)
1675 {
1676         static GdkPixbufModulePattern signature[] = {
1677                 { "GIF8", NULL, 100 },
1678                 { NULL, NULL, 0 }
1679         };
1680         static gchar * mime_types[] = {
1681                 "image/gif",
1682                 NULL
1683         };
1684         static gchar * extensions[] = {
1685                 "gif",
1686                 NULL
1687         };
1688
1689         info->name = "gif";
1690         info->signature = signature;
1691         info->description = N_("The GIF image format");
1692         info->mime_types = mime_types;
1693         info->extensions = extensions;
1694         info->flags = GDK_PIXBUF_FORMAT_THREADSAFE;
1695         info->license = "LGPL";
1696 }