gdk-pixbuf-io.c 47.3 KB
Newer Older
1
/* -*- mode: C; c-file-style: "linux" -*- */
2
/* GdkPixbuf library - Main loading interface.
Arturo Espinosa's avatar
Arturo Espinosa committed
3
 *
4 5 6 7 8 9
 * Copyright (C) 1999 The Free Software Foundation
 *
 * Authors: Miguel de Icaza <miguel@gnu.org>
 *          Federico Mena-Quintero <federico@gimp.org>
 *
 * This library is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU Lesser General Public
11 12 13 14 15 16
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17
 * Lesser General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Lesser General Public
20 21 22
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
Arturo Espinosa's avatar
Arturo Espinosa committed
23
 */
24

25
#include <config.h>
26

27 28
#include <stdlib.h>
#include <stdio.h>
29
#include <string.h>
30
#include <glib.h>
31
#include <errno.h>
32 33 34 35
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

36
#include "gdk-pixbuf-private.h"
37
#include "gdk-pixbuf-io.h"
Arturo Espinosa's avatar
Arturo Espinosa committed
38

39 40 41 42 43 44
#ifdef G_OS_WIN32
#define STRICT
#include <windows.h>
#undef STRICT
#endif

45 46
static gint 
format_check (GdkPixbufModule *module, guchar *buffer, int size)
47
{
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
	int j;
	gchar m;
	GdkPixbufModulePattern *pattern;

	for (pattern = module->info->signature; pattern->prefix; pattern++) {
		for (j = 0; j < size && pattern->prefix[j] != 0; j++) {
			m = pattern->mask ? pattern->mask[j] : ' ';
			if (m == ' ') {
				if (buffer[j] != pattern->prefix[j])
					break;
			}
			else if (m == '!') {
				if (buffer[j] == pattern->prefix[j])
					break;
			}
			else if (m == 'z') {
				if (buffer[j] != 0)
					break;
			}
			else if (m == 'n') {
				if (buffer[j] == 0)
					break;
			}
		} 
		if (pattern->prefix[j] == 0) 
			return pattern->relevance;
	}
	return 0;
76 77
}

78
static GSList *file_formats = NULL;
79

80
static void gdk_pixbuf_io_init ();
81

82 83
static GSList *
get_file_formats ()
84
{
85 86 87 88
	if (file_formats == NULL)
		gdk_pixbuf_io_init ();
	
	return file_formats;
89 90
}

91

92
#ifdef USE_GMODULE 
93 94

static gboolean
95
scan_string (const char **pos, GString *out)
96
{
97 98 99 100 101 102 103 104
	const char *p = *pos, *q = *pos;
	char *tmp, *tmp2;
	gboolean quoted;
	
	while (g_ascii_isspace (*p))
		p++;
	
	if (!*p)
105
		return FALSE;
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
	else if (*p == '"') {
		p++;
		quoted = FALSE;
		for (q = p; (*q != '"') || quoted; q++) {
			if (!*q)
				return FALSE;
			quoted = (*q == '\\') && !quoted;
		}
		
		tmp = g_strndup (p, q - p);
		tmp2 = g_strcompress (tmp);
		g_string_truncate (out, 0);
		g_string_append (out, tmp2);
		g_free (tmp);
		g_free (tmp2);
121
	}
122 123 124 125
	
	q++;
	*pos = q;
	
126 127 128
	return TRUE;
}

129
static gboolean
130
scan_int (const char **pos, int *out)
131
{
132 133 134 135 136 137 138 139
	int i = 0;
	char buf[32];
	const char *p = *pos;
	
	while (g_ascii_isspace (*p))
		p++;
	
	if (*p < '0' || *p > '9')
140
		return FALSE;
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
	
	while ((*p >= '0') && (*p <= '9') && i < sizeof (buf)) {
		buf[i] = *p;
		i++;
		p++;
	}
	
	if (i == sizeof (buf))
  		return FALSE;
	else
		buf[i] = '\0';
	
	*out = atoi (buf);
	
	*pos = p;
156 157 158 159

	return TRUE;
}

160
static gboolean
161
skip_space (const char **pos)
162
{
163 164 165 166 167 168 169 170
	const char *p = *pos;
	
	while (g_ascii_isspace (*p))
		p++;
  
	*pos = p;
	
	return !(*p == '\0');
171
}
172
  
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
#ifdef G_OS_WIN32

/* DllMain function needed to tuck away the gdk-pixbuf DLL name */
G_WIN32_DLLMAIN_FOR_DLL_NAME (static, dll_name)

static char *
get_toplevel (void)
{
  static char *toplevel = NULL;

  if (toplevel == NULL)
    toplevel = g_win32_get_package_installation_subdirectory
      (GETTEXT_PACKAGE, dll_name, "");

  return toplevel;
}

