PhotoMetadata.vala 38.9 KB
Newer Older
Eric Gregory's avatar
Eric Gregory committed
1
/* Copyright 2010-2011 Yorba Foundation
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 *
 * This software is licensed under the GNU Lesser General Public License
 * (version 2.1 or later).  See the COPYING file in this distribution. 
 */

//
// PhotoMetadata
//
// PhotoMetadata is a wrapper class around gexiv2.  The reasoning for this is (a) to facilitiate
// interface changes to meet Shotwell's requirements without needing modifications of the library
// itself, and (b) some requirements for this class (i.e. obtaining raw metadata) is not available
// in gexiv2, and so must be done by hand.
//
// Although it's perceived that Exiv2 will remain Shotwell's metadata library of choice, this
// may change in the future, and so this wrapper helps with that as well.
//
// There is no expectation of thread-safety in this class (yet).
//
// Tags come from Exiv2's naming scheme:
// http://www.exiv2.org/metadata.html
//

public enum MetadataDomain {
    UNKNOWN,
    EXIF,
    XMP,
    IPTC
}

31
public class HierarchicalKeywordField {
32 33 34 35 36 37 38 39 40 41 42 43 44 45
    public string field_name;
    public string path_separator;
    public bool wants_leading_separator;
    public bool is_writeable;
    
    public HierarchicalKeywordField(string field_name, string path_separator,
        bool wants_leading_separator, bool is_writeable) {
        this.field_name = field_name;
        this.path_separator = path_separator;
        this.wants_leading_separator = wants_leading_separator;
        this.is_writeable = is_writeable;
    }
}

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
public abstract class PhotoPreview {
    private string name;
    private Dimensions dimensions;
    private uint32 size;
    private string mime_type;
    private string extension;
    
    public PhotoPreview(string name, Dimensions dimensions, uint32 size, string mime_type, string extension) {
        this.name = name;
        this.dimensions = dimensions;
        this.size = size;
        this.mime_type = mime_type;
        this.extension = extension;
    }
    
    public string get_name() {
        return name;
    }
    
    public Dimensions get_pixel_dimensions() {
        return dimensions;
    }
    
    public uint32 get_size() {
        return size;
    }
    
    public string get_mime_type() {
        return mime_type;
    }
    
    public string get_extension() {
        return extension;
    }
    
    public abstract uint8[] flatten() throws Error;
    
    public virtual Gdk.Pixbuf? get_pixbuf() throws Error {
        uint8[] flattened = flatten();
        
        // Need to create from stream or file for decode ... catch decode error and return null,
        // different from an I/O error causing the problem
        try {
89 90
            return new Gdk.Pixbuf.from_stream(new MemoryInputStream.from_data(flattened, null),
                null);
91 92 93 94 95 96 97 98
        } catch (Error err) {
            warning("Unable to decode thumbnail for %s: %s", name, err.message);
            
            return null;
        }
    }
}

99
public class PhotoMetadata : MediaMetadata {
100 101 102 103 104 105
    public enum SetOption {
        ALL_DOMAINS,
        ONLY_IF_DOMAIN_PRESENT,
        AT_LEAST_DEFAULT_DOMAIN
    }
    
106 107
    private const PrepareInputTextOptions PREPARE_STRING_OPTIONS =
        PrepareInputTextOptions.INVALID_IS_NULL
108
        | PrepareInputTextOptions.EMPTY_IS_NULL
109
        | PrepareInputTextOptions.STRIP
110
        | PrepareInputTextOptions.STRIP_CRLF
111 112 113
        | PrepareInputTextOptions.NORMALIZE
        | PrepareInputTextOptions.VALIDATE;
    
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
    private class InternalPhotoPreview : PhotoPreview {
        public PhotoMetadata owner;
        public uint number;
        
        public InternalPhotoPreview(PhotoMetadata owner, string name, uint number, 
            GExiv2.PreviewProperties props) {
            base (name, Dimensions((int) props.get_width(), (int) props.get_height()), 
                props.get_size(), props.get_mime_type(), props.get_extension());
            
            this.owner = owner;
            this.number = number;
        }
        
        public override uint8[] flatten() throws Error {
            unowned GExiv2.PreviewProperties?[] props = owner.exiv2.get_preview_properties();
            assert(props != null && props.length > number);
            
            return owner.exiv2.get_preview_image(props[number]).get_data();
        }
    }
    
    private GExiv2.Metadata exiv2 = new GExiv2.Metadata();
    private Exif.Data? exif = null;
    string source_name = "<uninitialized>";
    
    public PhotoMetadata() {
    }
    
142
    public override void read_from_file(File file) throws Error {
143
        exiv2 = new GExiv2.Metadata();
144 145
        exif = null;
        
146 147 148 149 150 151 152 153 154 155
        exiv2.open_path(file.get_path());
        exif = Exif.Data.new_from_file(file.get_path());
        source_name = file.get_basename();
    }
    
    public void write_to_file(File file) throws Error {
        exiv2.save_file(file.get_path());
    }
    
