propertiesView: Show basic EXIF data

Use libgweather to determine the city for EXIF GPS coordinates.
Make ImageMetadata a GObject to use it's properties in UI.
This commit is contained in:
Sophie Herold 2022-11-06 01:08:43 +01:00 • committed by Christopher Davis
parent e04992b46d
commit 65808f5894
11 changed files with 946 additions and 158 deletions

View file

@ -1,104 +0,0 @@
use gio::prelude::*;
#[derive(Default)]
pub enum ImageMetadata {
Exif(exif::Exif),
#[default]
None,
}
impl ImageMetadata {
pub fn load(file: &gio::File) -> Self {
if let Some(path) = file.path() {
if let Ok(file) = std::fs::File::open(path) {
let mut bufreader = std::io::BufReader::new(&file);
let exifreader = exif::Reader::new();
if let Ok(exif) = exifreader.read_from_container(&mut bufreader) {
return Self::Exif(exif);
}
}
}
Self::None
}
pub fn orientation(&self) -> Orientation {
match self {
Self::Exif(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()
}
}
Self::None => Orientation::default(),
}
}
}
impl std::fmt::Debug for ImageMetadata {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
Self::Exif(exif) => {
let list = exif.fields().into_iter().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()
}
Self::None => fmt.write_str("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(),
}
}
}

125
src/image_metadata/gps.rs Normal file
View file

@ -0,0 +1,125 @@
#[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}″ {reference}")
} else if let Some(min) = self.min {
format!("{deg}° {min}′ {reference}")
} else {
format!("{deg}° {reference}")
}
}
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>)> {
Some((
position.get(0).map(exif::Rational::to_f64)?,
position.get(1).map(exif::Rational::to_f64),
position.get(2).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());
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 { "N" } else { "S" };
coord.display(reference)
}
pub fn longitude_display(&self) -> String {
let coord = self.longitude;
let reference = if coord.sing { "E" } else { "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}")
}
}

247
src/image_metadata/mod.rs Normal file
View file

@ -0,0 +1,247 @@
/*! Resources for working with EXIF Metadata
- <https://github.com/ianare/exif-samples>
*/
mod gps;
mod obj;
pub use gps::GPSLocation;
pub use obj::LpImageMetadata;
use gio::prelude::*;
use crate::i18n::*;
use gtk::glib;
#[derive(Default)]
pub enum ImageMetadata {
Exif(exif::Exif),
#[default]
None,
}
impl std::fmt::Debug for ImageMetadata {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
Self::Exif(exif) => {
let list = exif.fields().into_iter().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()
}
Self::None => fmt.write_str("None"),
}
}
}
impl ImageMetadata {
pub fn load(file: &gio::File) -> Self {
if let Some(path) = file.path() {
log::debug!("Loading metadata for {:?}", path);
if let Ok(file) = std::fs::File::open(path) {
let mut bufreader = std::io::BufReader::new(&file);
let exifreader = exif::Reader::new();
if let Ok(exif) = exifreader.read_from_container(&mut bufreader) {
return Self::Exif(exif);
}
}
}
Self::None
}
pub fn is_none(&self) -> bool {
matches!(self, Self::None)
}
pub fn orientation(&self) -> Orientation {
match self {
Self::Exif(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()
}
}
Self::None => Orientation::default(),
}
}
pub fn originally_created(&self) -> Option<String> {
if let Self::Exif(exif) = self {
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(),
) {
// Translators: Date (%x) and time (%X) combined
if let Ok(formatted) = datetime.format(&i18n("%x %X")) {
return Some(formatted.to_string());
}
}
}
}
}
return Some(field.display_value().to_string());
}
}
None
}
pub fn f_number(&self) -> Option<String> {
if let Self::Exif(exif) = self {
if let Some(field) = exif.get_field(exif::Tag::FNumber, exif::In::PRIMARY) {
return Some(format!("ƒ\u{2215}{}", field.display_value()));
}
}
None
}
pub fn exposure_time(&self) -> Option<String> {
if let Self::Exif(exif) = self {
let field = exif.get_field(exif::Tag::ExposureTime, exif::In::PRIMARY)?;
if let exif::Value::Rational(rational) = &field.value {
let exposure = format!("{:.0}", 1. / rational.first()?.to_f32());
// Translators: Unit for exposure time in seconds
return Some(i18n_f("1\u{2215}{}\u{202F}s", &[&exposure]));
}
}
None
}
pub fn iso(&self) -> Option<String> {
if let Self::Exif(exif) = self {
if let Some(field) =
exif.get_field(exif::Tag::PhotographicSensitivity, exif::In::PRIMARY)
{
return Some(field.display_value().to_string());
}
}
None
}
pub fn focal_length(&self) -> Option<String> {
if let Self::Exif(exif) = self {
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(i18n_f("{}\u{202F}mm", &[&length]));
}
}
None
}
pub fn camera_model(&self) -> Option<String> {
if let Self::Exif(exif) = self {
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
}
pub fn gps_location(&self) -> Option<GPSLocation> {
if let Self::Exif(exif) = self {
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(),
}
}
}