static char *
get_sysconfdir (void)
{
  static char *sysconfdir = NULL;

  if (sysconfdir == NULL)
    sysconfdir = g_win32_get_package_installation_subdirectory
      (GETTEXT_PACKAGE, dll_name, "etc");

  return sysconfdir;
}

#undef GTK_SYSCONFDIR
#define GTK_SYSCONFDIR get_sysconfdir()

static void
correct_prefix (gchar **path)
{
  if (strncmp (*path, GTK_PREFIX "/", strlen (GTK_PREFIX "/")) == 0 ||
      strncmp (*path, GTK_PREFIX "\\", strlen (GTK_PREFIX "\\")) == 0)
    {
      /* This is an entry put there by gdk-pixbuf-query-loaders on the
       * packager's system. On Windows a prebuilt GTK+ package can be
       * installed in a random location. The gdk-pixbuf.loaders file
       * distributed in such a package contains paths from the package
       * builder's machine. Replace the build-time prefix with the
       * installation prefix on this machine.
       */
      gchar *tem = *path;
      *path = g_strconcat (get_toplevel (), tem + strlen (GTK_PREFIX), NULL);
      g_free (tem);
    }
}

#endif

226 227
static gchar *
gdk_pixbuf_get_module_file (void)
228
{
229
  gchar *result = g_strdup (g_getenv ("GDK_PIXBUF_MODULE_FILE"));
230

231 232
  if (!result)
	  result = g_build_filename (GTK_SYSCONFDIR, "gtk-2.0", "gdk-pixbuf.loaders", NULL);
233

234
  return result;
235 236
}

237 238
static void 
gdk_pixbuf_io_init ()
239
{
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
	GIOChannel *channel;
	gchar *line_buf;
	gsize term;
	GString *tmp_buf = g_string_new (NULL);
	gboolean have_error = FALSE;
	GdkPixbufModule *module = NULL;
	gchar *filename = gdk_pixbuf_get_module_file ();
	int flags;
	int n_patterns = 0;
	GdkPixbufModulePattern *pattern;
	GError *error = NULL;

	channel = g_io_channel_new_file (filename, "r",  &error);
	if (!channel) {
		g_warning ("Can not open pixbuf loader module file '%s': %s",
			   filename, error->message);
		return;
	}
	
	while (!have_error && g_io_channel_read_line (channel, &line_buf, NULL, &term, NULL) == G_IO_STATUS_NORMAL) {
		const char *p;
		
		p = line_buf;
263

264
		line_buf[term] = 0;
265

266 267 268 269
		if (!skip_space (&p)) {
				/* Blank line marking the end of a module
				 */
			if (module && *p != '#') {
270 271 272
#ifdef G_OS_WIN32
				correct_prefix (&module->module_path);
#endif
273 274 275 276 277 278
				file_formats = g_slist_prepend (file_formats, module);
				module = NULL;
			}
			
			goto next_line;
		}
Arturo Espinosa's avatar
Arturo Espinosa committed
279

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
		if (*p == '#') 
			goto next_line;
		
		if (!module) {
				/* Read a module location
				 */
			module = g_new0 (GdkPixbufModule, 1);
			n_patterns = 0;
			
			if (!scan_string (&p, tmp_buf)) {
				g_warning ("Error parsing loader info in '%s'\n  %s", 
					   filename, line_buf);
				have_error = TRUE;
			}
			module->module_path = g_strdup (tmp_buf->str);
		}
		else if (!module->module_name) {
			module->info = g_new0 (GdkPixbufFormat, 1);
			if (!scan_string (&p, tmp_buf)) {
				g_warning ("Error parsing loader info in '%s'\n  %s", 
					   filename, line_buf);
				have_error = TRUE;
			}
			module->info->name =  g_strdup (tmp_buf->str);
			module->module_name = module->info->name;
Federico Mena Quintero's avatar
Federico Mena Quintero committed
305

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
			if (!scan_int (&p, &flags)) {
				g_warning ("Error parsing loader info in '%s'\n  %s", 
					   filename, line_buf);
				have_error = TRUE;
			}
			module->info->flags = flags;
			
			if (!scan_string (&p, tmp_buf)) {
				g_warning ("Error parsing loader info in '%s'\n  %s", 
					   filename, line_buf);
				have_error = TRUE;
			}			
			if (tmp_buf->str[0] != 0)
				module->info->domain = g_strdup (tmp_buf->str);

			if (!scan_string (&p, tmp_buf)) {
				g_warning ("Error parsing loader info in '%s'\n  %s", 
					   filename, line_buf);
				have_error = TRUE;
			}			
			module->info->description = g_strdup (tmp_buf->str);
		}
		else if (!module->info->mime_types) {
			int n = 1;
			module->info->mime_types = g_new0 (gchar*, 1);
			while (scan_string (&p, tmp_buf)) {
				if (tmp_buf->str[0] != 0) {
					module->info->mime_types =
						g_realloc (module->info->mime_types, (n + 1) * sizeof (gchar*));
					module->info->mime_types[n - 1] = g_strdup (tmp_buf->str);
					module->info->mime_types[n] = 0;
					n++;
				}
			}
		}
		else if (!module->info->extensions) {
			int n = 1;
			module->info->extensions = g_new0 (gchar*, 1);
			while (scan_string (&p, tmp_buf)) {
				if (tmp_buf->str[0] != 0) {
					module->info->extensions =
						g_realloc (module->info->extensions, (n + 1) * sizeof (gchar*));
					module->info->extensions[n - 1] = g_strdup (tmp_buf->str);
					module->info->extensions[n] = 0;
					n++;
				}
			}
		}
		else {
			n_patterns++;
			module->info->signature = (GdkPixbufModulePattern *)
				g_realloc (module->info->signature, (n_patterns + 1) * sizeof (GdkPixbufModulePattern));
			pattern = module->info->signature + n_patterns;
			pattern->prefix = NULL;
			pattern->mask = NULL;
			pattern->relevance = 0;
			pattern--;
			if (!scan_string (&p, tmp_buf))
				goto context_error;
			pattern->prefix = g_strdup (tmp_buf->str);
			
			if (!scan_string (&p, tmp_buf))
				goto context_error;
			if (*tmp_buf->str)
				pattern->mask = g_strdup (tmp_buf->str);
			else
				pattern->mask = NULL;
			
			if (!scan_int (&p, &pattern->relevance))
				goto context_error;
			
			goto next_line;

		context_error:
			g_free (pattern->prefix);
			g_free (pattern->mask);
			g_free (pattern);
			g_warning ("Error parsing loader info in '%s'\n  %s", 
				   filename, line_buf);
			have_error = TRUE;
		}
	next_line:
		g_free (line_buf);
	}
	g_string_free (tmp_buf, TRUE);
	g_io_channel_unref (channel);
	g_free (filename);
Federico Mena Quintero's avatar
Federico Mena Quintero committed
393
}
394 395 396 397