    public void read_from_buffer(uint8[] buffer, int length = 0) throws Error {
156 157 158
        if (length <= 0)
            length = buffer.length;
        
159 160
        assert(buffer.length >= length);
        
161
        exiv2 = new GExiv2.Metadata();
162 163
        exif = null;
        
164 165 166 167 168
        exiv2.open_buf(buffer, length);
        exif = Exif.Data.new_from_data(buffer, length);
        source_name = "<memory buffer %d bytes>".printf(length);
    }
    
169 170 171 172 173 174 175
    public void read_from_app1_segment(uint8[] buffer, int length = 0) throws Error {
        if (length <= 0)
            length = buffer.length;
        
        assert(buffer.length >= length);
        
        exiv2 = new GExiv2.Metadata();
176 177
        exif = null;
        
178
        exiv2.from_app1_segment(buffer, length);
179
        exif = Exif.Data.new_from_data(buffer, length);
180 181 182
        source_name = "<app1 segment %d bytes>".printf(length);
    }
    
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 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
    public static MetadataDomain get_tag_domain(string tag) {
        if (GExiv2.Metadata.is_exif_tag(tag))
            return MetadataDomain.EXIF;
        
        if (GExiv2.Metadata.is_xmp_tag(tag))
            return MetadataDomain.XMP;
        
        if (GExiv2.Metadata.is_iptc_tag(tag))
            return MetadataDomain.IPTC;
        
        return MetadataDomain.UNKNOWN;
    }
    
    public bool has_domain(MetadataDomain domain) {
        switch (domain) {
            case MetadataDomain.EXIF:
                return exiv2.has_exif();
            
            case MetadataDomain.XMP:
                return exiv2.has_xmp();
            
            case MetadataDomain.IPTC:
                return exiv2.has_iptc();
            
            case MetadataDomain.UNKNOWN:
            default:
                return false;
        }
    }
    
    public bool has_exif() {
        return has_domain(MetadataDomain.EXIF);
    }
    
    public bool has_xmp() {
        return has_domain(MetadataDomain.XMP);
    }
    
    public bool has_iptc() {
        return has_domain(MetadataDomain.IPTC);
    }
    
    public bool can_write_to_domain(MetadataDomain domain) {
        switch (domain) {
            case MetadataDomain.EXIF:
                return exiv2.get_supports_exif();
            
            case MetadataDomain.XMP:
                return exiv2.get_supports_xmp();
            
            case MetadataDomain.IPTC:
                return exiv2.get_supports_iptc();
            
            case MetadataDomain.UNKNOWN:
            default:
                return false;
        }
    }
    
    public bool can_write_exif() {
        return can_write_to_domain(MetadataDomain.EXIF);
    }
    
    public bool can_write_xmp() {
        return can_write_to_domain(MetadataDomain.XMP);
    }
    
    public bool can_write_iptc() {
        return can_write_to_domain(MetadataDomain.IPTC);
    }
    
    public bool has_tag(string tag) {
        return exiv2.has_tag(tag);
    }
    
258 259 260 261 262 263 264 265
    private Gee.Set<string> create_string_set(CompareFunc? compare_func) {
        // ternary doesn't work here
        if (compare_func == null)
            return new Gee.HashSet<string>();
        else
            return new Gee.TreeSet<string>(compare_func);
    }
    
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
    public Gee.Collection<string>? get_tags(MetadataDomain domain, CompareFunc? compare_func = null) {
        string[] tags = null;
        switch (domain) {
            case MetadataDomain.EXIF:
                tags = exiv2.get_exif_tags();
            break;
            
            case MetadataDomain.XMP:
                tags = exiv2.get_xmp_tags();
            break;
            
            case MetadataDomain.IPTC:
                tags = exiv2.get_iptc_tags();
            break;
        }
        
        if (tags == null || tags.length == 0)
            return null;
        
285
        Gee.Collection<string> collection = create_string_set(compare_func);
286 287 288 289 290 291 292
        foreach (string tag in tags)
            collection.add(tag);
        
        return collection;
    }
    
    public Gee.Collection<string> get_all_tags(CompareFunc? compare_func = null) {
293
        Gee.Collection<string> all_tags = create_string_set(compare_func);
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
        
        Gee.Collection<string>? exif_tags = get_tags(MetadataDomain.EXIF);
        if (exif_tags != null && exif_tags.size > 0)
            all_tags.add_all(exif_tags);
        
        Gee.Collection<string>? xmp_tags = get_tags(MetadataDomain.XMP);
        if (xmp_tags != null && xmp_tags.size > 0)
            all_tags.add_all(xmp_tags);
        
        Gee.Collection<string>? iptc_tags = get_tags(MetadataDomain.IPTC);
        if (iptc_tags != null && iptc_tags.size > 0)
            all_tags.add_all(iptc_tags);
        
        return all_tags.size > 0 ? all_tags : null;
    }
    
    public string? get_tag_label(string tag) {
        return GExiv2.Metadata.get_tag_label(tag);
    }
    
    public string? get_tag_description(string tag) {
        return GExiv2.Metadata.get_tag_description(tag);
    }
    
