gdk-pixbuf-io.c 33.1 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

Arturo Espinosa's avatar
Arturo Espinosa committed
25
#include <config.h>
26 27
#include <stdlib.h>
#include <stdio.h>
28
#include <string.h>
29
#include <glib.h>
30
#include <errno.h>
31
#include "gdk-pixbuf-private.h"
32
#include "gdk-pixbuf-io.h"
Arturo Espinosa's avatar
Arturo Espinosa committed
33

34 35 36 37 38 39
#ifdef G_OS_WIN32
#define STRICT
#include <windows.h>
#undef STRICT
#endif

40 41
static gint 
format_check (GdkPixbufModule *module, guchar *buffer, int size)
42
{
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
	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;
71 72
}

73
static GSList *file_formats = NULL;
74

75
static void gdk_pixbuf_io_init ();
76

77 78
static GSList *
get_file_formats ()
79
{
80 81 82 83
	if (file_formats == NULL)
		gdk_pixbuf_io_init ();
	
	return file_formats;
84 85
}

86

87
#ifdef USE_GMODULE 
88 89

static gboolean
90
scan_string (const char **pos, GString *out)
91
{
92 93 94 95 96 97 98 99
	const char *p = *pos, *q = *pos;
	char *tmp, *tmp2;
	gboolean quoted;
	
	while (g_ascii_isspace (*p))
		p++;
	
	if (!*p)
100
		return FALSE;
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
	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);
116
	}
117 118 119 120
	
	q++;
	*pos = q;
	
121 122 123
	return TRUE;
}

124
static gboolean
125
scan_int (const char **pos, int *out)
126
{
127 128 129 130 131 132 133 134
	int i = 0;
	char buf[32];
	const char *p = *pos;
	
	while (g_ascii_isspace (*p))
		p++;
	
	if (*p < '0' || *p > '9')
135
		return FALSE;
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
	
	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;
151 152 153 154

	return TRUE;
}

155
static gboolean
156
skip_space (const char **pos)
157
{
158 159 160 161 162 163 164 165
	const char *p = *pos;
	
	while (g_ascii_isspace (*p))
		p++;
  
	*pos = p;
	
	return !(*p == '\0');
166
}
167 168 169
  
static gchar *
gdk_pixbuf_get_module_file (void)
170
{
171
  gchar *result = g_strdup (g_getenv ("GDK_PIXBUF_MODULE_FILE"));
172

173 174
  if (!result)
	  result = g_build_filename (GTK_SYSCONFDIR, "gtk-2.0", "gdk-pixbuf.loaders", NULL);
175

176
  return result;
177 178
}

179 180
static void 
gdk_pixbuf_io_init ()
181
{
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
	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;
205

206
		line_buf[term] = 0;
207

208 209 210 211 212 213 214 215 216 217
		if (!skip_space (&p)) {
				/* Blank line marking the end of a module
				 */
			if (module && *p != '#') {
				file_formats = g_slist_prepend (file_formats, module);
				module = NULL;
			}
			
			goto next_line;
		}
Arturo Espinosa's avatar
Arturo Espinosa committed
218

219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
		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
244

245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 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 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
			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
332
}
333

Tor Lillqvist's avatar
Tor Lillqvist committed
334 335
#ifdef G_OS_WIN32

336 337 338 339
/* DllMain function needed to tuck away the gdk-pixbuf DLL name */

G_WIN32_DLLMAIN_FOR_DLL_NAME (static, dll_name)

Tor Lillqvist's avatar
Tor Lillqvist committed
340 341 342 343 344 345
static char *
get_libdir (void)
{
  static char *libdir = NULL;

  if (libdir == NULL)
Tor Lillqvist's avatar
Tor Lillqvist committed
346
    libdir = g_win32_get_package_installation_subdirectory
347
      (GETTEXT_PACKAGE, dll_name, "lib\\gtk-2.0\\" GTK_BINARY_VERSION "\\loaders");
Tor Lillqvist's avatar
Tor Lillqvist committed
348 349 350 351

  return libdir;
}

352
#undef PIXBUF_LIBDIR
Tor Lillqvist's avatar
Tor Lillqvist committed
353 354 355 356
#define PIXBUF_LIBDIR get_libdir ()

#endif

