gdk-pixbuf-io.c 52.7 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-alias.h"
37
#include "gdk-pixbuf-private.h"
38
#include "gdk-pixbuf-io.h"
Arturo Espinosa's avatar
Arturo Espinosa committed
39

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

46 47
static gint 
format_check (GdkPixbufModule *module, guchar *buffer, int size)
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 76
	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;
77 78
}

79
static GSList *file_formats = NULL;
80

81
static void gdk_pixbuf_io_init ();
82

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

92

93
#ifdef USE_GMODULE 
94 95

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

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

	return TRUE;
}

161
static gboolean
162
skip_space (const char **pos)
163
{
164 165 166 167 168 169 170 171
	const char *p = *pos;
	
	while (g_ascii_isspace (*p))
		p++;
  
	*pos = p;
	
	return !(*p == '\0');
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 226
#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

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

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

235
  return result;
236 237
}

238 239
static void 
gdk_pixbuf_io_init ()
240
{
241 242 243 244 245 246 247 248 249 250 251 252 253 254
	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) {
255
		g_warning ("Cannot open pixbuf loader module file '%s': %s",
256 257 258 259 260 261 262 263
			   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;
264

265
		line_buf[term] = 0;
266

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

/* 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
399
gboolean
400 401
_gdk_pixbuf_load_module (GdkPixbufModule *image_module,
                         GError         **error)
Arturo Espinosa's avatar
Arturo Espinosa committed
402
{
403 404
	char *path;
	GModule *module;
405
	gpointer sym;
Federico Mena Quintero's avatar
Federico Mena Quintero committed
406
	
Havoc Pennington's avatar
Havoc Pennington committed
407
        g_return_val_if_fail (image_module->module == NULL, FALSE);
408

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

        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;
419 420
        }

421 422
	image_module->module = module;        
        
423 424
        if (g_module_symbol (module, "fill_vtable", &sym)) {
                GdkPixbufModuleFillVtableFunc func = (GdkPixbufModuleFillVtableFunc) sym;
425
                (* func) (image_module);
426
                return TRUE;
427 428 429 430 431 432
        } 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);
433
                return FALSE;
434
        }
Arturo Espinosa's avatar
Arturo Espinosa committed
435
}
Federico Mena Quintero's avatar
Federico Mena Quintero committed
436 437
#else

438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
#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);
455
module (pcx);
Federico Mena Quintero's avatar
Federico Mena Quintero committed
456

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

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

466 467 468 469
        if (FALSE) {
                /* Ugly hack so we can use else if unconditionally below ;-) */
        }
        
470
#ifdef INCLUDE_png	
471 472 473
	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
474
	}
475
#endif
Federico Mena Quintero's avatar
Federico Mena Quintero committed
476

477
#ifdef INCLUDE_bmp	
478 479 480
	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
481
	}
482
#endif
Federico Mena Quintero's avatar
Federico Mena Quintero committed
483

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

491
#ifdef INCLUDE_gif
492 493 494
	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
495
	}
496
#endif
Federico Mena Quintero's avatar
Federico Mena Quintero committed
497

498
#ifdef INCLUDE_ico
499 500 501
	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
502
	}
503
#endif
Federico Mena Quintero's avatar
Federico Mena Quintero committed
504

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

512
#ifdef INCLUDE_jpeg
513 514 515
	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
516
	}
517 518 519
#endif

#ifdef INCLUDE_pnm
520 521 522
	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
523
	}
524 525 526
#endif

#ifdef INCLUDE_ras
527 528 529
	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
530
	}
531 532 533
#endif

#ifdef INCLUDE_tiff
534 535 536
	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
537
	}
538
#endif
Havoc Pennington's avatar
Havoc Pennington committed
539

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

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

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

573 574 575 576 577 578 579 580 581 582
                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
583 584
}

