improv(icon): IconSource paths now stored as Cow<Path>

This commit is contained in:
Michael Aaron Murphy 2023-01-05 13:19:29 +01:00 committed by Michael Murphy
parent dc4edb2a4d
commit 38f9de4405

View file

@ -9,21 +9,33 @@ use iced::{
widget::{svg, Image}, widget::{svg, Image},
ContentFit, Length, ContentFit, Length,
}; };
use std::hash::Hash; use std::{hash::Hash, path::PathBuf};
use std::{ use std::{
borrow::Cow, collections::hash_map::DefaultHasher, ffi::OsStr, hash::Hasher, path::Path, borrow::Cow, collections::hash_map::DefaultHasher, ffi::OsStr, hash::Hasher, path::Path,
}; };
#[derive(Debug, Hash)] #[derive(Debug, Hash)]
pub enum IconSource<'a> { pub enum IconSource<'a> {
Path(&'a Path), Path(Cow<'a, Path>),
Name(Cow<'a, str>), Name(Cow<'a, str>),
Embedded(Image), Embedded(Image),
} }
impl<'a> From<Cow<'a, Path>> for IconSource<'a> {
fn from(value: Cow<'a, Path>) -> Self {
Self::Path(value)
}
}
impl From<PathBuf> for IconSource<'static> {
fn from(value: PathBuf) -> Self {
Self::Path(Cow::Owned(value))
}
}
impl<'a> From<&'a Path> for IconSource<'a> { impl<'a> From<&'a Path> for IconSource<'a> {
fn from(value: &'a Path) -> Self { fn from(value: &'a Path) -> Self {
Self::Path(value) Self::Path(Cow::Borrowed(value))
} }
} }
@ -33,7 +45,7 @@ impl<'a> From<Cow<'a, str>> for IconSource<'a> {
} }
} }
impl<'a> From<String> for IconSource<'a> { impl From<String> for IconSource<'static> {
fn from(value: String) -> Self { fn from(value: String) -> Self {
Self::Name(value.into()) Self::Name(value.into())
} }
@ -101,23 +113,26 @@ impl<'a> Icon<'a> {
self.hash(&mut hasher); self.hash(&mut hasher);
iced_lazy::lazy(hasher.finish(), move || -> Element<Message> { iced_lazy::lazy(hasher.finish(), move || -> Element<Message> {
let icon = match &self.name { let name_path_buffer: Option<PathBuf>;
IconSource::Path(path) => Some(Cow::from(*path)), let icon: Option<&Path> = match &self.name {
IconSource::Path(path) => Some(path),
IconSource::Name(name) => { IconSource::Name(name) => {
let icon = freedesktop_icons::lookup(name) let icon = freedesktop_icons::lookup(name)
.with_size(self.size) .with_size(self.size)
.with_theme(&self.theme) .with_theme(&self.theme)
.with_cache() .with_cache()
.find(); .find();
if icon.is_none() {
name_path_buffer = if icon.is_none() {
freedesktop_icons::lookup(name) freedesktop_icons::lookup(name)
.with_size(self.size) .with_size(self.size)
.with_cache() .with_cache()
.find() .find()
} else { } else {
icon icon
} };
.map(Cow::from)
name_path_buffer.as_deref()
} }
IconSource::Embedded(_) => unimplemented!(), IconSource::Embedded(_) => unimplemented!(),
}; };