exiv2-utils.cpp 29.8 KB
Newer Older
Paolo Bacchilega's avatar
Paolo Bacchilega committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* -*- Mode: CPP; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */

/*
 *  GThumb
 *
 *  Copyright (C) 2008-2009 Free Software Foundation, Inc.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
 */

#include <config.h>
24
#include <glib.h>
25
#define GDK_PIXBUF_ENABLE_BACKEND
26
#include <gdk-pixbuf/gdk-pixbuf.h>
Paolo Bacchilega's avatar
Paolo Bacchilega committed
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
#include <exiv2/basicio.hpp>
#include <exiv2/error.hpp>
#include <exiv2/image.hpp>
#include <exiv2/exif.hpp>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <exiv2/xmp.hpp>
#include <gthumb.h>
#include "exiv2-utils.h"

using namespace std;


/* Some bits of information may be contained in more than one metadata tag.
   The arrays below define the valid tags for a particular piece of
   information, in decreasing order of preference (best one first) */

const char *_DATE_TAG_NAMES[] = {
	"Exif::Image::DateTime",
	"Xmp::exif::DateTime",
	"Exif::Photo::DateTimeOriginal",
	"Xmp::exif::DateTimeOriginal",
	"Exif::Photo::DateTimeDigitized",
	"Xmp::exif::DateTimeDigitized",
	"Xmp::xmp::CreateDate",
	"Xmp::photoshop::DateCreated",
	"Xmp::xmp::ModifyDate",
	"Xmp::xmp::MetadataDate",
	NULL
};

60 61 62 63 64 65 66 67
const char *_LAST_DATE_TAG_NAMES[] = {
	"Exif::Image::DateTime",
	"Xmp::exif::DateTime",
	"Xmp::xmp::ModifyDate",
	"Xmp::xmp::MetadataDate",
	NULL
};

68 69 70 71 72 73 74 75 76 77
const char *_ORIGINAL_DATE_TAG_NAMES[] = {
	"Exif::Photo::DateTimeOriginal",
	"Xmp::exif::DateTimeOriginal",
	"Exif::Photo::DateTimeDigitized",
	"Xmp::exif::DateTimeDigitized",
	"Xmp::xmp::CreateDate",
	"Xmp::photoshop::DateCreated",
	NULL
};

Paolo Bacchilega's avatar
Paolo Bacchilega committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
const char *_EXPOSURE_TIME_TAG_NAMES[] = {
	"Exif::Photo::ExposureTime",
	"Xmp::exif::ExposureTime",
	"Exif::Photo::ShutterSpeedValue",
	"Xmp::exif::ShutterSpeedValue",
	NULL
};

const char *_EXPOSURE_MODE_TAG_NAMES[] = {
	"Exif::Photo::ExposureMode",
	"Xmp::exif::ExposureMode",
	NULL
};

const char *_ISOSPEED_TAG_NAMES[] = {
	"Exif::Photo::ISOSpeedRatings",
	"Xmp::exif::ISOSpeedRatings",
	NULL
};

const char *_APERTURE_TAG_NAMES[] = {
	"Exif::Photo::ApertureValue",
	"Xmp::exif::ApertureValue",
	"Exif::Photo::FNumber",
	"Xmp::exif::FNumber",
	NULL
};

const char *_FOCAL_LENGTH_TAG_NAMES[] = {
	"Exif::Photo::FocalLength",
	"Xmp::exif::FocalLength",
	NULL
};

const char *_SHUTTER_SPEED_TAG_NAMES[] = {
	"Exif::Photo::ShutterSpeedValue",
	"Xmp::exif::ShutterSpeedValue",
	NULL
};

const char *_MAKE_TAG_NAMES[] = {
	"Exif::Image::Make",
	"Xmp::tiff::Make",
	NULL
};

const char *_MODEL_TAG_NAMES[] = {
	"Exif::Image::Model",
	"Xmp::tiff::Model",
	NULL
};

const char *_FLASH_TAG_NAMES[] = {
	"Exif::Photo::Flash",
	"Xmp::exif::Flash",
	NULL
};

const char *_ORIENTATION_TAG_NAMES[] = {
	"Exif::Image::Orientation",
	"Xmp::tiff::Orientation",
	NULL
};

142
const char *_DESCRIPTION_TAG_NAMES[] = {
143 144
	"Iptc::Application2::Caption",
	"Xmp::dc::description",
Paolo Bacchilega's avatar
Paolo Bacchilega committed
145 146
	"Exif::Photo::UserComment",
	"Exif::Image::ImageDescription",
147
	"Xmp::tiff::ImageDescription",
Paolo Bacchilega's avatar
Paolo Bacchilega committed
148 149 150 151
	"Iptc::Application2::Headline",
	NULL
};

152 153 154 155 156
const char *_TITLE_TAG_NAMES[] = {
	"Xmp::dc::title",
	NULL
};

Paolo Bacchilega's avatar
Paolo Bacchilega committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
const char *_LOCATION_TAG_NAMES[] = {
	"Xmp::iptc::Location",
	"Iptc::Application2::LocationName",
	NULL
};

const char *_KEYWORDS_TAG_NAMES[] = {
	"Xmp::dc::subject",
	"Xmp::iptc::Keywords",
	"Iptc::Application2::Keywords",
	NULL
};


inline static char *
exiv2_key_from_attribute (const char *attribute)
{
	return _g_replace (attribute, "::", ".");
}


inline static char *
exiv2_key_to_attribute (const char *key)
{
	return _g_replace (key, ".", "::");
}


185 186 187 188 189 190 191 192 193 194 195 196 197 198
static gboolean
attribute_is_date (const char *key)
{
	int i;

	for (i = 0; _DATE_TAG_NAMES[i] != NULL; i++) {
		if (strcmp (_DATE_TAG_NAMES[i], key) == 0)
			return TRUE;
	}

	return FALSE;
}


