]> Pileus Git - ~andy/gtk/blob - gdk-pixbuf/io-xbm.c
05c45ac97c7a11f7b37daebda3b78ee588335140
[~andy/gtk] / gdk-pixbuf / io-xbm.c
1 /* -*- mode: C; c-file-style: "linux" -*- */
2 /* GdkPixbuf library - XBM image loader
3  *
4  * Copyright (C) 1999 Mark Crichton
5  * Copyright (C) 1999 The Free Software Foundation
6  * Copyright (C) 2001 Eazel, Inc.
7  *
8  * Authors: Mark Crichton <crichton@gimp.org>
9  *          Federico Mena-Quintero <federico@gimp.org>
10  *          Jonathan Blandford <jrb@redhat.com>
11  *          John Harper <jsh@eazel.com>
12  *
13  * This library is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU Library General Public
15  * License as published by the Free Software Foundation; either
16  * version 2 of the License, or (at your option) any later version.
17  *
18  * This library is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21  * Library General Public License for more details.
22  *
23  * You should have received a copy of the GNU Library General Public
24  * License along with this library; if not, write to the
25  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26  * Boston, MA 02111-1307, USA.
27  */
28
29 /* Following code adapted from io-tiff.c, which was ``(almost) blatantly
30    ripped from Imlib'' */
31
32 #include "config.h"
33 #include <stdlib.h>
34 #include <string.h>
35 #ifdef HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif
38 #include <stdio.h>
39 #include <errno.h>
40 #include "gdk-pixbuf-private.h"
41 #include "gdk-pixbuf-io.h"
42 #include <glib/gstdio.h>
43 \f
44
45 typedef struct _XBMData XBMData;
46 struct _XBMData
47 {
48         GdkPixbufModulePreparedFunc prepare_func;
49         GdkPixbufModuleUpdatedFunc update_func;
50         gpointer user_data;
51
52         gchar *tempname;
53         FILE *file;
54         gboolean all_okay;
55 };
56
57 \f
58 /* xbm parser borrowed from xc/lib/X11/RdBitF.c */
59
60 #define MAX_SIZE 255
61
62 /* shared data for the image read/parse logic */
63 static short hex_table[256];            /* conversion value */
64 static gboolean initialized = FALSE;    /* easier to fill in at run time */
65
66
67 /* Table index for the hex values. Initialized once, first time.
68  * Used for translation value or delimiter significance lookup.
69  */
70 static void
71 init_hex_table (void)
72 {
73         /*
74          * We build the table at run time for several reasons:
75          *
76          * 1. portable to non-ASCII machines.
77          * 2. still reentrant since we set the init flag after setting table.
78          * 3. easier to extend.
79          * 4. less prone to bugs.
80          */
81         hex_table['0'] = 0;
82         hex_table['1'] = 1;
83         hex_table['2'] = 2;
84         hex_table['3'] = 3;
85         hex_table['4'] = 4;
86         hex_table['5'] = 5;
87         hex_table['6'] = 6;
88         hex_table['7'] = 7;
89         hex_table['8'] = 8;
90         hex_table['9'] = 9;
91         hex_table['A'] = 10;
92         hex_table['B'] = 11;
93         hex_table['C'] = 12;
94         hex_table['D'] = 13;
95         hex_table['E'] = 14;
96         hex_table['F'] = 15;
97         hex_table['a'] = 10;
98         hex_table['b'] = 11;
99         hex_table['c'] = 12;
100         hex_table['d'] = 13;
101         hex_table['e'] = 14;
102         hex_table['f'] = 15;
103
104         /* delimiters of significance are flagged w/ negative value */
105         hex_table[' '] = -1;
106         hex_table[','] = -1;
107         hex_table['}'] = -1;
108         hex_table['\n'] = -1;
109         hex_table['\t'] = -1;
110
111         initialized = TRUE;
112 }
113
114 /* Read next hex value in the input stream, return -1 if EOF */
115 static int
116 next_int (FILE *fstream)
117 {
118         int ch;
119         int value = 0;
120         int gotone = 0;
121         int done = 0;
122     
123         /* loop, accumulate hex value until find delimiter 
124            skip any initial delimiters found in read stream */
125
126         while (!done) {
127                 ch = getc (fstream);
128                 if (ch == EOF) {
129                         value = -1;
130                         done++;
131                 } else {
132                         /* trim high bits, check type and accumulate */
133                         ch &= 0xff;
134                         if (g_ascii_isxdigit (ch)) {
135                                 value = (value << 4) + g_ascii_xdigit_value (ch);
136                                 gotone++;
137                         } else if ((hex_table[ch]) < 0 && gotone) {
138                                 done++;
139                         }
140                 }
141         }
142         return value;
143 }
144
145 static gboolean
146 read_bitmap_file_data (FILE    *fstream,
147                        guint   *width, 
148                        guint   *height,
149                        guchar **data,
150                        int     *x_hot, 
151                        int     *y_hot)
152 {
153         guchar *bits = NULL;            /* working variable */
154         char line[MAX_SIZE];            /* input line from file */
155         int size;                       /* number of bytes of data */
156         char name_and_type[MAX_SIZE];   /* an input line */
157         char *type;                     /* for parsing */
158         int value;                      /* from an input line */
159         int version10p;                 /* boolean, old format */
160         int padding;                    /* to handle alignment */
161         int bytes_per_line;             /* per scanline of data */
162         guint ww = 0;                   /* width */
163         guint hh = 0;                   /* height */
164         int hx = -1;                    /* x hotspot */
165         int hy = -1;                    /* y hotspot */
166
167         /* first time initialization */
168         if (!initialized) {
169                 init_hex_table ();
170         }
171
172         /* error cleanup and return macro */
173 #define RETURN(code) { g_free (bits); return code; }
174
175         while (fgets (line, MAX_SIZE, fstream)) {
176                 if (strlen (line) == MAX_SIZE-1)
177                         RETURN (FALSE);
178                 if (sscanf (line,"#define %s %d",name_and_type,&value) == 2) {
179                         if (!(type = strrchr (name_and_type, '_')))
180                                 type = name_and_type;
181                         else {
182                                 type++;
183                         }
184
185                         if (!strcmp ("width", type))
186                                 ww = (unsigned int) value;
187                         if (!strcmp ("height", type))
188                                 hh = (unsigned int) value;
189                         if (!strcmp ("hot", type)) {
190                                 if (type-- == name_and_type
191                                     || type-- == name_and_type)
192                                         continue;
193                                 if (!strcmp ("x_hot", type))
194                                         hx = value;
195                                 if (!strcmp ("y_hot", type))
196                                         hy = value;
197                         }
198                         continue;
199                 }
200     
201                 if (sscanf (line, "static short %s = {", name_and_type) == 1)
202                         version10p = 1;
203                 else if (sscanf (line,"static const unsigned char %s = {",name_and_type) == 1)
204                         version10p = 0;
205                 else if (sscanf (line,"static unsigned char %s = {",name_and_type) == 1)
206                         version10p = 0;
207                 else if (sscanf (line, "static const char %s = {", name_and_type) == 1)
208                         version10p = 0;
209                 else if (sscanf (line, "static char %s = {", name_and_type) == 1)
210                         version10p = 0;
211                 else
212                         continue;
213
214                 if (!(type = strrchr (name_and_type, '_')))
215                         type = name_and_type;
216                 else
217                         type++;
218
219                 if (strcmp ("bits[]", type))
220                         continue;
221     
222                 if (!ww || !hh)
223                         RETURN (FALSE);
224
225                 if ((ww % 16) && ((ww % 16) < 9) && version10p)
226                         padding = 1;
227                 else
228                         padding = 0;
229
230                 bytes_per_line = (ww+7)/8 + padding;
231
232                 size = bytes_per_line * hh;
233                 bits = g_malloc (size);
234
235                 if (version10p) {
236                         unsigned char *ptr;
237                         int bytes;
238
239                         for (bytes = 0, ptr = bits; bytes < size; (bytes += 2)) {
240                                 if ((value = next_int (fstream)) < 0)
241                                         RETURN (FALSE);
242                                 *(ptr++) = value;
243                                 if (!padding || ((bytes+2) % bytes_per_line))
244                                         *(ptr++) = value >> 8;
245                         }
246                 } else {
247                         unsigned char *ptr;
248                         int bytes;
249
250                         for (bytes = 0, ptr = bits; bytes < size; bytes++, ptr++) {
251                                 if ((value = next_int (fstream)) < 0) 
252                                         RETURN (FALSE);
253                                 *ptr=value;
254                         }
255                 }
256                 break;
257         }
258
259         if (!bits)
260                 RETURN (FALSE);
261
262         *data = bits;
263         *width = ww;
264         *height = hh;
265         if (x_hot)
266                 *x_hot = hx;
267         if (y_hot)
268                 *y_hot = hy;
269
270         return TRUE;
271 }
272
273 \f
274
275 static GdkPixbuf *
276 gdk_pixbuf__xbm_image_load_real (FILE     *f, 
277                                  XBMData  *context, 
278                                  GError  **error)
279 {
280         guint w, h;
281         int x_hot, y_hot;
282         guchar *data, *ptr;
283         guchar *pixels;
284         guint row_stride;
285         int x, y;
286         int reg = 0; /* Quiet compiler */
287         int bits;
288
289         GdkPixbuf *pixbuf;
290
291         if (!read_bitmap_file_data (f, &w, &h, &data, &x_hot, &y_hot)) {
292                 g_set_error_literal (error,
293                                      GDK_PIXBUF_ERROR,
294                                      GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
295                                      _("Invalid XBM file"));
296                 return NULL;
297         }
298
299         pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, FALSE, 8, w, h);
300
301         if (pixbuf == NULL) {
302                 g_set_error_literal (error,
303                                      GDK_PIXBUF_ERROR,
304                                      GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
305                                      _("Insufficient memory to load XBM image file"));
306                 return NULL;
307         }
308         
309         if (x_hot != -1 && y_hot != -1) {
310                 gchar hot[10];
311                 g_snprintf (hot, 10, "%d", x_hot);
312                 gdk_pixbuf_set_option (pixbuf, "x_hot", hot);
313                 g_snprintf (hot, 10, "%d", y_hot);
314                 gdk_pixbuf_set_option (pixbuf, "y_hot", hot);
315         }
316
317         pixels = gdk_pixbuf_get_pixels (pixbuf);
318         row_stride = gdk_pixbuf_get_rowstride (pixbuf);
319
320         if (context && context->prepare_func)
321                 (* context->prepare_func) (pixbuf, NULL, context->user_data);
322
323
324         /* Initialize PIXBUF */
325
326         ptr = data;
327         for (y = 0; y < h; y++) {
328                 bits = 0;
329                 for (x = 0; x < w; x++) {
330                         guchar channel;
331                         if (bits == 0) {
332                                 reg = *ptr++;
333                                 bits = 8;
334                         }
335
336                         channel = (reg & 1) ? 0 : 255;
337                         reg >>= 1;
338                         bits--;
339
340                         pixels[x*3+0] = channel;
341                         pixels[x*3+1] = channel;
342                         pixels[x*3+2] = channel;
343                 }
344                 pixels += row_stride;
345         }
346         g_free (data);
347
348         if (context) {
349                 if (context->update_func)
350                         (* context->update_func) (pixbuf, 0, 0, w, h, context->user_data);
351         }
352
353         return pixbuf;
354 }
355
356 \f
357 /* Static loader */
358
359 static GdkPixbuf *
360 gdk_pixbuf__xbm_image_load (FILE    *f, 
361                             GError **error)
362 {
363         return gdk_pixbuf__xbm_image_load_real (f, NULL, error);
364 }
365
366 \f
367 /* Progressive loader */
368
369 /*
370  * Proper XBM progressive loading isn't implemented.  Instead we write
371  * it to a file, then load the file when it's done.  It's not pretty.
372  */
373
374 static gpointer
375 gdk_pixbuf__xbm_image_begin_load (GdkPixbufModuleSizeFunc       size_func,
376                                   GdkPixbufModulePreparedFunc   prepare_func,
377                                   GdkPixbufModuleUpdatedFunc    update_func,
378                                   gpointer                      user_data,
379                                   GError                      **error)
380 {
381         XBMData *context;
382         gint fd;
383
384         context = g_new (XBMData, 1);
385         context->prepare_func = prepare_func;
386         context->update_func = update_func;
387         context->user_data = user_data;
388         context->all_okay = TRUE;
389         fd = g_file_open_tmp ("gdkpixbuf-xbm-tmp.XXXXXX",
390                               &context->tempname,
391                               NULL);
392         if (fd < 0) {
393                 g_free (context);
394                 return NULL;
395         }
396
397         context->file = fdopen (fd, "w+");
398         if (context->file == NULL) {
399                 g_free (context->tempname);
400                 g_free (context);
401                 return NULL;
402         }
403
404         return context;
405 }
406
407 static gboolean
408 gdk_pixbuf__xbm_image_stop_load (gpointer   data,
409                                  GError   **error)
410 {
411         XBMData *context = (XBMData*) data;
412         gboolean retval = TRUE;
413
414         g_return_val_if_fail (data != NULL, TRUE);
415
416         fflush (context->file);
417         rewind (context->file);
418         if (context->all_okay) {
419                 GdkPixbuf *pixbuf;
420                 pixbuf = gdk_pixbuf__xbm_image_load_real (context->file, 
421                                                           context,
422                                                           error);
423                 if (pixbuf == NULL)
424                         retval = FALSE;
425                 else
426                         g_object_unref (pixbuf);
427         }
428
429         fclose (context->file);
430         g_unlink (context->tempname);
431         g_free (context->tempname);
432         g_free ((XBMData *) context);
433
434         return retval;
435 }
436
437 static gboolean
438 gdk_pixbuf__xbm_image_load_increment (gpointer       data,
439                                       const guchar  *buf,
440                                       guint          size,
441                                       GError       **error)
442 {
443         XBMData *context = (XBMData *) data;
444
445         g_return_val_if_fail (data != NULL, FALSE);
446
447         if (fwrite (buf, sizeof (guchar), size, context->file) != size) {
448                 gint save_errno = errno;
449                 context->all_okay = FALSE;
450                 g_set_error_literal (error,
451                                      G_FILE_ERROR,
452                                      g_file_error_from_errno (save_errno),
453                                      _("Failed to write to temporary file when loading XBM image"));
454                 return FALSE;
455         }
456
457         return TRUE;
458 }
459
460 #ifndef INCLUDE_xbm
461 #define MODULE_ENTRY(function) G_MODULE_EXPORT void function
462 #else
463 #define MODULE_ENTRY(function) void _gdk_pixbuf__xbm_ ## function
464 #endif
465
466 MODULE_ENTRY (fill_vtable) (GdkPixbufModule *module)
467 {
468         module->load = gdk_pixbuf__xbm_image_load;
469         module->begin_load = gdk_pixbuf__xbm_image_begin_load;
470         module->stop_load = gdk_pixbuf__xbm_image_stop_load;
471         module->load_increment = gdk_pixbuf__xbm_image_load_increment;
472 }
473
474 MODULE_ENTRY (fill_info) (GdkPixbufFormat *info)
475 {
476         static GdkPixbufModulePattern signature[] = {
477                 { "#define ", NULL, 100 },
478                 { "/*", NULL, 50 },
479                 { NULL, NULL, 0 }
480         };
481         static gchar * mime_types[] = {
482                 "image/x-xbitmap",
483                 NULL
484         };
485         static gchar * extensions[] = {
486                 "xbm",
487                 NULL
488         };
489
490         info->name = "xbm";
491         info->signature = signature;
492         info->description = N_("The XBM image format");
493         info->mime_types = mime_types;
494         info->extensions = extensions;
495         info->flags = GDK_PIXBUF_FORMAT_THREADSAFE;
496         info->license = "LGPL";
497 }