exiv2-utils.cpp 20.7 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>
Paolo Bacchilega's avatar
Paolo Bacchilega committed
25 26 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
#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
};

58 59 60 61 62 63 64 65 66 67
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
68 69 70 71 72 73 74 75 76 77 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
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
};

132
const char *_DESCRIPTION_TAG_NAMES[] = {
Paolo Bacchilega's avatar
Paolo Bacchilega committed
133 134 135
	"Exif::Photo::UserComment",
	"Exif::Image::ImageDescription",
	"Xmp::dc::description",
136
	"Xmp::tiff::ImageDescription",
Paolo Bacchilega's avatar
Paolo Bacchilega committed
137 138 139 140 141
	"Iptc::Application2::Caption",
	"Iptc::Application2::Headline",
	NULL
};

142 143 144 145 146
const char *_TITLE_TAG_NAMES[] = {
	"Xmp::dc::title",
	NULL
};

Paolo Bacchilega's avatar
Paolo Bacchilega committed
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
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, ".", "::");
}


175 176 177 178 179 180 181 182 183 184 185 186 187 188
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;
}


189
static void
Paolo Bacchilega's avatar
Paolo Bacchilega committed
190 191 192 193 194
set_file_info (GFileInfo  *info,
	       const char *key,
	       const char *description,
	       const char *formatted_value,
	       const char *raw_value,
195 196
	       const char *category,
	       const char *type_name)
Paolo Bacchilega's avatar
Paolo Bacchilega committed
197 198 199 200 201 202 203 204 205 206 207 208
{
	char            *attribute;
	GthMetadataInfo *metadata_info;
	GthMetadata     *metadata;
	char            *description_utf8;
	char            *formatted_value_utf8;

	if (_g_utf8_all_spaces (formatted_value))
		return;

	attribute = exiv2_key_to_attribute (key);
	description_utf8 = g_locale_to_utf8 (description, -1, NULL, NULL, NULL);
209 210 211 212 213 214 215 216
	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);
	}
217 218 219 220 221 222 223 224 225
	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
226 227 228 229 230 231 232 233 234 235

/*
g_print ("%s (%s): %s (%s)\n", key, description, formatted_value, raw_value);
*/

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

		info.id = attribute;
236
		info.type = (type_name != NULL) ? g_strdup (type_name) : NULL;
Paolo Bacchilega's avatar
Paolo Bacchilega committed
237 238 239 240 241 242 243 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
		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);
	}

	if ((metadata_info->display_name == NULL) && (description_utf8 != NULL))
		metadata_info->display_name = g_strdup (description_utf8);

	metadata = gth_metadata_new ();
	g_object_set (metadata, "id", key, "description", description_utf8, "formatted", formatted_value_utf8, "raw", raw_value, NULL);
	g_file_info_set_attribute_object (info, attribute, G_OBJECT (metadata));

	g_object_unref (metadata);
	g_free (formatted_value_utf8);
	g_free (description_utf8);
	g_free (attribute);
}


static void
set_attribute_from_tagset (GFileInfo  *info,
			   const char *attribute,
			   const char *tagset[])
{
	GObject *metadata;
	int      i;
	char    *key;
	char    *description;
	char    *formatted_value;
	char    *raw_value;

	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;

	g_object_get (metadata,
		      "id", &key,
		      "description", &description,
		      "formatted", &formatted_value,
		      "raw", &raw_value,
		      NULL);
286
	set_file_info (info, attribute, description, formatted_value, raw_value, NULL, NULL);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
287 288 289 290
}


static void
291 292 293
set_string_list_attribute_from_tagset (GFileInfo  *info,
				       const char *attribute,
				       const char *tagset[])
Paolo Bacchilega's avatar
Paolo Bacchilega committed
294
{
295 296 297 298 299
	GObject        *metadata;
	int             i;
	char           *raw;
	char          **keywords;
	GthStringList  *string_list;
Paolo Bacchilega's avatar
Paolo Bacchilega committed
300

301 302 303 304 305 306 307 308 309 310 311
	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;

	g_object_get (metadata, "raw", &raw, NULL);
312
	keywords = g_strsplit (raw, ", ", -1);
313 314 315 316 317 318 319
	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);
}

320