/* actually load the image handler - gdk_pixbuf_get_module only get a */
/* reference to the module to load, it doesn't actually load it       */
/* perhaps these actions should be combined in one function           */
Havoc Pennington's avatar
Havoc Pennington committed
398
gboolean
399 400
_gdk_pixbuf_load_module (GdkPixbufModule *image_module,
                         GError         **error)
Arturo Espinosa's avatar
Arturo Espinosa committed
401
{
402 403
	char *path;
	GModule *module;
404
	gpointer sym;
Federico Mena Quintero's avatar
Federico Mena Quintero committed
405
	
Havoc Pennington's avatar
Havoc Pennington committed
406
        g_return_val_if_fail (image_module->module == NULL, FALSE);
407

408
	path = image_module->module_path;
409
	module = g_module_open (path, G_MODULE_BIND_LAZY);
410 411 412 413 414 415 416 417

        if (!module) {
                g_set_error (error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_FAILED,
                             _("Unable to load image-loading module: %s: %s"),
                             path, g_module_error ());
                return FALSE;
418 419
        }

420 421
	image_module->module = module;        
        
422 423
        if (g_module_symbol (module, "fill_vtable", &sym)) {
                GdkPixbufModuleFillVtableFunc func = (GdkPixbufModuleFillVtableFunc) sym;
424
                (* func) (image_module);
425
                return TRUE;
426 427 428 429 430 431
        } else {
                g_set_error (error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_FAILED,
                             _("Image-loading module %s does not export the proper interface; perhaps it's from a different GTK version?"),
                             path);
432
                return FALSE;
433
        }
Arturo Espinosa's avatar
Arturo Espinosa committed
434
}
Federico Mena Quintero's avatar
Federico Mena Quintero committed
435 436
#else

437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
#define module(type) \
  extern void MODULE_ENTRY (type, fill_info)   (GdkPixbufFormat *info);   \
  extern void MODULE_ENTRY (type, fill_vtable) (GdkPixbufModule *module)

module (png);
module (bmp);
module (wbmp);
module (gif);
module (ico);
module (ani);
module (jpeg);
module (pnm);
module (ras);
module (tiff);
module (xpm);
module (xbm);
module (tga);
454
module (pcx);
Federico Mena Quintero's avatar
Federico Mena Quintero committed
455

Havoc Pennington's avatar
Havoc Pennington committed
456
gboolean
457 458
_gdk_pixbuf_load_module (GdkPixbufModule *image_module,
                         GError         **error)