    public string? get_string(string tag) {
319
        return prepare_input_text(exiv2.get_tag_string(tag), PREPARE_STRING_OPTIONS, DEFAULT_USER_TEXT_INPUT_LENGTH);
320 321 322
    }
    
    public string? get_string_interpreted(string tag) {
323
        return prepare_input_text(exiv2.get_tag_interpreted_string(tag), PREPARE_STRING_OPTIONS, DEFAULT_USER_TEXT_INPUT_LENGTH);
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
    }
    
    public string? get_first_string(string[] tags) {
        foreach (string tag in tags) {
            string? value = get_string(tag);
            if (value != null)
                return value;
        }
        
        return null;
    }
    
    public string? get_first_string_interpreted(string[] tags) {
        foreach (string tag in tags) {
            string? value = get_string_interpreted(tag);
            if (value != null)
                return value;
        }
        
        return null;
    }
    
346 347 348 349 350 351 352
    // Returns a List that has been filtered through a Set, so no duplicates will be returned.
    //
    // NOTE: get_tag_multiple() in gexiv2 currently does not work with EXIF tags (as EXIF can 
    // never return a list of strings).  It will quietly return NULL if attempted.  Until fixed
    // (there or here), don't use this function to access EXIF.  See:
    // http://trac.yorba.org/ticket/2966
    public Gee.List<string>? get_string_multiple(string tag) {
353 354 355 356
        string[] values = exiv2.get_tag_multiple(tag);
        if (values == null || values.length == 0)
            return null;
        
357 358 359
        Gee.List<string> list = new Gee.ArrayList<string>();
        
        Gee.HashSet<string> collection = new Gee.HashSet<string>();
360
        foreach (string value in values) {
361 362 363
            string? prepped = prepare_input_text(value, PREPARE_STRING_OPTIONS,
                DEFAULT_USER_TEXT_INPUT_LENGTH);
                
364 365
            if (prepped != null && !collection.contains(prepped)) {
                list.add(prepped);
366
                collection.add(prepped);
367
            }
368
        }
369
        
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
        return list.size > 0 ? list : null;
    }
    
    // Returns a List that has been filtered through a Set, so no duplicates will be found.
    //
    // NOTE: get_tag_multiple() in gexiv2 currently does not work with EXIF tags (as EXIF can 
    // never return a list of strings).  It will quietly return NULL if attempted.  Until fixed
    // (there or here), don't use this function to access EXIF.  See:
    // http://trac.yorba.org/ticket/2966
    public Gee.List<string>? get_first_string_multiple(string[] tags) {
        foreach (string tag in tags) {
            Gee.List<string>? values = get_string_multiple(tag);
            if (values != null && values.size > 0)
                return values;
        }
        
        return null;
387 388 389
    }
    
    public void set_string(string tag, string value) {
390
        string? prepped = prepare_input_text(value, PREPARE_STRING_OPTIONS, DEFAULT_USER_TEXT_INPUT_LENGTH);
391
        if (prepped == null) {
392 393 394 395 396
            warning("Not setting tag %s to string %s: invalid UTF-8", tag, value);
            
            return;
        }
        
397
        if (!exiv2.set_tag_string(tag, prepped))
398 399 400
            warning("Unable to set tag %s to string %s from source %s", tag, value, source_name);
    }
    
401 402 403 404
    private delegate void SetGenericValue(string tag);
    
    private void set_all_generic(string[] tags, SetOption option, SetGenericValue setter) {
        bool written = false;
405
        foreach (string tag in tags) {
406 407 408 409
            if (option == SetOption.ALL_DOMAINS || has_domain(get_tag_domain(tag))) {
                setter(tag);
                written = true;
            }
410
        }
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
        
        if (option == SetOption.AT_LEAST_DEFAULT_DOMAIN && !written && tags.length > 0) {
            MetadataDomain default_domain = get_tag_domain(tags[0]);
            
            // write at least the first one, as it's the default
            setter(tags[0]);
            
            // write the remainder, if they are of the same domain
            for (int ctr = 1; ctr < tags.length; ctr++) {
                if (get_tag_domain(tags[ctr]) == default_domain)
                    setter(tags[ctr]);
            }
        }
    }
    
    public void set_all_string(string[] tags, string value, SetOption option) {
        set_all_generic(tags, option, (tag) => { set_string(tag, value); });
428 429 430
    }
    
    public void set_string_multiple(string tag, Gee.Collection<string> collection) {
431 432
        string[] values = new string[0];
        foreach (string value in collection) {
433
            string? prepped = prepare_input_text(value, PREPARE_STRING_OPTIONS,-1);
434 435
            if (prepped != null)
                values += prepped;
436 437
            else
                warning("Unable to set string %s to %s: invalid UTF-8", value, tag);
438
        }
439
        
440 441
        if (values.length == 0)
            return;
442 443 444 445 446 447

        // append a null pointer to the end of the string array -- this is a necessary
        // workaround for http://trac.yorba.org/ticket/3264. See also
        // http://trac.yorba.org/ticket/3257, which describes the user-visible behavior
        // seen in the Flickr Connector as a result of the former bug.
        values += null;
448
        
449 450 451 452
        if (!exiv2.set_tag_multiple(tag, values))
            warning("Unable to set %d strings to tag %s from source %s", values.length, tag, source_name);
    }
    
453 454
    public void set_all_string_multiple(string[] tags, Gee.Collection<string> values, SetOption option) {
        set_all_generic(tags, option, (tag) => { set_string_multiple(tag, values); });
455 456 457
    }
    