107
src/image_metadata/obj.rs Normal file
View file

@ -0,0 +1,107 @@
use gio::prelude::*;
use super::{GPSLocation, ImageMetadata, Orientation};
use glib::subclass::prelude::*;
use gtk::glib;
use once_cell::sync::Lazy;
use std::cell::RefCell;
glib::wrapper! {
pub struct LpImageMetadata(ObjectSubclass<imp::LpImageMetadata>);
}
impl LpImageMetadata {
pub fn load(file: &gio::File) -> Self {
let obj = glib::Object::new::<Self>(&[]);
let metadata = ImageMetadata::load(file);
obj.imp().metadata.replace(metadata);
obj
}
pub fn orientation(&self) -> Orientation {
self.imp().metadata.borrow().orientation()
}
pub fn gps_location(&self) -> Option<GPSLocation> {
self.imp().metadata.borrow().gps_location()
}
}
impl From<ImageMetadata> for LpImageMetadata {
fn from(metadata: ImageMetadata) -> Self {
let obj = glib::Object::new::<Self>(&[]);
obj.imp().metadata.replace(metadata);
obj
}
}
impl Default for LpImageMetadata {
fn default() -> Self {
glib::Object::new(&[])
}
}
mod imp {
use super::*;
#[derive(Default)]
pub struct LpImageMetadata {
pub(super) metadata: RefCell<ImageMetadata>,
}
#[glib::object_subclass]
impl ObjectSubclass for LpImageMetadata {
const NAME: &'static str = "LpImageMetadata";
type Type = super::LpImageMetadata;
type ParentType = glib::Object;
}
impl ObjectImpl for LpImageMetadata {
fn properties() -> &'static [glib::ParamSpec] {
static PROPERTIES: Lazy<Vec<glib::ParamSpec>> = Lazy::new(|| {
let mut vec = vec![glib::ParamSpecBoolean::builder("has-information").build()];
vec.append(
&mut [
"originally-created",
"location",
"f-number",
"exposure-time",
"iso",
"focal-length",
"camera-model",
]
.iter()
.map(|name| glib::ParamSpecString::builder(name).read_only().build())
.collect(),
);
vec
});
PROPERTIES.as_ref()
}
fn property(&self, _id: usize, pspec: &glib::ParamSpec) -> glib::Value {
//let obj = self.instance();
let metadata = self.metadata.borrow();
match pspec.name() {
"has-information" => (!metadata.is_none()).to_value(),
"originally-created" => metadata.originally_created().to_value(),
"location" => metadata.gps_location().map(|x| x.display()).to_value(),
"f-number" => metadata.f_number().to_value(),
"exposure-time" => metadata.exposure_time().to_value(),
"iso" => metadata.iso().to_value(),
"focal-length" => metadata.focal_length().to_value(),
"camera-model" => metadata.camera_model().to_value(),
name => unimplemented!("property {name}"),
}
}
}
}

View file