357 358 359
/* 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
360
gboolean
361 362
_gdk_pixbuf_load_module (GdkPixbufModule *image_module,
                         GError         **error)
Arturo Espinosa's avatar
Arturo Espinosa committed
363
{
364 365
	char *path;
	GModule *module;
366
	gpointer sym;
Federico Mena Quintero's avatar
Federico Mena Quintero committed
367
	
Havoc Pennington's avatar
Havoc Pennington committed
368
        g_return_val_if_fail (image_module->module == NULL, FALSE);
369

370
	path = image_module->module_path;
371
	module = g_module_open (path, G_MODULE_BIND_LAZY);
372 373 374 375 376 377 378 379

        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;
380 381
        }

382 383
	image_module->module = module;        
        
384 385
        if (g_module_symbol (module, "fill_vtable", &sym)) {
                GdkPixbufModuleFillVtableFunc func = (GdkPixbufModuleFillVtableFunc) sym;
386
                (* func) (image_module);
387
                return TRUE;
388 389 390 391 392 393
        } 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);
394
                return FALSE;
395
        }
Arturo Espinosa's avatar
Arturo Espinosa committed
396
}
Federico Mena Quintero's avatar
Federico Mena Quintero committed
397 398
#else

399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
#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);
416
module (pcx);
Federico Mena Quintero's avatar
Federico Mena Quintero committed
417

Havoc Pennington's avatar
Havoc Pennington committed
418
gboolean
419 420
_gdk_pixbuf_load_module (GdkPixbufModule *image_module,
                         GError         **error)
Federico Mena Quintero's avatar
Federico Mena Quintero committed
421
{
422 423 424
	GdkPixbufModuleFillInfoFunc fill_info = NULL;
        GdkPixbufModuleFillVtableFunc fill_vtable = NULL;

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

427 428 429 430
        if (FALSE) {
                /* Ugly hack so we can use else if unconditionally below ;-) */
        }
        
431
#ifdef INCLUDE_png	
432 433 434
	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
435
	}
436
#endif
Federico Mena Quintero's avatar
Federico Mena Quintero committed
437

438
#ifdef INCLUDE_bmp	
439 440 441
	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
442
	}
443
#endif
Federico Mena Quintero's avatar
Federico Mena Quintero committed
444

445
#ifdef INCLUDE_wbmp
446 447 448
	else if (strcmp (image_module->module_name, "wbmp") == 0) {
                fill_info = MODULE_ENTRY (wbmp, fill_info);
                fill_vtable = MODULE_ENTRY (wbmp, fill_vtable);
449
	}
450
#endif
451

452
#ifdef INCLUDE_gif
453 454 455
	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
456
	}
457
#endif
Federico Mena Quintero's avatar
Federico Mena Quintero committed
458

459
#ifdef INCLUDE_ico
460 461 462
	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
463
	}
464
#endif
Federico Mena Quintero's avatar
Federico Mena Quintero committed
465

466
#ifdef INCLUDE_ani
467 468 469
	else if (strcmp (image_module->module_name, "ani") == 0) {
                fill_info = MODULE_ENTRY (ani, fill_info);
                fill_vtable = MODULE_ENTRY (ani, fill_vtable);
470 471 472
	}
#endif

473
#ifdef INCLUDE_jpeg
474 475 476
	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
477
	}
478 479 480
#endif

#ifdef INCLUDE_pnm
481 482 483
	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
484
	}
485 486 487
#endif

#ifdef INCLUDE_ras
488 489 490
	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
491
	}
492 493 494
#endif

#ifdef INCLUDE_tiff
495 496 497
	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
498
	}
499
#endif
Havoc Pennington's avatar
Havoc Pennington committed
500

501
#ifdef INCLUDE_xpm
502 503 504
	else if (strcmp (image_module->module_name, "xpm") == 0) {
                fill_info = MODULE_ENTRY (xpm, fill_info);
                fill_vtable = MODULE_ENTRY (xpm, fill_vtable);
505 506 507
	}
#endif

508
#ifdef INCLUDE_xbm
509 510 511
	else if (strcmp (image_module->module_name, "xbm") == 0) {
                fill_info = MODULE_ENTRY (xbm, fill_info);
                fill_vtable = MODULE_ENTRY (xbm, fill_vtable);
512 513 514
	}
#endif

515
#ifdef INCLUDE_tga
516 517 518
	else if (strcmp (image_module->module_name, "tga") == 0) {
                fill_info = MODULE_ENTRY (tga, fill_info);
		fill_vtable = MODULE_ENTRY (tga, fill_vtable);
519 520
	}
#endif
521
        
522 523 524 525 526 527 528
#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
        
529 530
        if (fill_vtable) {
                (* fill_vtable) (image_module);
531 532 533
		image_module->info = g_new0 (GdkPixbufFormat, 1);
		(* fill_info) (image_module->info);

534 535 536 537 538 539 540 541 542 543
                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
544 545
}