    public bool get_long(string tag, out long value) {
458 459 460
        if (!has_tag(tag)) {
            value = 0;
            
461
            return false;
462
        }
463 464 465 466 467 468 469 470 471 472 473 474
        
        value = exiv2.get_tag_long(tag);
        
        return true;
    }
    
    public bool get_first_long(string[] tags, out long value) {
        foreach (string tag in tags) {
            if (get_long(tag, out value))
                return true;
        }
        
475 476
        value = 0;
        
477 478 479 480 481 482 483 484
        return false;
    }
    
    public void set_long(string tag, long value) {
        if (!exiv2.set_tag_long(tag, value))
            warning("Unable to set tag %s to long %ld from source %s", tag, value, source_name);
    }
    
485 486
    public void set_all_long(string[] tags, long value, SetOption option) {
        set_all_generic(tags, option, (tag) => { set_long(tag, value); });
487 488 489
    }
    
    public bool get_rational(string tag, out MetadataRational rational) {
490 491 492 493 494 495
        int numerator, denominator;
        bool result = exiv2.get_exif_tag_rational(tag, out numerator, out denominator);
        
        rational = MetadataRational(numerator, denominator);
        
        return result;
496 497 498 499 500 501 502 503
    }
    
    public bool get_first_rational(string[] tags, out MetadataRational rational) {
        foreach (string tag in tags) {
            if (get_rational(tag, out rational))
                return true;
        }
        
504 505
        rational = MetadataRational(0, 0);
        
506 507 508 509 510 511 512 513 514 515
        return false;
    }
    
    public void set_rational(string tag, MetadataRational rational) {
        if (!exiv2.set_exif_tag_rational(tag, rational.numerator, rational.denominator)) {
            warning("Unable to set tag %s to rational %s from source %s", tag, rational.to_string(),
                source_name);
        }
    }
    
516 517
    public void set_all_rational(string[] tags, MetadataRational rational, SetOption option) {
        set_all_generic(tags, option, (tag) => { set_rational(tag, rational); });
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 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
    }
    
    public MetadataDateTime? get_date_time(string tag) {
        string? value = get_string(tag);
        if (value == null)
            return null;
        
        try {
            switch (get_tag_domain(tag)) {
                case MetadataDomain.XMP:
                    return new MetadataDateTime.from_xmp(value);
                
                // TODO: IPTC date/time support (which is tricky here, because date/time values
                // are stored in separate tags)
                case MetadataDomain.IPTC:
                    return null;
                
                case MetadataDomain.EXIF:
                default:
                    return new MetadataDateTime.from_exif(value);
            }
        } catch (Error err) {
            warning("Unable to read date/time %s from source %s: %s", tag, source_name, err.message);
            
            return null;
        }
    }
    
    public MetadataDateTime? get_first_date_time(string[] tags) {
        foreach (string tag in tags) {
            MetadataDateTime? date_time = get_date_time(tag);
            if (date_time != null)
                return date_time;
        }
        
        return null;
    }
    
    public void set_date_time(string tag, MetadataDateTime date_time) {
        switch (get_tag_domain(tag)) {
            case MetadataDomain.EXIF:
                set_string(tag, date_time.get_exif_label());
            break;
            
            case MetadataDomain.XMP:
                set_string(tag, date_time.get_xmp_label());
            break;
            
            // TODO: Support IPTC date/time (which are stored in separate tags)
            case MetadataDomain.IPTC:
            default:
                warning("Cannot set date/time for %s from source %s: unsupported metadata domain %s", tag,
                    source_name, get_tag_domain(tag).to_string());
            break;
        }
    }
    
575 576
    public void set_all_date_time(string[] tags, MetadataDateTime date_time, SetOption option) {
        set_all_generic(tags, option, (tag) => { set_date_time(tag, date_time); });
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
    }
    
    // Returns raw bytes of EXIF metadata, including signature and optionally the preview (if present).
    public uint8[]? flatten_exif(bool include_preview) {
        if (exif == null)
            return null;
        
        // save thumbnail to strip if no attachments requested (so it can be added back and
        // deallocated automatically)
        uchar *thumbnail = exif.data;
        uint thumbnail_size = exif.size;
        if (!include_preview) {
            exif.data = null;
            exif.size = 0;
        }
        
        uint8[]? flattened = null;
        
        // save the struct to a buffer and copy into a Vala-friendly one
        uchar *saved_data = null;
        uint saved_size = 0;
        exif.save_data(&saved_data, &saved_size);
        if (saved_size > 0 && saved_data != null) {
            flattened = new uint8[saved_size];
            Memory.copy(flattened, saved_data, saved_size);
            
            Exif.Mem.new_default().free(saved_data);
        }
        
        // restore thumbnail (this works in either case)
        exif.data = thumbnail;
        exif.size = thumbnail_size;
        
        return flattened;
    }
    