199 200 201 202 203 204 205
static GthMetadata *
create_metadata (const char *key,
		 const char *description,
		 const char *formatted_value,
		 const char *raw_value,
		 const char *category,
		 const char *type_name)
Paolo Bacchilega's avatar
Paolo Bacchilega committed
206 207 208 209 210 211 212
{
	char            *attribute;
	GthMetadataInfo *metadata_info;
	GthMetadata     *metadata;
	char            *description_utf8;
	char            *formatted_value_utf8;

Paolo Bacchilega's avatar
Paolo Bacchilega committed
213
	if (_g_utf8_all_spaces (formatted_value))
214
		return NULL;
Paolo Bacchilega's avatar
Paolo Bacchilega committed
215 216 217

	attribute = exiv2_key_to_attribute (key);
	description_utf8 = g_locale_to_utf8 (description, -1, NULL, NULL, NULL);
218 219 220 221 222 223 224 225
	if (attribute_is_date (attribute)) {
		GTimeVal time_;

		if (_g_time_val_from_exif_date (raw_value, &time_))
			formatted_value_utf8 = _g_time_val_strftime (&time_, "%x %X");
		else
			formatted_value_utf8 = g_locale_to_utf8 (formatted_value, -1, NULL, NULL, NULL);
	}
226 227 228 229 230 231 232 233 234
	else {
		const char *formatted_clean;

		if (strncmp (formatted_value, "lang=", 5) == 0)
			formatted_clean = strchr (formatted_value, ' ') + 1;
		else
			formatted_clean = formatted_value;
		formatted_value_utf8 = g_locale_to_utf8 (formatted_clean, -1, NULL, NULL, NULL);
	}
Paolo Bacchilega's avatar
Paolo Bacchilega committed
235 236 237 238 239 240

	metadata_info = gth_main_get_metadata_info (attribute);
	if ((metadata_info == NULL) && (category != NULL)) {
		GthMetadataInfo info;

		info.id = attribute;
241
		info.type = (type_name != NULL) ? g_strdup (type_name) : NULL;
Paolo Bacchilega's avatar
Paolo Bacchilega committed
242 243 244 245 246 247 248
		info.display_name = description_utf8;
		info.category = category;
		info.sort_order = 500;
		info.flags = GTH_METADATA_ALLOW_IN_PROPERTIES_VIEW;
		metadata_info = gth_main_register_metadata_info (&info);
	}

Paolo Bacchilega's avatar
Paolo Bacchilega committed
249 250 251
	if ((metadata_info != NULL) && (metadata_info->type == NULL) && (type_name != NULL))
		metadata_info->type = g_strdup (type_name);

252
	if ((metadata_info != NULL) && (metadata_info->display_name == NULL) && (description_utf8 != NULL))
Paolo Bacchilega's avatar
Paolo Bacchilega committed
253 254 255
		metadata_info->display_name = g_strdup (description_utf8);

	metadata = gth_metadata_new ();
Paolo Bacchilega's avatar
Paolo Bacchilega committed
256 257 258 259 260 261 262
	g_object_set (metadata,
		      "id", key,
		      "description", description_utf8,
		      "formatted", formatted_value_utf8,
		      "raw", raw_value,
		      "value-type", type_name,
		      NULL);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
263 264 265 266

	g_free (formatted_value_utf8);
	g_free (description_utf8);
	g_free (attribute);
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 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

	return metadata;
}


static void
set_file_info (GFileInfo  *info,
	       const char *key,
	       const char *description,
	       const char *formatted_value,
	       const char *raw_value,
	       const char *category,
	       const char *type_name)
{
	char        *attribute;
	GthMetadata *metadata;

	attribute = exiv2_key_to_attribute (key);
	metadata = create_metadata (key, description, formatted_value, raw_value, category, type_name);
	if (metadata != NULL) {
		g_file_info_set_attribute_object (info, attribute, G_OBJECT (metadata));
		g_object_unref (metadata);
	}

	g_free (attribute);
}


GHashTable *
create_metadata_hash (void)
{
	return g_hash_table_new_full (g_str_hash,
				      g_str_equal,
				      g_free,
				      g_object_unref);
}


static void
add_metadata_to_hash (GHashTable  *table,
		      GthMetadata *metadata)
{
	char     *key;
	gpointer  object;

	if (metadata == NULL)
		return;

	key = exiv2_key_to_attribute (gth_metadata_get_id (metadata));
	object = g_hash_table_lookup (table, key);
	if (object != NULL) {
		GthStringList *string_list;
		GList         *list;

		string_list = NULL;
		if (GTH_IS_METADATA (object)) {
			string_list = gth_string_list_new (NULL);
			list = g_list_append (NULL, g_strdup (gth_metadata_get_raw (GTH_METADATA (object))));
			gth_string_list_set_list (string_list, list);
		}
		else if (GTH_IS_STRING_LIST (object))
			string_list = GTH_STRING_LIST (g_object_ref (object));

		if (string_list == NULL)
			return;

		list = gth_string_list_get_list (string_list);
		list = g_list_append (list, g_strdup (gth_metadata_get_raw (metadata)));
		gth_string_list_set_list (string_list, list);

		g_hash_table_replace (table,
				      g_strdup (key),
				      g_object_ref (string_list));

		g_object_unref (string_list);
	}
	else
		g_hash_table_insert (table,
				     g_strdup (key),
				     g_object_ref (metadata));

	g_free (key);
}