585 586 587 588 589 590
static void 
gdk_pixbuf_io_init ()
{
	gchar *included_formats[] = { 
		"ani", "png", "bmp", "wbmp", "gif", 
		"ico", "jpeg", "pnm", "ras", "tiff", 
591
		"xpm", "xbm", "tga", "pcx",
592 593 594 595 596 597 598 599 600 601 602 603 604 605
		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
606 607

#endif
Arturo Espinosa's avatar
Arturo Espinosa committed
608

609 610


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

617 618
	for (modules = get_file_formats (); modules; modules = g_slist_next (modules)) {
		GdkPixbufModule *module = (GdkPixbufModule *)modules->data;
619 620 621 622

		if (module->info->disabled)
			continue;

623 624
		if (!strcmp (name, module->module_name))
			return module;
625 626
	}

Havoc Pennington's avatar
Havoc Pennington committed
627 628 629 630 631 632
        g_set_error (error,
                     GDK_PIXBUF_ERROR,
                     GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
                     _("Image type '%s' is not supported"),
                     name);
        
633 634 635
	return NULL;
}

636
GdkPixbufModule *
637 638 639
_gdk_pixbuf_get_module (guchar *buffer, guint size,
                        const gchar *filename,
                        GError **error)
640
{
641 642 643 644
	GSList *modules;

	gint score, best = 0;
	GdkPixbufModule *selected = NULL;
645 646
	gchar *utf8_filename = NULL;

647 648
	for (modules = get_file_formats (); modules; modules = g_slist_next (modules)) {
		GdkPixbufModule *module = (GdkPixbufModule *)modules->data;
649 650 651 652

		if (module->info->disabled)
			continue;

653 654 655 656 657 658 659
		score = format_check (module, buffer, size);
		if (score > best) {
			best = score; 
			selected = module;
		}
		if (score >= 100) 
			break;
660
	}
661 662
	if (selected != NULL)
		return selected;
663

Havoc Pennington's avatar
Havoc Pennington committed
664
        if (filename)
665 666 667 668 669 670 671 672 673 674 675
		utf8_filename = g_filename_to_utf8 (filename, -1,
						    NULL, NULL, NULL);
	
	if (utf8_filename) {
		g_set_error (error,
			     GDK_PIXBUF_ERROR,
			     GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
			     _("Couldn't recognize the image file format for file '%s'"),
			     utf8_filename);
		g_free (utf8_filename);
	}
Havoc Pennington's avatar
Havoc Pennington committed
676 677 678 679 680 681
        else
                g_set_error (error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
                             _("Unrecognized image file format"));

682

683 684 685
	return NULL;
}

686 687 688 689 690 691 692 693 694 695 696

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

697 698 699 700
GdkPixbuf *
_gdk_pixbuf_generic_image_load (GdkPixbufModule *module,
				FILE *f,
				GError **error)
701 702 703 704
{
	guchar buffer[4096];
	size_t length;
	GdkPixbuf *pixbuf = NULL;
705
	GdkPixbufAnimation *animation = NULL;
706 707 708 709 710
	gpointer context;

	if (module->load != NULL)
		return (* module->load) (f, error);
	
711 712 713
	if (module->begin_load != NULL) {
		
		context = module->begin_load (NULL, prepared_notify, NULL, &pixbuf, error);
714
	
715 716 717
		if (!context)
			return NULL;
		
718
		while (!feof (f) && !ferror (f)) {
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
			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;
736
	}
737 738 739 740 741
	
	if (module->load_animation != NULL) {
		animation = (* module->load_animation) (f, error);
		if (animation != NULL) {
			pixbuf = gdk_pixbuf_animation_get_static_image (animation);
742

743 744 745 746 747 748
			g_object_ref (pixbuf);

			g_object_unref (animation);
			
			return pixbuf;
		}
749
	}
750 751

	return NULL;
752 753
}

Federico Mena Quintero's avatar
Federico Mena Quintero committed
754 755 756
/**
 * gdk_pixbuf_new_from_file:
 * @filename: Name of file to load.
Havoc Pennington's avatar
Havoc Pennington committed
757
 * @error: Return location for an error
Federico Mena Quintero's avatar
Federico Mena Quintero committed
758
 *
Federico Mena Quintero's avatar
Federico Mena Quintero committed
759
 * Creates a new pixbuf by loading an image from a file.  The file format is
Matthias Clasen's avatar
Matthias Clasen committed
760
 * detected automatically. If %NULL is returned, then @error will be set.
Havoc Pennington's avatar
Havoc Pennington committed
761
 * Possible errors are in the #GDK_PIXBUF_ERROR and #G_FILE_ERROR domains.
Federico Mena Quintero's avatar
Federico Mena Quintero committed
762
 *
Matthias Clasen's avatar
Matthias Clasen committed
763
 * Return value: A newly-created pixbuf with a reference count of 1, or %NULL if
Federico Mena Quintero's avatar
Federico Mena Quintero committed
764 765 766
 * 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
767
 **/
768
GdkPixbuf *
Havoc Pennington's avatar
Havoc Pennington committed
769 770
gdk_pixbuf_new_from_file (const char *filename,
                          GError    **error)
Arturo Espinosa's avatar
Arturo Espinosa committed
771
{
772
	GdkPixbuf *pixbuf;
773
	int size;
Arturo Espinosa's avatar
Arturo Espinosa committed
774
	FILE *f;
775
	guchar buffer [128];
776
	GdkPixbufModule *image_module;
Arturo Espinosa's avatar
Arturo Espinosa committed
777

778
	g_return_val_if_fail (filename != NULL, NULL);
779
        g_return_val_if_fail (error == NULL || *error == NULL, NULL);
780

Tor Lillqvist's avatar
Tor Lillqvist committed
781
	f = fopen (filename, "rb");
Havoc Pennington's avatar
Havoc Pennington committed
782
	if (!f) {
783 784
                gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
                                                           NULL, NULL, NULL);
Havoc Pennington's avatar
Havoc Pennington committed
785 786 787 788
                g_set_error (error,
                             G_FILE_ERROR,
                             g_file_error_from_errno (errno),
                             _("Failed to open file '%s': %s"),
789 790 791
                             utf8_filename ? utf8_filename : "???",
                             g_strerror (errno));
                g_free (utf8_filename);
Arturo Espinosa's avatar
Arturo Espinosa committed
792
		return NULL;
Havoc Pennington's avatar
Havoc Pennington committed
793
        }
794

795 796
	size = fread (&buffer, 1, sizeof (buffer), f);
	if (size == 0) {
797 798
                gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
                                                           NULL, NULL, NULL);
Havoc Pennington's avatar
Havoc Pennington committed
799 800 801 802
                g_set_error (error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                             _("Image file '%s' contains no data"),
803 804
                             utf8_filename ? utf8_filename : "???");
                g_free (utf8_filename);
805
		fclose (f);
Arturo Espinosa's avatar
Arturo Espinosa committed
806
		return NULL;
807
	}
Arturo Espinosa's avatar
Arturo Espinosa committed
808

809
	image_module = _gdk_pixbuf_get_module (buffer, size, filename, error);
Havoc Pennington's avatar
Havoc Pennington committed
810 811 812 813
        if (image_module == NULL) {
                fclose (f);
                return NULL;
        }
814

815
	if (image_module->module == NULL)
816
                if (!_gdk_pixbuf_load_module (image_module, error)) {
Havoc Pennington's avatar
Havoc Pennington committed
817 818 819
                        fclose (f);
                        return NULL;
                }
820

821
	fseek (f, 0, SEEK_SET);
822
	pixbuf = _gdk_pixbuf_generic_image_load (image_module, f, error);
823
	fclose (f);
824

Havoc Pennington's avatar
Havoc Pennington committed
825
        if (pixbuf == NULL && error != NULL && *error == NULL) {
826

Havoc Pennington's avatar
Havoc Pennington committed
827 828 829
                /* 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
830
                 * the invariant that error gets set if NULL is returned.
Havoc Pennington's avatar
Havoc Pennington committed
831
                 */
832 833 834 835

                gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
                                                           NULL, NULL, NULL);

Havoc Pennington's avatar
Havoc Pennington committed
836 837 838 839 840
                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"),
841 842
                             utf8_filename ? utf8_filename : "???");
                g_free (utf8_filename);