546 547 548 549 550 551
static void 
gdk_pixbuf_io_init ()
{
	gchar *included_formats[] = { 
		"ani", "png", "bmp", "wbmp", "gif", 
		"ico", "jpeg", "pnm", "ras", "tiff", 
552
		"xpm", "xbm", "tga", "pcx",
553 554 555 556 557 558 559 560 561 562 563 564 565 566
		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
567 568

#endif
Arturo Espinosa's avatar
Arturo Espinosa committed
569

570 571


572
GdkPixbufModule *
573 574
_gdk_pixbuf_get_named_module (const char *name,
                              GError **error)
575
{
576
	GSList *modules;
577

578 579 580 581
	for (modules = get_file_formats (); modules; modules = g_slist_next (modules)) {
		GdkPixbufModule *module = (GdkPixbufModule *)modules->data;
		if (!strcmp (name, module->module_name))
			return module;
582 583
	}

Havoc Pennington's avatar
Havoc Pennington committed
584 585 586 587 588 589
        g_set_error (error,
                     GDK_PIXBUF_ERROR,
                     GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
                     _("Image type '%s' is not supported"),
                     name);
        
590 591 592
	return NULL;
}

593
GdkPixbufModule *
594 595 596
_gdk_pixbuf_get_module (guchar *buffer, guint size,
                        const gchar *filename,
                        GError **error)
597
{
598 599 600 601 602 603 604 605 606 607 608 609 610
	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;
611
	}
612 613
	if (selected != NULL)
		return selected;
614

Havoc Pennington's avatar
Havoc Pennington committed
615 616 617 618 619 620 621 622 623 624 625 626 627
        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"));

        
628 629 630
	return NULL;
}

631 632 633 634 635 636 637 638 639 640 641

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

642 643 644 645
GdkPixbuf *
_gdk_pixbuf_generic_image_load (GdkPixbufModule *module,
				FILE *f,
				GError **error)
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
{
	guchar buffer[4096];
	size_t length;
	GdkPixbuf *pixbuf = NULL;
	gpointer context;

	if (module->load != NULL)
		return (* module->load) (f, error);
	
	context = module->begin_load (NULL, prepared_notify, NULL, &pixbuf, error);
	
	if (!context)
		return NULL;
	
	while (!feof (f)) {
		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;
}

Federico Mena Quintero's avatar
Federico Mena Quintero committed
680 681 682
/**
 * gdk_pixbuf_new_from_file:
 * @filename: Name of file to load.
Havoc Pennington's avatar
Havoc Pennington committed
683
 * @error: Return location for an error
Federico Mena Quintero's avatar
Federico Mena Quintero committed
684
 *
Federico Mena Quintero's avatar
Federico Mena Quintero committed
685
 * Creates a new pixbuf by loading an image from a file.  The file format is
Matthias Clasen's avatar
Matthias Clasen committed
686
 * detected automatically. If %NULL is returned, then @error will be set.
Havoc Pennington's avatar
Havoc Pennington committed
687
 * Possible errors are in the #GDK_PIXBUF_ERROR and #G_FILE_ERROR domains.
Federico Mena Quintero's avatar
Federico Mena Quintero committed
688
 *
Matthias Clasen's avatar
Matthias Clasen committed
689
 * Return value: A newly-created pixbuf with a reference count of 1, or %NULL if
Federico Mena Quintero's avatar
Federico Mena Quintero committed
690 691 692
 * 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
693
 **/
694
GdkPixbuf *
Havoc Pennington's avatar
Havoc Pennington committed
695 696
gdk_pixbuf_new_from_file (const char *filename,
                          GError    **error)
Arturo Espinosa's avatar
Arturo Espinosa committed
697
{
698
	GdkPixbuf *pixbuf;
699
	int size;
Arturo Espinosa's avatar
Arturo Espinosa committed
700
	FILE *f;
701
	guchar buffer [128];
702
	GdkPixbufModule *image_module;
Arturo Espinosa's avatar
Arturo Espinosa committed
703

704
	g_return_val_if_fail (filename != NULL, NULL);
705
        g_return_val_if_fail (error == NULL || *error == NULL, NULL);
706

Tor Lillqvist's avatar
Tor Lillqvist committed
707
	f = fopen (filename, "rb");
Havoc Pennington's avatar
Havoc Pennington committed
708 709 710 711 712 713
	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
714
		return NULL;
Havoc Pennington's avatar
Havoc Pennington committed
715
        }
716

717 718
	size = fread (&buffer, 1, sizeof (buffer), f);
	if (size == 0) {
Havoc Pennington's avatar
Havoc Pennington committed
719 720 721 722 723 724
                g_set_error (error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                             _("Image file '%s' contains no data"),
                             filename);
                
725
		fclose (f);
Arturo Espinosa's avatar
Arturo Espinosa committed
726
		return NULL;
727
	}
Arturo Espinosa's avatar
Arturo Espinosa committed
728

729
	image_module = _gdk_pixbuf_get_module (buffer, size, filename, error);
Havoc Pennington's avatar
Havoc Pennington committed
730 731 732 733
        if (image_module == NULL) {
                fclose (f);
                return NULL;
        }
734

735
	if (image_module->module == NULL)
736
                if (!_gdk_pixbuf_load_module (image_module, error)) {
Havoc Pennington's avatar
Havoc Pennington committed
737 738 739
                        fclose (f);
                        return NULL;
                }
740

741
	fseek (f, 0, SEEK_SET);
742
	pixbuf = _gdk_pixbuf_generic_image_load (image_module, f, error);
743
	fclose (f);
744

Havoc Pennington's avatar
Havoc Pennington committed
745 746 747 748
        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
749
                 * the invariastable/gdk-pixbuf/nt that error gets set if NULL is returned.
Havoc Pennington's avatar
Havoc Pennington committed
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
                 */
                
                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);
        }
                