    // Returns raw bytes of EXIF preview, if present
    public uint8[]? flatten_exif_preview() {
615 616
        uchar[] buffer;
        return exiv2.get_exif_thumbnail(out buffer) ? buffer : null;
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
    }
    
    public uint get_preview_count() {
        unowned GExiv2.PreviewProperties?[] props = exiv2.get_preview_properties();
        
        return (props != null) ? props.length : 0;
    }
    
    // Previews are sorted from smallest to largest (width x height)
    public PhotoPreview? get_preview(uint number) {
        unowned GExiv2.PreviewProperties?[] props = exiv2.get_preview_properties();
        if (props == null || props.length <= number)
            return null;
        
        return new InternalPhotoPreview(this, source_name, number, props[number]);
    }
    
    public void remove_exif_thumbnail() {
        exiv2.erase_exif_thumbnail();
        if (exif != null) {
            Exif.Mem.new_default().free(exif.data);
638
            exif.data = null;
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
            exif.size = 0;
        }
    }
    
    public void remove_tag(string tag) {
        exiv2.clear_tag(tag);
    }
    
    public void remove_tags(string[] tags) {
        foreach (string tag in tags)
            remove_tag(tag);
    }
    
    public void clear_domain(MetadataDomain domain) {
        switch (domain) {
            case MetadataDomain.EXIF:
                exiv2.clear_exif();
            break;
            
            case MetadataDomain.XMP:
                exiv2.clear_xmp();
            break;
            
            case MetadataDomain.IPTC:
                exiv2.clear_iptc();
            break;
        }
    }
    
    public void clear() {
        exiv2.clear();
    }
    
    private static string[] DATE_TIME_TAGS = {
        "Exif.Image.DateTime",
        "Xmp.tiff.DateTime",
        "Xmp.xmp.ModifyDate"
    };
    
    public MetadataDateTime? get_modification_date_time() {
        return get_first_date_time(DATE_TIME_TAGS);
    }
    
682
    public void set_modification_date_time(MetadataDateTime? date_time,
683
        SetOption option = SetOption.ALL_DOMAINS) {
684
        if (date_time != null)
685
            set_all_date_time(DATE_TIME_TAGS, date_time, option);
686 687 688 689 690 691 692
        else
            remove_tags(DATE_TIME_TAGS);
    }
    
    private static string[] EXPOSURE_DATE_TIME_TAGS = {
        "Exif.Photo.DateTimeOriginal",
        "Xmp.exif.DateTimeOriginal",
693 694 695 696
        "Xmp.xmp.CreateDate",
        "Exif.Photo.DateTimeDigitized",
        "Xmp.exif.DateTimeDigitized",
        "Exif.Image.DateTime"
697 698 699 700 701 702
    };
    
    public MetadataDateTime? get_exposure_date_time() {
        return get_first_date_time(EXPOSURE_DATE_TIME_TAGS);
    }
    
703
    public void set_exposure_date_time(MetadataDateTime? date_time,
704
        SetOption option = SetOption.ALL_DOMAINS) {
705
        if (date_time != null)
706
            set_all_date_time(EXPOSURE_DATE_TIME_TAGS, date_time, option);
707 708 709 710 711 712 713 714 715 716 717 718 719
        else
            remove_tags(EXPOSURE_DATE_TIME_TAGS);
    }
    
    private static string[] DIGITIZED_DATE_TIME_TAGS = {
        "Exif.Photo.DateTimeDigitized",
        "Xmp.exif.DateTimeDigitized"
    };
    
    public MetadataDateTime? get_digitized_date_time() {
        return get_first_date_time(DIGITIZED_DATE_TIME_TAGS);
    }
    
720
    public void set_digitized_date_time(MetadataDateTime? date_time,
721
        SetOption option = SetOption.ALL_DOMAINS) {
722
        if (date_time != null)
723
            set_all_date_time(DIGITIZED_DATE_TIME_TAGS, date_time, option);
724 725 726 727
        else
            remove_tags(DIGITIZED_DATE_TIME_TAGS);
    }
    
728 729 730 731 732 733 734 735
    public override MetadataDateTime? get_creation_date_time() {
        MetadataDateTime? creation = get_exposure_date_time();
        if (creation == null)
            creation = get_digitized_date_time();
        
        return creation;
    }
    
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 765 766 767 768 769
    private static string[] WIDTH_TAGS = {
        "Exif.Photo.PixelXDimension",
        "Xmp.exif.PixelXDimension",
        "Xmp.tiff.ImageWidth",
        "Xmp.exif.PixelXDimension"
    };
    
    public static string[] HEIGHT_TAGS = {
        "Exif.Photo.PixelYDimension",
        "Xmp.exif.PixelYDimension",
        "Xmp.tiff.ImageHeight",
        "Xmp.exif.PixelYDimension"
    };
    
