use super::{mime, FileError};
use std::{
borrow::Cow,
path::{Path, PathBuf},
sync::Arc,
};
#[derive(Clone, Debug)]
pub(super) enum Source {
Path(PathBuf),
Memory(Arc<[u8]>),
Placeholder,
#[cfg(target_arch = "wasm32")]
Web(web_sys::File),
#[cfg(target_arch = "wasm32")]
#[cfg_attr(not(feature = "file-dialogs"), allow(dead_code))]
Download,
}
#[derive(Clone, Debug)]
pub struct PickedFile {
name: String,
size: Option<u64>,
dir: bool,
mime: Option<Cow<'static, str>>,
pub(super) source: Source,
}
impl PickedFile {
pub fn from_path(path: impl Into<PathBuf>) -> Self {
let path = path.into();
let (size, dir) = match std::fs::metadata(&path) {
Ok(meta) => (meta.is_file().then_some(meta.len()), meta.is_dir()),
Err(_) => (None, false),
};
let name = path
.file_name()
.map_or_else(|| path.to_string_lossy(), |n| n.to_string_lossy())
.into_owned();
Self::build(name, size, dir, None, Source::Path(path))
}
pub fn from_memory(name: impl Into<String>, bytes: impl Into<Arc<[u8]>>) -> Self {
let bytes = bytes.into();
Self::build(
name.into(),
Some(bytes.len() as u64),
false,
None,
Source::Memory(bytes),
)
}
pub fn directory(name: impl Into<String>) -> Self {
Self::build(name.into(), None, true, None, Source::Placeholder)
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn placeholder(mime: Option<String>) -> Self {
let mime = mime.filter(|m| !m.is_empty()).map(Cow::Owned);
Self::build(String::new(), None, false, mime, Source::Placeholder)
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn from_web(file: web_sys::File) -> Self {
let mime = Some(file.type_()).filter(|m| !m.is_empty()).map(Cow::Owned);
let size = Some(file.size() as u64);
Self::build(file.name(), size, false, mime, Source::Web(file))
}
#[cfg(all(target_arch = "wasm32", feature = "file-dialogs"))]
pub(crate) fn download(name: String) -> Self {
Self::build(name, None, false, None, Source::Download)
}
fn build(
name: String,
size: Option<u64>,
dir: bool,
mime: Option<Cow<'static, str>>,
source: Source,
) -> Self {
let mut file = Self {
name,
size,
dir,
mime,
source,
};
if file.mime.is_none() && !file.dir {
file.mime = file
.extension()
.and_then(mime::from_extension)
.map(Cow::Borrowed);
}
file
}
pub fn name(&self) -> &str {
&self.name
}
pub fn path(&self) -> Option<&Path> {
match &self.source {
Source::Path(path) => Some(path),
_ => None,
}
}
pub fn size(&self) -> Option<u64> {
self.size
}
pub fn is_dir(&self) -> bool {
self.dir
}
pub fn extension(&self) -> Option<&str> {
if self.dir {
return None;
}
match self.name.rsplit_once('.') {
Some((stem, ext)) if !stem.is_empty() && !ext.is_empty() => Some(ext),
_ => None,
}
}
pub fn mime(&self) -> Option<&str> {
self.mime.as_deref()
}
pub fn read_blocking(&self) -> Result<Vec<u8>, FileError> {
match &self.source {
Source::Path(path) => std::fs::read(path).map_err(|e| FileError::io(&e)),
Source::Memory(bytes) => Ok(bytes.to_vec()),
_ => Err(FileError::Unsupported(
"this file cannot be read synchronously; use Context::read_file".into(),
)),
}
}
}