Federico Mena Quintero's avatar
Federico Mena Quintero committed
459
{
460 461 462
	GdkPixbufModuleFillInfoFunc fill_info = NULL;
        GdkPixbufModuleFillVtableFunc fill_vtable = NULL;

Federico Mena Quintero's avatar
Federico Mena Quintero committed
463
	image_module->module = (void *) 1;
464

465 466 467 468
        if (FALSE) {
                /* Ugly hack so we can use else if unconditionally below ;-) */
        }
        
469
#ifdef INCLUDE_png	
470 471 472
	else if (strcmp (image_module->module_name, "png") == 0) {
                fill_info = MODULE_ENTRY (png, fill_info);
                fill_vtable = MODULE_ENTRY (png, fill_vtable);
Federico Mena Quintero's avatar
Federico Mena Quintero committed
473
	}
474
#endif
Federico Mena Quintero's avatar
Federico Mena Quintero committed
475

476
#ifdef INCLUDE_bmp	
477 478 479
	else if (strcmp (image_module->module_name, "bmp") == 0) {
                fill_info = MODULE_ENTRY (bmp, fill_info);
                fill_vtable = MODULE_ENTRY (bmp, fill_vtable);
Federico Mena Quintero's avatar
Federico Mena Quintero committed
480
	}
481
#endif
Federico Mena Quintero's avatar
Federico Mena Quintero committed
482

483
#ifdef INCLUDE_wbmp
484 485 486
	else if (strcmp (image_module->module_name, "wbmp") == 0) {
                fill_info = MODULE_ENTRY (wbmp, fill_info);
                fill_vtable = MODULE_ENTRY (wbmp, fill_vtable);
487
	}
488
#endif
489

490
#ifdef INCLUDE_gif
491 492 493
	else if (strcmp (image_module->module_name, "gif") == 0) {
                fill_info = MODULE_ENTRY (gif, fill_info);
                fill_vtable = MODULE_ENTRY (gif, fill_vtable);
Federico Mena Quintero's avatar
Federico Mena Quintero committed
494
	}
495
#endif
Federico Mena Quintero's avatar
Federico Mena Quintero committed
496

497
#ifdef INCLUDE_ico
498 499 500
	else if (strcmp (image_module->module_name, "ico") == 0) {
                fill_info = MODULE_ENTRY (ico, fill_info);
                fill_vtable = MODULE_ENTRY (ico, fill_vtable);
Federico Mena Quintero's avatar
Federico Mena Quintero committed
501
	}
502
#endif
Federico Mena Quintero's avatar
Federico Mena Quintero committed
503

504
#ifdef INCLUDE_ani
505 506 507
	else if (strcmp (image_module->module_name, "ani") == 0) {
                fill_info = MODULE_ENTRY (ani, fill_info);
                fill_vtable = MODULE_ENTRY (ani, fill_vtable);
508 509 510
	}
#endif

511
#ifdef INCLUDE_jpeg
512 513 514
	else if (strcmp (image_module->module_name, "jpeg") == 0) {
                fill_info = MODULE_ENTRY (jpeg, fill_info);
                fill_vtable = MODULE_ENTRY (jpeg, fill_vtable);
Federico Mena Quintero's avatar
Federico Mena Quintero committed
515
	}
516 517 518
#endif

#ifdef INCLUDE_pnm
519 520 521
	else if (strcmp (image_module->module_name, "pnm") == 0) {
                fill_info = MODULE_ENTRY (pnm, fill_info);
                fill_vtable = MODULE_ENTRY (pnm, fill_vtable);
Federico Mena Quintero's avatar
Federico Mena Quintero committed
522
	}
523 524 525
#endif

#ifdef INCLUDE_ras
526 527 528
	else if (strcmp (image_module->module_name, "ras") == 0) {
                fill_info = MODULE_ENTRY (ras, fill_info);
                fill_vtable = MODULE_ENTRY (ras, fill_vtable);
Federico Mena Quintero's avatar
Federico Mena Quintero committed
529
	}
530 531 532
#endif

#ifdef INCLUDE_tiff
533 534 535
	else if (strcmp (image_module->module_name, "tiff") == 0) {
                fill_info = MODULE_ENTRY (tiff, fill_info);
                fill_vtable = MODULE_ENTRY (tiff, fill_vtable);
Federico Mena Quintero's avatar
Federico Mena Quintero committed
536
	}
537
#endif
Havoc Pennington's avatar
Havoc Pennington committed
538

539
#ifdef INCLUDE_xpm
540 541 542
	else if (strcmp (image_module->module_name, "xpm") == 0) {
                fill_info = MODULE_ENTRY (xpm, fill_info);
                fill_vtable = MODULE_ENTRY (xpm, fill_vtable);
543 544 545
	}
#endif

546
#ifdef INCLUDE_xbm
547 548 549
	else if (strcmp (image_module->module_name, "xbm") == 0) {
                fill_info = MODULE_ENTRY (xbm, fill_info);
                fill_vtable = MODULE_ENTRY (xbm, fill_vtable);
550 551 552
	}
#endif

553
#ifdef INCLUDE_tga
554 555 556
	else if (strcmp (image_module->module_name, "tga") == 0) {
                fill_info = MODULE_ENTRY (tga, fill_info);
		fill_vtable = MODULE_ENTRY (tga, fill_vtable);
557 558
	}
#endif
559
        
560 561 562 563 564 565 566
#ifdef INCLUDE_pcx
	else if (strcmp (image_module->module_name, "pcx") == 0) {
                fill_info = MODULE_ENTRY (pcx, fill_info);
		fill_vtable = MODULE_ENTRY (pcx, fill_vtable);
	}
#endif
        
567 568
        if (fill_vtable) {
                (* fill_vtable) (image_module);
569 570 571
		image_module->info = g_new0 (GdkPixbufFormat, 1);
		(* fill_info) (image_module->info);

572 573 574 575 576 577 578 579 580 581
                return TRUE;
        } else {
                g_set_error (error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
                             _("Image type '%s' is not supported"),
                             image_module->module_name);

                return FALSE;
        }
Federico Mena Quintero's avatar
Federico Mena Quintero committed
582 583
}