    public Dimensions? get_pixel_dimensions() {
        // walk the tag arrays concurrently, returning the dimensions of the first found pair
        assert(WIDTH_TAGS.length == HEIGHT_TAGS.length);
        for (int ctr = 0; ctr < WIDTH_TAGS.length; ctr++) {
            // Can't turn this into a single if statement with an || bailing out due to this bug:
            // https://bugzilla.gnome.org/show_bug.cgi?id=565385
            long width;
            if (!get_long(WIDTH_TAGS[ctr], out width))
                continue;
            
            long height;
            if (!get_long(HEIGHT_TAGS[ctr], out height))
                continue;
            
            return Dimensions((int) width, (int) height);
        }
        
        return null;
    }
    
770
    public void set_pixel_dimensions(Dimensions? dim, SetOption option = SetOption.ALL_DOMAINS) {
771
         if (dim != null) {
772 773
            set_all_long(WIDTH_TAGS, dim.width, option);
            set_all_long(HEIGHT_TAGS, dim.height, option);
774 775 776 777 778 779
         } else {
            remove_tags(WIDTH_TAGS);
            remove_tags(HEIGHT_TAGS);
         }
    }
    
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
    //
    // A note regarding titles and descriptions:
    //
    // iPhoto stores its title in Iptc.Application2.ObjectName and its description in
    // Iptc.Application2.Caption.  Most others use .Caption for the title and another
    // (sometimes) appropriate tag for the description.  And there's general confusion about
    // whether Exif.Image.ImageDescription is a description (which is what the tag name
    // suggests) or a title (which is what the specification states).
    // See: http://trac.yorba.org/wiki/PhotoTags
    //
    // Hence, the following logic tries to do the right thing in most of these cases.  If
    // the iPhoto title tag is detected, it and the iPhoto description tag are used.  Otherwise,
    // the title/description are searched out from a list of standard tags.
    //
    // Exif.Image.ImageDescription seems to be abused, both in that iPhoto uses it as a multiline
    // description and that some cameras insert their make & model information there (IN ALL CAPS,
    // to really rub it in).  We are ignoring the field until a compelling reason to support it
    // is found.
    //
    
    private const string IPHOTO_TITLE_TAG = "Iptc.Application2.ObjectName";
    
    private static string[] STANDARD_TITLE_TAGS = {
        "Iptc.Application2.Caption",
        "Xmp.dc.title",
        "Iptc.Application2.Headline",
        "Xmp.photoshop.Headline"
807 808
    };
    
809
    public override string? get_title() {
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
        // using get_string_multiple()/get_first_string_multiple() because it's possible for
        // multiple strings to be specified in XMP for different language codes, and want to
        // retrieve only the first one (other get_string variants will return ugly strings like
        //
        //   lang="x-default" Xyzzy
        //
        // but get_string_multiple will return a list of titles w/o language information
        Gee.List<string>? titles = has_tag(IPHOTO_TITLE_TAG)
            ? get_string_multiple(IPHOTO_TITLE_TAG)
            : get_first_string_multiple(STANDARD_TITLE_TAGS);
        
        // use the first string every time (assume it's default)
        // TODO: We could get a list of all titles by their lang="<iso code>" and attempt to find
        // the right one for the user's locale, but this does not seem to be a normal use case
        string? title = (titles != null && titles.size > 0) ? titles[0] : null;
825 826
        
        // strip out leading and trailing whitespace
827 828 829
        if (title != null)
            title = title.strip();
        
830 831 832
        // check for \n and \r to prevent multiline titles, which have been spotted in the wild
        return (!is_string_empty(title) && !title.contains("\n") && !title.contains("\r")) ?
            title : null;
833 834
    }
    
835
    public void set_title(string? title, SetOption option = SetOption.ALL_DOMAINS) {
836 837 838 839
        if (!is_string_empty(title)) {
            if (has_tag(IPHOTO_TITLE_TAG))
                set_string(IPHOTO_TITLE_TAG, title);
            else
840
                set_all_string(STANDARD_TITLE_TAGS, title, option);
841 842 843 844 845
        } else {
            remove_tags(STANDARD_TITLE_TAGS);
        }
    }
    
846
    private static string[] KEYWORD_TAGS = {
847
        "Xmp.dc.subject",
848 849 850
        "Iptc.Application2.Keywords"
    };
    
851 852 853
    private static HierarchicalKeywordField[] HIERARCHICAL_KEYWORD_TAGS = {
        // Xmp.lr.hierarchicalSubject should be writeable but isn't due to this bug
        // in libexiv2: http://dev.exiv2.org/issues/784
854 855 856
        new HierarchicalKeywordField("Xmp.lr.hierarchicalSubject", "|", false, false),
        new HierarchicalKeywordField("Xmp.digiKam.TagsList", "/", false, true),
        new HierarchicalKeywordField("Xmp.MicrosoftPhoto.LastKeywordXMP", "/", false, true)
857 858
    };
    
859 860
    public Gee.Set<string>? get_keywords(CompareFunc? compare_func = null) {
        Gee.Set<string> keywords = null;
861 862 863
        foreach (string tag in KEYWORD_TAGS) {
            Gee.Collection<string>? values = get_string_multiple(tag);
            if (values != null && values.size > 0) {
864 865
                if (keywords == null)
                    keywords = create_string_set(compare_func);
866 867 868

                foreach (string current_value in values)
                    keywords.add(HierarchicalTagUtilities.make_flat_tag_safe(current_value));
869 870 871 872 873 874
            }
        }
        
        return (keywords != null && keywords.size > 0) ? keywords : null;
    }
    
875
    private void internal_set_hierarchical_keywords(HierarchicalTagIndex? index) {
876 877 878 879
        foreach (HierarchicalKeywordField current_field in HIERARCHICAL_KEYWORD_TAGS)
            remove_tag(current_field.field_name);

        if (index == null)
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
            return;

        foreach (HierarchicalKeywordField current_field in HIERARCHICAL_KEYWORD_TAGS) {
            if (!current_field.is_writeable)
                continue;

            Gee.Set<string> writeable_set = new Gee.TreeSet<string>();

            foreach (string current_path in index.get_all_paths()) {
                string writeable_path = current_path.replace(Tag.PATH_SEPARATOR_STRING,
                    current_field.path_separator);
                if (!current_field.wants_leading_separator)
                    writeable_path = writeable_path.substring(1);

                writeable_set.add(writeable_path);
            }
            
            set_string_multiple(current_field.field_name, writeable_set);
        }
    }
    
901
    public void set_keywords(Gee.Collection<string>? keywords, SetOption option = SetOption.ALL_DOMAINS) {
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
        HierarchicalTagIndex htag_index = new HierarchicalTagIndex();
        Gee.Set<string> flat_keywords = new Gee.TreeSet<string>();

        if (keywords != null) {
            foreach (string keyword in keywords) {
                if (keyword.has_prefix(Tag.PATH_SEPARATOR_STRING)) {
                    Gee.Collection<string> path_components =
                        HierarchicalTagUtilities.enumerate_path_components(keyword);
                    foreach (string component in path_components)
                        htag_index.add_path(component, keyword);
                } else {
                    flat_keywords.add(keyword);
                }
            }
            
            flat_keywords.add_all(htag_index.get_all_tags());
        }

        if (keywords != null) {
            set_all_string_multiple(KEYWORD_TAGS, flat_keywords, option);
            internal_set_hierarchical_keywords(htag_index);
        } else {
924
            remove_tags(KEYWORD_TAGS);
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
            internal_set_hierarchical_keywords(null);
        }
    }
    