Havoc Pennington's avatar
Havoc Pennington committed
843 844 845 846
        } else if (error != NULL && *error != NULL) {

          /* Add the filename to the error message */
          GError *e = *error;
847 848 849 850
          gchar  *old;
          gchar  *utf8_filename = g_filename_to_utf8 (filename, -1,
                                                      NULL, NULL, NULL);

Havoc Pennington's avatar
Havoc Pennington committed
851 852 853
          old = e->message;

          e->message = g_strdup_printf (_("Failed to load image '%s': %s"),
854 855
                                        utf8_filename ? utf8_filename : "???",
                                        old);
Havoc Pennington's avatar
Havoc Pennington committed
856

857
          g_free (utf8_filename);
Havoc Pennington's avatar
Havoc Pennington committed
858 859
          g_free (old);
        }
860

861
	return pixbuf;
Arturo Espinosa's avatar
Arturo Espinosa committed
862
}
863

864 865 866 867 868 869 870
static void
size_prepared_cb (GdkPixbufLoader *loader, 
		  int              width,
		  int              height,
		  gpointer         data)
{
	struct {
871 872 873
		gint width;
		gint height;
		gboolean preserve_aspect_ratio;
874 875 876 877
	} *info = data;

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

878 879 880 881 882 883 884 885 886
	if(info->preserve_aspect_ratio) {
		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;
		}
887 888
	} else {
		width = info->width;
889
		height = info->height;
890
	}
891
	
892 893 894
	gdk_pixbuf_loader_set_size (loader, width, height);
}