321 322 323
static void
set_attributes_from_tagsets (GFileInfo *info)
{
324
	set_attribute_from_tagset (info, "general::datetime", _DATE_TAG_NAMES);
325
	set_attribute_from_tagset (info, "general::description", _DESCRIPTION_TAG_NAMES);
326
	set_attribute_from_tagset (info, "general::title", _TITLE_TAG_NAMES);
327 328
	set_attribute_from_tagset (info, "general::location", _LOCATION_TAG_NAMES);
	set_string_list_attribute_from_tagset (info, "general::tags", _KEYWORDS_TAG_NAMES);
329
	set_attribute_from_tagset (info, "Embedded::Photo::DateTimeOriginal", _ORIGINAL_DATE_TAG_NAMES);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
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
	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";
}


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
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) {
			stringstream value;
			value << *md;

			stringstream short_name;
			if (md->ifdId () > Exiv2::ifd1Id) {
				// Must be a MakerNote - include group name
				short_name << md->groupName() << "." << md->tagName();
			}
			else {
				// Normal exif tag - just use tag name
				short_name << md->tagName();
			}

			set_file_info (info,
				       md->key().c_str(),
				       short_name.str().c_str(),
				       value.str().c_str(),
				       md->toString().c_str(),
383 384
				       get_exif_default_category (*md),
				       md->typeName());
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
		}
	}

	Exiv2::IptcData &iptcData = image->iptcData();
	if (! iptcData.empty()) {
		Exiv2::IptcData::iterator end = iptcData.end();
		for (Exiv2::IptcData::iterator md = iptcData.begin(); md != end; ++md) {
			stringstream value;
			value << *md;

			stringstream short_name;
			short_name << md->tagName();

			set_file_info (info,
				       md->key().c_str(),
				       short_name.str().c_str(),
				       value.str().c_str(),
				       md->toString().c_str(),
403 404
				       "Iptc",
				       md->typeName());
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
		}
	}

	Exiv2::XmpData &xmpData = image->xmpData();
	if (! xmpData.empty()) {
		Exiv2::XmpData::iterator end = xmpData.end();
		for (Exiv2::XmpData::iterator md = xmpData.begin(); md != end; ++md) {
			stringstream value;
			value << *md;

			stringstream short_name;
			short_name << md->groupName() << "." << md->tagName();

			set_file_info (info,
				       md->key().c_str(),
				       short_name.str().c_str(),
				       value.str().c_str(),
				       md->toString().c_str(),
423 424
				       "Xmp::Embedded",
				       md->typeName());
425 426 427 428 429 430 431
		}
	}

	set_attributes_from_tagsets (info);
}


Paolo Bacchilega's avatar
Paolo Bacchilega committed
432
/*
433
 * exiv2_read_metadata_from_file
Paolo Bacchilega's avatar
Paolo Bacchilega committed
434 435 436 437 438 439
 * reads metadata from image files
 * code relies heavily on example1 from the exiv2 website
 * http://www.exiv2.org/example1.html
 */
extern "C"
gboolean
440 441 442
exiv2_read_metadata_from_file (GFile      *file,
			       GFileInfo  *info,
			       GError    **error)
Paolo Bacchilega's avatar
Paolo Bacchilega committed
443 444 445 446 447
{
	try {
		char *path;

		path = g_file_get_path (file);
448 449 450 451 452 453
		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
454 455 456 457
		Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(path);
		g_free (path);

		if (image.get() == 0) {
458 459
			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
460 461 462
			return FALSE;
		}

463 464
		exiv2_read_metadata (image, info);
	}
465
	catch (Exiv2::AnyError& e) {
466
		if (error != NULL)
467
			*error = g_error_new_literal (G_IO_ERROR, G_IO_ERROR_FAILED, e.what());
468 469
		return FALSE;
	}
Paolo Bacchilega's avatar
Paolo Bacchilega committed
470

471 472
	return TRUE;
}
Paolo Bacchilega's avatar
Paolo Bacchilega committed
473 474


475 476 477 478 479 480 481 482 483
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
484

485 486 487 488
		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
489 490
		}

491
		exiv2_read_metadata (image, info);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
492
	}
493
	catch (Exiv2::AnyError& e) {
494
		if (error != NULL)
495
			*error = g_error_new_literal (G_IO_ERROR, G_IO_ERROR_FAILED, e.what());
Paolo Bacchilega's avatar
Paolo Bacchilega committed
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
		return FALSE;
	}

	return TRUE;
}


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

		path = g_file_get_path (file);