static void
set_file_info_from_hash (GFileInfo  *info,
			 GHashTable *table)
{
	GHashTableIter iter;
	gpointer       key;
	gpointer       value;

	g_hash_table_iter_init (&iter, table);
	while (g_hash_table_iter_next (&iter, &key, &value))
		g_file_info_set_attribute_object (info, (char *)key, G_OBJECT (value));
Paolo Bacchilega's avatar
Paolo Bacchilega committed
363 364 365 366
}


static void
367 368 369
set_attribute_from_metadata (GFileInfo  *info,
			     const char *attribute,
			     GObject    *metadata)
Paolo Bacchilega's avatar
Paolo Bacchilega committed
370
{
371 372 373 374 375
	char *key;
	char *description;
	char *formatted_value;
	char *raw_value;
	char *type_name;
Paolo Bacchilega's avatar
Paolo Bacchilega committed
376 377 378 379 380 381 382 383 384

	if (metadata == NULL)
		return;

	g_object_get (metadata,
		      "id", &key,
		      "description", &description,
		      "formatted", &formatted_value,
		      "raw", &raw_value,
Paolo Bacchilega's avatar
Paolo Bacchilega committed
385
		      "value-type", &type_name,
Paolo Bacchilega's avatar
Paolo Bacchilega committed
386
		      NULL);
387

Paolo Bacchilega's avatar
Paolo Bacchilega committed
388 389 390 391 392 393 394
	set_file_info (info,
		       attribute,
		       description,
		       formatted_value,
		       raw_value,
		       NULL,
		       type_name);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
395 396 397
}


398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
static void
set_attribute_from_tagset (GFileInfo  *info,
			   const char *attribute,
			   const char *tagset[])
{
	GObject *metadata;
	int      i;

	metadata = NULL;
	for (i = 0; tagset[i] != NULL; i++) {
		metadata = g_file_info_get_attribute_object (info, tagset[i]);
		if (metadata != NULL)
			break;
	}

	if (metadata != NULL)
		set_attribute_from_metadata (info, attribute, metadata);
}


Paolo Bacchilega's avatar
Paolo Bacchilega committed
418
static void
419 420 421
set_string_list_attribute_from_tagset (GFileInfo  *info,
				       const char *attribute,
				       const char *tagset[])
Paolo Bacchilega's avatar
Paolo Bacchilega committed
422
{
423 424
	GObject *metadata;
	int      i;
Paolo Bacchilega's avatar
Paolo Bacchilega committed
425

426 427 428 429 430 431 432 433 434 435
	metadata = NULL;
	for (i = 0; tagset[i] != NULL; i++) {
		metadata = g_file_info_get_attribute_object (info, tagset[i]);
		if (metadata != NULL)
			break;
	}

	if (metadata == NULL)
		return;

436 437 438 439
	if (GTH_IS_METADATA (metadata)) {
		char           *raw;
		char          **keywords;
		GthStringList  *string_list;
440

441 442 443 444 445 446 447 448 449 450
		g_object_get (metadata, "raw", &raw, NULL);
		keywords = g_strsplit (raw, ", ", -1);
		string_list = gth_string_list_new_from_strv (keywords);
		g_file_info_set_attribute_object (info, attribute, G_OBJECT (string_list));

		g_strfreev (keywords);
		g_free (raw);
	}
	else if (GTH_IS_STRING_LIST (metadata))
		g_file_info_set_attribute_object (info, attribute, metadata);
451 452
}

453

454 455 456
static void
set_attributes_from_tagsets (GFileInfo *info)
{
457 458 459 460
	set_attribute_from_tagset (info, "general::datetime", _LAST_DATE_TAG_NAMES);
	if (g_file_info_get_attribute_object (info, "general::datetime") == NULL)
		set_attribute_from_tagset (info, "general::datetime", _ORIGINAL_DATE_TAG_NAMES);

461
	set_attribute_from_tagset (info, "general::description", _DESCRIPTION_TAG_NAMES);
462
	set_attribute_from_tagset (info, "general::title", _TITLE_TAG_NAMES);
463

464 465
	/* if iptc::caption and iptc::headline are different use iptc::headline
	 * to set general::title, if not already set. */
466 467 468 469 470 471 472 473 474 475 476 477 478

	if (g_file_info_get_attribute_object (info, "general::title") == NULL) {
		GObject *iptc_caption;
		GObject *iptc_headline;

		iptc_caption = g_file_info_get_attribute_object (info, "Iptc::Application2::Caption");
		iptc_headline = g_file_info_get_attribute_object (info, "Iptc::Application2::Headline");

		if ((iptc_caption != NULL)
		    && (iptc_headline != NULL)
		    && (g_strcmp0 (gth_metadata_get_raw (GTH_METADATA (iptc_caption)),
				   gth_metadata_get_raw (GTH_METADATA (iptc_headline))) != 0))
		{
479
			set_attribute_from_metadata (info, "general::title", iptc_headline);
480 481 482
		}
	}

483 484
	set_attribute_from_tagset (info, "general::location", _LOCATION_TAG_NAMES);
	set_string_list_attribute_from_tagset (info, "general::tags", _KEYWORDS_TAG_NAMES);
485
	set_attribute_from_tagset (info, "Embedded::Photo::DateTimeOriginal", _ORIGINAL_DATE_TAG_NAMES);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
	set_attribute_from_tagset (info, "Embedded::Image::Orientation", _ORIENTATION_TAG_NAMES);
}


static const char *
get_exif_default_category (const Exiv2::Exifdatum &md)
{
	if (Exiv2::ExifTags::isMakerIfd(md.ifdId()))
		return "Exif::MakerNotes";

	switch (md.ifdId()) {
	case Exiv2::ifd1Id:
		return "Exif::Thumbnail";
	case Exiv2::gpsIfdId:
		return "Exif::GPS";
	case Exiv2::iopIfdId:
		return "Exif::Versions";
	default:
		break;
	}

	return "Exif::Other";
}