773
	return pixbuf;
Arturo Espinosa's avatar
Arturo Espinosa committed
774
}
775

776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
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);
}

801 802 803 804 805 806 807 808 809 810
/**
 * 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.
811
 * The image will be scaled to fit in the requested size, preserving its aspect ratio.
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
 *
 * 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;
832 833 834 835
	struct {
		gint width;
		gint height;
	} info;
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850

	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 ();
851 852 853 854 855

	info.width = width;
	info.height = height;
		
	g_signal_connect (loader, "size-prepared", G_CALLBACK (size_prepared_cb), &info);
856 857 858 859 860

	while (!feof (f)) {
		length = fread (buffer, 1, sizeof (buffer), f);
		if (length > 0)
			if (!gdk_pixbuf_loader_write (loader, buffer, length, error)) {
861
				gdk_pixbuf_loader_close (loader, NULL);
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
				fclose (f);
				g_object_unref (G_OBJECT (loader));
				return NULL;
			}
	}

	fclose (f);

	if (!gdk_pixbuf_loader_close (loader, error)) {
		g_object_unref (G_OBJECT (loader));
		return NULL;
	}

	pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);

	if (!pixbuf) {
		g_object_unref (G_OBJECT (loader));
		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);

	g_object_unref (G_OBJECT (loader));

	return pixbuf;
}

Federico Mena Quintero's avatar
Federico Mena Quintero committed
894 895
/**
 * gdk_pixbuf_new_from_xpm_data:
Federico Mena Quintero's avatar
Federico Mena Quintero committed
896
 * @data: Pointer to inline XPM data.
897
 *
Federico Mena Quintero's avatar
Federico Mena Quintero committed
898 899
 * 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.
900
 *
Federico Mena Quintero's avatar
Federico Mena Quintero committed
901 902
 * Return value: A newly-created pixbuf with a reference count of 1.
 **/
903
GdkPixbuf *
904
gdk_pixbuf_new_from_xpm_data (const char **data)
905
{
906 907
	GdkPixbuf *(* load_xpm_data) (const char **data);
	GdkPixbuf *pixbuf;
Havoc Pennington's avatar
Havoc Pennington committed
908
        GError *error = NULL;
909 910 911 912 913 914
	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;
	}
915

916 917
	if (xpm_module->module == NULL) {
                if (!_gdk_pixbuf_load_module (xpm_module, &error)) {
Havoc Pennington's avatar
Havoc Pennington committed
918 919
                        g_warning ("Error loading XPM image loader: %s", error->message);
                        g_error_free (error);
920
                        return NULL;
Havoc Pennington's avatar
Havoc Pennington committed
921 922 923
                }
        }
          
924
	if (xpm_module->load_xpm_data == NULL) {
925
		g_warning ("gdk-pixbuf XPM module lacks XPM data capability");
926
		return NULL;
927
	} else
928
		load_xpm_data = xpm_module->load_xpm_data;
929

930 931
	pixbuf = (* load_xpm_data) (data);
	return pixbuf;
932
}
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972

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*);
    }
}