584 585 586 587 588 589
static void 
gdk_pixbuf_io_init ()
{
	gchar *included_formats[] = { 
		"ani", "png", "bmp", "wbmp", "gif", 
		"ico", "jpeg", "pnm", "ras", "tiff", 
590
		"xpm", "xbm", "tga", "pcx",
591 592 593 594 595 596 597 598 599 600 601 602 603 604
		NULL
	};
	gchar **name;
	GdkPixbufModule *module = NULL;
	
	for (name = included_formats; *name; name++) {
		module = g_new0 (GdkPixbufModule, 1);
		module->module_name = *name;
		if (_gdk_pixbuf_load_module (module, NULL))
			file_formats = g_slist_prepend (file_formats, module);
		else
			g_free (module);
	}
}
Federico Mena Quintero's avatar
Federico Mena Quintero committed
605 606

#endif
Arturo Espinosa's avatar
Arturo Espinosa committed
607

608 609


610
GdkPixbufModule *
611 612
_gdk_pixbuf_get_named_module (const char *name,
                              GError **error)
613
{
614
	GSList *modules;
615

616 617 618 619
	for (modules = get_file_formats (); modules; modules = g_slist_next (modules)) {
		GdkPixbufModule *module = (GdkPixbufModule *)modules->data;
		if (!strcmp (name, module->module_name))
			return module;
620 621
	}

Havoc Pennington's avatar
Havoc Pennington committed
622 623 624 625 626 627
        g_set_error (error,
                     GDK_PIXBUF_ERROR,
                     GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
                     _("Image type '%s' is not supported"),
                     name);
        
628 629 630
	return NULL;
}

631
GdkPixbufModule *
632 633 634
_gdk_pixbuf_get_module (guchar *buffer, guint size,
                        const gchar *filename,
                        GError **error)
635
{
636 637 638 639 640 641 642 643 644 645 646 647 648
	GSList *modules;

	gint score, best = 0;
	GdkPixbufModule *selected = NULL;
	for (modules = get_file_formats (); modules; modules = g_slist_next (modules)) {
		GdkPixbufModule *module = (GdkPixbufModule *)modules->data;
		score = format_check (module, buffer, size);
		if (score > best) {
			best = score; 
			selected = module;
		}
		if (score >= 100) 
			break;
649
	}
650 651
	if (selected != NULL)
		return selected;
652

Havoc Pennington's avatar
Havoc Pennington committed
653 654 655 656 657 658 659 660 661 662 663 664 665
        if (filename)
                g_set_error (error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
                             _("Couldn't recognize the image file format for file '%s'"),
                             filename);        
        else
                g_set_error (error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
                             _("Unrecognized image file format"));

        
666 667 668
	return NULL;
}

669 670 671 672 673 674 675 676 677 678 679

static void
prepared_notify (GdkPixbuf *pixbuf, 
		 GdkPixbufAnimation *anim, 
		 gpointer user_data)
{
	if (pixbuf != NULL)
		g_object_ref (pixbuf);
	*((GdkPixbuf **)user_data) = pixbuf;
}

680 681 682 683
GdkPixbuf *
_gdk_pixbuf_generic_image_load (GdkPixbufModule *module,
				FILE *f,
				GError **error)
684 685 686 687
{
	guchar buffer[4096];
	size_t length;
	GdkPixbuf *pixbuf = NULL;
688
	GdkPixbufAnimation *animation = NULL;
689 690 691 692 693
	gpointer context;

	if (module->load != NULL)
		return (* module->load) (f, error);
	
694 695 696
	if (module->begin_load != NULL) {
		
		context = module->begin_load (NULL, prepared_notify, NULL, &pixbuf, error);
697
	
698 699 700
		if (!context)
			return NULL;
		
701
		while (!feof (f) && !ferror (f)) {
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
			length = fread (buffer, 1, sizeof (buffer), f);
			if (length > 0)
				if (!module->load_increment (context, buffer, length, error)) {
					module->stop_load (context, NULL);
					if (pixbuf != NULL)
						g_object_unref (pixbuf);
					return NULL;
				}
		}
		
		if (!module->stop_load (context, error)) {
			if (pixbuf != NULL)
				g_object_unref (pixbuf);
			return NULL;
		}
		
		return pixbuf;
719
	}
720 721 722 723 724
	
	if (module->load_animation != NULL) {
		animation = (* module->load_animation) (f, error);
		if (animation != NULL) {
			pixbuf = gdk_pixbuf_animation_get_static_image (animation);
725

726 727 728 729 730 731
			g_object_ref (pixbuf);

			g_object_unref (animation);
			
			return pixbuf;
		}
732
	}
733 734

	return NULL;
735 736
}