511 512 513 514 515 516 517 518 519 520
static void
exiv2_read_metadata (Exiv2::Image::AutoPtr  image,
		     GFileInfo             *info)
{
	image->readMetadata();

	Exiv2::ExifData &exifData = image->exifData();
	if (! exifData.empty()) {
		Exiv2::ExifData::const_iterator end = exifData.end();
		for (Exiv2::ExifData::const_iterator md = exifData.begin(); md != end; ++md) {
Paolo Bacchilega's avatar
Paolo Bacchilega committed
521 522
			stringstream raw_value;
			raw_value << md->value();
523

Paolo Bacchilega's avatar
Paolo Bacchilega committed
524 525 526 527
			stringstream description;
			if (! md->tagLabel().empty())
				description << md->tagLabel();
			else if (md->ifdId () > Exiv2::ifd1Id)
528
				// Must be a MakerNote - include group name
Paolo Bacchilega's avatar
Paolo Bacchilega committed
529 530
				description << md->groupName() << "." << md->tagName();
			else
531
				// Normal exif tag - just use tag name
Paolo Bacchilega's avatar
Paolo Bacchilega committed
532
				description << md->tagName();
533 534 535

			set_file_info (info,
				       md->key().c_str(),
Paolo Bacchilega's avatar
Paolo Bacchilega committed
536
				       description.str().c_str(),
537
				       md->print(&exifData).c_str(),
Paolo Bacchilega's avatar
Paolo Bacchilega committed
538
				       raw_value.str().c_str(),
539 540
				       get_exif_default_category (*md),
				       md->typeName());
541 542 543 544 545
		}
	}

	Exiv2::IptcData &iptcData = image->iptcData();
	if (! iptcData.empty()) {
546 547
		GHashTable *table = create_metadata_hash ();

548 549
		Exiv2::IptcData::iterator end = iptcData.end();
		for (Exiv2::IptcData::iterator md = iptcData.begin(); md != end; ++md) {
Paolo Bacchilega's avatar
Paolo Bacchilega committed
550 551
			stringstream raw_value;
			raw_value << md->value();
552

Paolo Bacchilega's avatar
Paolo Bacchilega committed
553 554 555 556 557
			stringstream description;
			if (! md->tagLabel().empty())
				description << md->tagLabel();
			else
				description << md->tagName();
558

559 560 561 562 563 564 565 566 567 568
			GthMetadata *metadata;
			metadata = create_metadata (md->key().c_str(),
						    description.str().c_str(),
						    md->print().c_str(),
						    raw_value.str().c_str(),
						    "Iptc",
						    md->typeName());

			add_metadata_to_hash (table, metadata);
			_g_object_unref (metadata);
569
		}
570 571 572

		set_file_info_from_hash (info, table);
		g_hash_table_unref (table);
573 574 575 576
	}

	Exiv2::XmpData &xmpData = image->xmpData();
	if (! xmpData.empty()) {
577 578
		GHashTable *table = create_metadata_hash ();

579 580
		Exiv2::XmpData::iterator end = xmpData.end();
		for (Exiv2::XmpData::iterator md = xmpData.begin(); md != end; ++md) {
Paolo Bacchilega's avatar
Paolo Bacchilega committed
581 582
			stringstream raw_value;
			raw_value << md->value();
583

Paolo Bacchilega's avatar
Paolo Bacchilega committed
584 585 586 587 588
			stringstream description;
			if (! md->tagLabel().empty())
				description << md->tagLabel();
			else
				description << md->groupName() << "." << md->tagName();
589

590 591 592 593 594 595 596 597 598
			GthMetadata *metadata;
			metadata = create_metadata (md->key().c_str(),
						    description.str().c_str(),
						    md->print().c_str(),
						    raw_value.str().c_str(),
						    "Xmp::Embedded",
						    md->typeName());
			add_metadata_to_hash (table, metadata);
			_g_object_unref (metadata);
599
		}
600 601 602

		set_file_info_from_hash (info, table);
		g_hash_table_unref (table);
603 604 605 606 607 608
	}

	set_attributes_from_tagsets (info);
}


Paolo Bacchilega's avatar
Paolo Bacchilega committed
609
/*
610
 * exiv2_read_metadata_from_file
Paolo Bacchilega's avatar
Paolo Bacchilega committed
611 612 613 614 615 616
 * reads metadata from image files
 * code relies heavily on example1 from the exiv2 website
 * http://www.exiv2.org/example1.html
 */
extern "C"
gboolean
617 618 619
exiv2_read_metadata_from_file (GFile      *file,
			       GFileInfo  *info,
			       GError    **error)
Paolo Bacchilega's avatar
Paolo Bacchilega committed
620 621 622 623 624
{
	try {
		char *path;

		path = g_file_get_path (file);
625 626 627 628 629 630
		if (path == NULL) {
			if (error != NULL)
				*error = g_error_new_literal (G_IO_ERROR, G_IO_ERROR_FAILED, _("Invalid file format"));
			return FALSE;
		}

Paolo Bacchilega's avatar
Paolo Bacchilega committed
631 632 633 634
		Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(path);
		g_free (path);

		if (image.get() == 0) {
635 636
			if (error != NULL)
				*error = g_error_new_literal (G_IO_ERROR, G_IO_ERROR_FAILED, _("Invalid file format"));
Paolo Bacchilega's avatar
Paolo Bacchilega committed
637 638 639
			return FALSE;
		}

640 641
		exiv2_read_metadata (image, info);
	}
642
	catch (Exiv2::AnyError& e) {
643
		if (error != NULL)
644
			*error = g_error_new_literal (G_IO_ERROR, G_IO_ERROR_FAILED, e.what());
645 646
		return FALSE;
	}
Paolo Bacchilega's avatar
Paolo Bacchilega committed
647

648 649
	return TRUE;
}
Paolo Bacchilega's avatar
Paolo Bacchilega committed
650 651


