metadata: Use gufo instead of kamadak exif

A bunch of metadata code is now provided by gufo.
This commit is contained in:
Sophie Herold 2024-11-12 00:35:05 +01:00
parent 51b4ddbc5c
commit 5409203ec9
12 changed files with 212 additions and 438 deletions

View file

@ -1,5 +1,4 @@
// Copyright (c) 2022-2024 Sophie Herold
// Copyright (c) 2023 FineFindus
//
// 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
@ -22,59 +21,38 @@
*/
mod file;
mod gps;
use std::path::PathBuf;
use std::str::FromStr;
use chrono::prelude::*;
pub use file::FileInfo;
use glib::TimeZone;
use glycin::{Frame, FrameDetails, ImageInfoDetails, MemoryFormat};
pub use gps::GPSLocation;
use gufo::common::datetime::DateTime;
use gufo::common::orientation::Orientation;
use crate::deps::*;
use crate::util;
use crate::util::gettext::*;
#[derive(Default)]
#[derive(Default, Debug)]
pub struct Metadata {
mime_type: Option<String>,
exif: Option<exif::Exif>,
exif: gufo::Metadata,
file_info: Option<FileInfo>,
image_info: Option<glycin::ImageInfoDetails>,
frame_info: Option<FrameDetails>,
memory_format: Option<MemoryFormat>,
}
impl std::fmt::Debug for Metadata {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
if let Some(exif) = &self.exif {
let list = exif.fields().map(|f| {
let mut value = f.display_value().to_string();
// Remove long values
if value.len() > 100 {
value = String::from("…");
}
(f.ifd_num.to_string(), f.tag.to_string(), value)
});
fmt.write_str("Exif")?;
fmt.debug_list().entries(list).finish()
} else {
fmt.write_str("Empty")
}
}
}
impl Metadata {
fn set_exif_bytes(&mut self, bytes: Vec<u8>) {
let reader = exif::Reader::new();
let exif = reader.read_raw(bytes);
let result = self.exif.add_raw_exif(bytes);
if let Err(err) = &exif {
if let Err(err) = &result {
log::warn!("Failed to decode EXIF bytes: {err}");
}
self.exif = exif.ok();
}
pub fn set_image_info(&mut self, image_info: ImageInfoDetails) {
@ -98,7 +76,7 @@ impl Metadata {
}
pub fn merge(&mut self, other: Self) {
if self.exif.is_none() {
if self.exif.is_empty() {
self.exif = other.exif;
}
if self.file_info.is_none() {
@ -165,18 +143,9 @@ impl Metadata {
pub fn orientation(&self) -> Orientation {
if self.transformations_applied() {
// HEIF library already does it's transformations on its own
Orientation::default()
} else if let Some(exif) = &self.exif {
if let Some(orientation) = exif
.get_field(exif::Tag::Orientation, exif::In::PRIMARY)
.and_then(|x| x.value.get_uint(0))
{
Orientation::from(orientation)
} else {
Orientation::default()
}
Orientation::Id
} else {
Orientation::default()
self.exif.orientation().unwrap_or(Orientation::Id)
}
}
@ -224,44 +193,41 @@ impl Metadata {
}
pub fn originally_created(&self) -> Option<String> {
if let Some(exif) = &self.exif {
if let Some(field) = exif
.get_field(exif::Tag::DateTimeOriginal, exif::In::PRIMARY)
.or_else(|| exif.get_field(exif::Tag::DateTime, exif::In::PRIMARY))
{
if let exif::Value::Ascii(ascii_vec) = &field.value {
if let Some(ascii) = ascii_vec.first() {
if let Ok(dt) = exif::DateTime::from_ascii(ascii) {
if let Ok(datetime) = glib::DateTime::from_local(
dt.year.into(),
dt.month.into(),
dt.day.into(),
dt.hour.into(),
dt.minute.into(),
dt.second.into(),
) {
return util::datetime_fmt(&datetime);
}
}
}
if let Some(date_time) = &self.exif.date_time_original() {
let glib_date_time = match date_time {
DateTime::Naive(naive) => {
glib::DateTime::from_unix_local(naive.and_utc().timestamp()).ok()
}
DateTime::FixedOffset(fixed) => {
let naive = fixed.naive_utc();
glib::DateTime::new(
&TimeZone::from_offset(fixed.timezone().local_minus_utc() * 60),
naive.year(),
naive.month() as i32,
naive.day() as i32,
naive.hour() as i32,
naive.minute() as i32,
naive.second() as f64,
)
.ok()
}
};
return Some(field.display_value().to_string());
if let Some(glib_date_time) = glib_date_time {
util::datetime_fmt(&glib_date_time)
} else {
Some(date_time.to_string())
}
} else {
None
}
None
}
pub fn f_number(&self) -> Option<String> {
if let Some(field) = self
.exif
.as_ref()
.and_then(|exif| exif.get_field(exif::Tag::FNumber, exif::In::PRIMARY))
{
if let Some(f_number) = self.exif.f_number() {
return Some(
// Translators: Display of the f-number <https://en.wikipedia.org/wiki/F-number>. {} will be replaced with the number
gettext_f(r"\u{192}\u{2215}{}", [field.display_value().to_string()]),
gettext_f(r"\u{192}\u{2215}{}", [f_number.to_string()]),
);
}
@ -269,53 +235,34 @@ impl Metadata {
}
pub fn exposure_time(&self) -> Option<String> {
if let Some(exif) = &self.exif {
let field = exif.get_field(exif::Tag::ExposureTime, exif::In::PRIMARY)?;
if let exif::Value::Rational(rational) = &field.value {
let speed = rational.first()?.to_f32();
if speed <= 0.5 {
let exposure = format!("{:.0}", 1. / speed);
// Translators: Fractional exposure time (photography) in seconds
return Some(gettext_f(r"1\u{2215}{}\u{202F}s", [exposure]));
if let Some((num, denom)) = self.exif.exposure_time() {
let speed = num as f64 / denom as f64;
if speed <= 0.5 {
let exposure = format!("{:.0}", 1. / speed);
// Translators: Fractional exposure time (photography) in seconds
Some(gettext_f(r"1\u{2215}{}\u{202F}s", [exposure]))
} else {
let exposure = if speed < 5. {
format!("{:.1}", speed)
} else {
let exposure = if speed < 5. {
format!("{:.1}", speed)
} else {
format!("{:.0}", speed)
};
// Translators: Exposure time (photography) in seconds
return Some(gettext_f(r"{}\u{202F}s", [exposure]));
}
format!("{:.0}", speed)
};
// Translators: Exposure time (photography) in seconds
Some(gettext_f(r"{}\u{202F}s", [exposure]))
}
} else {
None
}
None
}
pub fn iso(&self) -> Option<String> {
if let Some(exif) = &self.exif {
if let Some(field) =
exif.get_field(exif::Tag::PhotographicSensitivity, exif::In::PRIMARY)
{
return Some(field.display_value().to_string());
}
}
None
self.exif.iso_speed_rating().map(|iso| iso.to_string())
}
pub fn focal_length(&self) -> Option<String> {
if let Some(exif) = &self.exif {
let field = exif.get_field(exif::Tag::FocalLength, exif::In::PRIMARY)?;
if let exif::Value::Rational(rational) = &field.value {
let length = format!("{:.0}", rational.first()?.to_f32());
// Translators: Unit for focal length in millimeters
return Some(gettext_f(r"{}\u{202F}mm", [length]));
}
}
None
self.exif
.focal_length()
.map(|focal_length| gettext_f(r"{}\u{202F}mm", [focal_length.to_string()]))
}
/// Combined maker and model info
@ -337,99 +284,77 @@ impl Metadata {
}
pub fn model(&self) -> Option<String> {
if let Some(exif) = &self.exif {
if let Some(field) = exif.get_field(exif::Tag::Model, exif::In::PRIMARY) {
if let exif::Value::Ascii(value) = &field.value {
if let Some(entry) = value.first() {
return Some(String::from_utf8_lossy(entry).to_string());
}
}
}
}
None
self.exif.model()
}
pub fn maker(&self) -> Option<String> {
if let Some(exif) = &self.exif {
if let Some(field) = exif.get_field(exif::Tag::Make, exif::In::PRIMARY) {
if let exif::Value::Ascii(value) = &field.value {
if let Some(entry) = value.first() {
return Some(String::from_utf8_lossy(entry).to_string());
self.exif.make()
}
pub fn gps_location(&self) -> Option<gufo::common::geography::Location> {
self.exif.gps_location()
}
pub fn gps_location_display(&self) -> Option<String> {
if let Some(location) = self.gps_location() {
let (lat_ref, (lat_deg, lat_min, lat_sec)) = location.lat_ref_deg_min_sec();
let lat_ref = match lat_ref {
gufo::common::geography::LatRef::North => {
// Translators: short for "north" in GPS coordinate
gettext("N")
}
gufo::common::geography::LatRef::South => {
// Translators: short for "south" in GPS coordinate
gettext("S")
}
};
let (lon_ref, (lon_deg, lon_min, lon_sec)) = location.lon_ref_deg_min_sec();
let lon_ref = match lon_ref {
gufo::common::geography::LonRef::East => {
// Translators: short for "east" in GPS coordinate
gettext("E")
}
gufo::common::geography::LonRef::West => {
// Translators: short for "west" in GPS coordinate
gettext("W")
}
};
let lat = format!("{lat_deg}° {lat_min}′ {lat_sec:05.2}″ {lat_ref}");
let lon = format!("{lon_deg}° {lon_min}′ {lon_sec:05.2}″ {lon_ref}");
Some(format!("{lat}\n{lon}"))
} else {
None
}
}
/// Outputs location as "City, County" if possible
///
/// Falls back to coordinates
pub fn gps_location_place(&self) -> Option<String> {
if let Some(location) = self.gps_location() {
if let Some(world) = libgweather::Location::world() {
let lat = location.lat.0;
let lon = location.lon.0;
let nearest_city = world.find_nearest_city(lat, lon);
let location_exact = libgweather::Location::new_detached("", None, lat, lon);
// do not use city if more than 15 km away
if nearest_city.distance(&location_exact) < 15. {
if let (Some(city), Some(country)) =
(nearest_city.city_name(), nearest_city.country_name())
{
return Some(format!("{city}, {country}"));
}
}
}
}
None
}
pub fn gps_location(&self) -> Option<GPSLocation> {
if let Some(exif) = &self.exif {
if let (Some(latitude), Some(latitude_ref), Some(longitude), Some(longitude_ref)) = (
exif.get_field(exif::Tag::GPSLatitude, exif::In::PRIMARY),
exif.get_field(exif::Tag::GPSLatitudeRef, exif::In::PRIMARY),
exif.get_field(exif::Tag::GPSLongitude, exif::In::PRIMARY),
exif.get_field(exif::Tag::GPSLongitudeRef, exif::In::PRIMARY),
) {
if let (
exif::Value::Rational(latitude),
exif::Value::Ascii(latitude_ref),
exif::Value::Rational(longitude),
exif::Value::Ascii(longitude_ref),
) = (
&latitude.value,
&latitude_ref.value,
&longitude.value,
&longitude_ref.value,
) {
return GPSLocation::for_exif(latitude, latitude_ref, longitude, longitude_ref);
}
}
}
None
}
}
#[derive(Default, Debug, Clone, Copy)]
pub struct Orientation {
pub rotation: f64,
pub mirrored: bool,
}
impl From<u32> for Orientation {
fn from(number: u32) -> Self {
match number {
8 => Self {
rotation: 90.,
mirrored: false,
},
3 => Self {
rotation: 180.,
mirrored: false,
},
6 => Self {
rotation: 270.,
mirrored: false,
},
2 => Self {
rotation: 0.,
mirrored: true,
},
5 => Self {
rotation: 90.,
mirrored: true,
},
4 => Self {
rotation: 180.,
mirrored: true,
},
7 => Self {
rotation: 270.,
mirrored: true,
},
_ => Self::default(),
self.gps_location_display()
} else {
None
}
}
}

View file

@ -19,6 +19,7 @@ use crate::deps::*;
const ATTRIBUTE_HOST_PATH: &str = "xattr::document-portal.host-path";
#[derive(Debug)]
pub struct FileInfo {
pub(super) display_name: glib::GString,
pub(super) file_size: Option<u64>,

View file

@ -1,205 +0,0 @@
// Copyright (c) 2022-2024 Sophie Herold
// Copyright (c) 2023 FineFindus
// Copyright (c) 2023 Lubosz Sarnecki
//
// 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 3 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, see <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-or-later
use crate::util::gettext::*;
#[derive(Debug, Clone, Copy)]
pub struct GPSLocation {
pub latitude: GPSCoord,
pub longitude: GPSCoord,
}
#[derive(Debug, Clone, Copy)]
pub struct GPSCoord {
sing: bool,
deg: f64,
min: Option<f64>,
sec: Option<f64>,
}
impl GPSCoord {
fn to_f64(self) -> f64 {
let sign = if self.sing { 1. } else { -1. };
let min = self.min.unwrap_or_default();
let sec = self.sec.unwrap_or_default();
sign * (self.deg + min / 60. + sec / 60. / 60.)
}
fn display(&self, reference: &str) -> String {
let deg = self.deg;
if let (Some(min), Some(sec)) = (self.min, self.sec) {
format!("{deg}° {min}′ {sec:05.2}″ {reference}")
} else if let Some(min) = self.min {
format!("{deg}° {min:06.3}′ {reference}")
} else {
format!("{deg:08.5}° {reference}")
}
}
fn machine_readable(&self, reference: &str) -> String {
let deg = self.deg;
if let (Some(min), Some(sec)) = (self.min, self.sec) {
format!("{reference}{deg}°{min}'{sec:05.2}\"")
} else if let Some(min) = self.min {
format!("{reference}{deg}°{min:06.3}'")
} else {
format!("{reference}{deg:08.5}°")
}
}
fn latitude_sign(reference: &[Vec<u8>]) -> Option<bool> {
let reference = reference.first().and_then(|x| x.first())?;
match reference.to_ascii_uppercase() {
b'N' => Some(true),
b'S' => Some(false),
_ => None,
}
}
fn longitude_sign(reference: &[Vec<u8>]) -> Option<bool> {
let reference = reference.first().and_then(|x| x.first())?;
match reference.to_ascii_uppercase() {
b'E' => Some(true),
b'W' => Some(false),
_ => None,
}
}
fn position_exif(position: &[exif::Rational]) -> Option<(f64, Option<f64>, Option<f64>)> {
let (deg, mut min, mut sec) = (position.first()?, position.get(1), position.get(2));
if let (Some(min_), Some(sec_)) = (min, sec) {
if min_.denom > 1 && sec_.num == 0 {
sec = None;
}
}
if min.is_some_and(|min_| deg.denom > 1 && min_.num == 0) {
min = None;
}
Some((
deg.to_f64(),
min.map(exif::Rational::to_f64),
sec.map(exif::Rational::to_f64),
))
}
}
impl GPSLocation {
pub fn for_exif(
latitude: &[exif::Rational],
latitude_ref: &[Vec<u8>],
longitude: &[exif::Rational],
longitude_ref: &[Vec<u8>],
) -> Option<Self> {
let (lat_deg, lat_min, lat_sec) = GPSCoord::position_exif(latitude)?;
let lat_sign = GPSCoord::latitude_sign(latitude_ref)?;
let (lon_deg, lon_min, lon_sec) = GPSCoord::position_exif(longitude)?;
let lon_sign = GPSCoord::longitude_sign(longitude_ref)?;
Some(Self {
latitude: GPSCoord {
sing: lat_sign,
deg: lat_deg,
min: lat_min,
sec: lat_sec,
},
longitude: GPSCoord {
sing: lon_sign,
deg: lon_deg,
min: lon_min,
sec: lon_sec,
},
})
}
pub fn display(&self) -> String {
if let Some(world) = libgweather::Location::world() {
let location = world.find_nearest_city(self.latitude.to_f64(), self.longitude.to_f64());
let location_exact = libgweather::Location::new_detached(
"",
None,
self.latitude.to_f64(),
self.longitude.to_f64(),
);
// do not use city if more than 15 km away
if location.distance(&location_exact) < 15. {
if let (Some(city), Some(country)) = (location.city_name(), location.country_name())
{
return format!("{city}, {country}");
}
}
}
// fallback
self.latitude_display() + "\n" + &self.longitude_display()
}
pub fn latitude_display(&self) -> String {
let coord = self.latitude;
let reference = if coord.sing {
// Translators: short for "north" in GPS coordinate
gettext("N")
} else {
// Translators: short for "south" in GPS coordinate
gettext("S")
};
coord.display(&reference)
}
pub fn machine_readable(&self) -> String {
let coord = self.latitude;
let reference = if coord.sing { "N" } else { "S" };
let lat = coord.machine_readable(reference);
let coord = self.longitude;
let reference = if coord.sing { "E" } else { "W" };
let lon = coord.machine_readable(reference);
format!("{lat} {lon}")
}
pub fn longitude_display(&self) -> String {
let coord = self.longitude;
let reference = if coord.sing {
// Translators: short for "east" in GPS coordinate
gettext("E")
} else {
// Translators: short for "west" in GPS coordinate
gettext("W")
};
coord.display(&reference)
}
pub fn geo_uri(&self) -> String {
let latitude = self.latitude.to_f64();
let longitude = self.longitude.to_f64();
// six decimal places gives as more than a meter accuracy
format!("geo:{latitude:.6},{longitude:.6}")
}
}

View file

@ -1,6 +1,7 @@
// Copyright (c) 2021 Christopher Davis
// Copyright (c) 2022-2024 Sophie Herold
// Copyright (c) 2023 Lubosz Sarnecki
// Copyright (c) 2024 kramo
// Copyright (c) 2024 Maximiliano Sandoval
//
// This program is free software: you can redistribute it and/or modify

View file

@ -1,4 +1,4 @@
// Copyright (c) 2023 Sophie Herold
// Copyright (c) 2023-2024 Sophie Herold
//
// 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
@ -44,8 +44,8 @@ impl LpImage {
imp.snapshot_rotate_mirror(
&snapshot,
-orientation.rotation as f32,
orientation.mirrored,
-(orientation.rotate().degrees() as f32),
orientation.mirror(),
scale as f64,
);

View file

@ -15,6 +15,8 @@
//
// SPDX-License-Identifier: GPL-3.0-or-later
use gufo::common::orientation::Rotation;
use super::*;
use crate::metadata;
@ -98,7 +100,7 @@ impl LpImage {
/// Image size of original image with EXIF rotation applied
pub fn image_size(&self) -> (i32, i32) {
let orientation = self.imp().metadata.borrow().orientation();
if orientation.rotation.abs() == 90. || orientation.rotation.abs() == 270. {
if orientation.rotate() == Rotation::_90 || orientation.rotate() == Rotation::_270 {
let (x, y) = self.imp().original_dimensions();
(y, x)
} else {

View file

@ -31,8 +31,8 @@ impl LpImage {
self.imp().snapshot_rotate_mirror(
&snapshot,
-orientation.rotation as f32,
orientation.mirrored,
-(orientation.rotate().degrees() as f32),
orientation.mirror(),
scale,
);

View file

@ -76,9 +76,11 @@ impl LpImage {
pub fn reset_rotation(&self) {
log::debug!("Resetting rotation");
let orientation = self.metadata().orientation();
self.imp().rotation_target.set(-orientation.rotation);
self.set_mirrored(orientation.mirrored);
self.set_rotation(-orientation.rotation);
self.imp()
.rotation_target
.set(-(orientation.rotate().degrees() as f64));
self.set_mirrored(orientation.mirror());
self.set_rotation(-(orientation.rotate().degrees() as f64));
}
pub fn rotate_by(&self, angle: f64) {

View file

@ -223,7 +223,7 @@ mod imp {
// Details (EXIF)
let has_details = [
Self::update_row(&self.location, metadata.gps_location().map(|x| x.display())),
Self::update_row(&self.location, metadata.gps_location_place()),
Self::update_row(&self.originally_created, metadata.originally_created()),
Self::update_row(&self.aperture, metadata.f_number()),
Self::update_row(&self.exposure, metadata.exposure_time()),
@ -318,7 +318,7 @@ mod imp {
if let Some(location) = obj.image().and_then(|x| x.metadata().gps_location()) {
let clipboard = obj.display().clipboard();
clipboard.set_text(&location.machine_readable());
clipboard.set_text(&location.iso_6709());
let _ = obj.activate_action(
"win.show-toast",
Some(