Federico Mena Quintero's avatar
Federico Mena Quintero committed
737 738 739
/**
 * gdk_pixbuf_new_from_file:
 * @filename: Name of file to load.
Havoc Pennington's avatar
Havoc Pennington committed
740
 * @error: Return location for an error
Federico Mena Quintero's avatar
Federico Mena Quintero committed
741
 *
Federico Mena Quintero's avatar
Federico Mena Quintero committed
742
 * Creates a new pixbuf by loading an image from a file.  The file format is
Matthias Clasen's avatar
Matthias Clasen committed
743
 * detected automatically. If %NULL is returned, then @error will be set.
Havoc Pennington's avatar
Havoc Pennington committed
744
 * Possible errors are in the #GDK_PIXBUF_ERROR and #G_FILE_ERROR domains.
Federico Mena Quintero's avatar
Federico Mena Quintero committed
745
 *
Matthias Clasen's avatar
Matthias Clasen committed
746
 * Return value: A newly-created pixbuf with a reference count of 1, or %NULL if
Federico Mena Quintero's avatar
Federico Mena Quintero committed
747 748 749
 * any of several error conditions occurred:  the file could not be opened,
 * there was no loader for the file's format, there was not enough memory to
 * allocate the image buffer, or the image file contained invalid data.
Federico Mena Quintero's avatar
Federico Mena Quintero committed
750
 **/
751
GdkPixbuf *
Havoc Pennington's avatar
Havoc Pennington committed
752 753
gdk_pixbuf_new_from_file (const char *filename,
                          GError    **error)
Arturo Espinosa's avatar
Arturo Espinosa committed
754
{
755
	GdkPixbuf *pixbuf;
756
	int size;
Arturo Espinosa's avatar
Arturo Espinosa committed
757
	FILE *f;
758
	guchar buffer [128];
759
	GdkPixbufModule *image_module;
Arturo Espinosa's avatar
Arturo Espinosa committed
760

761
	g_return_val_if_fail (filename != NULL, NULL);
762
        g_return_val_if_fail (error == NULL || *error == NULL, NULL);
763

Tor Lillqvist's avatar
Tor Lillqvist committed
764
	f = fopen (filename, "rb");
Havoc Pennington's avatar
Havoc Pennington committed
765 766 767 768 769 770
	if (!f) {
                g_set_error (error,
                             G_FILE_ERROR,
                             g_file_error_from_errno (errno),
                             _("Failed to open file '%s': %s"),
                             filename, g_strerror (errno));
Arturo Espinosa's avatar
Arturo Espinosa committed
771
		return NULL;
Havoc Pennington's avatar
Havoc Pennington committed
772
        }
773

774 775
	size = fread (&buffer, 1, sizeof (buffer), f);
	if (size == 0) {
Havoc Pennington's avatar
Havoc Pennington committed
776 777 778 779 780 781
                g_set_error (error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                             _("Image file '%s' contains no data"),
                             filename);
                
782
		fclose (f);
Arturo Espinosa's avatar
Arturo Espinosa committed
783
		return NULL;
784
	}
Arturo Espinosa's avatar
Arturo Espinosa committed
785

786
	image_module = _gdk_pixbuf_get_module (buffer, size, filename, error);
Havoc Pennington's avatar
Havoc Pennington committed
787 788 789 790
        if (image_module == NULL) {
                fclose (f);
                return NULL;
        }
791

792
	if (image_module->module == NULL)
793
                if (!_gdk_pixbuf_load_module (image_module, error)) {
Havoc Pennington's avatar
Havoc Pennington committed
794 795 796
                        fclose (f);
                        return NULL;
                }
797

798
	fseek (f, 0, SEEK_SET);
799
	pixbuf = _gdk_pixbuf_generic_image_load (image_module, f, error);
800
	fclose (f);
801

Havoc Pennington's avatar
Havoc Pennington committed
802 803 804 805
        if (pixbuf == NULL && error != NULL && *error == NULL) {
                /* I don't trust these crufty longjmp()'ing image libs
                 * to maintain proper error invariants, and I don't
                 * want user code to segfault as a result. We need to maintain
806
                 * the invariastable/gdk-pixbuf/nt that error gets set if NULL is returned.
Havoc Pennington's avatar
Havoc Pennington committed
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
                 */
                
                g_warning ("Bug! gdk-pixbuf loader '%s' didn't set an error on failure.", image_module->module_name);
                g_set_error (error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_FAILED,
                             _("Failed to load image '%s': reason not known, probably a corrupt image file"),
                             filename);
                
        } else if (error != NULL && *error != NULL) {

          /* Add the filename to the error message */
          GError *e = *error;
          gchar *old;
          
          old = e->message;

          e->message = g_strdup_printf (_("Failed to load image '%s': %s"),
                                        filename, old);

          g_free (old);
        }
                
830
	return pixbuf;
Arturo Espinosa's avatar
Arturo Espinosa committed
831
}
832