652 653 654 655 656 657 658 659 660
extern "C"
gboolean
exiv2_read_metadata_from_buffer (void       *buffer,
				 gsize       buffer_size,
				 GFileInfo  *info,
				 GError    **error)
{
	try {
		Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open ((Exiv2::byte*) buffer, buffer_size);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
661

662 663 664 665
		if (image.get() == 0) {
			if (error != NULL)
				*error = g_error_new_literal (G_IO_ERROR, G_IO_ERROR_FAILED, _("Invalid file format"));
			return FALSE;
Paolo Bacchilega's avatar
Paolo Bacchilega committed
666 667
		}

668
		exiv2_read_metadata (image, info);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
669
	}
670
	catch (Exiv2::AnyError& e) {
671
		if (error != NULL)
672
			*error = g_error_new_literal (G_IO_ERROR, G_IO_ERROR_FAILED, e.what());
Paolo Bacchilega's avatar
Paolo Bacchilega committed
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
		return FALSE;
	}

	return TRUE;
}


extern "C"
gboolean
exiv2_read_sidecar (GFile     *file,
		    GFileInfo *info)
{
	try {
		char *path;

		path = g_file_get_path (file);
689 690 691
		if (path == NULL)
			return FALSE;

Paolo Bacchilega's avatar
Paolo Bacchilega committed
692 693 694 695 696 697 698 699 700 701 702
		Exiv2::DataBuf buf = Exiv2::readFile(path);
		g_free (path);

		std::string xmpPacket;
		xmpPacket.assign(reinterpret_cast<char*>(buf.pData_), buf.size_);
		Exiv2::XmpData xmpData;

		if (0 != Exiv2::XmpParser::decode(xmpData, xmpPacket))
			return FALSE;

		if (! xmpData.empty()) {
703 704
			GHashTable *table = create_metadata_hash ();

Paolo Bacchilega's avatar
Paolo Bacchilega committed
705 706
			Exiv2::XmpData::iterator end = xmpData.end();
			for (Exiv2::XmpData::iterator md = xmpData.begin(); md != end; ++md) {
Paolo Bacchilega's avatar
Paolo Bacchilega committed
707 708
				stringstream raw_value;
				raw_value << md->value();
Paolo Bacchilega's avatar
Paolo Bacchilega committed
709

Paolo Bacchilega's avatar
Paolo Bacchilega committed
710 711 712 713 714
				stringstream description;
				if (! md->tagLabel().empty())
					description << md->tagLabel();
				else
					description << md->groupName() << "." << md->tagName();
Paolo Bacchilega's avatar
Paolo Bacchilega committed
715

716 717 718 719 720 721 722 723 724
				GthMetadata *metadata;
				metadata = create_metadata (md->key().c_str(),
							    description.str().c_str(),
							    md->print().c_str(),
							    raw_value.str().c_str(),
							    "Xmp::Sidecar",
							    md->typeName());
				add_metadata_to_hash (table, metadata);
				_g_object_unref (metadata);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
725
			}
726 727 728

			set_file_info_from_hash (info, table);
			g_hash_table_unref (table);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
729 730 731 732 733 734
		}
		Exiv2::XmpParser::terminate();

		set_attributes_from_tagsets (info);
	}
	catch (Exiv2::AnyError& e) {
735
		std::cerr << "Caught Exiv2 exception '" << e << "'\n";
Paolo Bacchilega's avatar
Paolo Bacchilega committed
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
		return FALSE;
	}

	return TRUE;
}


static void
mandatory_int (Exiv2::ExifData &checkdata,
	       const char      *tag,
	       int              value)
{
	Exiv2::ExifKey key = Exiv2::ExifKey(tag);
	if (checkdata.findKey(key) == checkdata.end())
		checkdata[tag] = value;
}


static void
mandatory_string (Exiv2::ExifData &checkdata,
		  const char      *tag,
		  const char      *value)
{
	Exiv2::ExifKey key = Exiv2::ExifKey(tag);
	if (checkdata.findKey(key) == checkdata.end())
		checkdata[tag] = value;
}


Paolo Bacchilega's avatar
Paolo Bacchilega committed
765
const char *
766 767
gth_main_get_metadata_type (gpointer    metadata,
			    const char *attribute)
Paolo Bacchilega's avatar
Paolo Bacchilega committed
768 769 770 771
{
	const char      *value_type;
	GthMetadataInfo *metadatum_info;

772 773 774 775
	if (GTH_IS_METADATA (metadata)) {
		value_type = gth_metadata_get_value_type (GTH_METADATA (metadata));
		if (g_strcmp0 (value_type, "Undefined") == 0)
			value_type = NULL;
Paolo Bacchilega's avatar
Paolo Bacchilega committed
776

777 778 779
		if (value_type != NULL)
			return value_type;
	}
Paolo Bacchilega's avatar
Paolo Bacchilega committed
780

781
	metadatum_info = gth_main_get_metadata_info (attribute);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
782 783 784 785 786 787 788
	if (metadatum_info != NULL)
		value_type = metadatum_info->type;

	return value_type;
}


789 790 791 792
static Exiv2::DataBuf
exiv2_write_metadata_private (Exiv2::Image::AutoPtr  image,
			      GFileInfo             *info,
			      GdkPixbuf             *pixbuf)