    public bool has_hierarchical_keywords() {
        foreach (HierarchicalKeywordField field in HIERARCHICAL_KEYWORD_TAGS) {
            Gee.Collection<string>? values = get_string_multiple(field.field_name);
            
            if (values != null && values.size > 0)
                return true;
        }
        
        return false;
    }
    
    public Gee.Set<string> get_hierarchical_keywords() {
        assert(has_hierarchical_keywords());

        Gee.Set<string> h_keywords = create_string_set(null);

        foreach (HierarchicalKeywordField field in HIERARCHICAL_KEYWORD_TAGS) {
            Gee.Collection<string>? values = get_string_multiple(field.field_name);
            
            if (values == null || values.size < 1)
                continue;
            
            foreach (string current_value in values) {
                string? canonicalized = HierarchicalTagUtilities.canonicalize(current_value,
                    field.path_separator);

                if (canonicalized != null)
                    h_keywords.add(canonicalized);
            }
        }
        
        return h_keywords;
961 962 963 964 965 966 967 968 969 970 971
    }
    
    public bool has_orientation() {
        return exiv2.get_orientation() == GExiv2.Orientation.UNSPECIFIED;
    }
    
    // If not present, returns Orientation.TOP_LEFT.
    public Orientation get_orientation() {
        // GExiv2.Orientation is the same value-wise as Orientation, with one exception:
        // GExiv2.Orientation.UNSPECIFIED must be handled
        GExiv2.Orientation orientation = exiv2.get_orientation();
972 973
        if (orientation ==  GExiv2.Orientation.UNSPECIFIED || orientation < Orientation.MIN ||
            orientation > Orientation.MAX)
974 975 976 977 978 979 980 981 982 983 984 985
            return Orientation.TOP_LEFT;
        else
            return (Orientation) orientation;
    }
    
    public void set_orientation(Orientation orientation) {
        // GExiv2.Orientation is the same value-wise as Orientation
        exiv2.set_orientation((GExiv2.Orientation) orientation);
    }
    
    public bool get_gps(out double longitude, out string long_ref, out double latitude, out string lat_ref,
        out double altitude) {
986 987 988 989
        if (!exiv2.get_gps_info(out longitude, out latitude, out altitude)) {
            long_ref = null;
            lat_ref = null;
            
990
            return false;
991
        }
992 993 994 995 996 997 998 999 1000 1001 1002 1003
        
        long_ref = get_string("Exif.GPSInfo.GPSLongitudeRef");
        lat_ref = get_string("Exif.GPSInfo.GPSLatitudeRef");
        
        return true;
    }
    