512 513 514
		if (path == NULL)
			return FALSE;

Paolo Bacchilega's avatar
Paolo Bacchilega committed
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
		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()) {
			Exiv2::XmpData::iterator end = xmpData.end();
			for (Exiv2::XmpData::iterator md = xmpData.begin(); md != end; ++md) {
				stringstream value;
				value << *md;

				stringstream short_name;
				short_name << md->groupName() << "." << md->tagName();

				set_file_info (info,
					       md->key().c_str(),
					       short_name.str().c_str(),
					       value.str().c_str(),
					       md->toString().c_str(),
539 540
					       "Xmp::Sidecar",
					       md->typeName());
Paolo Bacchilega's avatar
Paolo Bacchilega committed
541 542 543 544 545 546 547
			}
		}
		Exiv2::XmpParser::terminate();

		set_attributes_from_tagsets (info);
	}
	catch (Exiv2::AnyError& e) {
548
		std::cerr << "Caught Exiv2 exception '" << e << "'\n";
Paolo Bacchilega's avatar
Paolo Bacchilega committed
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
		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;
}


578 579 580 581
static Exiv2::DataBuf
exiv2_write_metadata_private (Exiv2::Image::AutoPtr  image,
			      GFileInfo             *info,
			      GdkPixbuf             *pixbuf)
Paolo Bacchilega's avatar
Paolo Bacchilega committed
582
{
583 584
	char **attributes;
	int    i;
Paolo Bacchilega's avatar
Paolo Bacchilega committed
585

586
	image->readMetadata();
Paolo Bacchilega's avatar
Paolo Bacchilega committed
587

588
	// EXIF Data
Paolo Bacchilega's avatar
Paolo Bacchilega committed
589

590 591 592 593 594
	Exiv2::ExifData &ed = image->exifData();
	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
595

596 597
		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
598

599
		try {
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
			/* 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,
			 * the type defaults to Ascii.
			 * We always create the metadatum explicilty if the
			 * type is available to avoid type errors.
			 * See bug #610389 for more details.  The original
			 * expanation is here:
			 * http://uk.groups.yahoo.com/group/exiv2/message/1472
			 */

			GthMetadataInfo *metadatum_info = gth_main_get_metadata_info (attributes[i]);
			if ((metadatum_info != NULL) && (metadatum_info->type != NULL)) {
				Exiv2::Value::AutoPtr value = Exiv2::Value::create (Exiv2::TypeInfo::typeId (metadatum_info->type));
				Exiv2::ExifKey exif_key(key);
				ed.add (exif_key, value.get());
			}
617 618
			ed[key] = gth_metadata_get_raw (metadatum);
		}
619
		catch (Exiv2::AnyError& e) {
620
			/* we don't care about invalid key errors */
621
			g_warning ("%s", e.what());
622
		}
Paolo Bacchilega's avatar
Paolo Bacchilega committed
623

624 625 626
		g_free (key);
	}
	g_strfreev (attributes);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
627

628
	// Mandatory tags - add if not already present
Paolo Bacchilega's avatar
Paolo Bacchilega committed
629

630 631 632 633 634 635 636 637
	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
638

639
	// Overwrite the software tag
Paolo Bacchilega's avatar
Paolo Bacchilega committed
640

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

643
	// Update the dimension tags with actual image values
Paolo Bacchilega's avatar
Paolo Bacchilega committed
644

645 646
	int width = 0;
	int height = 0;
Paolo Bacchilega's avatar
Paolo Bacchilega committed
647

648 649
	if (pixbuf != NULL) {
		width = gdk_pixbuf_get_width (pixbuf);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
650 651 652
		if (width > 0)
			ed["Exif.Photo.PixelXDimension"] = width;

653
		height = gdk_pixbuf_get_height (pixbuf);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
654 655
		if (height > 0)
			ed["Exif.Photo.PixelYDimension"] = height;
656
	}
Paolo Bacchilega's avatar
Paolo Bacchilega committed
657

658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
	// Update the thumbnail

	Exiv2::ExifThumb thumb(image->exifData());
	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
674 675 676 677
		}
		else
			thumb.erase();

678 679 680 681
		g_object_unref (thumb_pixbuf);
	}
	else
		thumb.erase();
Paolo Bacchilega's avatar
Paolo Bacchilega committed
682

683
	// Update the DateTime tag