Paolo Bacchilega's avatar
Paolo Bacchilega committed
793
{
794 795
	char **attributes;
	int    i;
Paolo Bacchilega's avatar
Paolo Bacchilega committed
796

797
	image->clearMetadata();
Paolo Bacchilega's avatar
Paolo Bacchilega committed
798

799
	// EXIF Data
Paolo Bacchilega's avatar
Paolo Bacchilega committed
800

801
	Exiv2::ExifData ed;
802 803 804 805
	attributes = g_file_info_list_attributes (info, "Exif");
	for (i = 0; attributes[i] != NULL; i++) {
		GthMetadata *metadatum;
		char *key;
Paolo Bacchilega's avatar
Paolo Bacchilega committed
806

807 808
		metadatum = (GthMetadata *) g_file_info_get_attribute_object (info, attributes[i]);
		key = exiv2_key_from_attribute (attributes[i]);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
809

810
		try {
811 812 813
			/* If the metadatum has no value yet, a new empty value
			 * is created. The type is taken from Exiv2's tag
			 * lookup tables. If the tag is not found in the table,
Paolo Bacchilega's avatar
Paolo Bacchilega committed
814 815
			 * the type defaults to ASCII.
			 * We always create the metadatum explicitly if the
816 817
			 * type is available to avoid type errors.
			 * See bug #610389 for more details.  The original
Paolo Bacchilega's avatar
Paolo Bacchilega committed
818
			 * explanation is here:
819 820 821
			 * http://uk.groups.yahoo.com/group/exiv2/message/1472
			 */

Paolo Bacchilega's avatar
Paolo Bacchilega committed
822
			const char *raw_value = gth_metadata_get_raw (metadatum);
823
			const char *value_type = gth_main_get_metadata_type (metadatum, attributes[i]);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
824

825
			if ((raw_value != NULL) && (strcmp (raw_value, "") != 0) && (value_type != NULL)) {
Paolo Bacchilega's avatar
Paolo Bacchilega committed
826 827
				Exiv2::Value::AutoPtr value = Exiv2::Value::create (Exiv2::TypeInfo::typeId (value_type));
				value->read (raw_value);
828 829 830
				Exiv2::ExifKey exif_key(key);
				ed.add (exif_key, value.get());
			}
831
		}
832
		catch (Exiv2::AnyError& e) {
833
			/* we don't care about invalid key errors */
834
			g_warning ("%s", e.what());
835
		}
Paolo Bacchilega's avatar
Paolo Bacchilega committed
836

837 838 839
		g_free (key);
	}
	g_strfreev (attributes);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
840

841
	// Mandatory tags - add if not already present
Paolo Bacchilega's avatar
Paolo Bacchilega committed
842

843 844 845 846 847 848 849 850
	mandatory_int (ed, "Exif.Image.XResolution", 72);
	mandatory_int (ed, "Exif.Image.YResolution", 72);
	mandatory_int (ed, "Exif.Image.ResolutionUnit", 2);
	mandatory_int (ed, "Exif.Image.YCbCrPositioning", 1);
	mandatory_int (ed, "Exif.Photo.ColorSpace", 1);
	mandatory_string (ed, "Exif.Photo.ExifVersion", "48 50 50 49");
	mandatory_string (ed, "Exif.Photo.ComponentsConfiguration", "1 2 3 0");
	mandatory_string (ed, "Exif.Photo.FlashpixVersion", "48 49 48 48");
Paolo Bacchilega's avatar
Paolo Bacchilega committed
851

852
	// Overwrite the software tag
Paolo Bacchilega's avatar
Paolo Bacchilega committed
853

854
	ed["Exif.Image.Software"] = PACKAGE " " VERSION;
Paolo Bacchilega's avatar
Paolo Bacchilega committed
855

856
	// Update the dimension tags with actual image values
Paolo Bacchilega's avatar
Paolo Bacchilega committed
857

858 859
	int width = 0;
	int height = 0;
Paolo Bacchilega's avatar
Paolo Bacchilega committed
860

861 862
	if (pixbuf != NULL) {
		width = gdk_pixbuf_get_width (pixbuf);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
863 864 865
		if (width > 0)
			ed["Exif.Photo.PixelXDimension"] = width;

866
		height = gdk_pixbuf_get_height (pixbuf);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
867 868
		if (height > 0)
			ed["Exif.Photo.PixelYDimension"] = height;
869

870
		ed["Exif.Image.Orientation"] = 1;
871
	}
Paolo Bacchilega's avatar
Paolo Bacchilega committed
872

873 874
	// Update the thumbnail

875
	Exiv2::ExifThumb thumb(ed);
876 877 878 879 880 881 882 883 884 885 886 887 888
	if ((pixbuf != NULL) && (width > 0) && (height > 0)) {
		GdkPixbuf *thumb_pixbuf;
		char      *buffer;
		gsize      buffer_size;

		scale_keeping_ratio (&width, &height, 128, 128, FALSE);
		thumb_pixbuf = _gdk_pixbuf_scale_simple_safe (pixbuf, width, height, GDK_INTERP_BILINEAR);
		if (gdk_pixbuf_save_to_buffer (thumb_pixbuf, &buffer, &buffer_size, "jpeg", NULL, NULL)) {
			thumb.setJpegThumbnail ((Exiv2::byte*) buffer, buffer_size);
			ed["Exif.Thumbnail.XResolution"] = 72;
			ed["Exif.Thumbnail.YResolution"] = 72;
			ed["Exif.Thumbnail.ResolutionUnit"] =  2;
			g_free (buffer);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
889 890 891 892
		}
		else
			thumb.erase();

893 894 895 896
		g_object_unref (thumb_pixbuf);
	}
	else
		thumb.erase();
Paolo Bacchilega's avatar
Paolo Bacchilega committed
897

898
	// Update the DateTime tag
Paolo Bacchilega's avatar
Paolo Bacchilega committed
899

900 901 902 903 904 905 906
	if (g_file_info_get_attribute_object (info, "Exif::Image::DateTime") == NULL) {
		GTimeVal current_time;
		g_get_current_time (&current_time);
		char *date_time = _g_time_val_to_exif_date (&current_time);
		ed["Exif.Image.DateTime"] = date_time;
		g_free (date_time);
	}
Paolo Bacchilega's avatar
Paolo Bacchilega committed
907

908
	// IPTC Data
Paolo Bacchilega's avatar
Paolo Bacchilega committed
909

910
	Exiv2::IptcData id;
911 912
	attributes = g_file_info_list_attributes (info, "Iptc");
	for (i = 0; attributes[i] != NULL; i++) {
913 914
		gpointer  metadatum = (GthMetadata *) g_file_info_get_attribute_object (info, attributes[i]);
		char     *key = exiv2_key_from_attribute (attributes[i]);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
915

916
		try {
917
			const char *value_type;
Paolo Bacchilega's avatar
Paolo Bacchilega committed
918

919 920
			value_type = gth_main_get_metadata_type (metadatum, attributes[i]);
			if (value_type != NULL) {
Paolo Bacchilega's avatar
Paolo Bacchilega committed
921 922
				/* See the exif data code above for an explanation. */
				Exiv2::Value::AutoPtr value = Exiv2::Value::create (Exiv2::TypeInfo::typeId (value_type));
923
				Exiv2::IptcKey iptc_key(key);
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945

				if (GTH_IS_STRING_LIST (metadatum)) {
					GthStringList *string_list;
					GList         *scan;

					string_list = GTH_STRING_LIST (metadatum);
					for (scan = gth_string_list_get_list (string_list); scan; scan = scan->next) {
						char *single_value = (char *) scan->data;

						value->read (single_value);
						id.add (iptc_key, value.get());
					}
				}
				else if (GTH_IS_METADATA (metadatum)) {
					const char *raw_value;

					raw_value = gth_metadata_get_raw (GTH_METADATA (metadatum));
					if ((raw_value != NULL) && (strcmp (raw_value, "") != 0)) {
						value->read (raw_value);
						id.add (iptc_key, value.get());
					}
				}
946
			}
947
		}
948
		catch (Exiv2::AnyError& e) {
949
			/* we don't care about invalid key errors */
950
			g_warning ("%s", e.what());
Paolo Bacchilega's avatar
Paolo Bacchilega committed
951 952
		}

953 954 955
		g_free (key);
	}
	g_strfreev (attributes);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
956

957
	// XMP Data
Paolo Bacchilega's avatar
Paolo Bacchilega committed
958

959
	Exiv2::XmpData xd;
960 961
	attributes = g_file_info_list_attributes (info, "Xmp");
	for (i = 0; attributes[i] != NULL; i++) {
962 963
		gpointer  metadatum = (GthMetadata *) g_file_info_get_attribute_object (info, attributes[i]);
		char     *key = exiv2_key_from_attribute (attributes[i]);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
964

965 966 967
		// Remove existing tags of the same type.
		// Seems to be needed for storing category keywords.
		// Not exactly sure why!
968
		/*Exiv2::XmpData::iterator iter = xd.findKey (Exiv2::XmpKey (key));
969
		if (iter != xd.end ())
970
			xd.erase (iter);*/
Paolo Bacchilega's avatar
Paolo Bacchilega committed
971

972
		try {
973
			const char *value_type;
974

975 976
			value_type = gth_main_get_metadata_type (metadatum, attributes[i]);
			if (value_type != NULL) {
977
				/* See the exif data code above for an explanation. */
Paolo Bacchilega's avatar
Paolo Bacchilega committed
978 979
				Exiv2::Value::AutoPtr value = Exiv2::Value::create (Exiv2::TypeInfo::typeId (value_type));
				Exiv2::XmpKey xmp_key(key);
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001

				if (GTH_IS_STRING_LIST (metadatum)) {
					GthStringList *string_list;
					GList         *scan;

					string_list = GTH_STRING_LIST (metadatum);
					for (scan = gth_string_list_get_list (string_list); scan; scan = scan->next) {
						char *single_value = (char *) scan->data;

						value->read (single_value);
						xd.add (xmp_key, value.get());
					}
				}
				else if (GTH_IS_METADATA (metadatum)) {
					const char *raw_value;

					raw_value = gth_metadata_get_raw (GTH_METADATA (metadatum));
					if ((raw_value != NULL) && (strcmp (raw_value, "") != 0)) {
						value->read (raw_value);
						xd.add (xmp_key, value.get());
					}
				}
1002
			}
Paolo Bacchilega's avatar
Paolo Bacchilega committed
1003
		}
1004
		catch (Exiv2::AnyError& e) {
1005
			/* we don't care about invalid key errors */
1006
			g_warning ("%s", e.what());
1007 1008 1009 1010 1011 1012
		}

		g_free (key);
	}
	g_strfreev (attributes);

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
	try {
		image->setExifData(ed);
		image->setIptcData(id);
		image->setXmpData(xd);
		image->writeMetadata();
	}
	catch (Exiv2::AnyError& e) {
		g_warning ("%s", e.what());
	}

1023 1024 1025 1026 1027 1028 1029
	Exiv2::BasicIo &io = image->io();
	io.open();

	return io.read(io.size());
}