833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
static void
size_prepared_cb (GdkPixbufLoader *loader, 
		  int              width,
		  int              height,
		  gpointer         data)
{
	struct {
		int width;
		int height;
	} *info = data;

	g_return_if_fail (width > 0 && height > 0);

	if ((double)height * (double)info->width >
	    (double)width * (double)info->height) {
		width = 0.5 + (double)width * (double)info->height / (double)height;
		height = info->height;
	} else {
		height = 0.5 + (double)height * (double)info->width / (double)width;
		width = info->width;
	}

	gdk_pixbuf_loader_set_size (loader, width, height);
}

858 859 860 861 862 863 864 865 866 867
/**
 * gdk_pixbuf_new_from_file_at_size:
 * @filename: Name of file to load.
 * @width: The width the image should have
 * @height: The height the image should have
 * @error: Return location for an error
 *
 * Creates a new pixbuf by loading an image from a file.  The file format is
 * detected automatically. If %NULL is returned, then @error will be set.
 * Possible errors are in the #GDK_PIXBUF_ERROR and #G_FILE_ERROR domains.
868
 * The image will be scaled to fit in the requested size, preserving its aspect ratio.
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
 *
 * Return value: A newly-created pixbuf with a reference count of 1, or %NULL if
 * any of several error conditions occurred:  the file could not be opened,
 * there was no loader for the file's format, there was not enough memory to
 * allocate the image buffer, or the image file contained invalid data.
 *
 * Since: 2.4
 **/
GdkPixbuf *
gdk_pixbuf_new_from_file_at_size (const char *filename,
				  int         width, 
				  int         height,
				  GError    **error)
{
	GdkPixbufLoader *loader;
	GdkPixbuf       *pixbuf;

	guchar buffer [4096];
	int length;
	FILE *f;
889 890 891 892
	struct {
		gint width;
		gint height;
	} info;
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907

	g_return_val_if_fail (filename != NULL, NULL);
        g_return_val_if_fail (width > 0 && height > 0, NULL);

	f = fopen (filename, "rb");
	if (!f) {
                g_set_error (error,
                             G_FILE_ERROR,
                             g_file_error_from_errno (errno),
                             _("Failed to open file '%s': %s"),
                             filename, g_strerror (errno));
		return NULL;
        }

	loader = gdk_pixbuf_loader_new ();
908 909 910 911 912

	info.width = width;
	info.height = height;
		
	g_signal_connect (loader, "size-prepared", G_CALLBACK (size_prepared_cb), &info);
913

914
	while (!feof (f) && !ferror (f)) {
915 916 917
		length = fread (buffer, 1, sizeof (buffer), f);
		if (length > 0)
			if (!gdk_pixbuf_loader_write (loader, buffer, length, error)) {
918
				gdk_pixbuf_loader_close (loader, NULL);
919
				fclose (f);
920
				g_object_unref (loader);
921 922 923 924 925 926 927
				return NULL;
			}
	}

	fclose (f);

	if (!gdk_pixbuf_loader_close (loader, error)) {
928
		g_object_unref (loader);
929 930 931 932 933 934
		return NULL;
	}

	pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);

	if (!pixbuf) {
935
		g_object_unref (loader);
936 937 938 939 940 941 942 943 944 945
		g_set_error (error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_FAILED,
                             _("Failed to load image '%s': reason not known, probably a corrupt image file"),
                             filename);
		return NULL;
	}

	g_object_ref (pixbuf);

946
	g_object_unref (loader);
947 948 949 950

	return pixbuf;
}

951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
static void
info_cb (GdkPixbufLoader *loader, 
	 int              width,
	 int              height,
	 gpointer         data)
{
	struct {
		GdkPixbufFormat *format;
		int width;
		int height;
	} *info = data;

	g_return_if_fail (width > 0 && height > 0);

	info->format = gdk_pixbuf_loader_get_format (loader);
	info->width = width;
	info->height = height;

	gdk_pixbuf_loader_set_size (loader, 0, 0);
}

/**
 * gdk_pixbuf_get_file_info:
 * @filename: The name of the file to identify.
 * @width: Return location for the width of the image, or %NULL
 * @height: Return location for the height of the image, or %NULL
 * 
 * Parses an image file far enough to determine its format and size.
 * 
 * Returns: A #GdkPixbufFormat describing the image format of the file 
 *    or %NULL if the image format wasn't recognized. The return value 
 *    is owned by GdkPixbuf and should not be freed.
 *
 * Since: 2.4
 **/