Paolo Bacchilega's avatar
Paolo Bacchilega committed
684

685 686 687 688 689 690 691
	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
692

693
	// IPTC Data
Paolo Bacchilega's avatar
Paolo Bacchilega committed
694

695 696 697 698 699
	Exiv2::IptcData &id = image->iptcData();
	attributes = g_file_info_list_attributes (info, "Iptc");
	for (i = 0; attributes[i] != NULL; i++) {
		GthMetadata *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
700

701
		try {
702 703 704 705 706 707 708
			/* See the exif data code above for an explanation. */
			GthMetadataInfo *metadatum_info = gth_main_get_metadata_info (attributes[i]);
			if ((metadatum_info != NULL) && (metadatum_info->type != NULL)) {
				Exiv2::Value::AutoPtr value = Exiv2::Value::create (Exiv2::TypeInfo::typeId (metadatum_info->type));
				Exiv2::IptcKey iptc_key(key);
				id.add (iptc_key, value.get());
			}
709 710
			id[key] = gth_metadata_get_raw (metadatum);
		}
711
		catch (Exiv2::AnyError& e) {
712
			/* we don't care about invalid key errors */
713
			g_warning ("%s", e.what());
Paolo Bacchilega's avatar
Paolo Bacchilega committed
714 715
		}

716 717 718
		g_free (key);
	}
	g_strfreev (attributes);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
719

720
	// XMP Data
Paolo Bacchilega's avatar
Paolo Bacchilega committed
721

722 723 724 725 726
	Exiv2::XmpData &xd = image->xmpData();
	attributes = g_file_info_list_attributes (info, "Xmp");
	for (i = 0; attributes[i] != NULL; i++) {
		GthMetadata *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
727

728 729 730 731 732 733
		// Remove existing tags of the same type.
		// Seems to be needed for storing category keywords.
		// Not exactly sure why!
		Exiv2::XmpData::iterator iter = xd.findKey (Exiv2::XmpKey (key));
		if (iter != xd.end ())
			xd.erase (iter);
Paolo Bacchilega's avatar
Paolo Bacchilega committed
734

735
		try {
736 737
			const char *value = gth_metadata_get_raw (metadatum);

738 739 740 741 742 743 744 745
			if ((value != NULL) && strcmp (value, "") != 0) {
				/* See the exif data code above for an explanation. */
				GthMetadataInfo *metadatum_info = gth_main_get_metadata_info (attributes[i]);
				if ((metadatum_info != NULL) && (metadatum_info->type != NULL)) {
					Exiv2::Value::AutoPtr value = Exiv2::Value::create (Exiv2::TypeInfo::typeId (metadatum_info->type));
					Exiv2::XmpKey xmp_key(key);
					xd.add (xmp_key, value.get());
				}
746
				xd[key] = gth_metadata_get_raw (metadatum);
747
			}
Paolo Bacchilega's avatar
Paolo Bacchilega committed
748
		}
749
		catch (Exiv2::AnyError& e) {
750
			/* we don't care about invalid key errors */
751
			g_warning ("%s", e.what());
752 753 754 755 756 757 758 759 760 761 762 763 764 765
		}

		g_free (key);
	}
	g_strfreev (attributes);

	image->writeMetadata();
	Exiv2::BasicIo &io = image->io();
	io.open();

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


766 767
extern "C"
gboolean
768
exiv2_supports_writes (const char *mime_type)
769
{
770 771
	return (_g_content_type_is_a (mime_type, "image/jpeg") ||
		_g_content_type_is_a (mime_type, "image/png"));
772 773 774
}


775 776 777 778
extern "C"
gboolean
exiv2_write_metadata (SavePixbufData *data)
{
779
	if (exiv2_supports_writes (data->mime_type)) {
780 781 782
		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
783

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

786 787 788 789 790 791 792
			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
793
			g_warning ("%s\n", e.what());
794 795
			return FALSE;
		}
Paolo Bacchilega's avatar
Paolo Bacchilega committed
796
	}
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819

	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_;
	}
820
	catch (Exiv2::AnyError& e) {
821
		if (error != NULL)
822
			*error = g_error_new_literal (G_IO_ERROR, G_IO_ERROR_FAILED, e.what());
823 824 825 826
		return FALSE;
	}

	return TRUE;
Paolo Bacchilega's avatar
Paolo Bacchilega committed
827
}