1030 1031
extern "C"
gboolean
1032
exiv2_supports_writes (const char *mime_type)
1033
{
1034 1035 1036 1037 1038
	return (g_content_type_equals (mime_type, "image/jpeg")
#if HAVE_EXIV2_020
		|| g_content_type_equals (mime_type, "image/tiff")
#endif
		|| g_content_type_equals (mime_type, "image/png"));
1039 1040 1041
}


1042 1043 1044 1045
extern "C"
gboolean
exiv2_write_metadata (SavePixbufData *data)
{
1046
	if (exiv2_supports_writes (data->mime_type)) {
1047 1048 1049
		try {
			Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open ((Exiv2::byte*) data->buffer, data->buffer_size);
			g_assert (image.get() != 0);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
1050

1051
			Exiv2::DataBuf buf = exiv2_write_metadata_private (image, data->file_data->info, data->pixbuf);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
1052

1053 1054 1055 1056 1057 1058 1059
			g_free (data->buffer);
			data->buffer = g_memdup (buf.pData_, buf.size_);
			data->buffer_size = buf.size_;
		}
		catch (Exiv2::AnyError& e) {
			if (data->error != NULL)
				*data->error = g_error_new_literal (G_IO_ERROR, G_IO_ERROR_FAILED, e.what());
Paolo Bacchilega's avatar
Paolo Bacchilega committed
1060
			g_warning ("%s\n", e.what());
1061 1062
			return FALSE;
		}
Paolo Bacchilega's avatar
Paolo Bacchilega committed
1063
	}
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086

	return TRUE;
}