GdkPixbufFormat *
gdk_pixbuf_get_file_info (const gchar  *filename,
			  gint         *width, 
			  gint         *height)
{
	GdkPixbufLoader *loader;
	guchar buffer [4096];
	int length;
	FILE *f;
	struct {
		GdkPixbufFormat *format;
		gint width;
		gint height;
	} info;

	g_return_val_if_fail (filename != NULL, NULL);

	f = fopen (filename, "rb");
	if (!f)
		return NULL;

	loader = gdk_pixbuf_loader_new ();

	info.format = NULL;
	info.width = -1;
	info.height = -1;
		
	g_signal_connect (loader, "size-prepared", G_CALLBACK (info_cb), &info);

1015
	while (!feof (f) && !ferror (f)) {
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
		length = fread (buffer, 1, sizeof (buffer), f);
		if (length > 0) {
			if (!gdk_pixbuf_loader_write (loader, buffer, length, NULL))
				break;
		}
		if (info.format != NULL)
			break;
	}

	fclose (f);
	gdk_pixbuf_loader_close (loader, NULL);
1027
	g_object_unref (loader);
1028 1029 1030 1031 1032 1033 1034 1035 1036

	if (width) 
		*width = info.width;
	if (height) 
		*height = info.height;

	return info.format;
}

Federico Mena Quintero's avatar
Federico Mena Quintero committed
1037 1038
/**
 * gdk_pixbuf_new_from_xpm_data:
Federico Mena Quintero's avatar
Federico Mena Quintero committed
1039
 * @data: Pointer to inline XPM data.
1040
 *
Federico Mena Quintero's avatar
Federico Mena Quintero committed
1041 1042
 * Creates a new pixbuf by parsing XPM data in memory.  This data is commonly
 * the result of including an XPM file into a program's C source.
1043
 *
Federico Mena Quintero's avatar
Federico Mena Quintero committed
1044 1045
 * Return value: A newly-created pixbuf with a reference count of 1.
 **/
1046
GdkPixbuf *
1047
gdk_pixbuf_new_from_xpm_data (const char **data)
1048
{
1049 1050
	GdkPixbuf *(* load_xpm_data) (const char **data);
	GdkPixbuf *pixbuf;
Havoc Pennington's avatar
Havoc Pennington committed
1051
        GError *error = NULL;
1052 1053 1054 1055 1056 1057
	GdkPixbufModule *xpm_module = _gdk_pixbuf_get_named_module ("xpm", &error);
	if (xpm_module == NULL) {
		g_warning ("Error loading XPM image loader: %s", error->message);
		g_error_free (error);
		return NULL;
	}
1058

1059 1060
	if (xpm_module->module == NULL) {
                if (!_gdk_pixbuf_load_module (xpm_module, &error)) {
Havoc Pennington's avatar
Havoc Pennington committed
1061 1062
                        g_warning ("Error loading XPM image loader: %s", error->message);
                        g_error_free (error);
1063
                        return NULL;
Havoc Pennington's avatar
Havoc Pennington committed
1064 1065 1066
                }
        }
          
1067
	if (xpm_module->load_xpm_data == NULL) {
1068
		g_warning ("gdk-pixbuf XPM module lacks XPM data capability");
1069
		return NULL;
1070
	} else
1071
		load_xpm_data = xpm_module->load_xpm_data;
1072

1073 1074
	pixbuf = (* load_xpm_data) (data);
	return pixbuf;
1075
}
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112

static void
collect_save_options (va_list   opts,
                      gchar  ***keys,
                      gchar  ***vals)
{
  gchar *key;
  gchar *val;
  gchar *next;
  gint count;

  count = 0;
  *keys = NULL;
  *vals = NULL;
  
  next = va_arg (opts, gchar*);
  while (next)
    {
      key = next;
      val = va_arg (opts, gchar*);

      ++count;

      /* woo, slow */
      *keys = g_realloc (*keys, sizeof(gchar*) * (count + 1));
      *vals = g_realloc (*vals, sizeof(gchar*) * (count + 1));
      
      (*keys)[count-1] = g_strdup (key);
      (*vals)[count-1] = g_strdup (val);

      (*keys)[count] = NULL;
      (*vals)[count] = NULL;
      
      next = va_arg (opts, gchar*);
    }
}

1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
static gboolean
save_to_file_callback (const gchar *buf,
		       gsize        count,
		       GError     **error,
		       gpointer     data)
{
	FILE *filehandle = data;
	gsize n;

	n = fwrite (buf, 1, count, filehandle);
	if (n != count) {
                g_set_error (error,
                             G_FILE_ERROR,
                             g_file_error_from_errno (errno),
                             _("Error writing to image file: %s"),
                             g_strerror (errno));
                return FALSE;
	}
	return TRUE;
}