@ -26,7 +26,7 @@ use once_cell::unsync::OnceCell;
use std::cell::{Cell, RefCell};
use crate::i18n::i18n;
use crate::image_metadata::ImageMetadata;
use crate::image_metadata::{ImageMetadata, LpImageMetadata};
use crate::util;
const ZOOM_ANIMATION_DURATION: u32 = 200;
@ -79,7 +79,7 @@ mod imp {
pub vadjustment: RefCell<Option<gtk::Adjustment>>,
/// Currently EXIF data
pub image_metadata: RefCell<ImageMetadata>,
pub image_metadata: RefCell<LpImageMetadata>,
/// This will often be available earlier than the complete image
pub image_original_size: Cell<(i32, i32)>,
@ -115,6 +115,9 @@ mod imp {
glib::ParamSpecBoolean::builder("is-loaded")
.read_only()
.build(),
glib::ParamSpecObject::builder::<LpImageMetadata>("metadata")
.read_only()
.build(),
glib::ParamSpecDouble::builder("rotation")
.explicit_notify()
.build(),
@ -148,6 +151,7 @@ mod imp {
match pspec.name() {
"file" => obj.file().to_value(),
"is-loaded" => obj.is_loaded().to_value(),
"metadata" => obj.metadata().to_value(),
"rotation" => obj.rotation().to_value(),
"mirrored" => obj.mirrored().to_value(),
"zoom" => obj.zoom().to_value(),
@ -572,11 +576,13 @@ impl LpImage {
.await?;
let orientation = metadata.orientation();
imp.image_metadata.replace(metadata);
imp.image_metadata.replace(LpImageMetadata::from(metadata));
imp.rotation_target.set(-orientation.rotation);
imp.rotation.set(-orientation.rotation);
imp.mirrored.set(orientation.mirrored);
self.notify("metadata");
log::debug!("Loading image size");
let (_, x, y) = util::spawn(
"image-load-size",
@ -1082,6 +1088,10 @@ impl LpImage {
self.width() as f64
}
pub fn metadata(&self) -> LpImageMetadata {
self.imp().image_metadata.borrow().clone()
}
/// Drag and drop content provider
pub fn content_provider(&self) -> Option<gdk::ContentProvider> {
let file = self.file()?;

View file

@ -34,7 +34,10 @@ use std::cell::RefCell;
use gtk_macros::spawn;
const FALLBACK: &str = "-";
use crate::image_metadata::LpImageMetadata;
use crate::widgets::image::LpImage;
const FALLBACK: &str = "–";
mod imp {
use super::*;
@ -43,6 +46,10 @@ mod imp {
#[template(resource = "/org/gnome/Loupe/gtk/properties_view.ui")]
pub struct LpPropertiesView {
pub file: RefCell<Option<glib::WeakRef<gio::File>>>,
pub image: RefCell<Option<glib::WeakRef<LpImage>>>,
pub metadata: RefCell<LpImageMetadata>,
pub file_info: RefCell<Option<gio::FileInfo>>,
pub dimensions: RefCell<Option<String>>,
@ -63,6 +70,10 @@ mod imp {
klass.install_action("properties.open-folder", None, move |properties, _, _| {
properties.open_directory();
});
klass.install_action("properties.open-location", None, move |properties, _, _| {
properties.open_location();
});
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
@ -86,6 +97,12 @@ mod imp {
.read_only()
.explicit_notify()
.build(),
glib::ParamSpecObject::builder::<LpImage>("image")
.explicit_notify()
.build(),
glib::ParamSpecObject::builder::<LpImageMetadata>("metadata")
.read_only()
.build(),
]
});
@ -98,6 +115,8 @@ mod imp {
match prop_name {
"file" => obj.file().to_value(),
"image" => obj.image().to_value(),
"metadata" => self.metadata.borrow().to_value(),
"file-info" => obj.file_info().to_value(),
"dimensions" => self.dimensions.borrow().to_value(),
_ => unimplemented!("Failed to get property \"{prop_name}\""),
@ -110,6 +129,7 @@ mod imp {
match prop_name {
"file" => obj.set_file(&value.get().ok()),
"image" => obj.set_image(&value.get().ok()),
_ => unimplemented!(),
}
}
@ -119,6 +139,24 @@ mod imp {
self.parent_constructed();
obj.action_set_enabled("properties.open-folder", false);
// watch changes to image metadata
obj.property_expression("image")
.chain_property::<LpImage>("metadata")
.watch(
glib::Object::NONE,
glib::clone!(@weak obj => move || {
let metadata = if let Some(image) = obj.image() {
image.metadata()
} else {
LpImageMetadata::default()
};
// set metadata since image might have changed
obj.imp().metadata.replace(metadata);
obj.notify("metadata");
}),
);
}
}
@ -167,6 +205,18 @@ impl LpPropertiesView {
imp.file.borrow().as_ref().and_then(|w| w.upgrade())
}
fn set_image(&self, image: &Option<LpImage>) {
let imp = self.imp();
imp.image.replace(image.as_ref().map(|x| x.downgrade()));
self.notify("image");
}
fn image(&self) -> Option<LpImage> {
let imp = self.imp();
imp.image.borrow().as_ref().and_then(|w| w.upgrade())
}
fn file_info(&self) -> Option<gio::FileInfo> {
let imp = self.imp();
imp.file_info.borrow().clone()
@ -304,6 +354,26 @@ impl LpPropertiesView {
}
}
/// Open GPS location in apps like Maps via `geo:` URI
fn open_location(&self) {
if let Some(uri) = self
.image()
.and_then(|x| x.metadata().gps_location())
.map(|x| x.geo_uri())
{
gio::AppInfo::launch_default_for_uri_async(
&uri,
gio::AppLaunchContext::NONE,
gio::Cancellable::NONE,
|result| {
if let Err(err) = result {
log::error!("Failed to show geo URI: {err}")
}
},
);
}
}
// In the LpPropertiesView UI file we define a few `gtk::Expression`s
// that are closures. These closures take either the current `gio::File`
// or the current file's associated `gio::FileInfo` and process them
@ -356,6 +426,11 @@ impl LpPropertiesView {
.map(|t| t.to_string())
.unwrap_or_else(|| FALLBACK.to_owned())
}
#[template_callback]
fn has_content(&self, content: Option<String>) -> bool {
content.map_or(false, |x| !x.is_empty())
}
}
async fn parse_svg_file_future(path: std::path::PathBuf) -> anyhow::Result<svg_metadata::Metadata> {