extern "C"
gboolean
exiv2_write_metadata_to_buffer (void      **buffer,
				gsize      *buffer_size,
				GFileInfo  *info,
				GdkPixbuf  *pixbuf,
				GError    **error)
{
	try {
		Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open ((Exiv2::byte*) *buffer, *buffer_size);
		g_assert (image.get() != 0);

		Exiv2::DataBuf buf = exiv2_write_metadata_private (image, info, pixbuf);

		g_free (*buffer);
		*buffer = g_memdup (buf.pData_, buf.size_);
		*buffer_size = buf.size_;
	}
1087
	catch (Exiv2::AnyError& e) {
1088
		if (error != NULL)
1089
			*error = g_error_new_literal (G_IO_ERROR, G_IO_ERROR_FAILED, e.what());
1090 1091 1092 1093
		return FALSE;
	}

	return TRUE;
Paolo Bacchilega's avatar
Paolo Bacchilega committed
1094
}
1095 1096


1097 1098 1099
#define MAX_RATIO_ERROR_TOLERANCE 0.01


1100 1101 1102
GdkPixbuf *
exiv2_generate_thumbnail (const char *uri,
			  const char *mime_type,
1103
			  int         requested_size)
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
{
	GdkPixbuf *pixbuf = NULL;

	if (! _g_content_type_is_a (mime_type, "image/jpeg")
	    && ! _g_content_type_is_a (mime_type, "image/tiff"))
	{
		return NULL;
	}

	try {
		char *path;

		path = g_filename_from_uri (uri, NULL, NULL);
		if (path != NULL) {
			Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open (path);
			image->readMetadata ();
			Exiv2::ExifThumbC exifThumb (image->exifData ());
			Exiv2::DataBuf thumb = exifThumb.copy ();

			if (thumb.pData_ != NULL) {
				Exiv2::ExifData &ed = image->exifData();
1125

1126
				long orientation = ed["Exif.Image.Orientation"].toLong();
1127 1128 1129
				long image_width = ed["Exif.Photo.PixelXDimension"].toLong();
				long image_height = ed["Exif.Photo.PixelYDimension"].toLong();

1130
				if ((orientation == 1) && (image_width > 0) && (image_height > 0)) {
1131 1132 1133 1134 1135 1136 1137 1138 1139
					GInputStream *stream = g_memory_input_stream_new_from_data (thumb.pData_, thumb.size_, NULL);
					pixbuf = gdk_pixbuf_new_from_stream (stream, NULL, NULL);

					if (pixbuf != NULL) {
						/* Heuristic to find out-of-date thumbnails: the thumbnail and image aspect ratios must be equal */

						double image_ratio = (((double) image_width) / image_height);
						double thumbnail_ratio = (((double) gdk_pixbuf_get_width (pixbuf)) / gdk_pixbuf_get_height (pixbuf));
						double ratio_delta = (image_ratio > thumbnail_ratio) ? (image_ratio - thumbnail_ratio) : (thumbnail_ratio - image_ratio);
1140

1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
						if (ratio_delta > MAX_RATIO_ERROR_TOLERANCE) {
							g_object_unref (pixbuf);
							pixbuf = NULL;
						}
						else {
							/* Save the original image size in the pixbuf options */

							char *s = g_strdup_printf ("%ld", image_width);
							gdk_pixbuf_set_option (pixbuf, "tEXt::Thumb::Image::Width", s);
							g_object_set_data (G_OBJECT (pixbuf), "gnome-original-width", GINT_TO_POINTER ((int) image_width));
							g_free (s);

							s = g_strdup_printf ("%ld", image_height);
							gdk_pixbuf_set_option (pixbuf, "tEXt::Thumb::Image::Height", s);
							g_object_set_data (G_OBJECT (pixbuf), "gnome-original-height", GINT_TO_POINTER ((int) image_height));
							g_free (s);

							/* Set the orientation option to correctly rotate the thumbnail
							 * in gnome_desktop_thumbnail_factory_generate_thumbnail() */

1161 1162 1163 1164
							long  orientation = ed["Exif.Image.Orientation"].toLong();
							char *orientation_s = g_strdup_printf ("%ld", orientation);
							gdk_pixbuf_set_option (pixbuf, "orientation", orientation_s);
							g_free (orientation_s);
1165 1166 1167 1168
						}
					}

					g_object_unref (stream);
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
				}
			}

			g_free (path);
		}
	}
	catch (Exiv2::AnyError& e) {
	}

	return pixbuf;
}