static gboolean
gdk_pixbuf_real_save (GdkPixbuf     *pixbuf, 
                      FILE          *filehandle, 
973
                      const char    *type, 
974 975 976 977 978
                      gchar        **keys,
                      gchar        **values,
                      GError       **error)
{
       GdkPixbufModule *image_module = NULL;       
Havoc Pennington's avatar
Havoc Pennington committed
979

980
       image_module = _gdk_pixbuf_get_named_module (type, error);
Havoc Pennington's avatar
Havoc Pennington committed
981 982 983

       if (image_module == NULL)
               return FALSE;
984
       
Havoc Pennington's avatar
Havoc Pennington committed
985
       if (image_module->module == NULL)
986
               if (!_gdk_pixbuf_load_module (image_module, error))
Havoc Pennington's avatar
Havoc Pennington committed
987 988 989
                       return FALSE;

       if (image_module->save == NULL) {
990 991
               g_set_error (error,
                            GDK_PIXBUF_ERROR,
Havoc Pennington's avatar
Havoc Pennington committed
992 993 994
                            GDK_PIXBUF_ERROR_UNSUPPORTED_OPERATION,
                            _("This build of gdk-pixbuf does not support saving the image format: %s"),
                            type);
995 996
               return FALSE;
       }
Havoc Pennington's avatar
Havoc Pennington committed
997
               
998 999 1000 1001 1002 1003 1004 1005
       return (* image_module->save) (filehandle, pixbuf,
                                      keys, values,
                                      error);
}

 
/**
 * gdk_pixbuf_save:
1006 1007
 * @pixbuf: a #GdkPixbuf.
 * @filename: name of file to save.
1008
 * @type: name of file format.
1009
 * @error: return location for error, or %NULL
1010 1011
 * @Varargs: list of key-value save options
 *
1012 1013
 * Saves pixbuf to a file in @type, which is currently "jpeg", "png" or
 * "ico".  If @error is set, %FALSE will be returned. Possible errors include 
1014
 * those in the #GDK_PIXBUF_ERROR domain and those in the #G_FILE_ERROR domain.
1015
 *
Matthias Clasen's avatar
Matthias Clasen committed
1016
 * The variable argument list should be %NULL-terminated; if not empty,
1017 1018
 * it should contain pairs of strings that modify the save
 * parameters. For example:
Matthias Clasen's avatar
Matthias Clasen committed
1019
 * <informalexample><programlisting>
1020
 * gdk_pixbuf_save (pixbuf, handle, "jpeg", &amp;error,
1021
 *                  "quality", "100", NULL);
Matthias Clasen's avatar
Matthias Clasen committed
1022
 * </programlisting></informalexample>
1023
 *
1024 1025 1026 1027
 * Currently only few parameters exist. JPEG images can be saved with a 
 * "quality" parameter; its value should be in the range [0,100]. 
 * Text chunks can be attached to PNG images by specifying parameters of
 * the form "tEXt::key", where key is an ASCII string of length 1-79.
1028
 * The values are UTF-8 encoded strings. 
1029 1030 1031
 * ICO images can be saved in depth 16, 24, or 32, by using the "depth"
 * parameter. When the ICO saver is given "x_hot" and "y_hot" parameters,
 * it produces a CUR instead of an ICO.
1032 1033 1034 1035 1036 1037 1038
 *
 * Return value: whether an error was set
 **/

gboolean
gdk_pixbuf_save (GdkPixbuf  *pixbuf, 
                 const char *filename, 
1039
                 const char *type, 
1040 1041 1042 1043 1044 1045 1046
                 GError    **error,
                 ...)
{
        gchar **keys = NULL;
        gchar **values = NULL;
        va_list args;
        gboolean result;
1047 1048

        g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1049 1050 1051 1052 1053 1054 1055
        
        va_start (args, error);
        
        collect_save_options (args, &keys, &values);
        
        va_end (args);

1056
        result = gdk_pixbuf_savev (pixbuf, filename, type,
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
                                   keys, values,
                                   error);

        g_strfreev (keys);
        g_strfreev (values);

        return result;
}

/**
 * gdk_pixbuf_savev:
1068 1069
 * @pixbuf: a #GdkPixbuf.
 * @filename: name of file to save.
1070
 * @type: name of file format.
Matthias Clasen's avatar
Matthias Clasen committed
1071
 * @option_keys: name of options to set, %NULL-terminated
1072
 * @option_values: values for named options
Matthias Clasen's avatar
Matthias Clasen committed
1073
 * @error: return location for error, or %NULL
1074
 *
1075
 * Saves pixbuf to a file in @type, which is currently "jpeg" or "png".
Matthias Clasen's avatar
Matthias Clasen committed
1076
 * If @error is set, %FALSE will be returned. See gdk_pixbuf_save () for more