    public bool get_exposure(out MetadataRational exposure) {
        return get_rational("Exif.Photo.ExposureTime", out exposure);
    }
    
    public string? get_exposure_string() {
1004 1005 1006 1007 1008 1009 1010
        MetadataRational exposure_time;
        if (!get_rational("Exif.Photo.ExposureTime", out exposure_time))
            return null;
        
        if (!exposure_time.is_valid())
            return null;

1011 1012 1013 1014
        return get_string_interpreted("Exif.Photo.ExposureTime");
    }
    
    public bool get_iso(out long iso) {
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
        bool fetched_ok = get_long("Exif.Photo.ISOSpeedRatings", out iso);

        if (fetched_ok == false)
            return false;
        
        // lower boundary is original (ca. 1935) Kodachrome speed, the lowest ISO rated film ever
        // manufactured; upper boundary is 4 x fastest high-speed digital camera speeds
        if ((iso < 6) || (iso > 409600))
            return false;
        
        return true;
1026 1027 1028
    }
    
    public string? get_iso_string() {
1029 1030 1031 1032
        long iso;
        if (!get_iso(out iso))
            return null;

1033 1034 1035 1036 1037 1038 1039
        return get_string_interpreted("Exif.Photo.ISOSpeedRatings");
    }
    
    public bool get_aperture(out MetadataRational aperture) {
        return get_rational("Exif.Photo.FNumber", out aperture);
    }
    
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
    public string? get_aperture_string(bool pango_formatted = false) {
        MetadataRational aperture;
        if (!get_aperture(out aperture))
            return null;
        
        double aperture_value = ((double) aperture.numerator) / ((double) aperture.denominator);
        aperture_value = ((int) (aperture_value * 10.0)) / 10.0;

        return (pango_formatted ? "<i>f</i>/" : "f/") + 
            ((aperture_value % 1 == 0) ? "%.0f" : "%.1f").printf(aperture_value);
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
    }
    
    public string? get_camera_make() {
        return get_string_interpreted("Exif.Image.Make");
    }
    
    public string? get_camera_model() {
        return get_string_interpreted("Exif.Image.Model");
    }
    
    public bool get_flash(out long flash) {
        // Exif.Image.Flash does not work for some reason
        return get_long("Exif.Photo.Flash", out flash);
    }
    
    public string? get_flash_string() {
        // Exif.Image.Flash does not work for some reason
        return get_string_interpreted("Exif.Photo.Flash");
    }
    
    public bool get_focal_length(out MetadataRational focal_length) {
        return get_rational("Exif.Photo.FocalLength", out focal_length);
    }
    
    public string? get_focal_length_string() {
        return get_string_interpreted("Exif.Photo.FocalLength");
    }
    
1078 1079 1080 1081 1082
    private static string[] ARTIST_TAGS = {
        "Exif.Image.Artist",
        "Exif.Canon.OwnerName" // Custom tag used by Canon DSLR cameras
    };
    
1083
    public string? get_artist() {
1084
        return get_first_string_interpreted(ARTIST_TAGS);
1085 1086 1087 1088 1089 1090 1091 1092 1093
    }
    
    public string? get_copyright() {
        return get_string_interpreted("Exif.Image.Copyright");
    }
    
    public string? get_software() {
        return get_string_interpreted("Exif.Image.Software");
    }
1094
    
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
    public void set_software(string software, string version) {
        // always set this one, even if EXIF not present
        set_string("Exif.Image.Software", "%s %s".printf(software, version));
        
        if (has_iptc()) {
            set_string("Iptc.Application2.Program", software);
            set_string("Iptc.Application2.ProgramVersion", version);
        }
    }
    
    public void remove_software() {
        remove_tag("Exif.Image.Software");
        remove_tag("Iptc.Application2.Program");
        remove_tag("Iptc.Application2.ProgramVersion");
    }
    
1111 1112 1113
    public string? get_exposure_bias() {
        return get_string_interpreted("Exif.Photo.ExposureBiasValue");
    }
1114 1115 1116 1117 1118 1119 1120 1121 1122
    
    private static string[] RATING_TAGS = {
        "Xmp.xmp.Rating",
        "Iptc.Application2.Urgency",
        "Xmp.photoshop.Urgency"
    };
    
    public Rating get_rating() {
        string? rating_string = get_first_string(RATING_TAGS);
1123
        return rating_string == null ? Rating.UNRATED : Rating.unserialize(int.parse(rating_string));
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
    }
    
    // Among photo managers, Xmp.xmp.Rating tends to be the standard way to represent ratings.
    // Other photo managers, notably F-Spot, take hints from Urgency fields about what the rating
    // of an imported photo should be, and we have decided to do as well. Xmp.xmp.Rating is the only 
    // field we've seen photo manages export ratings to, while Urgency fields seem to have a fundamentally
    // different meaning. See http://trac.yorba.org/wiki/PhotoTags#Rating for more information.
    public void set_rating(Rating rating) {
        set_string("Xmp.xmp.Rating", rating.serialize().to_string());
    }
1134 1135
}