895
/**
896
 * gdk_pixbuf_new_from_file_at_scale:
897 898 899
 * @filename: Name of file to load.
 * @width: The width the image should have
 * @height: The height the image should have
900
 * @preserve_aspect_ratio: %TRUE to preserve the image's aspect ratio
901 902 903 904 905
 * @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.
906 907
 * The image will be scaled to fit in the requested size, optionally preserving
 * the image's aspect ratio.
908
 *
909 910
 * 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,
911 912 913
 * 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.
 *
914
 * Since: 2.6
915 916
 **/
GdkPixbuf *
917 918 919 920 921
gdk_pixbuf_new_from_file_at_scale (const char *filename,
				   int         width, 
				   int         height,
				   gboolean    preserve_aspect_ratio,
				   GError    **error)
922
{
923

924 925 926 927 928 929
	GdkPixbufLoader *loader;
	GdkPixbuf       *pixbuf;

	guchar buffer [4096];
	int length;
	FILE *f;
930 931 932
	struct {
		gint width;
		gint height;
933
		gboolean preserve_aspect_ratio;
934
	} info;
935 936 937 938 939 940

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

	f = fopen (filename, "rb");
	if (!f) {
941 942
                gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
                                                           NULL, NULL, NULL);
943 944 945 946
                g_set_error (error,
                             G_FILE_ERROR,
                             g_file_error_from_errno (errno),
                             _("Failed to open file '%s': %s"),
947 948 949
                             utf8_filename ? utf8_filename : "???",
                             g_strerror (errno));
                g_free (utf8_filename);
950 951 952 953
		return NULL;
        }

	loader = gdk_pixbuf_loader_new ();
954 955 956

	info.width = width;
	info.height = height;
957
        info.preserve_aspect_ratio = preserve_aspect_ratio;
958

959
	g_signal_connect (loader, "size-prepared", G_CALLBACK (size_prepared_cb), &info);
960

961
	while (!feof (f) && !ferror (f)) {
962 963 964
		length = fread (buffer, 1, sizeof (buffer), f);
		if (length > 0)
			if (!gdk_pixbuf_loader_write (loader, buffer, length, error)) {
965
				gdk_pixbuf_loader_close (loader, NULL);
966
				fclose (f);
967
				g_object_unref (loader);
968 969 970 971 972 973 974
				return NULL;
			}
	}

	fclose (f);

	if (!gdk_pixbuf_loader_close (loader, error)) {
975
		g_object_unref (loader);
976 977 978 979 980 981
		return NULL;
	}

	pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);

	if (!pixbuf) {
982 983 984
                gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
                                                           NULL, NULL, NULL);

985
		g_object_unref (loader);
986 987

                g_set_error (error,
988 989 990
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_FAILED,
                             _("Failed to load image '%s': reason not known, probably a corrupt image file"),
991 992
                             utf8_filename ? utf8_filename : "???");
                g_free (utf8_filename);
993 994 995 996 997
		return NULL;
	}

	g_object_ref (pixbuf);

998
	g_object_unref (loader);
999 1000 1001 1002

	return pixbuf;
}

1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
/**
 * 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.
 * The image will be scaled to fit in the requested size, preserving
 * the image's aspect ratio.
 *
 * 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)
{
	return gdk_pixbuf_new_from_file_at_scale (filename, 
						  width, height, 
						  TRUE, error);
}

1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
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);

1099
	while (!feof (f) && !ferror (f)) {
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
		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);
1111
	g_object_unref (loader);
1112 1113 1114 1115 1116 1117 1118 1119 1120

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

	return info.format;
}

Federico Mena Quintero's avatar
Federico Mena Quintero committed
1121 1122
/**
 * gdk_pixbuf_new_from_xpm_data:
Federico Mena Quintero's avatar
Federico Mena Quintero committed
1123
 * @data: Pointer to inline XPM data.
1124
 *
Federico Mena Quintero's avatar
Federico Mena Quintero committed
1125 1126
 * 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.
1127
 *
Federico Mena Quintero's avatar
Federico Mena Quintero committed
1128 1129
 * Return value: A newly-created pixbuf with a reference count of 1.
 **/
1130
GdkPixbuf *
1131
gdk_pixbuf_new_from_xpm_data (const char **data)
1132
{
1133 1134
	GdkPixbuf *(* load_xpm_data) (const char **data);
	GdkPixbuf *pixbuf;
Havoc Pennington's avatar
Havoc Pennington committed
1135
        GError *error = NULL;
1136 1137 1138 1139 1140 1141
	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;
	}
1142

1143 1144
	if (xpm_module->module == NULL) {
                if (!_gdk_pixbuf_load_module (