1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /* GdkPixbuf library - XPM image loader
4 * Copyright (C) 1999 Mark Crichton
5 * Copyright (C) 1999 The Free Software Foundation
7 * Authors: Mark Crichton <crichton@gimp.org>
8 * Federico Mena-Quintero <federico@gimp.org>
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the
22 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 * Boston, MA 02111-1307, USA.
32 #include <unistd.h> /* for unlink */
35 #include "gdk-pixbuf-private.h"
36 #include "gdk-pixbuf-io.h"
37 #include <glib/gstdio.h>
40 /* I have must have done something to deserve this.
41 * XPM is such a crappy format to handle.
42 * This code is an ugly hybred from gdkpixmap.c
43 * modified to respect transparent colors.
44 * It's still a mess, though.
72 /* The following 2 routines (parse_color, find_color) come from Tk, via the Win32
73 * port of GDK. The licensing terms on these (longer than the functions) is:
75 * This software is copyrighted by the Regents of the University of
76 * California, Sun Microsystems, Inc., and other parties. The following
77 * terms apply to all files associated with the software unless explicitly
78 * disclaimed in individual files.
80 * The authors hereby grant permission to use, copy, modify, distribute,
81 * and license this software and its documentation for any purpose, provided
82 * that existing copyright notices are retained in all copies and that this
83 * notice is included verbatim in any distributions. No written agreement,
84 * license, or royalty fee is required for any of the authorized uses.
85 * Modifications to this software may be copyrighted by their authors
86 * and need not follow the licensing terms described here, provided that
87 * the new terms are clearly indicated on the first page of each file where
90 * IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
91 * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
92 * ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
93 * DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
94 * POSSIBILITY OF SUCH DAMAGE.
96 * THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
97 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
98 * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
99 * IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
100 * NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
103 * GOVERNMENT USE: If you are acquiring this software on behalf of the
104 * U.S. government, the Government shall have only "Restricted Rights"
105 * in the software and related documentation as defined in the Federal
106 * Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
107 * are acquiring the software on behalf of the Department of Defense, the
108 * software shall be classified as "Commercial Computer Software" and the
109 * Government shall have only "Restricted Rights" as defined in Clause
110 * 252.227-7013 (c) (1) of DFARs. Notwithstanding the foregoing, the
111 * authors grant the U.S. Government and others acting in its behalf
112 * permission to use and distribute the software in accordance with the
113 * terms specified in this license.
116 #include "xpm-color-table.h"
119 *----------------------------------------------------------------------
123 * This routine finds the color entry that corresponds to the
127 * Returns non-zero on success. The RGB values of the XColor
128 * will be initialized to the proper values on success.
133 *----------------------------------------------------------------------
137 compare_xcolor_entries (const void *a, const void *b)
139 return g_ascii_strcasecmp ((const char *) a,
140 color_names + ((const XPMColorEntry *)b)->name_offset);
144 find_color(const char *name,
147 XPMColorEntry *found;
149 found = bsearch (name, xColors, G_N_ELEMENTS (xColors), sizeof (XPMColorEntry),
150 compare_xcolor_entries);
154 colorPtr->red = (found->red * 65535) / 255;
155 colorPtr->green = (found->green * 65535) / 255;
156 colorPtr->blue = (found->blue * 65535) / 255;
162 *----------------------------------------------------------------------
166 * Partial implementation of X color name parsing interface.
169 * Returns TRUE on success.
174 *----------------------------------------------------------------------
178 parse_color (const char *spec,
181 if (spec[0] == '#') {
183 int i, red, green, blue;
185 if ((i = strlen (spec + 1)) % 3) {
190 g_snprintf (fmt, 16, "%%%dx%%%dx%%%dx", i, i, i);
192 if (sscanf (spec + 1, fmt, &red, &green, &blue) != 3) {
197 colorPtr->green = green;
198 colorPtr->blue = blue;
200 colorPtr->red = (red * 65535) / 15;
201 colorPtr->green = (green * 65535) / 15;
202 colorPtr->blue = (blue * 65535) / 15;
205 colorPtr->red = (red * 65535) / 255;
206 colorPtr->green = (green * 65535) / 255;
207 colorPtr->blue = (blue * 65535) / 255;
208 } else /* if (i == 3) */ {
209 colorPtr->red = (red * 65535) / 4095;
210 colorPtr->green = (green * 65535) / 4095;
211 colorPtr->blue = (blue * 65535) / 4095;
214 if (!find_color(spec, colorPtr))
221 xpm_seek_string (FILE *infile, const gchar *str)
225 while (!feof (infile)) {
226 if (fscanf (infile, "%1023s", instr) < 0)
228 if (strcmp (instr, str) == 0)
236 xpm_seek_char (FILE *infile, gchar c)
240 while ((b = getc (infile)) != EOF) {
241 if (c != b && b == '/') {
246 else if (b == '*') { /* we have a comment */
253 } while (!(oldb == '*' && b == '/'));
263 xpm_read_string (FILE *infile, gchar **buffer, guint *buffer_size)
266 guint cnt = 0, bufsiz, ret = FALSE;
270 bufsiz = *buffer_size;
272 bufsiz = 10 * sizeof (gchar);
273 buf = g_new (gchar, bufsiz);
278 } while (c != EOF && c != '"');
283 while ((c = getc (infile)) != EOF) {
285 guint new_size = bufsiz * 2;
287 if (new_size > bufsiz)
292 buf = g_realloc (buf, bufsiz);
293 buf[bufsiz - 1] = '\0';
306 buf[bufsiz - 1] = '\0'; /* ensure null termination for errors */
308 *buffer_size = bufsiz;
313 xpm_extract_color (const gchar *buffer)
315 const gchar *p = &buffer[0];
318 gint current_key = 1;
320 gchar word[129], color[129], current_color[129];
325 current_color[0] = '\0';
327 /* skip whitespace */
328 for (; *p != '\0' && g_ascii_isspace (*p); p++) {
331 for (r = word; *p != '\0' && !g_ascii_isspace (*p) && r - word < sizeof (word) - 1; p++, r++) {
336 if (color[0] == '\0') /* incomplete colormap entry */
338 else /* end of entry, still store the last color */
341 else if (key > 0 && color[0] == '\0') /* next word must be a color name part */
344 if (strcmp (word, "c") == 0)
346 else if (strcmp (word, "g") == 0)
348 else if (strcmp (word, "g4") == 0)
350 else if (strcmp (word, "m") == 0)
352 else if (strcmp (word, "s") == 0)
357 if (new_key == 0) { /* word is a color name part */
358 if (key == 0) /* key expected */
360 /* accumulate color name */
361 if (color[0] != '\0') {
362 strncat (color, " ", space);
363 space -= MIN (space, 1);
365 strncat (color, word, space);
366 space -= MIN (space, strlen (word));
368 else { /* word is a key */
369 if (key > current_key) {
371 strcpy (current_color, color);
376 if (*p == '\0') break;
381 return g_strdup (current_color);
386 /* (almost) direct copy from gdkpixmap.c... loads an XPM from a file */
389 file_buffer (enum buf_op op, gpointer handle)
391 struct file_handle *h = handle;
395 if (xpm_seek_string (h->infile, "XPM") != TRUE)
398 if (xpm_seek_char (h->infile, '{') != TRUE)
400 /* Fall through to the next xpm_seek_char. */
403 xpm_seek_char (h->infile, '"');
404 fseek (h->infile, -1, SEEK_CUR);
405 /* Fall through to the xpm_read_string. */
408 if(!xpm_read_string (h->infile, &h->buffer, &h->buffer_size))
413 g_assert_not_reached ();
419 /* This reads from memory */
421 mem_buffer (enum buf_op op, gpointer handle)
423 struct mem_handle *h = handle;
428 if (h->data[h->offset]) {
431 retval = h->data[h->offset];
438 g_assert_not_reached ();
445 /* This function does all the work. */
447 pixbuf_create_from_xpm (const gchar * (*get_buf) (enum buf_op op, gpointer handle), gpointer handle,
450 gint w, h, n_col, cpp, x_hot, y_hot, items;
451 gint cnt, xcnt, ycnt, wbytes, n;
452 gint is_trans = FALSE;
456 GHashTable *color_hash;
457 XPMColor *colors, *color, *fallbackcolor;
461 fallbackcolor = NULL;
463 buffer = (*get_buf) (op_header, handle);
467 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
468 _("No XPM header found"));
471 items = sscanf (buffer, "%d %d %d %d %d %d", &w, &h, &n_col, &cpp, &x_hot, &y_hot);
473 if (items != 4 && items != 6) {
476 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
477 _("Invalid XPM header"));
484 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
485 _("XPM file has image width <= 0"));
492 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
493 _("XPM file has image height <= 0"));
497 if (cpp <= 0 || cpp >= 32) {
500 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
501 _("XPM has invalid number of chars per pixel"));
505 n_col >= G_MAXINT / (cpp + 1) ||
506 n_col >= G_MAXINT / sizeof (XPMColor)) {
509 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
510 _("XPM file has invalid number of colors"));
514 /* The hash is used for fast lookups of color from chars */
515 color_hash = g_hash_table_new (g_str_hash, g_str_equal);
517 name_buf = g_try_malloc (n_col * (cpp + 1));
521 GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
522 _("Cannot allocate memory for loading XPM image"));
523 g_hash_table_destroy (color_hash);
526 colors = (XPMColor *) g_try_malloc (sizeof (XPMColor) * n_col);
530 GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
531 _("Cannot allocate memory for loading XPM image"));
532 g_hash_table_destroy (color_hash);
537 for (cnt = 0; cnt < n_col; cnt++) {
540 buffer = (*get_buf) (op_cmap, handle);
544 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
545 _("Cannot read XPM colormap"));
546 g_hash_table_destroy (color_hash);
552 color = &colors[cnt];
553 color->color_string = &name_buf[cnt * (cpp + 1)];
554 strncpy (color->color_string, buffer, cpp);
555 color->color_string[cpp] = 0;
556 buffer += strlen (color->color_string);
557 color->transparent = FALSE;
559 color_name = xpm_extract_color (buffer);
561 if ((color_name == NULL) || (g_ascii_strcasecmp (color_name, "None") == 0)
562 || (parse_color (color_name, color) == FALSE)) {
563 color->transparent = TRUE;
571 g_hash_table_insert (color_hash, color->color_string, color);
574 fallbackcolor = color;
577 pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, is_trans, 8, w, h);
582 GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
583 _("Cannot allocate memory for loading XPM image"));
584 g_hash_table_destroy (color_hash);
592 for (ycnt = 0; ycnt < h; ycnt++) {
593 pixtmp = pixbuf->pixels + ycnt * pixbuf->rowstride;
595 buffer = (*get_buf) (op_body, handle);
596 if ((!buffer) || (strlen (buffer) < wbytes))
599 for (n = 0, cnt = 0, xcnt = 0; n < wbytes; n += cpp, xcnt++) {
600 strncpy (pixel_str, &buffer[n], cpp);
603 color = g_hash_table_lookup (color_hash, pixel_str);
607 color = fallbackcolor;
609 *pixtmp++ = color->red >> 8;
610 *pixtmp++ = color->green >> 8;
611 *pixtmp++ = color->blue >> 8;
613 if (is_trans && color->transparent)
620 g_hash_table_destroy (color_hash);
626 g_snprintf (hot, 10, "%d", x_hot);
627 gdk_pixbuf_set_option (pixbuf, "x_hot", hot);
628 g_snprintf (hot, 10, "%d", y_hot);
629 gdk_pixbuf_set_option (pixbuf, "y_hot", hot);
636 /* Shared library entry point for file loading */
638 gdk_pixbuf__xpm_image_load (FILE *f,
642 struct file_handle h;
644 memset (&h, 0, sizeof (h));
646 pixbuf = pixbuf_create_from_xpm (file_buffer, &h, error);
652 /* Shared library entry point for memory loading */
654 gdk_pixbuf__xpm_image_load_xpm_data (const gchar **data)
658 GError *error = NULL;
663 pixbuf = pixbuf_create_from_xpm (mem_buffer, &h, &error);
666 g_warning ("Inline XPM data is broken: %s", error->message);
667 g_error_free (error);
674 /* Progressive loader */
675 typedef struct _XPMContext XPMContext;
678 GdkPixbufModulePreparedFunc prepare_func;
679 GdkPixbufModuleUpdatedFunc update_func;
688 * FIXME xpm loading progressively is not properly implemented.
689 * Instead we will buffer to a file then load that file when done.
690 * This is very broken but it should be relayively simple to fix
694 gdk_pixbuf__xpm_image_begin_load (GdkPixbufModuleSizeFunc size_func,
695 GdkPixbufModulePreparedFunc prepare_func,
696 GdkPixbufModuleUpdatedFunc update_func,
703 context = g_new (XPMContext, 1);
704 context->prepare_func = prepare_func;
705 context->update_func = update_func;
706 context->user_data = user_data;
707 context->all_okay = TRUE;
708 fd = g_file_open_tmp ("gdkpixbuf-xpm-tmp.XXXXXX", &context->tempname,
715 context->file = fdopen (fd, "w+");
716 if (context->file == NULL) {
717 g_free (context->tempname);
726 gdk_pixbuf__xpm_image_stop_load (gpointer data,
729 XPMContext *context = (XPMContext*) data;
731 gboolean retval = FALSE;
733 g_return_val_if_fail (data != NULL, FALSE);
735 fflush (context->file);
736 rewind (context->file);
737 if (context->all_okay) {
738 pixbuf = gdk_pixbuf__xpm_image_load (context->file, error);
740 if (pixbuf != NULL) {
741 if (context->prepare_func)
742 (* context->prepare_func) (pixbuf,
745 if (context->update_func)
746 (* context->update_func) (pixbuf, 0, 0, pixbuf->width, pixbuf->height, context->user_data);
747 g_object_unref (pixbuf);
753 fclose (context->file);
754 g_unlink (context->tempname);
755 g_free (context->tempname);
756 g_free ((XPMContext *) context);
762 gdk_pixbuf__xpm_image_load_increment (gpointer data,
767 XPMContext *context = (XPMContext *) data;
769 g_return_val_if_fail (data != NULL, FALSE);
771 if (fwrite (buf, sizeof (guchar), size, context->file) != size) {
772 context->all_okay = FALSE;
775 g_file_error_from_errno (errno),
776 _("Failed to write to temporary file when loading XPM image"));
784 MODULE_ENTRY (xpm, fill_vtable) (GdkPixbufModule *module)
786 module->load = gdk_pixbuf__xpm_image_load;
787 module->load_xpm_data = gdk_pixbuf__xpm_image_load_xpm_data;
788 module->begin_load = gdk_pixbuf__xpm_image_begin_load;
789 module->stop_load = gdk_pixbuf__xpm_image_stop_load;
790 module->load_increment = gdk_pixbuf__xpm_image_load_increment;
794 MODULE_ENTRY (xpm, fill_info) (GdkPixbufFormat *info)
796 static GdkPixbufModulePattern signature[] = {
797 { "/* XPM */", NULL, 100 },
800 static gchar * mime_types[] = {
804 static gchar * extensions[] = {
810 info->signature = signature;
811 info->description = N_("The XPM image format");
812 info->mime_types = mime_types;
813 info->extensions = extensions;
814 info->flags = GDK_PIXBUF_FORMAT_THREADSAFE;
815 info->license = "LGPL";