metadata: Move file info and format to metadata
This commit is contained in:
parent
c36e7f4eb6
commit
c0f435386d
16 changed files with 327 additions and 339 deletions
38
src/metadata/file.rs
Normal file
38
src/metadata/file.rs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
use crate::deps::*;
|
||||
|
||||
pub struct FileInfo {
|
||||
pub(super) display_name: glib::GString,
|
||||
pub(super) file_size: Option<u64>,
|
||||
pub(super) mime_type: Option<glib::GString>,
|
||||
pub(super) created: Option<glib::DateTime>,
|
||||
pub(super) modified: Option<glib::DateTime>,
|
||||
}
|
||||
|
||||
impl FileInfo {
|
||||
pub async fn new(file: &gio::File) -> anyhow::Result<Self> {
|
||||
let file_info = crate::util::query_attributes_future(
|
||||
file,
|
||||
vec![
|
||||
gio::FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,
|
||||
gio::FILE_ATTRIBUTE_STANDARD_SIZE,
|
||||
gio::FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
|
||||
gio::FILE_ATTRIBUTE_TIME_CREATED,
|
||||
gio::FILE_ATTRIBUTE_TIME_MODIFIED,
|
||||
],
|
||||
)
|
||||
.await?;
|
||||
|
||||
let size = file_info.size();
|
||||
let file_size = if size > 0 { Some(size as u64) } else { None };
|
||||
|
||||
Ok(Self {
|
||||
display_name: file_info.display_name(),
|
||||
file_size,
|
||||
mime_type: file_info
|
||||
.content_type()
|
||||
.and_then(|x| gio::content_type_get_mime_type(&x)),
|
||||
created: file_info.creation_date_time(),
|
||||
modified: file_info.modification_date_time(),
|
||||
})
|
||||
}
|
||||
}
|
||||
28
src/metadata/format.rs
Normal file
28
src/metadata/format.rs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
#[derive(Clone, Debug)]
|
||||
pub struct ImageFormat {
|
||||
mime_type: glycin::MimeType,
|
||||
name: String,
|
||||
}
|
||||
|
||||
impl ImageFormat {
|
||||
pub fn new(mime_type: glycin::MimeType, name: String) -> Self {
|
||||
Self { mime_type, name }
|
||||
}
|
||||
|
||||
pub fn is_svg(&self) -> bool {
|
||||
matches!(
|
||||
self.mime_type.as_str(),
|
||||
"image/svg+xml" | "image/svg+xml-compressed"
|
||||
)
|
||||
}
|
||||
|
||||
pub fn is_potentially_transparent(&self) -> bool {
|
||||
!matches!(self.mime_type.as_str(), "image/bmp" | "image/jpeg")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ImageFormat {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
|
||||
write!(f, "{}", self.name)
|
||||
}
|
||||
}
|
||||
181
src/metadata/gps.rs
Normal file
181
src/metadata/gps.rs
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
// Copyright (c) 2022-2023 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}″ {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>)> {
|
||||
let (deg, mut min, mut sec) = (position.get(0)?, 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 100 km away
|
||||
if location.distance(&location_exact) < 100. {
|
||||
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 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}")
|
||||
}
|
||||
}
|
||||
360
src/metadata/mod.rs
Normal file
360
src/metadata/mod.rs
Normal file
|
|
@ -0,0 +1,360 @@
|
|||
// Copyright (c) 2022-2023 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
|
||||
// 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
|
||||
|
||||
/*! Resources for working with EXIF Metadata
|
||||
|
||||
- <https://github.com/ianare/exif-samples>
|
||||
*/
|
||||
|
||||
mod file;
|
||||
mod format;
|
||||
mod gps;
|
||||
|
||||
pub use file::FileInfo;
|
||||
pub use format::ImageFormat;
|
||||
pub use gps::GPSLocation;
|
||||
|
||||
use crate::util;
|
||||
use crate::util::gettext::*;
|
||||
|
||||
use crate::deps::*;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Metadata {
|
||||
exif: Option<exif::Exif>,
|
||||
file_info: Option<FileInfo>,
|
||||
format: Option<ImageFormat>,
|
||||
transformations_applied: Option<bool>,
|
||||
}
|
||||
|
||||
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 {
|
||||
pub fn set_exif_bytes(&mut self, bytes: Vec<u8>) {
|
||||
let reader = exif::Reader::new();
|
||||
let exif = reader.read_raw(bytes);
|
||||
|
||||
if let Err(err) = &exif {
|
||||
log::warn!("Failed to decode EXIF bytes: {err}");
|
||||
}
|
||||
|
||||
self.exif = exif.ok();
|
||||
}
|
||||
|
||||
pub fn set_transformations_applied(&mut self, applied: bool) {
|
||||
self.transformations_applied = Some(applied);
|
||||
}
|
||||
|
||||
pub fn set_file_info(&mut self, file_info: FileInfo) {
|
||||
self.file_info = Some(file_info);
|
||||
}
|
||||
|
||||
pub fn set_format(&mut self, format: ImageFormat) {
|
||||
self.format = Some(format);
|
||||
}
|
||||
|
||||
pub fn merge(&mut self, other: Self) {
|
||||
if self.exif.is_none() {
|
||||
self.exif = other.exif;
|
||||
}
|
||||
if self.file_info.is_none() {
|
||||
self.file_info = other.file_info;
|
||||
}
|
||||
if self.transformations_applied.is_none() {
|
||||
self.transformations_applied = other.transformations_applied;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mime_type(&self) -> Option<String> {
|
||||
self.file_info
|
||||
.as_ref()
|
||||
.and_then(|x| x.mime_type.as_ref())
|
||||
.map(|x| x.to_string())
|
||||
}
|
||||
|
||||
pub fn format(&self) -> Option<&ImageFormat> {
|
||||
self.format.as_ref()
|
||||
}
|
||||
|
||||
pub fn format_name(&self) -> Option<String> {
|
||||
self.format()
|
||||
.map(|x| x.to_string())
|
||||
.or_else(|| self.mime_type())
|
||||
}
|
||||
|
||||
pub fn transformations_applied(&self) -> bool {
|
||||
self.transformations_applied.unwrap_or(false)
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
} else {
|
||||
Orientation::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn file_name(&self) -> Option<String> {
|
||||
self.file_info.as_ref().map(|x| x.display_name.to_string())
|
||||
}
|
||||
|
||||
pub fn file_size(&self) -> Option<String> {
|
||||
self.file_info
|
||||
.as_ref()
|
||||
.and_then(|x| x.file_size)
|
||||
.map(|x| glib::format_size(x).to_string())
|
||||
}
|
||||
|
||||
pub fn file_created(&self) -> Option<String> {
|
||||
self.file_info
|
||||
.as_ref()
|
||||
.and_then(|x| x.created.as_ref())
|
||||
.and_then(util::datetime_fmt)
|
||||
}
|
||||
|
||||
pub fn file_modified(&self) -> Option<String> {
|
||||
self.file_info
|
||||
.as_ref()
|
||||
.and_then(|x| x.modified.as_ref())
|
||||
.and_then(util::datetime_fmt)
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Some(field.display_value().to_string());
|
||||
}
|
||||
}
|
||||
|
||||
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))
|
||||
{
|
||||
return Some(format!("ƒ\u{2215}{}", field.display_value()));
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
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 exposure = format!("{:.0}", 1. / rational.first()?.to_f32());
|
||||
|
||||
// Translators: Unit for exposure time in seconds
|
||||
return Some(gettext_f("1\u{2215}{}\u{202F}s", &[&exposure]));
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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("{}\u{202F}mm", &[&length]));
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Combined maker and model info
|
||||
pub fn maker_model(&self) -> Option<String> {
|
||||
if let Some(mut model) = self.model() {
|
||||
if let Some(maker) = self.maker() {
|
||||
// This is to avoid doubling the maker name
|
||||
// Canon for example also puts "Canon" in the model as well
|
||||
// NIKON sometimes puts "NIKON" in model and "NIKON CORPORATION" in maker
|
||||
if model.split_whitespace().next() != maker.split_whitespace().next() {
|
||||
model = format!("{maker} {model}");
|
||||
}
|
||||
}
|
||||
|
||||
Some(model)
|
||||
} else {
|
||||
self.maker()
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue